react-ai-agent 1.7.2 → 1.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("react"),t=require("react/jsx-runtime"),s=require("react-virtuoso"),a=require("streamdown"),n=require("react-syntax-highlighter"),r=require("react-markdown"),i=require("framer-motion"),o=require("react-window"),c=require("@tanstack/react-virtual");function l(e){return e&&e.__esModule?e:{default:e}}var d=l(e),u=l(r);class h{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 g extends h{constructor(e={}){super({chatUrl:"https://api.oblien.com/ai/chat/send",historyUrl:"https://api.oblien.com/ai/chat/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 a=await fetch(this.config.chatUrl,{method:"POST",headers:s,body:JSON.stringify(e),signal:this.abortController.signal,credentials:this.config.credentials||"same-origin"});if(!a.ok){const e=await a.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 a.json()};const n=a.body.getReader(),r=new TextDecoder;let i="";for(;;){const{value:e,done:s}=await n.read();if(s){t(JSON.stringify({event:"ai_response_end",data:{status:"end"}}));break}i+=r.decode(e,{stream:!0});const a=i.split("\n");i=a.pop()||"";for(const n of a)n.trim()&&t(n)}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:a=20,sessionId:n}=e,r=`${this.config.historyUrl}?offset=${s}&limit=${a}&sessionId=${n}`,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 a={};this.tokenManager?a.Authorization="Bearer "+await this.tokenManager.getAccessToken():this.config.token&&(a.Authorization="Bearer "+this.config.token);const n=await fetch(this.config.uploadUrl,{method:"POST",headers:a,body:s,signal:t,credentials:this.config.credentials||"same-origin"});if(!n.ok)throw Error("Upload failed");return(await n.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,a)=>{try{const a=new URL(this.socketUrl+"?token="+e+"&"+t.join("&"));this.socket=new WebSocket(a),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(n){}})}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,a)=>{if(!this.isConnected())return a(Error("WebSocket is not connected"));const n=e.requestId||`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,r={...e,requestId:n};this.pendingRequests||(this.pendingRequests=new Map),this.pendingRequests.set(n,{resolve:s,reject:a,timeoutId:setTimeout(()=>{this.pendingRequests.has(n)&&(this.pendingRequests.delete(n),a(Error(`Request ${n} 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),a=s.indexOf(t);-1!==a&&s.splice(a,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 p{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,a=0,n=!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)n=!n;else if(!n)if("{"===o)0===a&&(s=i),a++;else if("}"===o&&(a--,0===a&&-1!==s)){const a=e.slice(s,i+1);try{const e=JSON.parse(a);t.push(e)}catch{}s=-1}}return t}}class f{constructor(){this.jsonStreamParser=new p}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,a=e.event||"response";s=e.type&&("started"===e.type||"finished"===e.type||"status"===e.type||e.taskId)?e:e.data||e,"ai_response"===a?a="response":"ai_response_end"===a&&(a="response_end"),t(a,s)}}catch(s){}}}class x{constructor(e){this.chatApi=e,this.streamProcessor=new f,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(a){}this.streamProcessor.processRawChunk(e,(n,r)=>{if(t&&!s)try{t(e)}catch(a){}this.emit(n,r)})})}clear(){this.eventHandlers.clear()}}class y{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 a=1e3*s.exp;return Date.now()>=a-1e3*t}setRefreshCallback(e){this.refreshCallback=e}async setAuth({accessToken:e,refreshToken:t,expiresIn:s,sessionId:a}){this.accessToken=e,this.refreshToken=t,this.sessionId=a;const n=this.decodeJWT(e);n&&n.exp?(this.tokenExpiry=1e3*n.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 b{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 a=this.messageIndex.get(e);if(void 0===a)return null;const n=this.messages[a],r={};if(Object.entries(t).forEach(([e,t])=>{r[e]="function"==typeof t?t(n[e]):t}),s.silent)return Object.assign(this.messages[a],r),this.messages[a];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[a]={...n,...r,...i&&{uniqueKey:`msg-${e}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}},this._notify(),this.messages[a]}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 w{constructor(e,t){this.messageManager=e,this.statusRegistry=t,this.activeStreamingMessages=new Map}handleUserMessage({messageId:e,text:t,attachedFiles:s=[],...a}){return this.messageManager.addMessage({messageId:e||this.messageManager._generateId("user"),sender:"user",type:"user",text:t,attachedFiles:s,...a})}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 v{constructor(){this.handlers=new Map,this.globalHandlers=[],this.streamForwarders=new Map}register(e,t,s={}){this.handlers.has(e)||this.handlers.set(e,[]);const a={handler:t,filter:s};return this.handlers.get(e).push(a),()=>{const t=this.handlers.get(e);if(t){const e=t.indexOf(a);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,a=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 n=this.handlers.get(a)||[];await Promise.all(n.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,a,e):"finished"!==t?.state&&"error"!==t?.state||this._stopStreamForwarding(s,a,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(a){}})}_startStreamForwarding(e,t,s){this.streamForwarders.forEach(a=>{a.active=!0,a.messageId=e,a.statusType=t,a.forwarder.onStart&&a.forwarder.onStart({...s,statusType:t})})}_stopStreamForwarding(e,t,s){this.streamForwarders.forEach(a=>{a.messageId===e&&(a.active=!1,a.statusType=null,a.forwarder.onEnd&&a.forwarder.onEnd({...s,statusType:t}))})}clear(){this.handlers.clear(),this.globalHandlers=[],this.streamForwarders.clear()}}const k=new v;function S(){return k}const C={current:{}},j=new Map;class M{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=C.current.mode,this.speed=C.current.speed,this.batchSize=C.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(),j.delete(this.messageId))}}function I(e){return j.get(e)}class N{constructor(){}async processChunk(e,t=null,s,a){const n=e.messageId,r=function(e){if(j.has(e))return j.get(e);const t=new M(e);return j.set(e,t),t}(e.messageId);if(r.setFullText(e.text||"",e.isLive),s){const s=e.from&&this.forwardingManager?.handlers[e.from],a=t&&this.forwardingManager?this.forwardingManager.getSession(t):null,r=s&&a&&e.from===a?.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),a=this.forwardingManager.getSubscriptionMode(t);if(s){const s=I(n);s.hasForwarder||(s.hasForwarder=!0,s.subscribe(s=>{this.forwardingManager.forwardChunk(t,s,e.isLive)},{newOnly:"delta"===a}),s.onComplete=()=>{this.forwardingManager.cleanupSession(t)})}else this.forwardingManager.forwardChunk(t,e.text||"",e.isLive)}if(o)return}this.messageHandlers.messageManager.hasMessage(n)?this.messageHandlers.messageManager.updateMessage(n,{text:t=>t+(e.text||"")},{silent:!0}):this.messageHandlers.messageManager.addMessage({messageId:n,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(n){}const a=this.messageHandlers.messageManager.hasMessage(s);"started"!==e.type&&"status"!==e.type?"finished"!==e.type?a?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}):a&&this.messageHandlers.messageManager.updateMessage(s,{statusType:e.type,isFinished:!0}):a||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 T extends N{constructor(e,t,s,a=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=a}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],a=this.queueHistory.findIndex(e=>(e.messageId||e.taskId)==(s.messageId||s.taskId)),n=this.queueHistory[a-1];n&&!n.finalized&&(n.finalized=!0,await this.notifyPreviousItem(n)),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,a=e.taskId||e.messageId;switch(this.forwardingManager&&this.useForwarding&&("started"===t&&s&&this.forwardingManager.startSession(a,s,this.instanceId)&&(this.currentForwardingSession=a),"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,j.forEach(e=>{e.stopTyping(),e.isComplete=!0,e.cleanup()}),j.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 R=null;class E{constructor(e={}){this.initialHandlers={...e},this.dynamicHandlers={},this.handlers={...e},this.activeSessions=new Map}register(e,t,s={}){const a=s.instanceId?`${e}:${s.instanceId}`:e;return this.dynamicHandlers[a]={handler:t,mode:s.mode||"dual",animated:!1!==s.animated,subscriptionMode:s.subscriptionMode||"delta",instanceId:s.instanceId},this._rebuildHandlers(),()=>{delete this.dynamicHandlers[a],this._rebuildHandlers()}}_rebuildHandlers(){this.handlers={...this.initialHandlers},Object.assign(this.handlers,this.dynamicHandlers)}startSession(e,t,s=null){const a=s?`${t}:${s}`:null,n=a&&this.handlers[a]||this.handlers[t];return!(!n||n.instanceId&&n.instanceId!==s||(this.activeSessions.get(e)||this.activeSessions.set(e,{action:t,handler:n.handler,mode:n.mode,animated:n.animated,subscriptionMode:n.subscriptionMode,instanceId:n.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 a=this.activeSessions.get(e);if(!a)return!1;const n=t||"";if(0===n.length&&s)return!0;let r,i;"full"===a.subscriptionMode?(i=n,r=n):(a.fullText+=n,r=n,i=a.fullText);try{a.handler(r,i,{action:a.action,isLive:!a.streamEnded&&s,event:"chunk",subscriptionMode:a.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 A(e){return R?e&&Object.keys(e).length>0&&(R.initialHandlers={...e},R._rebuildHandlers()):R=new E(e),R}const F=e.createContext(null),H=e.createContext({}),z=()=>e.useContext(H),L=new Map,_=(e,t,s)=>{e&&(L.has(e)||L.set(e,{}),L.get(e)[t]=s)},D=(e,t)=>{if(!e||!t)return null;const s=L.get(e);if(!s)return null;const a=t.split(".");let n=s;for(const r of a){if(!n||"object"!=typeof n)return null;n=n[r]}return n||null},q=e.forwardRef((t,s)=>{const[a,n]=e.useState(t.authConfig),[r,i]=e.useState(t.loadingHistory),[o,c]=e.useState(t.loadingComponent),[l,u]=e.useState(t.welcomeComponent),[h,m]=e.useState(t.allowThinking??!0),[p,f]=e.useState(t.headerComponent),[v,k]=e.useState(t.config),[j,M]=e.useState(t.className??"h-full w-full"),[I,N]=e.useState(t.onError),[R,E]=e.useState(t.typingAnimation??{mode:"chars",speed:400}),[z,L]=e.useState(t.forwardingHandlers??{}),[D,q]=e.useState(t.agentId),[O,P]=e.useState(t.refreshTokenCallback),[B,U]=e.useState(t.apiHandler),$=e.useRef(D||"chat-"+Math.random().toString(36).substring(2,9)).current,[W,Y]=e.useState(!1),[J,K]=e.useState(a?.sessionId),[X,G]=e.useState(!1),[Q,V]=e.useState(!1),[Z,ee]=e.useState(!1),[te,se]=e.useState(null),[ae,ne]=e.useState(null),[re,ie]=e.useState(!1),[oe,ce]=e.useState(!1),[le,de]=e.useState(null),[ue,he]=e.useState(t.initialWelcome||{title:"Welcome to AI Chat Agent",description:"A perfect agent library for your needs, for docs visit oblien.com/docs/chat-agent"}),[ge,me]=e.useState([]),pe=e.useRef(!1),fe=e.useRef(!1),xe=e.useRef(!1),ye=e.useRef(new b),be=e.useRef(null),we=e.useRef(!1),ve=e.useRef(!1),ke=e.useMemo(()=>S(),[]),Se=e.useRef(O?new y:null),Ce=e.useRef(B||new g({...v,...Se.current&&{tokenManager:Se.current},token:a?.accessToken,sessionId:a?.sessionId})),je=e.useRef(new x(Ce.current)),Me=e.useRef(A(z)),Ie=e.useRef(new w(ye.current,ke)),Ne=e.useRef(new T(Ie.current,Me.current,Object.keys(z).length>0,$)),Te=e.useCallback(()=>{const e=pe.current||fe.current;V(e),e||G(!1)},[]),Re=e.useCallback(()=>{if(we.current&&ve.current){const t=Me.current.handlers._loading_end;if(t?.handler)try{t.handler({messageId:be.current||null,instanceId:$,timestamp:Date.now()})}catch(e){}}},[$]);e.useEffect(()=>{Ne.current.onQueueComplete=()=>{fe.current=!1,ve.current=!0,Te(),Re()}},[Te,Re]),e.useEffect(()=>{t.markdownComponents&&_($,"markdown",t.markdownComponents),t.statusComponents&&Object.keys(t.statusComponents).forEach(e=>{_($,"status."+e,t.statusComponents[e])}),o&&_($,"loading",o),p&&_($,"header",p),l&&_($,"welcome",l),_($,"welcomeData",ue)},[$,t.markdownComponents,t.statusComponents,l,ue,o,p]),e.useEffect(()=>{O&&Se.current&&Se.current.setRefreshCallback(O)},[O]);const Ee=e.useRef(!1),Ae=e.useRef(J),Fe=e.useRef(null);C.current=R;const He=e.useRef(new Set);e.useEffect(()=>{const e=ye.current.subscribe(e=>{me(e)});return()=>{e()}},[]),e.useEffect(()=>{Ae.current=J},[J]),e.useRef(!1),e.useEffect(()=>{(async()=>{if(a&&a.sessionId&&Se.current)try{await Se.current.setAuth(a)}catch(te){let t="Authentication failed. Please refresh the page.";te?.message?.includes("No refresh token")?t="Session expired. Please refresh the page to continue.":te?.message&&(t=te.message),se({type:"auth_error",message:t,error:te}),Y(!1)}})()},[!1,a]);const ze=e.useCallback(e=>{se(e.error)},[]),Le=e.useCallback(async()=>{try{if(He.current.has(J))return void Y(!1);He.current.add(J),Y(!0);const e=J||a?.sessionId,t=await Ce.current.getHistory({sessionId:e});if(t.error)return ze(t),void Y(!1);t.history&&t.history.length>0&&ye.current.insertMessages(t.history,"end"),ce(!!t.has_more),Y(!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),se({type:"history_error",message:t,error:e}),Y(!1)}},[J,ze]),_e=e.useCallback(async()=>{xe.current=!0,pe.current=!1,fe.current=!1,V(!1),G(!1),ee(!1),we.current=!1,ve.current=!1;const e=Ie.current.messageManager.getAllMessages(),t=[],s=[];for(const a of e)"thinking"!==a.type||!a.isLive&&a.finalized?"status"!==a.type||a.isFinished||s.push(a):t.push(a);t.length>0&&await Promise.all(t.map(e=>{const t=e.messageId.replace("-thinking","");return Ne.current.finishThinking({messageId:t})}));for(const a of s)Ie.current.messageManager.updateMessage(a.messageId,{isFinished:!0,statusType:"finished"});Ne.current.clear(),be.current=null,Ce.current.abort(),je.current.abort(),Ae.current&&Ce.current.abortRequest&&await Ce.current.abortRequest(Ae.current),setTimeout(()=>{xe.current=!1},100)},[]),De=e.useCallback(e=>{if(xe.current)return;const t={...e,id:e?.id||Math.random().toString(36).substring(2,9),timestamp:Date.now(),instanceId:$};ne(t),I&&I(t);const s=Me.current.handlers._error;if(s?.handler)try{s.handler(t)}catch(a){}},[I,$]),qe=e.useCallback(()=>{ne(null)},[]),Oe=e.useCallback(()=>{pe.current=!1;const e=be.current;if(e){Ne.current.endResponse(),be.current=null,we.current=!0;const s=Me.current.handlers._response_end;if(s?.handler)try{s.handler({messageId:e,instanceId:$,timestamp:Date.now()})}catch(t){}}else we.current=!0;Te(),Re()},[Te,$,Re]),Pe=e.useCallback(()=>{Ee.current=!1,pe.current=!1,Te()},[Te]),Be=e.useCallback(e=>{const t=e?.data?.messageId||e?.messageId;if(t&&(be.current=t),!Z){ee(!0),we.current=!1,ve.current=!1;const e=Me.current.handlers._response_start;if(e?.handler)try{e.handler({messageId:t,instanceId:$,timestamp:Date.now()})}catch(s){}}fe.current=!0,Ne.current.addToQueue(e),Te()},[Z,Te,$]);e.useEffect(()=>(je.current.on("stream_error",De),je.current.on("response",Be),je.current.on("response_end",Oe),je.current.on("disconnect",Pe),()=>{je.current.off("stream_error",De),je.current.off("response",Be),je.current.off("response_end",Oe),je.current.off("disconnect",Pe)}),[De,Be,Oe,Pe]);const Ue=async({messageId:e=Math.random().toString(36).substring(2,9),message:t="",attachedFiles:s=[],uploadId:a=null}={})=>{if(!t.trim())return;const n="user-"+e;try{Fe.current&&Fe.current?.messageId===n||Ie.current.handleUserMessage({messageId:n,text:t,attachedFiles:s}),Fe.current={messageId:n,message:t,attachedFiles:s,uploadId:a},G(!0),ee(!1),we.current=!1,ve.current=!1,xe.current=!1,pe.current=!0,Te();const e=Me.current.handlers._stream_feedback,r=e?.handler,i="raw"===e?.mode,o=await je.current.startStream({message:t,attachedFiles:s,uploadId:a,sessionId:Ae.current,context:null,allowThinking:h},r,i);o.status||(pe.current=!1,Te(),De({errorType:"connection_error",error:o.error||"Error occurred while connecting to server",message:o.message||"Failed to send message"}))}catch(r){pe.current=!1,Te(),De({errorType:"send_error",error:r.message||"Unknown error",message:"Failed to send message"})}finally{G(!1)}},$e=e.useCallback(async()=>{Fe.current&&await Ue(Fe.current)},[]),We=e.useCallback(e=>{const t={...a,...e};n(t),void 0!==e.sessionId&&K(e.sessionId),Ce.current&&(Ce.current.config&&(void 0!==t.accessToken&&(Ce.current.config.token=t.accessToken),void 0!==t.sessionId&&(Ce.current.config.sessionId=t.sessionId)),"function"==typeof Ce.current.updateConfig&&Ce.current.updateConfig({token:t.accessToken,sessionId:t.sessionId})),Se.current&&t.accessToken&&Se.current.setAuth(t).catch(e=>{})},[a]),Ye=e.useCallback(e=>{c(e),e&&_($,"loading",e)},[$]),Je=e.useCallback(e=>{f(e),e&&_($,"header",e)},[$]),Ke=e.useCallback(e=>{u(e),e&&_($,"welcome",e)},[$]),Xe=e.useCallback(e=>{he(e),e&&_($,"welcomeData",e)},[$]),Ge=e.useMemo(()=>({addMessage:e=>ye.current.addMessage(e),updateMessage:(e,t)=>ye.current.updateMessage(e,t),removeMessage:e=>ye.current.removeMessage(e),getMessage:e=>ye.current.getMessage(e),clear:()=>ye.current.clear()}),[]),Qe=e.useMemo(()=>({register:(e,t)=>ke.register(e,t,{instanceId:$}),registerGlobal:e=>ke.registerGlobal(e,{instanceId:$})}),[$,ke]),Ve={sendMsg:Ue,messages:ge,messageManager:Ge,isLoading:X,isStreaming:Q,isResponseStarted:Z,isInitialLoading:W,isLoadingMore:re,error:te,streamError:ae,clearStreamError:qe,getHistory:Le,loadMoreMessages:async()=>{if(!re&&oe){ie(!0);try{const e=ye.current.count,t=await Ce.current.getHistory({offset:e,limit:20});if(t.error)return ze(t),void ie(!1);t.history&&t.history.length>0?(ye.current.insertMessages(t.history,"start"),ce(t.has_more)):ce(!1)}catch(e){se({type:"load_more_error",message:"Failed to load more messages",error:e})}finally{ie(!1)}}},hasMoreMessages:oe,retryLastMessage:$e,abort:_e,sessionId:J,setSessionId:K,instanceId:$,currentSelectedFile:le,setCurrentSelectedFile:de,statusRegistry:Qe,typingAnimation:R,setAuthConfig:We,setLoadHistory:i,setLoadingComponent:Ye,setAllowThinking:m,setHeaderComponent:Je,setWelcomeComponent:Ke,setWelcome:Xe,setConfig:k,setClassName:M,setOnError:N,setMarkdownComponents:e=>_($,"markdown",e),registerComponent:_,setStatusComponents:e=>{Object.keys(e).forEach(t=>{_($,"status."+t,e[t])})},setTypingAnimation:E,setForwardingHandlers:L,authConfig:a,loadingHistory:r,allowThinking:h,config:v,className:j,onError:I,forwardingHandlers:z,setAgentId:q,setRefreshTokenCallback:P,setApiHandler:U};return e.useImperativeHandle(s,()=>Ve,[]),d.default.createElement("div",{className:"react-ai-agent-root "+j},d.default.createElement(H.Provider,{value:Ve},d.default.createElement(F.Provider,{value:$},t.children)))}),O={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"},P={figma:"/icons/project/Figma-logo.svg.png",githubraw:"/icons/project/github-mark-white.png"},B=(e,s,a="#000",n={},r=!1)=>{if(r)return t.jsx("img",{src:P[e]?.replace(/ /g,"%20"),alt:e,style:{width:s,height:s,objectFit:"contain",...n}});let i=O[e]?.replace(/ /g,"%20")||e?.replace(/ /g,"%20");return i=e.startsWith("http")?e:"https://cdn.oblien.com/static/png-icons/"+i,t.jsx("div",{style:{maskImage:`url('${i}')`,maskSize:"contain",maskRepeat:"no-repeat",maskPosition:"center",WebkitMaskSize:"contain",WebkitMaskRepeat:"no-repeat",WebkitMaskPosition:"center",width:s,height:s,backgroundColor:a,...n}})},U=({showLoadMore:e,enableHistory:s,hasMoreMessages:a,messagesLength:n,error:r,isInitialLoading:i,loadMoreMessages:o,isLoadingMore:c})=>e&&s&&a&&0!==n&&!r&&!i?t.jsx("div",{className:"react-chat-core-load-more flex justify-center py-4",children:t.jsx("button",{onClick:o,disabled:c,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:t.jsxs(t.Fragment,c?{children:[t.jsx("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"}),t.jsx("span",{className:"react-chat-core-load-more-text text-sm",children:"Loading..."})]}:{children:[B("refresh",18,"currentColor"),t.jsx("span",{className:"react-chat-core-load-more-text text-sm",children:"Load more messages"})]})})}):null,$=({error:e,instanceId:s})=>{const a=D(s,"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 t.jsx("div",{className:"react-ai-agent-start-chat flex flex-col items-center justify-center h-full",children:"object"!=typeof a||a?.title?t.jsxs("div",{className:"react-ai-agent-start-chat-content text-center mb-8 flex flex-col items-center justify-center gap-2",children:[e&&t.jsx("span",{className:"react-ai-agent-start-chat-error-icon",children:B("error",70,"currentColor",{marginBottom:"10px"})}),t.jsx("h2",{className:"react-ai-agent-start-chat-title text-2xl font-light text-theme-primary mb-4",children:e?"Something went wrong":a?.title}),t.jsx("p",{className:"react-ai-agent-start-chat-description text-theme-muted mb-6 max-w-md text-base leading-relaxed",children:e?n:a?.description}),e&&e.type&&t.jsx("p",{className:"react-ai-agent-start-chat-error-type text-xs text-theme-tertiary mt-2 opacity-50",children:e.type.replace("_"," ")})]}):a})},W=({error:e,isPanelOpen:s,instanceId:a})=>{const n=D(a,"welcome");return n?t.jsx(n,{error:e}):t.jsx($,{error:e,miniMode:s,instanceId:a})},Y=()=>t.jsxs("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:[t.jsxs("div",{className:"react-ai-agent-loading-mock-welcome flex items-start gap-4 mb-12",children:[t.jsx("div",{className:"react-ai-agent-loading-mock-avatar react-ai-agent-loading-mock-avatar-welcome w-10 h-10 rounded-full shimmer-skeleton"}),t.jsxs("div",{className:"react-ai-agent-loading-mock-content flex-1 space-y-3",children:[t.jsx("div",{className:"react-ai-agent-loading-mock-line react-ai-agent-loading-mock-line-1 h-4 rounded-full shimmer-skeleton w-2/3"}),t.jsx("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,s)=>t.jsxs("div",{className:"react-ai-agent-loading-mock-message-group space-y-6",children:[t.jsxs("div",{className:"react-ai-agent-loading-mock-message react-ai-agent-loading-mock-message-user flex items-start gap-4 justify-end",children:[t.jsx("div",{className:"react-ai-agent-loading-mock-message-content max-w-[70%] space-y-2",children:t.jsx("div",{className:"react-ai-agent-loading-mock-line h-3 rounded-full shimmer-skeleton w-full"})}),t.jsx("div",{className:"react-ai-agent-loading-mock-avatar react-ai-agent-loading-mock-avatar-user w-8 h-8 rounded-full shimmer-skeleton"})]}),t.jsxs("div",{className:"react-ai-agent-loading-mock-message react-ai-agent-loading-mock-message-ai flex items-start gap-4",children:[t.jsx("div",{className:"react-ai-agent-loading-mock-avatar react-ai-agent-loading-mock-avatar-ai w-8 h-8 rounded-full shimmer-skeleton"}),t.jsxs("div",{className:"react-ai-agent-loading-mock-message-content flex-1 space-y-3",children:[t.jsx("div",{className:"react-ai-agent-loading-mock-line react-ai-agent-loading-mock-line-1 h-3 rounded-full shimmer-skeleton w-4/5"}),t.jsx("div",{className:"react-ai-agent-loading-mock-line react-ai-agent-loading-mock-line-2 h-3 rounded-full shimmer-skeleton w-3/4"})]})]})]},s))]}),J=({onComplete:s,duration:a=800})=>{const[n,r]=e.useState(0),[i,o]=e.useState(!1),c=e.useRef(0);return e.useEffect(()=>{c.current=300,requestAnimationFrame(()=>{r(c.current)});const e=setTimeout(()=>{o(!0),s?.()},a);return()=>clearTimeout(e)},[a,s]),i?null:t.jsx("div",{style:{height:n+"px",transition:`height ${a}ms cubic-bezier(0.4, 0, 0.2, 1)`,pointerEvents:"none"}})},K=({message:e,allowEdit:s=!0})=>{const a=[];return s&&a.push({icon:"edit",text:"Edit",onClick:()=>{}}),e.snapshot&&a.push({icon:"refresh",text:"Restore checkpoint",onClick:()=>{}}),t.jsxs("div",{className:"react-ai-agent-user-message flex flex-col mb-2",children:[t.jsx("div",{className:"react-ai-agent-user-message-bubble-wrapper flex justify-end mb-2",children:t.jsx("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:t.jsx("p",{className:"react-ai-agent-user-message-text text-[16px] leading-[22px] tracking-wide",children:e.text})})}),t.jsx("div",{className:"react-ai-agent-user-message-actions flex justify-end gap-4",children:a.map((e,s)=>t.jsxs("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:[t.jsx("span",{className:"react-ai-agent-user-message-action-icon",children:B(e.icon,16,"currentColor")}),t.jsx("span",{className:"react-ai-agent-user-message-action-label text-[12px] font-[300] text-theme-primary",children:e.text})]},s))})]})},X=({message:s,instanceId:n})=>{const r=D(n,"markdown"),[i,o]=e.useState("");return e.useEffect(()=>{const e=I(s.messageId);if(e)return e.subscribe(e=>{o(e)});o(s.text||"")},[s.messageId,s.text]),t.jsx("div",{className:"react-ai-agent-ai-response mb-4 mx-auto",children:t.jsx("div",{className:"react-ai-agent-ai-content text-theme-primary prose prose-invert max-w-none",dir:"auto",style:{wordBreak:"break-word"},children:t.jsx(a.Streamdown,{parseIncompleteMarkdown:!0,mode:"streaming",components:r,children:i})})})};var G=e.memo(X),Q=e.memo(({text:e,instanceId:s})=>{const n=D(s,"markdown"),r=e||"";return t.jsx("div",{className:"react-ai-agent-ai-response mb-4 mx-auto",style:{minHeight:"20px"},children:t.jsx("div",{className:"react-ai-agent-ai-content text-theme-primary prose prose-invert max-w-none",dir:"auto",style:{wordBreak:"break-word",minHeight:"20px"},children:r?t.jsx(a.Streamdown,{parseIncompleteMarkdown:!0,mode:"static",components:n,children:r}):t.jsx("span",{style:{opacity:.5},children:"..."})})})}),V=e.memo(({message:e,animationConfig:s,instanceId:a})=>e.isLive&&!e.finalized?t.jsx(G,{message:e,animationConfig:s,instanceId:a}):t.jsx(Q,{text:e.text,instanceId:a}));const Z={'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"}},ee=e.memo(({message:s,isInCurrentSession:a})=>{const r=e.useRef(null),i=e.useRef(s.finalized),o=e.useRef(null),[c,l]=e.useState(!s.finalized),[d,h]=e.useState(!1),[g,m]=e.useState(""),p=s.isLive||!s.finalized,f=s.finalized||!a,x=s.duration||0,y=e.useMemo(()=>s.text||"",[s.text]);e.useEffect(()=>{requestAnimationFrame(()=>{h(!0)})},[]),e.useEffect(()=>{if(!p||!c)return void m(y);const e=g.length,t=y.length;if(e>=t)return;const s=Math.min(5,t-e),a=setTimeout(()=>{m(y.slice(0,e+s))},20);return()=>clearTimeout(a)},[y,g,p,c]),e.useEffect(()=>{if(r.current&&c&&p)return o.current&&cancelAnimationFrame(o.current),o.current=requestAnimationFrame(()=>{r.current&&(r.current.scrollTop=r.current.scrollHeight)}),()=>{o.current&&cancelAnimationFrame(o.current)}},[g,c,p]),e.useEffect(()=>{if(f&&!i.current&&c){const e=setTimeout(()=>{l(!1)},800);return()=>clearTimeout(e)}},[f,c]);const b=e.useCallback(()=>{l(e=>!e)},[]),w=e.useMemo(()=>({code({node:e,inline:s,className:a,children:r,...i}){const o=/language-(\w+)/.exec(a||""),c=(r+"").replace(/\n$/,""),l=!s&&c.includes("\n");return s||!l?t.jsx("code",{className:"react-ai-agent-thinking-code-inline px-1 py-0.5 bg-secondary rounded text-xs font-mono whitespace-pre-wrap",...i,children:r}):t.jsx("div",{className:"react-ai-agent-thinking-code-block rounded-[15px] overflow-hidden my-3",children:t.jsx(n.Prism,{language:o?.[1]||"javascript",style:Z,children:c})})},p:({children:e})=>t.jsx("p",{className:"react-ai-agent-thinking-paragraph mb-2 leading-5 text-sm",children:e}),ul:({children:e})=>t.jsx("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})=>t.jsx("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})=>t.jsx("li",{className:"react-ai-agent-thinking-list-item mb-1 text-sm",children:e}),h1:({children:e})=>t.jsx("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})=>t.jsx("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})=>t.jsx("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})=>t.jsx("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 t.jsxs("div",{className:"react-ai-agent-thinking-message mb-4 mx-auto opacity-50 transition-all duration-300 ease-out",style:{opacity:d?.5:0,transform:d?"translateY(0)":"translateY(-10px)"},children:[f?t.jsxs("button",{onClick:b,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:[t.jsx("span",{className:"react-ai-agent-thinking-toggle-icon transition-transform duration-300",children:B(c?"brain-10-1663078315.png":"brain-11-1663755045.png",20,"currentColor")}),t.jsxs("span",{className:"react-ai-agent-thinking-toggle-text",children:["Thought for ",x," second",1!==x?"s":""]})]}):t.jsxs("div",{className:"react-ai-agent-thinking-header text-theme-tertiary text-sm mb-2 flex items-center gap-2",children:[t.jsx("span",{className:"react-ai-agent-thinking-icon animate-pulse",children:B("brain-11-1663755045.png",20,"currentColor")}),t.jsx("span",{className:"react-ai-agent-thinking-label",children:"Thinking..."})]}),t.jsx("div",{style:{maxHeight:c?"150px":"0px",opacity:c?1:0,overflow:"hidden",transition:"max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.2s ease-out"},children:g&&t.jsx("div",{ref:r,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:t.jsx("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:p?.8:1,transition:"opacity 0.15s ease"},children:t.jsx(u.default,{components:w,children:g})})})})]})},(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);ee.displayName="ThinkingMessage";const te=({text:e,style:s,fontSize:a="1em",paddingRight:n="140px",backgroundSize:r="125px",isDark:i=!1})=>{let o=1;"string"==typeof a?o=parseFloat(a)||3:"number"==typeof a&&(o=a);let c=r;"125px"===r&&"3em"!==a&&(c=o/3*125+"px");const l={fontSize:a,paddingRight:n,WebkitBackgroundSize:c+" 100%",MozBackgroundSize:c+" 100%",backgroundSize:c+" 100%",...s};return t.jsx("div",{className:"react-ai-agent-shimmer-text shimmer "+(i?"dark":"light"),style:l,children:e})},se=({message:s,title:a,isProcessing:n,isFinished:r,icon:i,iconComponent:o,isFlat:c=!0,onClick:l,isDark:d=!1,unmountOnExit:u,action:h,data:g,className:m,style:p,metadata:f})=>{const x=h||s?.action,y=g||s?.data,b=void 0!==r?r:s?.isFinished,w=void 0!==n?n:!b,v=f||s?.metadata,k=a||v?.name||s?.title,S=o||s?.iconComponent,C=void 0!==c?c:void 0===s?.isFlat||s.isFlat,j=void 0!==u?u:s?.unmountOnExit,M=l,I=v?.icon||i,N=e.useMemo(()=>k?w?`Processing ${k}...`:"Finished "+k:x?(({data:e,action:t,isFinished:s})=>{if(!t||"string"!=typeof t)return"Processing...";try{const a=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?a:`${a}${e?.tool?" "+e?.tool:""}...`}catch(a){return t}})({data:y,action:x,isFinished:b}):"Processing...",[k,x,b,y]);return t.jsx("div",C?{className:"mx-auto mb-1 "+m,style:{cursor:M?"pointer":"default",...p},onClick:M,children:t.jsxs("div",{className:`flex items-center gap-3 px-0 rounded-[12px] text-${d?"white":"black"} relative overflow-auto`,children:[j?t.jsx("div",{className:`animate-spin h-[16px] w-[16px] mr-[4px] absolute border-[1.5px] border-${d?"white":"black"} rounded-full border-t-transparent opacity-50`}):S?S():B(I||"check circle-3-1660219236.png",20,d?"rgba(255,255,255,0.25)":"rgba(0,0,0,0.25)",{position:"absolute"}),w?t.jsx(te,{isDark:d,text:N,style:{fontSize:"14px",marginLeft:"30px"}}):t.jsx("span",{style:{color:d?"rgba(255,255,255,0.25)":"rgba(0,0,0,0.25)"},className:"text-[14px] ml-[30px] "+(S?"!ml-0":""),children:N})]})}:{className:"mb-[10px] mx-auto "+m,style:{cursor:M?"pointer":"default",...p},onClick:M,children:t.jsxs("div",{className:`flex items-center p-3 rounded-[12px] text-${d?"white":"black"} relative overflow-hidden`,style:{backgroundColor:d?"rgba(255,255,255,0.02)":"rgba(0,0,0,0.02)"},children:[w?t.jsx("div",{className:`animate-spin h-[16px] w-[16px] mr-[4px] absolute border-[1.5px] border-${d?"white":"black"} rounded-full border-t-transparent opacity-50`}):S?S():B(icon||"check circle-3-1660219236.png",20,d?"rgba(255,255,255,0.8)":"rgba(0,0,0,0.8)",{position:"absolute"}),t.jsx("div",{className:"flex-1",children:w?t.jsx(te,{isDark:d,text:N,style:{marginLeft:"28px",marginTop:"-2px",color:d?"rgba(255,255,255,0.2)":"rgba(0,0,0,0.2)"}}):t.jsx("span",{className:`text-[14px] text-${d?"white":"black"}/50 ml-[30px]`,children:N})})]})})};var ae=e.memo(({item:e,removeMessage:s,allowEditMessage:a,animationConfig:n,isInCurrentSession:r,instanceId:i})=>{if("user"===e.sender)return t.jsx("div",{className:"react-ai-agent-message-item react-ai-agent-message-user",children:t.jsx(K,{message:e,allowEdit:a})});if("status"===e.type&&e.action){const s=D(i,"status."+e.action);return t.jsx("div",{className:"react-ai-agent-message-item react-ai-agent-message-status",children:t.jsx(s||se,{message:e})})}return t.jsx("div","thinking"===e.type?{className:"react-ai-agent-message-item react-ai-agent-message-thinking",children:t.jsx(ee,{message:e,removeMessage:s,isInCurrentSession:r})}:{className:"react-ai-agent-message-item react-ai-agent-message-ai",children:t.jsx(V,{message:e,animationConfig:n,isInCurrentSession:r,instanceId:i})})});const ne=({type:e})=>{const s=["w-1.5 h-1.5","w-2.5 h-2.5","w-1.5 h-1.5"],a="text"===e?["L","O","A","D","I","N","G"]:Array.from({length:3}).fill(""),n=.6+.1*(a.length-1);return t.jsx("div",{className:"react-ai-agent-loading-response flex",children:t.jsx("div",{className:"react-ai-agent-loading-content flex justify-center items-center "+("text"===e?"text-7xl font-extrabold font-[Montserrat]":"gap-1.5"),children:a.map((a,r)=>t.jsx(i.motion.span,{className:`react-ai-agent-loading-item react-ai-agent-loading-item-${e} inline-block ${"text"===e?"mx-[-0.05em]":s[r]+" rounded-full bg-inverse"}`,animate:{scale:[.75,1.5,.75],opacity:[.75,1,.75],filter:["blur(4px)","blur(0px)","blur(4px)"]},transition:{repeat:1/0,duration:.6,ease:"easeInOut",repeatDelay:n-.6,delay:.1*r},children:"text"===e?a:""},r))})})},re=({messages:t,isLoading:s,isResponseStarted:a,showLoadingIndicator:n,showSpacer:r=!1,spacerKey:i=0,onSpacerComplete:o})=>e.useMemo(()=>{const e=[...t];return r&&e.push({type:"viewport-spacer",messageId:"viewport-spacer-"+i,onComplete:o,isResponseStarted:a}),n&&s&&!a&&e.push({type:"loading-indicator",messageId:"loading-indicator"}),e},[t,n,s,a,r,i,o]),ie=t=>e.useMemo(()=>{for(let e=t.length-1;e>=0;e--)if("user"===t[e].sender)return e;return-1},[t]),oe=({item:e,index:s,lastUserIndex:a,removeMessage:n,allowEditMessage:r,animationConfig:i,isLastItem:o=!1,isFirstItem:c=!1,instanceId:l})=>{if(!e)return null;if("viewport-spacer"===e.type)return t.jsx(J,{onComplete:e.onComplete,isResponseStarted:e.isResponseStarted});if("loading-indicator"===e.type)return t.jsx(ne,{});if("empty-message"===e.type)return t.jsx("div",{style:{paddingTop:"100px"}});const d=t.jsx(ae,{item:e,removeMessage:n,allowEditMessage:r,animationConfig:i,isInCurrentSession:s>a,instanceId:l});return o?t.jsx("div",{style:{paddingBottom:"200px"},children:d}):c?t.jsx("div",{style:{paddingTop:"100px"},children:d}):d},ce=({messages:a,removeMessage:n,allowEditMessage:r,animationConfig:i,height:o,width:c,shouldAutoScrollRef:l,isLoading:d,isResponseStarted:u,showLoadingIndicator:h,showSpacer:g,spacerKey:m,onSpacerComplete:p,instanceId:f})=>{const x=e.useRef(!0),y=re({messages:a,isLoading:d,isResponseStarted:u,showLoadingIndicator:h,showSpacer:g,spacerKey:m,onSpacerComplete:p}),b=ie(a),w=e.useCallback(e=>{x.current=e,l&&(l.current=e)},[l]);e.useCallback(()=>"smooth",[]);const v=e.useCallback(e=>oe({item:y[e],index:e,lastUserIndex:b,removeMessage:n,allowEditMessage:r,instanceId:f,isLastItem:e===y.length-1,animationConfig:i}),[y,b,n,r,i]);return t.jsx(s.Virtuoso,{style:{height:o,width:c},data:y,totalCount:y.length,itemContent:v,initialTopMostItemIndex:y.length-1,atBottomStateChange:w,alignToBottom:!0})},le=({dynamicHeight:s,messages:a,removeMessage:n,allowEditMessage:r,animationConfig:i,height:c,width:l,overscan:d,listRef:u,isLoading:h,isResponseStarted:g,showLoadingIndicator:m,showSpacer:p,spacerKey:f,onSpacerComplete:x,instanceId:y})=>{const b=re({messages:a,isLoading:h,isResponseStarted:g,showLoadingIndicator:m,showSpacer:p,spacerKey:f,onSpacerComplete:x}),w=ie(a),v=e.useRef(new Map),k=e.useMemo(()=>({itemsData:b,removeMessage:n,allowEditMessage:r,animationConfig:i,dynamicHeight:s,lastUserIndex:w,heightCacheRef:v}),[b,n,r,i,s,w]),S=e.useCallback(({index:e,style:s,ariaAttributes:a,...n})=>{const{itemsData:r,removeMessage:i,allowEditMessage:o,animationConfig:c,dynamicHeight:l,lastUserIndex:d,heightCacheRef:u}=n;return t.jsx("div",{style:s,ref:t=>{if(t){const s=r[e],a=s?.uniqueKey||s?.messageId||e;u.current.has(a)||requestAnimationFrame(()=>{const s=t.getBoundingClientRect().height;s!==l.getRowHeight(e)&&(l.setRowHeight(e,s),u.current.set(a,s))})}},...a,children:oe({item:r[e],index:e,lastUserIndex:d,removeMessage:i,isLastItem:e===r.length-1,allowEditMessage:o,animationConfig:c,instanceId:y})})},[]);return t.jsx("div",{style:{height:c,width:l,overflow:"hidden"},children:t.jsx(o.List,{listRef:u,rowComponent:S,rowCount:b.length,rowHeight:s,rowProps:k,overscanCount:d})})},de=({itemsData:t,scrollToBottom:s,shouldAutoScrollRef:a,isStreaming:n})=>{const r=e.useRef(0),i=e.useRef(!1);e.useEffect(()=>{!i.current&&t.length>0&&(i.current=!0,requestAnimationFrame(()=>{requestAnimationFrame(()=>{s(!1)})}))},[]),e.useEffect(()=>{t.length>r.current&&(r.current=t.length,!1!==a?.current&&s(!0))},[t.length,s,a]),e.useEffect(()=>{if(!n)return;const e=setInterval(()=>{!1!==a?.current&&s(!1)},100);return()=>clearInterval(e)},[n,s,a])},ue=({messages:s,removeMessage:a,allowEditMessage:n,animationConfig:r,height:i,width:o,isStreaming:l,shouldAutoScrollRef:d,instanceId:u})=>{const h=e.useRef(null),g=[{type:"empty-message",messageId:"empty-message"},...s],m=ie(s),p=e.useCallback(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 a=t.text||t.content||"",n=a.length;if(0===n)return s;s+=24*Math.ceil(n/90),"thinking"===t.type?s+=40:"status"===t.type&&(s+=30);const r=(a.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=c.useVirtualizer({count:g.length,getScrollElement:()=>h.current,estimateSize:p,overscan:10}),{handleScroll:x}=(t=>{const s=e.useRef(!1),a=e.useRef(null),n=e.useCallback(e=>{a.current&&clearTimeout(a.current),s.current=!0,a.current=setTimeout(()=>{s.current=!1},150),e&&t&&(t.current=50>Math.abs(e.scrollHeight-e.scrollTop-e.clientHeight))},[t]);return{isUserScrollingRef:s,handleScroll:n}})(d),y=e.useCallback((e=!0)=>{const t=h.current;t&&t.scrollTo({top:t.scrollHeight,behavior:e?"smooth":"auto"})},[]);de({itemsData:g,scrollToBottom:y,shouldAutoScrollRef:d,isStreaming:l});const b=f.getVirtualItems();return t.jsx("div",{ref:h,onScroll:()=>x(h.current),className:"tanstack-virtual-container",style:{height:i,width:o,overflowY:"auto",contain:"strict"},children:t.jsx("div",{style:{height:f.getTotalSize()+"px",width:"100%",position:"relative"},children:b.map(e=>t.jsx("div",{"data-index":e.index,ref:f.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${e.start}px)`},children:oe({item:g[e.index],index:e.index,lastUserIndex:m,removeMessage:a,allowEditMessage:n,animationConfig:r,isLastItem:e.index===g.length-1,instanceId:u,isFirstItem:0===e.index})},e.key))})})},he=({messages:e,removeMessage:s,allowEditMessage:a,animationConfig:n,scrollToBottom:r,shouldAutoScrollRef:i,isStreaming:o,scrollContainerRef:c,height:l,width:d,isLoading:u,isResponseStarted:h,showLoadingIndicator:g,showSpacer:m,spacerKey:p,onSpacerComplete:f,instanceId:x})=>{const y=re({messages:e,isLoading:u,isResponseStarted:h,showLoadingIndicator:g,showSpacer:m,spacerKey:p,onSpacerComplete:f}),b=ie(e);return de({itemsData:y,scrollToBottom:e=>r(),shouldAutoScrollRef:i,isStreaming:o}),t.jsx("div",{ref:c,className:"react-chat-core-simple-container overflow-y-auto scrollbar-hide",style:{height:l,width:d,overflowY:"auto"},children:y.map((e,r)=>e?t.jsx("div",{children:oe({item:e,index:r,lastUserIndex:b,removeMessage:s,allowEditMessage:a,animationConfig:n,instanceId:x})},e.uniqueKey||e.messageId||r):null)})},ge=e.forwardRef(({virtualization:s="tanstack",estimateSize:a=150,overscan:n=10,isDark:r=!1,className:i="",containerStyle:c={},useGradientMask:l=!0,gradientMaskStyle:d="linear-gradient(to bottom, transparent 6.5%, black 18%)",allowEditMessage:u=!1,showWelcome:h=!0,showLoadMore:g=!0,showLoadingIndicator:m=!0,keepUserMessageInView:p=!0,initialAnimation:f=null,height:x="100%",width:y="100%"},b)=>{const[w,v]=e.useState(!1),[k,S]=e.useState(!1),C=e.useRef(null),{sendMsg:j,messages:M,messageManager:I,isLoading:N,isStreaming:T,isPanelOpen:R,error:E,isInitialLoading:A,isResponseStarted:F,abort:H,loadMoreMessages:L,isLoadingMore:_,hasMoreMessages:q,animationConfig:O,instanceId:P}=z(),B=D(P,"loading"),{showSpacer:$,spacerKey:J,triggerSpacer:K,handleSpacerComplete:X}=(()=>{const[t,s]=e.useState(!1),[a,n]=e.useState(0);return{showSpacer:t,spacerKey:a,triggerSpacer:()=>{s(!0),n(e=>e+1)},handleSpacerComplete:()=>{s(!1)}}})(),{scrollContainerRef:G,shouldAutoScrollRef:Q,scrollToBottom:V,isAtBottom:Z}=(({onGradientChange:t,isStreaming:s})=>{const a=e.useRef(null),n=e.useRef(!0),r=e.useRef(!1),i=e.useCallback(()=>{const e=a.current;e&&(e.scrollTop=e.scrollHeight)},[]),o=e.useCallback(()=>{const e=a.current;return!!e&&50>e.scrollHeight-e.scrollTop-e.clientHeight},[]),c=e.useCallback(()=>{const e=a.current;if(!e)return;const s=e.scrollTop>20;s!==r.current&&(r.current=s,t&&t(s)),n.current=o()},[o,t]),l=e.useCallback((e=>{let t=0;return function(...s){const a=Date.now();100>a-t||(t=a,e(...s))}})(c),[c]);return e.useEffect(()=>{const e=a.current;if(e)return e.addEventListener("scroll",l),()=>e.removeEventListener("scroll",l)},[l]),e.useEffect(()=>{if(!s)return;const e=setInterval(()=>{n.current&&i()},100);return()=>clearInterval(e)},[s,i]),{scrollContainerRef:a,shouldAutoScrollRef:n,scrollToBottom:i,isAtBottom:o}})({onGradientChange:v,isStreaming:"none"===s&&T}),ee="react-window"===s?(({estimateSize:e})=>o.useDynamicRowHeight({defaultRowHeight:e}))({estimateSize:a}):null,te=e.useCallback(()=>{"virtuoso"!==s&&"tanstack"!==s&&("react-window"===s&&C.current?.scrollToBottomCustom?C.current.scrollToBottomCustom():"none"===s&&V())},[s,V]),se=e.useCallback(()=>{p&&setTimeout(()=>{K()},200)},[p,K]),{removeMessage:ae,handleSendMessage:ne}=(({messageManager:t,sendMsg:s,shouldAutoScrollRef:a,onUserMessageSent:n})=>({removeMessage:e.useCallback(e=>{t?.removeMessage&&t.removeMessage(e)},[t]),handleSendMessage:e.useCallback(async e=>{a&&(a.current=!0),n&&n(),await s(e)},[s,a,n])}))({messageManager:I,sendMsg:j,scrollToBottom:te,shouldAutoScrollRef:Q,onUserMessageSent:se});return e.useEffect(()=>{if(A)S(!1);else{if(M&&M.length>0&&!k){const e=setTimeout(()=>{S(!0)},100);return()=>clearTimeout(e)}M&&0!==M.length||S(!0)}},[A,M,k]),e.useImperativeHandle(b,()=>({scrollToBottom:te,isAtBottom:Z,scrollContainer:G.current,dynamicHeight:ee,listRef:C.current,sendMessage:ne,abort:H,isStreaming:T,isLoading:N,messages:M,messageManager:I}),[te,Z,ee,ne,H,T,N,M,I]),t.jsx("div",{className:"react-ai-agent-chat-core "+i,"data-theme":r?"dark":"light",style:{WebkitMaskImage:d,...c},children:A?t.jsx(B||Y,{}):M&&0!==M.length?t.jsxs("div",{className:"react-chat-core-messages h-full w-full",style:{opacity:k?1:0,transition:"opacity 0.3s ease-out"},children:[t.jsx(U,{showLoadMore:g,enableHistory:!0,hasMoreMessages:q,messagesLength:M.length,error:E,isInitialLoading:A,loadMoreMessages:L,isLoadingMore:_}),(()=>{const e={messages:M,removeMessage:ae,allowEditMessage:u,animationConfig:O,isLoading:N,isResponseStarted:F,showLoadingIndicator:m,isStreaming:T,showSpacer:p&&$,spacerKey:J,onSpacerComplete:X};switch(s){case"virtuoso":return t.jsx(ce,{height:x,width:y,listRef:C,shouldAutoScrollRef:Q,...e});case"react-window":return t.jsx(le,{dynamicHeight:ee,height:x,width:y,overscan:n,listRef:C,isStreaming:T,shouldAutoScrollRef:Q,...e});case"tanstack":return t.jsx(ue,{height:x,width:y,isStreaming:T,shouldAutoScrollRef:Q,...e});default:return t.jsx(he,{scrollToBottom:te,shouldAutoScrollRef:Q,isStreaming:T,scrollContainerRef:G,height:x,width:y,...e})}})()]}):h&&t.jsx("div",{style:{opacity:k?1:0,height:"100%",width:"100%",transition:"opacity 0.3s ease-out"},children:t.jsx(W,{error:E,isPanelOpen:R,instanceId:P})})})});ge.displayName="ChatCore";var me=e.memo(ge);const pe=({todos:e=[]})=>e&&0!==e?.length?t.jsx("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:t.jsxs("div",{className:"react-ai-agent-queue-manager-wrapper flex items-center w-full relative bottom-0",children:[t.jsx("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] "}),t.jsx("div",{className:"react-ai-agent-queue-manager-content flex items-center gap-2 w-full p-1 py-[5px] z-99"})]})}):null,fe=({children:e,content:s,visible:a})=>a?t.jsxs("div",{className:"react-ai-agent-tooltip-wrapper relative",children:[e,t.jsxs("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:[t.jsx("div",{className:"react-ai-agent-tooltip-content text-theme-secondary text-sm space-y-2",children:s}),t.jsx("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,xe=()=>{const[s,a]=e.useState(!1),{sessionMetrics:n,usedTokens:r,contextLimit:i}=z(),o=(100*(r/i||0)).toFixed(2),c=e=>e?1e6>e?1e3>e?""+e:(e/1e3).toFixed(1)+"K":(e/1e6).toFixed(1)+"M":"0",l=t.jsxs("div",{className:"space-y-2",children:[t.jsx("div",{className:"font-medium text-theme-primary border-b border-theme-tertiary pb-1",children:"Session Info"}),t.jsxs("div",{className:"space-y-1 text-xs",children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-theme-quaternary",children:"Context size:"}),t.jsxs("span",{children:[c(n?.contextUsed)," / ",c(n?.contextLimit)]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-theme-quaternary",children:"Session Tokens:"}),t.jsx("span",{children:c(n?.tokensUsed)})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-theme-quaternary",children:"All time tokens:"}),t.jsx("span",{children:c(n?.allTimeTokens)})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-theme-quaternary",children:"Requests:"}),t.jsx("span",{children:c(n?.requests)})]})]})]});return t.jsx(fe,{content:l,visible:s,children:t.jsxs("div",{className:"react-ai-agent-progress-bar flex items-center gap-2 cursor-pointer",onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[t.jsxs("span",{className:"react-ai-agent-progress-percentage text-theme-ghost font-light text-[12px] leading-[18px]",children:[o,"%"]}),t.jsxs("div",{className:"react-ai-agent-progress-circle-wrapper relative w-4 h-4 flex items-center justify-center",children:[t.jsx("div",{className:"react-ai-agent-progress-circle-bg absolute inset-0 rounded-full bg-theme-muted"}),t.jsx("div",{className:"react-ai-agent-progress-circle-fill absolute inset-0 rounded-full",style:{background:`conic-gradient(var(--rca-text-faint) ${o}%, transparent 0)`}}),t.jsx("div",{className:"react-ai-agent-progress-circle-inner absolute inset-0.5 rounded-full bg-secondary"})]})]})})},ye=({attachedFiles:e=[],removeFile:s})=>{const{currentSelectedFile:a,setIsHoldEnabled:n,setCurrentSelectedFile:r,manuallyAddedFiles:i=[],setManuallyAddedFiles:o=()=>{}}=z(),c=[...a?[a]:[],...i,...e];return t.jsxs("div",{className:"react-ai-agent-chat-bar flex items-center w-full mb-2 justify-between",children:[t.jsxs("div",{className:"react-ai-agent-chat-bar-left flex items-center",children:[c.length>0&&t.jsx(we,{files:c,handleRemoveFile:e=>{"object"==typeof e&&e.id?s&&s(e.id):e===a?(r(null),n(!1)):o(t=>t.filter(t=>t!==e))}}),t.jsxs("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:[t.jsx("span",{className:"react-ai-agent-context-button-icon",children:B("add",20,"currentColor",{marginLeft:"-5px"})}),0===c.length&&t.jsx("span",{className:"react-ai-agent-context-button-label",children:"Context"})]})]}),t.jsx("div",{className:"react-ai-agent-chat-bar-right",children:t.jsx(xe,{})})]})},be=({file:s,handleRemoveFile:a})=>{const[n,r]=e.useState(!1),i="object"==typeof s&&s.id,o=i?s.name:s.split("/").pop(),c=i?s.id:s;return t.jsxs("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:()=>r(!0),onMouseLeave:()=>r(!1),children:[n?t.jsx("button",{className:"react-ai-agent-file-item-remove w-[16px] opacity-50 hover:opacity-100 -ml-[2px] -mr-[2px] h-[16px]",onClick:e=>{e.stopPropagation(),a(s)},children:t.jsx("span",{className:"react-ai-agent-file-item-remove-icon",children:B("close",16,"currentColor")})}):t.jsx("div",{className:"react-ai-agent-file-item-icon-wrapper",children:i&&s.preview?t.jsx("img",{src:s.preview,alt:o,className:"react-ai-agent-file-item-preview w-3 h-4 object-cover rounded",style:{marginRight:0,width:"12px",height:"16px"}}):t.jsx(FileIcon,{fileName:o,style:{marginRight:0,width:"12px",height:"16px"}})}),t.jsx("div",{className:"react-ai-agent-file-item-name text-theme-quaternary hover:text-theme-primary text-[12px] leading-relaxed whitespace-nowrap truncate max-w-[100px]",children:o})]},c)},we=({files:e,handleRemoveFile:s})=>t.jsx("div",{className:"react-ai-agent-file-items flex items-center gap-2 mr-2",children:e.map(e=>t.jsx(be,{file:e,handleRemoveFile:s},"object"==typeof e&&e.id?e.id:e))}),ve=()=>{const[s,a]=e.useState(0),n=e.useRef(),r=e.useRef(0),i=e.useRef(0),o=e.useRef(null),c=e.useRef(1);return e.useEffect(()=>{const e=()=>{if(o.current){const{width:e,height:t}=o.current.getBoundingClientRect();c.current=e/t}};e();const t=new ResizeObserver(e);return o.current&&t.observe(o.current),()=>{t.disconnect()}},[]),e.useEffect(()=>{i.current=performance.now(),r.current=s;const e=t=>{const o=t-i.current;i.current=t,r.current+=o/1e3*360,360>r.current||(r.current-=360);const l=r.current*(Math.PI/180),d=c.current,u=Math.round((Math.atan2(Math.sin(l),Math.cos(l)/d)*(180/Math.PI)+360)%360);3>Math.abs(u-s)||a(u),n.current=requestAnimationFrame(e)};return n.current=requestAnimationFrame(e),()=>{n.current&&(cancelAnimationFrame(n.current),n.current=null)}},[]),t.jsx("div",{ref:o,className:"react-ai-agent-loader-animation w-full h-full absolute inset-0 rounded-[inherit]",children:t.jsx("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":s,display:"flex"},children:t.jsx("div",{className:"style_glow__i4Qpo"})})})},ke="image/*,video/*,audio/*,.pdf,.doc,.docx,.txt,.md,.json,.js,.ts,.jsx,.tsx,.py,.html,.css,.xml,.csv";function Se(){const[t,s]=e.useState([]),a=e.useRef(null),n=e.useCallback(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=e.useCallback(async e=>{const a=[];for(const s of e){if(t.some(e=>e.name===s.name&&e.size===s.size&&e.type===s.type))continue;let e=!1;if(5242880>s.size)try{const r=await n(s);t.some(e=>e.hash===r)||(a.push({file:s,id:Date.now()+Math.random(),name:s.name,size:s.size,type:s.type,hash:r,preview:s.type.startsWith("image/")?URL.createObjectURL(s):null}),e=!0)}catch(r){}e||a.push({file:s,id:Date.now()+Math.random(),name:s.name,size:s.size,type:s.type,preview:s.type.startsWith("image/")?URL.createObjectURL(s):null})}a.length>0&&s(e=>[...e,...a])},[t,n]),i=e.useCallback(e=>{const t=Array.from(e.target.files||[]);t.length>0&&r(t),e.target.value=""},[r]),o=e.useCallback(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]),c=e.useCallback(e=>{s(t=>{const s=t.filter(t=>t.id!==e),a=t.find(t=>t.id===e);return a?.preview&&URL.revokeObjectURL(a.preview),s})},[]),l=e.useCallback(()=>{s(e=>(e.forEach(e=>{e.preview&&URL.revokeObjectURL(e.preview)}),[]))},[]);return{attachedFiles:t,fileInputRef:a,onFileSelect:i,onPaste:o,removeFile:c,clearFiles:l}}const Ce=()=>{const{streamError:s,clearStreamError:a,retryLastMessage:n,sendRequestCallback:r,triggerLoadingStates:i}=z(),[o]=e.useState(s?.choices||[{id:"retry",label:"Retry"},{id:"cancel",label:"Cancel"}]);return s?t.jsx("div",{className:"react-ai-agent-stream-error w-full mb-3",children:t.jsxs("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:[t.jsx("div",{className:"react-ai-agent-error-message-wrapper",children:t.jsx("div",{className:"react-ai-agent-error-message text-[12px] text-theme-primary font-medium",children:s.message||"An error occurred during streaming"})}),t.jsx("div",{className:"react-ai-agent-error-actions flex gap-2 items-center",children:o&&o.length>0&&o.map(e=>t.jsx("button",{onClick:()=>(async e=>{"retry"===e?"connection_error"===s.errorType?await n():(i(),r({type:"stream_error",callback:"retry",requestId:s.requestId})):"cancel"===e&&(s.requestId&&r({type:"stream_error",callback:"cancel",requestId:s.requestId}),a())})(e.id),className:`react-ai-agent-error-action react-ai-agent-error-action-${e.id} text-[11px] font-medium px-3 py-1 rounded-md transition-all duration-200\n ${"retry"===e.id?"text-theme-primary hover:text-theme-secondary underline underline-offset-2":"cancel"===e.id?"text-theme-subtle hover:text-theme-tertiary":"text-theme-tertiary hover:text-theme-primary"}\n `,children:e.label},e.id))})]})}):null},je=({agents:s=[],selectedAgentId:a,onAgentChange:n,disabled:r=!1})=>{const[i,o]=e.useState(!1),c=e.useRef(null),l=s.find(e=>e.id===a)||s[0],[d,u]=e.useState(l?.id||s[0]?.id);e.useEffect(()=>{const e=e=>{c.current&&!c.current.contains(e.target)&&o(!1)};return i&&document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[i]);const h=s.find(e=>e.id===d)||l||s[0];return h?t.jsxs("div",{className:"react-ai-agent-switch relative",ref:c,children:[t.jsxs("button",{type:"button",onClick:()=>!r&&o(!i),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:i?"var(--rca-bg-muted)":"transparent"},children:[t.jsx("span",{className:"mr-2",children:B("brain",18,"currentColor")}),t.jsx("span",{className:"react-ai-agent-switch-label text-[13px] mr-2 text-theme-primary font-[400]",children:h.name||h.model||"Agent"}),t.jsx("span",{style:{transform:i?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease",display:"inline-flex",opacity:.6},children:B("arrowDown",14,"currentColor")})]}),i&&s.length>0&&t.jsx("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:t.jsx("div",{className:"react-ai-agent-switch-dropdown-content max-h-[320px] overflow-y-auto py-1",children:s.map(e=>{const s=e.id===d;return t.jsxs("button",{type:"button",onClick:()=>(e=>{r||e.id===d||(u(e.id),n?.(e)),o(!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:s?"var(--rca-bg-subtle)":"transparent",color:s?"var(--rca-text-primary)":"var(--rca-text-secondary)"},onMouseEnter:e=>{s||(e.currentTarget.style.background="var(--rca-bg-hover)")},onMouseLeave:e=>{s||(e.currentTarget.style.background="transparent")},children:[t.jsx("span",{className:"flex-shrink-0",style:{opacity:.8},children:B("brain",18,"currentColor")}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"flex items-center gap-2",children:t.jsx("div",{className:"react-ai-agent-switch-option-name text-[13px] font-medium",children:e.name})}),e.description&&t.jsx("div",{className:"react-ai-agent-switch-option-description text-[11px] mt-0.5 truncate",style:{color:"var(--text-quaternary)"},children:e.description})]}),s&&t.jsx("span",{className:"react-ai-agent-switch-option-check flex-shrink-0",style:{color:"var(--rca-text-accent)"},children:B("check",16,"currentColor")})]},e.id)})})})]}):null},Me=e.forwardRef(({onSendMessage:s,isStreaming:a,abort:n,mode:r="advanced",todos:i=[],agents:o=[],selectedAgentId:c,onAgentChange:l},d)=>{const[u,h]=e.useState(""),g=e.useRef(null),{attachedFiles:m,fileInputRef:p,onFileSelect:f,onPaste:x,removeFile:y,clearFiles:b}=Se();e.useEffect(()=>{g.current&&(g.current.style.height="auto",g.current.style.height=Math.min(g.current.scrollHeight,150)+"px")},[u]),e.useImperativeHandle(d,()=>({focus:()=>{g.current?.focus()}}),[]);const w=e=>{e.preventDefault(),(u.trim()||m.length>0)&&(s({message:u,attachedFiles:m}),h(""),b(),g.current&&(g.current.style.height="auto"))},v="advanced"===r,k=o&&o.length>0;return t.jsx("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:t.jsxs("div",{className:"react-ai-agent-input-wrapper mx-auto relative "+("advanced"===r?"min-h-[120px]":"min-h-[100px]"),children:[a&&t.jsx("div",{className:"absolute inset-0 pointer-events-none rounded-[15px]",style:{zIndex:1},children:t.jsx(ve,{})}),t.jsx("div",{className:"react-ai-agent-input-backdrop backdrop-blur-[20px] w-full h-full z-0 absolute bg-theme-overlay rounded-[15px]"}),t.jsxs("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:[v&&t.jsxs(t.Fragment,{children:[t.jsx(pe,{todos:i}),t.jsx(Ce,{}),t.jsx(ye,{attachedFiles:m,removeFile:y})]}),t.jsx("div",{className:`react-ai-agent-input-textarea-wrapper relative pb-[${"advanced"===r?"50px":"0px"}]`,children:t.jsx("textarea",{autoSave:"off",autoFocus:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false","data-form-type":"other",ref:g,value:u,onChange:e=>h(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),w(e))},onPaste:x,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})}),t.jsxs("div",{className:"react-ai-agent-input-actions flex items-center justify-between mt-auto bottom-[15px] absolute w-[calc(100%-40px)]",children:[t.jsx("input",{ref:p,type:"file",multiple:!0,accept:ke,onChange:f,className:"react-ai-agent-file-input hidden"}),t.jsx("div",{className:"react-ai-agent-input-actions-left flex items-center gap-2",children:"default"===r&&m.length>0?t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(we,{files:m,handleRemoveFile:e=>y(e.id)}),t.jsx("button",{type:"button",onClick:()=>p.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:B("add",20,"currentColor")})]}):t.jsxs("button",{type:"button",onClick:()=>p.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:[B("attach",18,"currentColor"),t.jsx("span",{className:"react-ai-agent-attach-label text-[14px] ml-2 font-[300]",children:"Attach"})]})}),t.jsxs("div",{className:"react-ai-agent-input-actions-right flex items-center",children:[k&&t.jsx(je,{agents:o,selectedAgentId:c,onAgentChange:l,disabled:a}),t.jsx("button",{type:"button",onClick:e=>{a?n():w(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:!u.trim()&&!a,children:B(a?"square":"send",a?15:20,"currentColor")})]})]})]})]})})});Me.displayName="ChatInputDefault";var Ie=e.memo(Me);const Ne=({isDark:s=!1,onCreateSession:a,onClose:n,showCloseButton:r=!1})=>{const[i,o]=e.useState(!1),[c,l]=e.useState(!1),{instanceId:d}=z(),u=D(d,"header");return u?u():t.jsxs("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:[t.jsxs("div",{className:"react-ai-agent-header-left flex items-center gap-4 opacity-50",children:[t.jsx("button",{className:"react-ai-agent-header-new-chat flex items-center cursor-pointer hover:opacity-80",style:{opacity:i?.5:1,cursor:i?"progress":"pointer"},disabled:i,onClick:async({replace:e=!1}={})=>{if(o(!0),a)try{await a({replace:e})}catch(t){}finally{o(!1)}else setTimeout(()=>{o(!1)},1e3)},children:B("add",25,s?"#fff":"#000")}),t.jsx("div",{className:"react-ai-agent-header-history flex items-center cursor-pointer hover:opacity-80",onClick:c?()=>l(!1):()=>l(!0),children:B(c?"close":"history",18,s?"#fff":"#000")})]}),r&&n?t.jsx("button",{className:"react-ai-agent-header-close flex items-center cursor-pointer hover:opacity-80 opacity-50 transition-opacity",onClick:n,"aria-label":"Close panel",children:B("close",24,s?"#fff":"#000")}):t.jsx("div",{className:"react-ai-agent-header-right w-[80px]"})]})};var Te=e.memo(Ne);const Re=e.memo(({coreRef:e,isDark:s,allowEditMessage:a,onCreateSession:n,handleSendMessage:r,isStreaming:i,abort:o,coreProps:c,inputProps:l,children:d,onClose:u,showCloseButton:h=!1,className:g=""})=>t.jsxs("div",{className:"react-ai-agent flex flex-col h-full relative chat-panel "+g,"data-theme":s?"dark":"light",children:[t.jsx(Te,{isDark:s,onCreateSession:n,onClose:u,showCloseButton:h}),t.jsxs("div",{className:"relative flex-grow w-full max-w-[600px] mx-auto h-full min-w-[300px]",children:[t.jsx(me,{ref:e,isDark:s,allowEditMessage:a,className:"px-[15px]",...c}),t.jsx(Ie,{onSendMessage:r,isStreaming:i,abort:o,...l})]}),d]}));Re.displayName="ChatPanelContent";const Ee=({isOpen:e,isDragging:s,isDark:a=!0})=>t.jsx("div",{className:`\n w-16 h-16 rounded-full flex items-center justify-center\n transition-all duration-300 ease-out\n ${s?"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:B(e?"close%20remove-8-1662452248.png":"chat%20intelligence-48-1686045820.png",32,"currentColor")}),Ae=e.memo(({onClick:s,isDark:a=!1,isOpen:n=!1,onPositionChange:r,livePositionUpdate:i=!0,edgeOffset:o=20,ContentComponent:c=Ee,onOpen:l,onClose:u,onDrag:h})=>{const g="react-ai-agent-floating-button-position",m=e.useRef(null),[p,f]=e.useState({width:64,height:64}),x="number"==typeof o?o:o?.x??20,y="number"==typeof o?o:o?.y??20,b=e.useCallback(()=>"undefined"==typeof window?{minX:x,minY:y,maxX:1024-p.width-x,maxY:768-p.height-y,width:1024,height:768}:{minX:x,minY:y,maxX:window.innerWidth-p.width-x,maxY:window.innerHeight-p.height-y,width:window.innerWidth,height:window.innerHeight},[p,x,y]),w=e.useCallback((e,t)=>{const s=b();return{x:Math.max(s.minX,Math.min(e,s.maxX)),y:Math.max(s.minY,Math.min(t,s.maxY))}},[b]),v=e.useCallback(e=>{const t=b();return!(t.minX>e.x||t.minY>e.y||e.x>t.maxX||e.y>t.maxY)},[b]),k=e.useCallback(()=>{const e=b(),{width:t,minX:s,minY:a,maxX:n,maxY:r}=e;return[{x:s,y:a,name:"top-left"},{x:(t-p.width)/2,y:a,name:"top-center"},{x:n,y:a,name:"top-right"},{x:s,y:r,name:"bottom-left"},{x:(t-p.width)/2,y:r,name:"bottom-center"},{x:n,y:r,name:"bottom-right"}]},[p,b]),S=e.useCallback(()=>{if("undefined"==typeof window)return k()[5];try{const e=localStorage.getItem(g);if(e){const t=JSON.parse(e);if(v(t))return t}}catch(e){}return k()[5]},[k,v]),[C,j]=e.useState(()=>"undefined"==typeof window?{x:0,y:0,name:"bottom-right"}:S()),[M,I]=e.useState(!1),[N,T]=e.useState(!1),[R,E]=e.useState({x:0,y:0}),[A,F]=e.useState({x:0,y:0}),[H,z]=e.useState(!1);e.useEffect(()=>{if("undefined"!=typeof window&&!H){z(!0);const e=S();e&&void 0!==e.x&&void 0!==e.y&&j(e)}},[H,S]);const L=e.useCallback((e,t)=>{const s=k();let a=s[0],n=1/0;return s.forEach(s=>{const r=Math.sqrt(Math.pow(s.x-e,2)+Math.pow(s.y-t,2));n>r&&(n=r,a=s)}),a},[k]),_=e.useCallback(e=>{if(0!==e.button)return;e.preventDefault();const t=m.current.getBoundingClientRect(),s=e.clientX-t.left,a=e.clientY-t.top;E({x:e.clientX,y:e.clientY}),F({x:s,y:a}),I(!0),T(!1),h?.(!0),m.current&&m.current.setPointerCapture(e.pointerId)},[h]),D=e.useCallback(e=>{if(!M)return;e.preventDefault(),Math.sqrt(Math.pow(e.clientX-R.x,2)+Math.pow(e.clientY-R.y,2))>5&&T(!0);const t=w(e.clientX-A.x,e.clientY-A.y);j(t),i&&r&&r(t,!0,p)},[M,A,R,w,r,i,p]),q=e.useCallback(e=>{if("undefined"!=typeof window)try{localStorage.setItem(g,JSON.stringify(e))}catch(t){}},[]),O=e.useCallback(e=>{if(M)if(e.preventDefault(),m.current&&m.current.releasePointerCapture(e.pointerId),I(!1),h?.(!1),N){const e=L(C.x,C.y);j(e),setTimeout(()=>{q(e)},0),r?.(e,!1,p)}else s?.()},[M,N,C,L,s,q,r,h,p]);return e.useEffect(()=>{if(M){const e=e=>D(e),t=e=>O(e);return document.addEventListener("pointermove",e,{passive:!1}),document.addEventListener("pointerup",t,{passive:!1}),document.addEventListener("pointercancel",t,{passive:!1}),document.body.style.userSelect="none",document.body.style.cursor="grabbing",()=>{document.removeEventListener("pointermove",e),document.removeEventListener("pointerup",t),document.removeEventListener("pointercancel",t),document.body.style.userSelect="",document.body.style.cursor=""}}},[M,D,O]),e.useEffect(()=>{if("undefined"==typeof window)return;const e=()=>{if(v(C)){const e=L(C.x,C.y);j(e),setTimeout(()=>{q(e)},0),r?.(e,!1,p)}else{const e=w(C.x,C.y),t=L(e.x,e.y);j(t),setTimeout(()=>{q(t)},0),r?.(t,!1,p)}};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[C,L,q,v,w,r]),e.useEffect(()=>{if("undefined"==typeof window||!m.current||!H)return;const e=()=>{if(m.current){const e=m.current.getBoundingClientRect(),t={width:e.width,height:e.height};f(e=>e.width===t.width&&e.height===t.height?e:t)}},t=setTimeout(()=>{e()},0),s=new ResizeObserver(()=>{e()});return s.observe(m.current),()=>{clearTimeout(t),s.disconnect()}},[H]),e.useEffect(()=>{if("undefined"==typeof window||!C)return;const e=w(C.x,C.y);e.x===C.x&&e.y===C.y||(j(e),setTimeout(()=>{q(e)},0),r?.(e,!1,p))},[p,w,r,C,q]),e.useEffect(()=>{C&&r&&requestAnimationFrame(()=>{r(C,!1,p)})},[]),t.jsx("div",{ref:m,className:"fixed z-[9999] select-none",style:{left:C.x+"px",top:C.y+"px",transition:M?"none":"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",cursor:M?"grabbing":"grab",willChange:M?"transform":"auto",transform:"translate3d(0, 0, 0)"},onPointerDown:_,children:d.default.isValidElement(c)?d.default.cloneElement(c,{isOpen:n,isDragging:M,isDark:a,onOpen:l,onClose:u,onDrag:h}):c?t.jsx(c,{isOpen:n,isDragging:M,isDark:a,onOpen:l,onClose:u,onDrag:h}):t.jsx(Ee,{isOpen:n,isDragging:M,isDark:a})})},(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});Ae.displayName="FloatingAIButton";const Fe=({isDark:s=!1,allowEditMessage:a=!1,children:n,onCreateSession:r,className:i="h-full w-full",coreProps:o={},inputProps:c={},mode:l="popup",livePositionUpdate:d=!0,popupOptions:u={},popupContainerClassName:h="",popupContainerStyle:g={},floatingButtonEdgeOffset:m=25,ContentComponent:p,onOpen:f,onClose:x,onDrag:y})=>{const b=e.useMemo(()=>({width:u.width??400,height:u.height??600,gap:u.gap??16,verticalPadding:u.verticalPadding??24}),[u.width,u.height,u.gap,u.verticalPadding]),w=e.useRef(null),v=e.useRef(null),[k,S]=e.useState("default"===l),[C,j]=e.useState(!1),[M,I]=e.useState(null),[N,T]=e.useState({width:64,height:64}),[R,E]=e.useState(!1),[A,F]=e.useState("right"),[H,L]=e.useState("bottom"),{sendMsg:_,isStreaming:D,abort:q}=z(),O=e.useCallback(async e=>{w.current?.sendMessage?await w.current.sendMessage(e):(await _(e),setTimeout(()=>{w.current?.scrollToBottom()},100))},[_]),P=e.useCallback(()=>{v.current&&clearTimeout(v.current),j(!0),S(!0),f?.(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{j(!1)})})},[f]),B=e.useCallback(()=>{v.current&&clearTimeout(v.current),S(!1),x?.(),j(!0),v.current=setTimeout(()=>{j(!1),v.current=null},450)},[x]),U=e.useCallback(()=>{k?B():P()},[k,P,B]),$=e.useCallback((e,t=!1,s={width:64,height:64})=>{if(E(t),I(e),T(s),!t&&"undefined"!=typeof window){const t=window.innerWidth,a=window.innerHeight,n=e.x+s.width/2;let r,i;r=t/3>n?"left":n>2*t/3?"right":"center",i=a/2>e.y+s.height/2?"top":"bottom",F(r),L(i)}},[]);e.useEffect(()=>()=>{v.current&&clearTimeout(v.current)},[]);const W=e.useMemo(()=>{if(!M||"undefined"==typeof window)return{bottom:"96px",left:"50%"};const e=window.innerHeight;let t;return t="bottom"===H?e-M.y+b.gap:e-(M.y+N.height)-b.height-b.gap,{bottom:t+"px",left:M.x+N.width/2+"px"}},[M,N,H,b.gap,b.height]),Y=e.useMemo(()=>{if("undefined"==typeof window||!M)return"translateX(-50%) translateY(0)";const e=window.innerWidth,t=window.innerHeight,s=M.x+N.width/2,a=N.width/2;let n,r;r="left"===A?s-a:"right"===A?s+a-b.width:s-b.width/2,n=0>r?-s+"px":r+b.width>e?e-s-b.width+"px":"left"===A?-a+"px":"right"===A?`calc(-100% + ${a}px)`:"-50%";let i=0;if(!R)if("bottom"===H){const e=M.y-b.gap-b.height;b.verticalPadding>e&&(i=b.verticalPadding-e)}else{const e=M.y+N.height+b.gap+b.height;e>t-b.verticalPadding&&(i=t-b.verticalPadding-e)}return`translateX(${n}) translateY(${i}px)`},[A,H,M,N,R,b.width,b.gap,b.height,b.verticalPadding]);e.useEffect(()=>{if("default"!==l&&"undefined"!=typeof window){const e=e=>{"Escape"===e.key&&k&&B()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)}},[l,k,B]);const J=e.useMemo(()=>({coreRef:w,isDark:s,allowEditMessage:a,onCreateSession:r,handleSendMessage:O,isStreaming:D,abort:q,coreProps:o,inputProps:c,children:n}),[s,a,r,O,D,q,o,c,n]);return"default"===l?t.jsx(Re,{...J,className:i}):t.jsxs(t.Fragment,"sliding"===l?{children:[k&&t.jsx("div",{className:"fixed inset-0 bg-black/50 z-[9990]",style:{backdropFilter:"blur(4px)",opacity:C?0:1,transition:"opacity 400ms cubic-bezier(0.4, 0, 0.2, 1)"},onClick:B}),t.jsx("div",{className:"fixed top-0 right-0 h-full z-[9995] shadow-2xl",style:{width:"min(600px, 100vw)",maxWidth:"100vw",backgroundColor:s?"#1a1a1a":"#ffffff",transform:k?"translateX(0)":"translateX(100%)",transition:"transform 400ms cubic-bezier(0.4, 0, 0.2, 1)"},children:t.jsx(Re,{...J,className:i,onClose:B,showCloseButton:!0})}),!k&&t.jsx(Ae,{onClick:P,isDark:s,onPositionChange:$,livePositionUpdate:d,edgeOffset:m,ContentComponent:p,onOpen:f,onClose:x,onDrag:y})]}:{children:[(k||C)&&t.jsx("div",{className:"fixed z-[9995]",style:{bottom:W.bottom,left:W.left,transition:R?"none":"bottom 200ms cubic-bezier(0.4, 0, 0.2, 1), left 200ms cubic-bezier(0.4, 0, 0.2, 1)",willChange:R?"bottom, left":"auto",pointerEvents:k?"auto":"none"},children:t.jsx("div",{className:("rounded-2xl shadow-2xl overflow-hidden "+h).trim(),style:{width:`min(${b.width}px, calc(100vw - 48px))`,height:`min(${b.height}px, calc(100vh - 160px))`,backgroundColor:s?"#1a1a1a":"#ffffff",transform:C?Y+" translateY(30px) rotateX(15deg)":Y+" rotateX(0deg)",transformOrigin:"bottom center",transformStyle:"preserve-3d",opacity:C?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",...g},children:t.jsx(Re,{...J,className:i,onClose:B,showCloseButton:!0})})}),t.jsx(Ae,{onClick:U,isDark:s,isOpen:k,onPositionChange:$,livePositionUpdate:d,edgeOffset:m,ContentComponent:p,onOpen:f,onClose:x,onDrag:y})]})};var He=e.memo(Fe);const ze={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}},Le=e.forwardRef(({onSendMessage:s,miniMode:a=!1,isStreaming:n,abort:r,todos:i,variant:o="default",placeholder:c="Type a message...",collapsed:l=!1,onExpand:d,position:u="bottom-center",compact:h},g)=>{const[m,p]=e.useState(""),[f,x]=e.useState(!1),y=e.useRef(null),{attachedFiles:b,fileInputRef:w,onFileSelect:v,onPaste:k,removeFile:S,clearFiles:C}=Se();e.useEffect(()=>{!l&&y.current&&(y.current.style.height="auto",y.current.style.height=Math.min(y.current.scrollHeight,150)+"px")},[m,l]),e.useImperativeHandle(g,()=>({focus:()=>{y.current?.focus()}}),[]);const j=e=>{e.preventDefault(),(m.trim()||b.length>0)&&(s({message:m,attachedFiles:b}),p(""),C(),!l&&y.current&&(y.current.style.height="auto"))},M=h?l?ze.collapsedCompact:ze.expandedCompact:l?ze.collapsed:ze.expanded;return t.jsxs("div",{className:"react-ai-agent-input-morph",style:{width:M.width,transition:"width 0.4s cubic-bezier(0.4, 0, 0.2, 1)"},"data-theme":"dark",children:[n&&!l&&t.jsx("div",{className:"absolute inset-0 pointer-events-none",style:{height:M.height,minHeight:M.minHeight||M.height,borderRadius:M.borderRadius,zIndex:1,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s, border-radius "+(l?"0.15s cubic-bezier(0.4, 0, 0.2, 1) 0.3s":"0.15s cubic-bezier(0.4, 0, 0.2, 1)")},children:t.jsx(ve,{})}),t.jsxs("div",{className:"react-ai-agent-input-wrapper relative",style:{height:M.height,minHeight:M.minHeight||M.height,zIndex:2,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s",overflow:"hidden"},children:[t.jsx("div",{className:"react-ai-agent-input-backdrop backdrop-blur-[20px] w-full h-full z-0 absolute bg-theme-overlay",style:{borderRadius:M.borderRadius,transition:l?"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)"}}),t.jsxs("div",{className:"relative z-10 h-full "+M.padding,style:{transition:"padding 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s"},children:[M.showTopContent&&t.jsxs("div",{style:{opacity:l?0:1,height:l?0:"auto",overflow:"hidden",pointerEvents:l?"none":"auto",transition:l?"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:[t.jsx(pe,{todos:i}),t.jsx(Ce,{}),t.jsx(ye,{attachedFiles:b,removeFile:S})]}),t.jsxs("div",{className:"flex items-center w-full "+(M.compact||l?M.gap:""),style:{position:M.compact||l?"relative":"static"},children:[t.jsx("input",{ref:w,type:"file",multiple:!0,accept:ke,onChange:v,className:"react-ai-agent-file-input hidden"}),M.compact&&M.showAttach&&t.jsx("div",{className:"flex-shrink-0",style:{opacity:l?0:1,width:l?0:"auto",overflow:"hidden",pointerEvents:l?"none":"auto",transition:l?"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:t.jsx("button",{type:"button",onClick:()=>w.current?.click(),className:(M.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:B("attach",M.compact?20:18,"currentColor")})}),t.jsx("div",{className:M.compact||l?"flex-1":"relative pb-[50px] w-full",style:{transition:"padding 0.3s ease-out 0.15s",marginTop:l&&!M.compact?"2px":void 0},children:t.jsx("textarea",{autoSave:"off",autoFocus:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false","data-form-type":"other",ref:y,value:m,onChange:e=>p(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),j(e))},onPaste:k,onFocus:()=>{x(!0),l&&d&&d()},onBlur:()=>{x(!1)},placeholder:c,className:"text-[14px] text-theme-primary resize-none outline-none bg-transparent "+(M.compact||l?"w-full pr-0 pl-3":"w-full min-h-[40px] max-h-[150px] pr-12"),style:{overflow:"auto",height:M.compact||l?"30px":void 0,maxHeight:M.compact||l?"30px":void 0,paddingTop:M.compact||l?"7px":void 0,paddingBottom:M.compact||l?"3px":void 0,lineHeight:M.compact||l?"16px":void 0,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s"},rows:1})}),t.jsxs("div",{className:"flex items-center "+(M.compact||l?"flex-shrink-0":"justify-between"),style:{position:M.compact||l?"static":"absolute",bottom:M.compact||l?"auto":"15px",left:M.compact||l?"auto":"20px",right:M.compact||l?"auto":"20px",width:M.compact||l?"auto":"calc(100% - 40px)"},children:[!M.compact&&t.jsx("div",{className:"react-ai-agent-input-actions-left flex items-center",style:{opacity:l||!M.showAttach?0:1,width:l||!M.showAttach?0:"auto",overflow:"hidden",pointerEvents:l||!M.showAttach?"none":"auto",transition:l?"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:t.jsxs("button",{type:"button",onClick:()=>w.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:[B("attach",18,"currentColor"),t.jsx("span",{className:"react-ai-agent-attach-label text-[14px] ml-2 font-[300]",children:"Attach"})]})}),t.jsxs("div",{className:"react-ai-agent-input-actions-right flex items-center",children:[t.jsx("div",{style:{opacity:l||!M.showAgent?0:1,width:l||!M.showAgent?0:"auto",overflow:"hidden",transition:l?"opacity 0.12s ease-out, width 0.12s ease-out":"opacity 0.3s ease-out 0.45s, width 0.3s ease-out 0.45s"},children:M.showAgent&&t.jsxs("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:[B("brain",18,"currentColor"),t.jsx("span",{className:"react-ai-agent-agent-label text-[12px] mx-2 text-theme-quaternary font-[300] -mt-[2px]",children:"Agent"}),B("arrowDown",16,"currentColor",{transform:"rotate(180deg)"})]})}),t.jsx("button",{type:"button",onClick:e=>{n?r():j(e)},className:"react-ai-agent-send-button flex justify-center items-center cursor-pointer bg-inverse text-inverse rounded-full hover:scale-110",disabled:!m.trim()&&!n,style:{width:M.sendButtonSize+"px",height:M.sendButtonSize+"px",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s, transform 0.2s ease-out"},children:B(n?"square":"send",n?15:l?18:20,"currentColor")})]})]})]})]})]})]})});Le.displayName="ChatInput";var _e=e.memo(Le);const De=({allowEditMessage:s=!1,children:a,placeholder:n="Ask me anything...",position:r="bottom-center",isDark:i,compact:o,coreProps:c={},inputProps:l={},onExpand:d,onClose:u,bottomBlur:h})=>{const[g,m]=e.useState(!1),[p,f]=e.useState(!1),[x,y]=e.useState(!1),[b,w]=e.useState(!1),v=e.useRef(null),k=e.useRef(null),S=e.useRef([]),[C,j]=e.useState(i),{isStreaming:M,abort:I}=z(),N=e.useCallback(()=>{S.current.forEach(e=>clearTimeout(e)),S.current=[]},[]),T=e.useCallback(async e=>{v.current?.sendMessage?await v.current.sendMessage(e):setTimeout(()=>{v.current?.scrollToBottom()},100)},[]),R=e.useCallback(()=>{N(),f(!1),y(!1),m(!0),w(!1),d?.(),j(!0);const e=setTimeout(()=>{w(!0)},350);S.current.push(e);const t=setTimeout(()=>{k.current?.focus()},400);S.current.push(t)},[N]),E=e.useCallback(()=>{N(),f(!0),m(!1),setTimeout(()=>{u?.(),j(i)},500);const e=setTimeout(()=>{y(!0)},250);S.current.push(e);const t=setTimeout(()=>{w(!1),f(!1),y(!1)},500);S.current.push(t)},[N]);e.useEffect(()=>{const e=e=>{"Escape"===e.key&&g&&E()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[g,E]),e.useEffect(()=>()=>{N()},[N]);const A=g||p;return t.jsxs("div",{className:"container",children:[A&&t.jsx("div",{className:"fixed inset-0 bg-black/80 z-40 transition-opacity duration-300 ease-in-out "+(x?"opacity-0":"opacity-100"),style:{backdropFilter:"blur(20px)"},onClick:E}),A&&t.jsx("div",{className:"fixed inset-0 z-45 flex items-center justify-center p-8 react-ai-agent",style:{pointerEvents:"none"},"data-theme":"dark",children:t.jsxs("div",{className:"relative w-full max-w-3xl rounded-3xl floating-panel",style:{height:"100vh",pointerEvents:"auto"},children:[t.jsx("div",{className:"mt-2 absolute",children:t.jsx(Te,{isDark:!0})}),b&&t.jsx("div",{className:"absolute inset-0 px-4 py-4 rounded-3xl",style:{opacity:p?0:1,transition:"opacity 0.25s ease-out"},children:t.jsx(me,{ref:v,isDark:i,allowEditMessage:s,className:"h-full w-full",...c})}),a]})}),A&&h&&t.jsxs("div",{className:"shader-blur absolute bottom-0 left-0 w-full",style:{height:"150px",transform:"scaleY(-1)",zIndex:99},children:[t.jsx("div",{}),t.jsx("div",{}),t.jsx("div",{}),t.jsx("div",{}),t.jsx("div",{}),t.jsx("div",{})]}),t.jsx("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":C?"dark":"light",children:t.jsx(_e,{ref:k,collapsed:!g,onExpand:R,onSendMessage:T,isStreaming:M,abort:I,variant:g?"pill":"collapsed",placeholder:n,position:r,compact:o,...l})})]})};var qe=e.memo(De);function Oe(e,t){return JSON.stringify({event:e,data:t})}function Pe(e,t,s=!0){return Oe("ai_response",{messageId:e,content:t,isLive:s})}function Be(){return Oe("ai_response_end",{status:"end"})}exports.BaseApiHandler=h,exports.ChatCore=me,exports.ChatHeader=Te,exports.ChatInput=_e,exports.ChatInstanceContext=F,exports.ChatLoadingMock=Y,exports.ChatProvider=q,exports.DefaultApiHandler=g,exports.DefaultPanel=He,exports.FloatingPanel=qe,exports.ForwardingManager=E,exports.LoadingResponse=ne,exports.MessageItem=ae,exports.MessageManager=b,exports.ModeToggle=({modes:e=[],activeMode:s,onModeChange:a,isDark:n=!1})=>e&&e.length>1?t.jsx("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=>t.jsx("button",{onClick:()=>a(e.id),className:`react-ai-agent-mode-button ${s===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 ${s===e.id?"bg-background text-theme-primary":"text-theme-subtle hover:text-theme-tertiary hover:bg-theme-subtle"}\n `,children:t.jsxs("div",{className:"react-ai-agent-mode-button-content flex items-center gap-1.5",children:[t.jsx("span",{className:"react-ai-agent-mode-button-icon",children:e.icon}),t.jsx("span",{className:"react-ai-agent-mode-button-label",children:e.label})]})},e.id))}):null,exports.SessionManager=class{constructor(e){this.tokenManager=e||new y,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()}},exports.ShimmerText=te,exports.StartChat=$,exports.StatusBlock=se,exports.StatusHandlerRegistry=v,exports.StreamService=x,exports.TokenManager=y,exports.WebSocketService=m,exports.adaptHistoryMessages=function(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()}):[]},exports.adaptOpenAIStream=function(e,t){try{if(e.startsWith("data: ")){const s=e.slice(6);if("[DONE]"===s)return Be();const a=JSON.parse(s),n=a.choices[0]?.delta?.content;if(n)return Pe(t,n,!0)}}catch(s){}return null},exports.createAIResponse=Pe,exports.createEndEvent=Be,exports.createErrorEvent=function(e,t=""){return Oe("stream_error",{errorType:"error",error:e,message:t})},exports.createSSEEvent=Oe,exports.createStatusUpdate=function(e,t,s,a=null){return Oe("status_update",{messageId:e,action:t,status:s,data:a})},exports.createThinkingEvent=function(e,t,s=!0){return Oe("ai_thinking",{messageId:e,content:t,isLive:s})},exports.createToolCallEvent=function(e,t,s){return Oe("tool_call",{messageId:e,toolName:t,args:s})},exports.getGlobalForwardingManager=A,exports.getGlobalStatusRegistry=S,exports.parseSSEChunk=function(e){try{const t=e.startsWith("data:")?e.slice(5).trim():e.trim();return t?JSON.parse(t):null}catch(t){return null}},exports.resetGlobalForwardingManager=function(){R=null},exports.setGlobalForwardingManager=function(e){R=e},exports.useChatContext=z,exports.useForwarding=function(t,s,a={}){const n=A(),r=e.useRef(new Map),i=!("string"!=typeof t||s||a&&0!==Object.keys(a).length),o=i?t:a.instanceId||null,c=e.useRef(s),l=e.useRef(a);e.useEffect(()=>{c.current=s,l.current=a}),e.useEffect(()=>{if(i)return;const e=[];if("object"!=typeof t||s){if("string"==typeof t&&s){const s=n.register(t,(...e)=>c.current(...e),{mode:l.current.mode||"dual",animated:!1!==l.current.animated,subscriptionMode:l.current.subscriptionMode||"delta",instanceId:l.current.instanceId||o});e.push(s)}}else Object.entries(t).forEach(([t,s])=>{const a=n.register(t,(...e)=>s.handler(...e),{mode:s.mode||"dual",animated:!1!==s.animated,subscriptionMode:s.subscriptionMode||"delta",instanceId:s.instanceId||o});e.push(a)});return()=>{e.forEach(e=>e())}},[t,n,o]);const d=e.useCallback((e,t,s={})=>{const a={...s,instanceId:s.instanceId||o},i=n.register(e,t,a);return r.current.set(e,i),i},[n,o]),u=e.useCallback(e=>{const t=r.current.get(e);t&&(t(),r.current.delete(e))},[]),h=e.useCallback(()=>n.getActiveSessions(),[n]),g=e.useCallback(e=>n.handlers[e],[n]),m=e.useCallback(()=>Object.entries(n.handlers).map(([e,t])=>({action:e,...t})),[n]);return{register:d,unregister:u,getActiveSessions:h,getHandler:g,getAllHandlers:m}},exports.useStatusSubscription=function(t,s,a={}){const n=e.useContext(F),r=void 0!==a.instanceId?a.instanceId:n,i=r?{instanceId:r}:{},o=S(),c=e.useRef(s);e.useEffect(()=>{c.current=s},[s]),e.useEffect(()=>{const e=[];if("object"==typeof t&&null!==t)Object.entries(t).forEach(([t,s])=>{if("*"===t){const t=o.registerGlobal(s,i);e.push(t)}else{const a=o.register(t,s,i);e.push(a)}});else if("string"==typeof t){const s=e=>c.current?.(e);if("*"===t){const t=o.registerGlobal(s,i);e.push(t)}else{const a=o.register(t,s,i);e.push(a)}}return()=>{e.forEach(e=>e?.())}},[t,r])};
|
|
1
|
+
"use strict";var e=require("react"),t=require("react/jsx-runtime"),s=require("react-virtuoso"),a=require("streamdown"),n=require("react-syntax-highlighter"),r=require("react-markdown"),i=require("framer-motion"),o=require("react-window"),c=require("@tanstack/react-virtual");function l(e){return e&&e.__esModule?e:{default:e}}var d=l(e),u=l(r);class h{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 g extends h{constructor(e={}){super({chatUrl:"https://api.oblien.com/ai/chat/send",historyUrl:"https://api.oblien.com/ai/chat/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 a=await fetch(this.config.chatUrl,{method:"POST",headers:s,body:JSON.stringify(e),signal:this.abortController.signal,credentials:this.config.credentials||"same-origin"});if(!a.ok){const e=await a.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 a.json()};const n=a.body.getReader(),r=new TextDecoder;let i="";for(;;){const{value:e,done:s}=await n.read();if(s){t(JSON.stringify({event:"ai_response_end",data:{status:"end"}}));break}i+=r.decode(e,{stream:!0});const a=i.split("\n");i=a.pop()||"";for(const n of a)n.trim()&&t(n)}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:a=20,sessionId:n}=e,r=`${this.config.historyUrl}?offset=${s}&limit=${a}&sessionId=${n}`,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 a={};this.tokenManager?a.Authorization="Bearer "+await this.tokenManager.getAccessToken():this.config.token&&(a.Authorization="Bearer "+this.config.token);const n=await fetch(this.config.uploadUrl,{method:"POST",headers:a,body:s,signal:t,credentials:this.config.credentials||"same-origin"});if(!n.ok)throw Error("Upload failed");return(await n.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,a)=>{try{const a=new URL(this.socketUrl+"?token="+e+"&"+t.join("&"));this.socket=new WebSocket(a),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(n){}})}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,a)=>{if(!this.isConnected())return a(Error("WebSocket is not connected"));const n=e.requestId||`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,r={...e,requestId:n};this.pendingRequests||(this.pendingRequests=new Map),this.pendingRequests.set(n,{resolve:s,reject:a,timeoutId:setTimeout(()=>{this.pendingRequests.has(n)&&(this.pendingRequests.delete(n),a(Error(`Request ${n} 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),a=s.indexOf(t);-1!==a&&s.splice(a,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 p{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,a=0,n=!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)n=!n;else if(!n)if("{"===o)0===a&&(s=i),a++;else if("}"===o&&(a--,0===a&&-1!==s)){const a=e.slice(s,i+1);try{const e=JSON.parse(a);t.push(e)}catch{}s=-1}}return t}}class f{constructor(){this.jsonStreamParser=new p}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,a=e.event||"response";s=e.type&&("started"===e.type||"finished"===e.type||"status"===e.type||e.taskId)?e:e.data||e,"ai_response"===a?a="response":"ai_response_end"===a&&(a="response_end"),t(a,s)}}catch(s){}}}class x{constructor(e){this.chatApi=e,this.streamProcessor=new f,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(a){}this.streamProcessor.processRawChunk(e,(n,r)=>{if(t&&!s)try{t(e)}catch(a){}this.emit(n,r)})})}clear(){this.eventHandlers.clear()}}class y{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 a=1e3*s.exp;return Date.now()>=a-1e3*t}setRefreshCallback(e){this.refreshCallback=e}async setAuth({accessToken:e,refreshToken:t,expiresIn:s,sessionId:a}){this.accessToken=e,this.refreshToken=t,this.sessionId=a;const n=this.decodeJWT(e);n&&n.exp?(this.tokenExpiry=1e3*n.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 b{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 a=this.messageIndex.get(e);if(void 0===a)return null;const n=this.messages[a],r={};if(Object.entries(t).forEach(([e,t])=>{r[e]="function"==typeof t?t(n[e]):t}),s.silent)return Object.assign(this.messages[a],r),this.messages[a];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[a]={...n,...r,...i&&{uniqueKey:`msg-${e}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}},this._notify(),this.messages[a]}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 w{constructor(e,t){this.messageManager=e,this.statusRegistry=t,this.activeStreamingMessages=new Map}handleUserMessage({messageId:e,text:t,attachedFiles:s=[],...a}){return this.messageManager.addMessage({messageId:e||this.messageManager._generateId("user"),sender:"user",type:"user",text:t,attachedFiles:s,...a})}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 v{constructor(){this.handlers=new Map,this.globalHandlers=[],this.streamForwarders=new Map}register(e,t,s={}){this.handlers.has(e)||this.handlers.set(e,[]);const a={handler:t,filter:s};return this.handlers.get(e).push(a),()=>{const t=this.handlers.get(e);if(t){const e=t.indexOf(a);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,a=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 n=this.handlers.get(a)||[];await Promise.all(n.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,a,e):"finished"!==t?.state&&"error"!==t?.state||this._stopStreamForwarding(s,a,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(a){}})}_startStreamForwarding(e,t,s){this.streamForwarders.forEach(a=>{a.active=!0,a.messageId=e,a.statusType=t,a.forwarder.onStart&&a.forwarder.onStart({...s,statusType:t})})}_stopStreamForwarding(e,t,s){this.streamForwarders.forEach(a=>{a.messageId===e&&(a.active=!1,a.statusType=null,a.forwarder.onEnd&&a.forwarder.onEnd({...s,statusType:t}))})}clear(){this.handlers.clear(),this.globalHandlers=[],this.streamForwarders.clear()}}const k=new v;function S(){return k}const C={current:{}},j=new Map;class I{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=C.current.mode,this.speed=C.current.speed,this.batchSize=C.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(),j.delete(this.messageId))}}function M(e){return j.get(e)}class N{constructor(){}async processChunk(e,t=null,s,a){const n=e.messageId,r=function(e){if(j.has(e))return j.get(e);const t=new I(e);return j.set(e,t),t}(e.messageId);if(r.setFullText(e.text||"",e.isLive),s){const s=e.from&&this.forwardingManager?.handlers[e.from],a=t&&this.forwardingManager?this.forwardingManager.getSession(t):null,r=s&&a&&e.from===a?.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),a=this.forwardingManager.getSubscriptionMode(t);if(s){const s=M(n);s.hasForwarder||(s.hasForwarder=!0,s.subscribe(s=>{this.forwardingManager.forwardChunk(t,s,e.isLive)},{newOnly:"delta"===a}),s.onComplete=()=>{this.forwardingManager.cleanupSession(t)})}else this.forwardingManager.forwardChunk(t,e.text||"",e.isLive)}if(o)return}this.messageHandlers.messageManager.hasMessage(n)?this.messageHandlers.messageManager.updateMessage(n,{text:t=>t+(e.text||"")},{silent:!0}):this.messageHandlers.messageManager.addMessage({messageId:n,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(n){}const a=this.messageHandlers.messageManager.hasMessage(s);"started"!==e.type&&"status"!==e.type?"finished"!==e.type?a?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}):a&&this.messageHandlers.messageManager.updateMessage(s,{statusType:e.type,isFinished:!0}):a||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 T extends N{constructor(e,t,s,a=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=a}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],a=this.queueHistory.findIndex(e=>(e.messageId||e.taskId)==(s.messageId||s.taskId)),n=this.queueHistory[a-1];n&&!n.finalized&&(n.finalized=!0,await this.notifyPreviousItem(n)),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,a=e.taskId||e.messageId;switch(this.forwardingManager&&this.useForwarding&&("started"===t&&s&&this.forwardingManager.startSession(a,s,this.instanceId)&&(this.currentForwardingSession=a),"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,j.forEach(e=>{e.stopTyping(),e.isComplete=!0,e.cleanup()}),j.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 R=null;class E{constructor(e={}){this.initialHandlers={...e},this.dynamicHandlers={},this.handlers={...e},this.activeSessions=new Map}register(e,t,s={}){const a=s.instanceId?`${e}:${s.instanceId}`:e;return this.dynamicHandlers[a]={handler:t,mode:s.mode||"dual",animated:!1!==s.animated,subscriptionMode:s.subscriptionMode||"delta",instanceId:s.instanceId},this._rebuildHandlers(),()=>{delete this.dynamicHandlers[a],this._rebuildHandlers()}}_rebuildHandlers(){this.handlers={...this.initialHandlers},Object.assign(this.handlers,this.dynamicHandlers)}startSession(e,t,s=null){const a=s?`${t}:${s}`:null,n=a&&this.handlers[a]||this.handlers[t];return!(!n||n.instanceId&&n.instanceId!==s||(this.activeSessions.get(e)||this.activeSessions.set(e,{action:t,handler:n.handler,mode:n.mode,animated:n.animated,subscriptionMode:n.subscriptionMode,instanceId:n.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 a=this.activeSessions.get(e);if(!a)return!1;const n=t||"";if(0===n.length&&s)return!0;let r,i;"full"===a.subscriptionMode?(i=n,r=n):(a.fullText+=n,r=n,i=a.fullText);try{a.handler(r,i,{action:a.action,isLive:!a.streamEnded&&s,event:"chunk",subscriptionMode:a.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 A(e){return R?e&&Object.keys(e).length>0&&(R.initialHandlers={...e},R._rebuildHandlers()):R=new E(e),R}const F=e.createContext(null),H=e.createContext({}),z=()=>e.useContext(H),L=new Map,_=(e,t,s)=>{e&&(L.has(e)||L.set(e,{}),L.get(e)[t]=s)},D=(e,t)=>{if(!e||!t)return null;const s=L.get(e);if(!s)return null;const a=t.split(".");let n=s;for(const r of a){if(!n||"object"!=typeof n)return null;n=n[r]}return n||null},q=e.forwardRef((t,s)=>{const[a,n]=e.useState(t.authConfig),[r,i]=e.useState(t.loadingHistory),[o,c]=e.useState(t.loadingComponent),[l,u]=e.useState(t.welcomeComponent),[h,m]=e.useState(t.allowThinking??!0),[p,f]=e.useState(t.headerComponent),[v,k]=e.useState(t.config),[j,I]=e.useState(t.className??"h-full w-full"),[M,N]=e.useState(t.onError),[R,E]=e.useState(t.typingAnimation??{mode:"chars",speed:400}),[z,L]=e.useState(t.forwardingHandlers??{}),[D,q]=e.useState(t.agentId),[O,P]=e.useState(t.refreshTokenCallback),[B,U]=e.useState(t.apiHandler),$=e.useRef(D||"chat-"+Math.random().toString(36).substring(2,9)).current,[W,Y]=e.useState(!1),[J,K]=e.useState(a?.sessionId),[X,G]=e.useState(!1),[Q,V]=e.useState(!1),[Z,ee]=e.useState(!1),[te,se]=e.useState(null),[ae,ne]=e.useState(null),[re,ie]=e.useState(!1),[oe,ce]=e.useState(!1),[le,de]=e.useState(null),[ue,he]=e.useState(t.initialWelcome||{title:"Welcome to AI Chat Agent",description:"A perfect agent library for your needs, for docs visit oblien.com/docs/chat-agent"}),[ge,me]=e.useState([]),pe=e.useRef(!1),fe=e.useRef(!1),xe=e.useRef(!1),ye=e.useRef(new b),be=e.useRef(null),we=e.useRef(!1),ve=e.useRef(!1),ke=e.useMemo(()=>S(),[]),Se=e.useRef(O?new y:null),Ce=e.useRef(B||new g({...v,...Se.current&&{tokenManager:Se.current},token:a?.accessToken,sessionId:a?.sessionId})),je=e.useRef(new x(Ce.current)),Ie=e.useRef(A(z)),Me=e.useRef(new w(ye.current,ke)),Ne=e.useRef(new T(Me.current,Ie.current,Object.keys(z).length>0,$)),Te=e.useCallback(()=>{const e=pe.current||fe.current;V(e),e||G(!1)},[]),Re=e.useCallback(()=>{if(we.current&&ve.current){const t=Ie.current.handlers._loading_end;if(t?.handler)try{t.handler({messageId:be.current||null,instanceId:$,timestamp:Date.now()})}catch(e){}}},[$]);e.useEffect(()=>{Ne.current.onQueueComplete=()=>{fe.current=!1,ve.current=!0,Te(),Re()}},[Te,Re]),e.useEffect(()=>{t.markdownComponents&&_($,"markdown",t.markdownComponents),t.statusComponents&&Object.keys(t.statusComponents).forEach(e=>{_($,"status."+e,t.statusComponents[e])}),o&&_($,"loading",o),p&&_($,"header",p),l&&_($,"welcome",l),_($,"welcomeData",ue)},[$,t.markdownComponents,t.statusComponents,l,ue,o,p]),e.useEffect(()=>{O&&Se.current&&Se.current.setRefreshCallback(O)},[O]);const Ee=e.useRef(!1),Ae=e.useRef(J),Fe=e.useRef(null);C.current=R;const He=e.useRef(new Set);e.useEffect(()=>{const e=ye.current.subscribe(e=>{me(e)});return()=>{e()}},[]),e.useEffect(()=>{Ae.current=J},[J]),e.useRef(!1),e.useEffect(()=>{(async()=>{if(a&&a.sessionId&&Se.current)try{await Se.current.setAuth(a)}catch(te){let t="Authentication failed. Please refresh the page.";te?.message?.includes("No refresh token")?t="Session expired. Please refresh the page to continue.":te?.message&&(t=te.message),se({type:"auth_error",message:t,error:te}),Y(!1)}})()},[!1,a]);const ze=e.useCallback(e=>{se(e.error)},[]),Le=e.useCallback(async e=>{try{if(He.current.has(J)&&!e)return void Y(!1);He.current.add(J),Y(!0);const t=J||a?.sessionId,s=await Ce.current.getHistory({sessionId:t});if(s.error)return ze(s),void Y(!1);s.history&&s.history.length>0&&ye.current.insertMessages(s.history,"end"),ce(!!s.has_more),Y(!1)}catch(t){let e="Could not load message history.";t?.message?.includes("No refresh token")?e="Session expired. Please refresh the page to continue.":t?.message?.includes("Network")?e="Network error. Please check your connection.":t?.message&&(e=t.message),se({type:"history_error",message:e,error:t}),Y(!1)}},[J,ze]),_e=e.useCallback(async()=>{xe.current=!0,pe.current=!1,fe.current=!1,V(!1),G(!1),ee(!1),we.current=!1,ve.current=!1;const e=Me.current.messageManager.getAllMessages(),t=[],s=[];for(const a of e)"thinking"!==a.type||!a.isLive&&a.finalized?"status"!==a.type||a.isFinished||s.push(a):t.push(a);t.length>0&&await Promise.all(t.map(e=>{const t=e.messageId.replace("-thinking","");return Ne.current.finishThinking({messageId:t})}));for(const a of s)Me.current.messageManager.updateMessage(a.messageId,{isFinished:!0,statusType:"finished"});Ne.current.clear(),be.current=null,Ce.current.abort(),je.current.abort(),Ae.current&&Ce.current.abortRequest&&await Ce.current.abortRequest(Ae.current),setTimeout(()=>{xe.current=!1},100)},[]),De=e.useCallback(e=>{if(xe.current)return;const t={...e,id:e?.id||Math.random().toString(36).substring(2,9),timestamp:Date.now(),instanceId:$};ne(t),M&&M(t);const s=Ie.current.handlers._error;if(s?.handler)try{s.handler(t)}catch(a){}},[M,$]),qe=e.useCallback(()=>{ne(null)},[]),Oe=e.useCallback(()=>{pe.current=!1;const e=be.current;if(e){Ne.current.endResponse(),be.current=null,we.current=!0;const s=Ie.current.handlers._response_end;if(s?.handler)try{s.handler({messageId:e,instanceId:$,timestamp:Date.now()})}catch(t){}}else we.current=!0;Te(),Re()},[Te,$,Re]),Pe=e.useCallback(()=>{Ee.current=!1,pe.current=!1,Te()},[Te]),Be=e.useCallback(e=>{const t=e?.data?.messageId||e?.messageId;if(t&&(be.current=t),!Z){ee(!0),we.current=!1,ve.current=!1;const e=Ie.current.handlers._response_start;if(e?.handler)try{e.handler({messageId:t,instanceId:$,timestamp:Date.now()})}catch(s){}}fe.current=!0,Ne.current.addToQueue(e),Te()},[Z,Te,$]);e.useEffect(()=>(je.current.on("stream_error",De),je.current.on("response",Be),je.current.on("response_end",Oe),je.current.on("disconnect",Pe),()=>{je.current.off("stream_error",De),je.current.off("response",Be),je.current.off("response_end",Oe),je.current.off("disconnect",Pe)}),[De,Be,Oe,Pe]);const Ue=async({messageId:e=Math.random().toString(36).substring(2,9),message:t="",attachedFiles:s=[],uploadId:a=null}={})=>{if(!t.trim())return;const n="user-"+e;try{Fe.current&&Fe.current?.messageId===n||Me.current.handleUserMessage({messageId:n,text:t,attachedFiles:s}),Fe.current={messageId:n,message:t,attachedFiles:s,uploadId:a},G(!0),ee(!1),we.current=!1,ve.current=!1,xe.current=!1,pe.current=!0,Te();const e=Ie.current.handlers._stream_feedback,r=e?.handler,i="raw"===e?.mode,o=await je.current.startStream({message:t,attachedFiles:s,uploadId:a,sessionId:Ae.current,context:null,allowThinking:h},r,i);o.status||(pe.current=!1,Te(),De({errorType:"connection_error",error:o.error||"Error occurred while connecting to server",message:o.message||"Failed to send message"}))}catch(r){pe.current=!1,Te(),De({errorType:"send_error",error:r.message||"Unknown error",message:"Failed to send message"})}finally{G(!1)}},$e=e.useCallback(async()=>{Fe.current&&await Ue(Fe.current)},[]),We=e.useCallback(()=>{ye.current.clear(),He.current.clear(),be.current=null,we.current=!1,ve.current=!1,pe.current=!1,fe.current=!1,se(null),ne(null),Y(!1),G(!1),V(!1),ee(!1),ce(!1)},[]),Ye=e.useCallback((e,t=!1)=>{void 0!==e.sessionId&&e.sessionId!==J&&e.sessionId!==a?.sessionId&&t&&We();const s={...a,...e};n(s),void 0!==e.sessionId&&K(e.sessionId),Ce.current&&(Ce.current.config&&(void 0!==s.accessToken&&(Ce.current.config.token=s.accessToken),void 0!==s.sessionId&&(Ce.current.config.sessionId=s.sessionId)),"function"==typeof Ce.current.updateConfig&&Ce.current.updateConfig({token:s.accessToken,sessionId:s.sessionId})),Se.current&&s.accessToken&&Se.current.setAuth(s).catch(e=>{})},[a,J]),Je=e.useCallback(e=>{c(e),e&&_($,"loading",e)},[$]),Ke=e.useCallback(e=>{f(e),e&&_($,"header",e)},[$]),Xe=e.useCallback(e=>{u(e),e&&_($,"welcome",e)},[$]),Ge=e.useCallback(e=>{he(e),e&&_($,"welcomeData",e)},[$]),Qe=e.useMemo(()=>({addMessage:e=>ye.current.addMessage(e),updateMessage:(e,t)=>ye.current.updateMessage(e,t),removeMessage:e=>ye.current.removeMessage(e),getMessage:e=>ye.current.getMessage(e),clear:()=>ye.current.clear()}),[]),Ve=e.useMemo(()=>({register:(e,t)=>ke.register(e,t,{instanceId:$}),registerGlobal:e=>ke.registerGlobal(e,{instanceId:$})}),[$,ke]),Ze={sendMsg:Ue,messages:ge,messageManager:Qe,isLoading:X,isStreaming:Q,isResponseStarted:Z,isInitialLoading:W,isLoadingMore:re,clearSessionState:We,error:te,streamError:ae,clearStreamError:qe,getHistory:Le,loadMoreMessages:async()=>{if(!re&&oe){ie(!0);try{const e=ye.current.count,t=await Ce.current.getHistory({offset:e,limit:20});if(t.error)return ze(t),void ie(!1);t.history&&t.history.length>0?(ye.current.insertMessages(t.history,"start"),ce(t.has_more)):ce(!1)}catch(e){se({type:"load_more_error",message:"Failed to load more messages",error:e})}finally{ie(!1)}}},loadHistory:Le,hasMoreMessages:oe,retryLastMessage:$e,abort:_e,sessionId:J,setSessionId:K,instanceId:$,currentSelectedFile:le,setCurrentSelectedFile:de,statusRegistry:Ve,typingAnimation:R,setAuthConfig:Ye,setLoadHistory:i,setLoadingComponent:Je,setAllowThinking:m,setHeaderComponent:Ke,setWelcomeComponent:Xe,setWelcome:Ge,setConfig:k,setClassName:I,setOnError:N,setMarkdownComponents:e=>_($,"markdown",e),registerComponent:_,setStatusComponents:e=>{Object.keys(e).forEach(t=>{_($,"status."+t,e[t])})},setTypingAnimation:E,setForwardingHandlers:L,authConfig:a,loadingHistory:r,allowThinking:h,config:v,className:j,onError:M,forwardingHandlers:z,setAgentId:q,setRefreshTokenCallback:P,setApiHandler:U};return e.useImperativeHandle(s,()=>Ze,[]),d.default.createElement("div",{className:"react-ai-agent-root "+j},d.default.createElement(H.Provider,{value:Ze},d.default.createElement(F.Provider,{value:$},t.children)))}),O={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"},P={figma:"/icons/project/Figma-logo.svg.png",githubraw:"/icons/project/github-mark-white.png"},B=(e,s,a="#000",n={},r=!1)=>{if(r)return t.jsx("img",{src:P[e]?.replace(/ /g,"%20"),alt:e,style:{width:s,height:s,objectFit:"contain",...n}});let i=O[e]?.replace(/ /g,"%20")||e?.replace(/ /g,"%20");return i=e.startsWith("http")?e:"https://cdn.oblien.com/static/png-icons/"+i,t.jsx("div",{style:{maskImage:`url('${i}')`,maskSize:"contain",maskRepeat:"no-repeat",maskPosition:"center",WebkitMaskSize:"contain",WebkitMaskRepeat:"no-repeat",WebkitMaskPosition:"center",width:s,height:s,backgroundColor:a,...n}})},U=({showLoadMore:e,enableHistory:s,hasMoreMessages:a,messagesLength:n,error:r,isInitialLoading:i,loadMoreMessages:o,isLoadingMore:c})=>e&&s&&a&&0!==n&&!r&&!i?t.jsx("div",{className:"react-chat-core-load-more flex justify-center py-4",children:t.jsx("button",{onClick:o,disabled:c,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:t.jsxs(t.Fragment,c?{children:[t.jsx("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"}),t.jsx("span",{className:"react-chat-core-load-more-text text-sm",children:"Loading..."})]}:{children:[B("refresh",18,"currentColor"),t.jsx("span",{className:"react-chat-core-load-more-text text-sm",children:"Load more messages"})]})})}):null,$=({error:e,instanceId:s})=>{const a=D(s,"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 t.jsx("div",{className:"react-ai-agent-start-chat flex flex-col items-center justify-center h-full",children:"object"!=typeof a||a?.title?t.jsxs("div",{className:"react-ai-agent-start-chat-content text-center mb-8 flex flex-col items-center justify-center gap-2",children:[e&&t.jsx("span",{className:"react-ai-agent-start-chat-error-icon",children:B("error",70,"currentColor",{marginBottom:"10px"})}),t.jsx("h2",{className:"react-ai-agent-start-chat-title text-2xl font-light text-theme-primary mb-4",children:e?"Something went wrong":a?.title}),t.jsx("p",{className:"react-ai-agent-start-chat-description text-theme-muted mb-6 max-w-md text-base leading-relaxed",children:e?n:a?.description}),e&&e.type&&t.jsx("p",{className:"react-ai-agent-start-chat-error-type text-xs text-theme-tertiary mt-2 opacity-50",children:e.type.replace("_"," ")})]}):a})},W=({error:e,isPanelOpen:s,instanceId:a})=>{const n=D(a,"welcome");return n?t.jsx(n,{error:e}):t.jsx($,{error:e,miniMode:s,instanceId:a})},Y=()=>t.jsxs("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:[t.jsxs("div",{className:"react-ai-agent-loading-mock-welcome flex items-start gap-4 mb-12",children:[t.jsx("div",{className:"react-ai-agent-loading-mock-avatar react-ai-agent-loading-mock-avatar-welcome w-10 h-10 rounded-full shimmer-skeleton"}),t.jsxs("div",{className:"react-ai-agent-loading-mock-content flex-1 space-y-3",children:[t.jsx("div",{className:"react-ai-agent-loading-mock-line react-ai-agent-loading-mock-line-1 h-4 rounded-full shimmer-skeleton w-2/3"}),t.jsx("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,s)=>t.jsxs("div",{className:"react-ai-agent-loading-mock-message-group space-y-6",children:[t.jsxs("div",{className:"react-ai-agent-loading-mock-message react-ai-agent-loading-mock-message-user flex items-start gap-4 justify-end",children:[t.jsx("div",{className:"react-ai-agent-loading-mock-message-content max-w-[70%] space-y-2",children:t.jsx("div",{className:"react-ai-agent-loading-mock-line h-3 rounded-full shimmer-skeleton w-full"})}),t.jsx("div",{className:"react-ai-agent-loading-mock-avatar react-ai-agent-loading-mock-avatar-user w-8 h-8 rounded-full shimmer-skeleton"})]}),t.jsxs("div",{className:"react-ai-agent-loading-mock-message react-ai-agent-loading-mock-message-ai flex items-start gap-4",children:[t.jsx("div",{className:"react-ai-agent-loading-mock-avatar react-ai-agent-loading-mock-avatar-ai w-8 h-8 rounded-full shimmer-skeleton"}),t.jsxs("div",{className:"react-ai-agent-loading-mock-message-content flex-1 space-y-3",children:[t.jsx("div",{className:"react-ai-agent-loading-mock-line react-ai-agent-loading-mock-line-1 h-3 rounded-full shimmer-skeleton w-4/5"}),t.jsx("div",{className:"react-ai-agent-loading-mock-line react-ai-agent-loading-mock-line-2 h-3 rounded-full shimmer-skeleton w-3/4"})]})]})]},s))]}),J=({onComplete:s,duration:a=800})=>{const[n,r]=e.useState(0),[i,o]=e.useState(!1),c=e.useRef(0);return e.useEffect(()=>{c.current=300,requestAnimationFrame(()=>{r(c.current)});const e=setTimeout(()=>{o(!0),s?.()},a);return()=>clearTimeout(e)},[a,s]),i?null:t.jsx("div",{style:{height:n+"px",transition:`height ${a}ms cubic-bezier(0.4, 0, 0.2, 1)`,pointerEvents:"none"}})},K=({message:e,allowEdit:s=!0})=>{const a=[];return s&&a.push({icon:"edit",text:"Edit",onClick:()=>{}}),e.snapshot&&a.push({icon:"refresh",text:"Restore checkpoint",onClick:()=>{}}),t.jsxs("div",{className:"react-ai-agent-user-message flex flex-col mb-2",children:[t.jsx("div",{className:"react-ai-agent-user-message-bubble-wrapper flex justify-end mb-2",children:t.jsx("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:t.jsx("p",{className:"react-ai-agent-user-message-text text-[16px] leading-[22px] tracking-wide",children:e.text})})}),t.jsx("div",{className:"react-ai-agent-user-message-actions flex justify-end gap-4",children:a.map((e,s)=>t.jsxs("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:[t.jsx("span",{className:"react-ai-agent-user-message-action-icon",children:B(e.icon,16,"currentColor")}),t.jsx("span",{className:"react-ai-agent-user-message-action-label text-[12px] font-[300] text-theme-primary",children:e.text})]},s))})]})},X=({message:s,instanceId:n})=>{const r=D(n,"markdown"),[i,o]=e.useState("");return e.useEffect(()=>{const e=M(s.messageId);if(e)return e.subscribe(e=>{o(e)});o(s.text||"")},[s.messageId,s.text]),t.jsx("div",{className:"react-ai-agent-ai-response mb-4 mx-auto",children:t.jsx("div",{className:"react-ai-agent-ai-content text-theme-primary prose prose-invert max-w-none",dir:"auto",style:{wordBreak:"break-word"},children:t.jsx(a.Streamdown,{parseIncompleteMarkdown:!0,mode:"streaming",components:r,children:i})})})};var G=e.memo(X),Q=e.memo(({text:e,instanceId:s})=>{const n=D(s,"markdown"),r=e||"";return t.jsx("div",{className:"react-ai-agent-ai-response mb-4 mx-auto",style:{minHeight:"20px"},children:t.jsx("div",{className:"react-ai-agent-ai-content text-theme-primary prose prose-invert max-w-none",dir:"auto",style:{wordBreak:"break-word",minHeight:"20px"},children:r?t.jsx(a.Streamdown,{parseIncompleteMarkdown:!0,mode:"static",components:n,children:r}):t.jsx("span",{style:{opacity:.5},children:"..."})})})}),V=e.memo(({message:e,animationConfig:s,instanceId:a})=>e.isLive&&!e.finalized?t.jsx(G,{message:e,animationConfig:s,instanceId:a}):t.jsx(Q,{text:e.text,instanceId:a}));const Z={'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"}},ee=e.memo(({message:s,isInCurrentSession:a})=>{const r=e.useRef(null),i=e.useRef(s.finalized),o=e.useRef(null),[c,l]=e.useState(!s.finalized),[d,h]=e.useState(!1),[g,m]=e.useState(""),p=s.isLive||!s.finalized,f=s.finalized||!a,x=s.duration||0,y=e.useMemo(()=>s.text||"",[s.text]);e.useEffect(()=>{requestAnimationFrame(()=>{h(!0)})},[]),e.useEffect(()=>{if(!p||!c)return void m(y);const e=g.length,t=y.length;if(e>=t)return;const s=Math.min(5,t-e),a=setTimeout(()=>{m(y.slice(0,e+s))},20);return()=>clearTimeout(a)},[y,g,p,c]),e.useEffect(()=>{if(r.current&&c&&p)return o.current&&cancelAnimationFrame(o.current),o.current=requestAnimationFrame(()=>{r.current&&(r.current.scrollTop=r.current.scrollHeight)}),()=>{o.current&&cancelAnimationFrame(o.current)}},[g,c,p]),e.useEffect(()=>{if(f&&!i.current&&c){const e=setTimeout(()=>{l(!1)},800);return()=>clearTimeout(e)}},[f,c]);const b=e.useCallback(()=>{l(e=>!e)},[]),w=e.useMemo(()=>({code({node:e,inline:s,className:a,children:r,...i}){const o=/language-(\w+)/.exec(a||""),c=(r+"").replace(/\n$/,""),l=!s&&c.includes("\n");return s||!l?t.jsx("code",{className:"react-ai-agent-thinking-code-inline px-1 py-0.5 bg-secondary rounded text-xs font-mono whitespace-pre-wrap",...i,children:r}):t.jsx("div",{className:"react-ai-agent-thinking-code-block rounded-[15px] overflow-hidden my-3",children:t.jsx(n.Prism,{language:o?.[1]||"javascript",style:Z,children:c})})},p:({children:e})=>t.jsx("p",{className:"react-ai-agent-thinking-paragraph mb-2 leading-5 text-sm",children:e}),ul:({children:e})=>t.jsx("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})=>t.jsx("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})=>t.jsx("li",{className:"react-ai-agent-thinking-list-item mb-1 text-sm",children:e}),h1:({children:e})=>t.jsx("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})=>t.jsx("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})=>t.jsx("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})=>t.jsx("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 t.jsxs("div",{className:"react-ai-agent-thinking-message mb-4 mx-auto opacity-50 transition-all duration-300 ease-out",style:{opacity:d?.5:0,transform:d?"translateY(0)":"translateY(-10px)"},children:[f?t.jsxs("button",{onClick:b,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:[t.jsx("span",{className:"react-ai-agent-thinking-toggle-icon transition-transform duration-300",children:B(c?"brain-10-1663078315.png":"brain-11-1663755045.png",20,"currentColor")}),t.jsxs("span",{className:"react-ai-agent-thinking-toggle-text",children:["Thought for ",x," second",1!==x?"s":""]})]}):t.jsxs("div",{className:"react-ai-agent-thinking-header text-theme-tertiary text-sm mb-2 flex items-center gap-2",children:[t.jsx("span",{className:"react-ai-agent-thinking-icon animate-pulse",children:B("brain-11-1663755045.png",20,"currentColor")}),t.jsx("span",{className:"react-ai-agent-thinking-label",children:"Thinking..."})]}),t.jsx("div",{style:{maxHeight:c?"150px":"0px",opacity:c?1:0,overflow:"hidden",transition:"max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.2s ease-out"},children:g&&t.jsx("div",{ref:r,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:t.jsx("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:p?.8:1,transition:"opacity 0.15s ease"},children:t.jsx(u.default,{components:w,children:g})})})})]})},(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);ee.displayName="ThinkingMessage";const te=({text:e,style:s,fontSize:a="1em",paddingRight:n="140px",backgroundSize:r="125px",isDark:i=!1})=>{let o=1;"string"==typeof a?o=parseFloat(a)||3:"number"==typeof a&&(o=a);let c=r;"125px"===r&&"3em"!==a&&(c=o/3*125+"px");const l={fontSize:a,paddingRight:n,WebkitBackgroundSize:c+" 100%",MozBackgroundSize:c+" 100%",backgroundSize:c+" 100%",...s};return t.jsx("div",{className:"react-ai-agent-shimmer-text shimmer "+(i?"dark":"light"),style:l,children:e})},se=({message:s,title:a,isProcessing:n,isFinished:r,icon:i,iconComponent:o,isFlat:c=!0,onClick:l,isDark:d=!1,unmountOnExit:u,action:h,data:g,className:m,style:p,metadata:f})=>{const x=h||s?.action,y=g||s?.data,b=void 0!==r?r:s?.isFinished,w=void 0!==n?n:!b,v=f||s?.metadata,k=a||v?.name||s?.title,S=o||s?.iconComponent,C=void 0!==c?c:void 0===s?.isFlat||s.isFlat,j=void 0!==u?u:s?.unmountOnExit,I=l,M=v?.icon||i,N=e.useMemo(()=>k?w?`Processing ${k}...`:"Finished "+k:x?(({data:e,action:t,isFinished:s})=>{if(!t||"string"!=typeof t)return"Processing...";try{const a=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?a:`${a}${e?.tool?" "+e?.tool:""}...`}catch(a){return t}})({data:y,action:x,isFinished:b}):"Processing...",[k,x,b,y]);return t.jsx("div",C?{className:"mx-auto mb-1 "+m,style:{cursor:I?"pointer":"default",...p},onClick:I,children:t.jsxs("div",{className:`flex items-center gap-3 px-0 rounded-[12px] text-${d?"white":"black"} relative overflow-auto`,children:[j?t.jsx("div",{className:`animate-spin h-[16px] w-[16px] mr-[4px] absolute border-[1.5px] border-${d?"white":"black"} rounded-full border-t-transparent opacity-50`}):S?S():B(M||"check circle-3-1660219236.png",20,d?"rgba(255,255,255,0.25)":"rgba(0,0,0,0.25)",{position:"absolute"}),w?t.jsx(te,{isDark:d,text:N,style:{fontSize:"14px",marginLeft:"30px"}}):t.jsx("span",{style:{color:d?"rgba(255,255,255,0.25)":"rgba(0,0,0,0.25)"},className:"text-[14px] ml-[30px] "+(S?"!ml-0":""),children:N})]})}:{className:"mb-[10px] mx-auto "+m,style:{cursor:I?"pointer":"default",...p},onClick:I,children:t.jsxs("div",{className:`flex items-center p-3 rounded-[12px] text-${d?"white":"black"} relative overflow-hidden`,style:{backgroundColor:d?"rgba(255,255,255,0.02)":"rgba(0,0,0,0.02)"},children:[w?t.jsx("div",{className:`animate-spin h-[16px] w-[16px] mr-[4px] absolute border-[1.5px] border-${d?"white":"black"} rounded-full border-t-transparent opacity-50`}):S?S():B(icon||"check circle-3-1660219236.png",20,d?"rgba(255,255,255,0.8)":"rgba(0,0,0,0.8)",{position:"absolute"}),t.jsx("div",{className:"flex-1",children:w?t.jsx(te,{isDark:d,text:N,style:{marginLeft:"28px",marginTop:"-2px",color:d?"rgba(255,255,255,0.2)":"rgba(0,0,0,0.2)"}}):t.jsx("span",{className:`text-[14px] text-${d?"white":"black"}/50 ml-[30px]`,children:N})})]})})};var ae=e.memo(({item:e,removeMessage:s,allowEditMessage:a,animationConfig:n,isInCurrentSession:r,instanceId:i})=>{if("user"===e.sender)return t.jsx("div",{className:"react-ai-agent-message-item react-ai-agent-message-user",children:t.jsx(K,{message:e,allowEdit:a})});if("status"===e.type&&e.action){const s=D(i,"status."+e.action);return t.jsx("div",{className:"react-ai-agent-message-item react-ai-agent-message-status",children:t.jsx(s||se,{message:e})})}return t.jsx("div","thinking"===e.type?{className:"react-ai-agent-message-item react-ai-agent-message-thinking",children:t.jsx(ee,{message:e,removeMessage:s,isInCurrentSession:r})}:{className:"react-ai-agent-message-item react-ai-agent-message-ai",children:t.jsx(V,{message:e,animationConfig:n,isInCurrentSession:r,instanceId:i})})});const ne=({type:e})=>{const s=["w-1.5 h-1.5","w-2.5 h-2.5","w-1.5 h-1.5"],a="text"===e?["L","O","A","D","I","N","G"]:Array.from({length:3}).fill(""),n=.6+.1*(a.length-1);return t.jsx("div",{className:"react-ai-agent-loading-response flex",children:t.jsx("div",{className:"react-ai-agent-loading-content flex justify-center items-center "+("text"===e?"text-7xl font-extrabold font-[Montserrat]":"gap-1.5"),children:a.map((a,r)=>t.jsx(i.motion.span,{className:`react-ai-agent-loading-item react-ai-agent-loading-item-${e} inline-block ${"text"===e?"mx-[-0.05em]":s[r]+" rounded-full bg-inverse"}`,animate:{scale:[.75,1.5,.75],opacity:[.75,1,.75],filter:["blur(4px)","blur(0px)","blur(4px)"]},transition:{repeat:1/0,duration:.6,ease:"easeInOut",repeatDelay:n-.6,delay:.1*r},children:"text"===e?a:""},r))})})},re=({messages:t,isLoading:s,isResponseStarted:a,showLoadingIndicator:n,showSpacer:r=!1,spacerKey:i=0,onSpacerComplete:o})=>e.useMemo(()=>{const e=[...t];return r&&e.push({type:"viewport-spacer",messageId:"viewport-spacer-"+i,onComplete:o,isResponseStarted:a}),n&&s&&!a&&e.push({type:"loading-indicator",messageId:"loading-indicator"}),e},[t,n,s,a,r,i,o]),ie=t=>e.useMemo(()=>{for(let e=t.length-1;e>=0;e--)if("user"===t[e].sender)return e;return-1},[t]),oe=({item:e,index:s,lastUserIndex:a,removeMessage:n,allowEditMessage:r,animationConfig:i,isLastItem:o=!1,isFirstItem:c=!1,instanceId:l})=>{if(!e)return null;if("viewport-spacer"===e.type)return t.jsx(J,{onComplete:e.onComplete,isResponseStarted:e.isResponseStarted});if("loading-indicator"===e.type)return t.jsx(ne,{});if("empty-message"===e.type)return t.jsx("div",{style:{paddingTop:"100px"}});const d=t.jsx(ae,{item:e,removeMessage:n,allowEditMessage:r,animationConfig:i,isInCurrentSession:s>a,instanceId:l});return o?t.jsx("div",{style:{paddingBottom:"200px"},children:d}):c?t.jsx("div",{style:{paddingTop:"100px"},children:d}):d},ce=({messages:a,removeMessage:n,allowEditMessage:r,animationConfig:i,height:o,width:c,shouldAutoScrollRef:l,isLoading:d,isResponseStarted:u,showLoadingIndicator:h,showSpacer:g,spacerKey:m,onSpacerComplete:p,instanceId:f})=>{const x=e.useRef(!0),y=re({messages:a,isLoading:d,isResponseStarted:u,showLoadingIndicator:h,showSpacer:g,spacerKey:m,onSpacerComplete:p}),b=ie(a),w=e.useCallback(e=>{x.current=e,l&&(l.current=e)},[l]);e.useCallback(()=>"smooth",[]);const v=e.useCallback(e=>oe({item:y[e],index:e,lastUserIndex:b,removeMessage:n,allowEditMessage:r,instanceId:f,isLastItem:e===y.length-1,animationConfig:i}),[y,b,n,r,i]);return t.jsx(s.Virtuoso,{style:{height:o,width:c},data:y,totalCount:y.length,itemContent:v,initialTopMostItemIndex:y.length-1,atBottomStateChange:w,alignToBottom:!0})},le=({dynamicHeight:s,messages:a,removeMessage:n,allowEditMessage:r,animationConfig:i,height:c,width:l,overscan:d,listRef:u,isLoading:h,isResponseStarted:g,showLoadingIndicator:m,showSpacer:p,spacerKey:f,onSpacerComplete:x,instanceId:y})=>{const b=re({messages:a,isLoading:h,isResponseStarted:g,showLoadingIndicator:m,showSpacer:p,spacerKey:f,onSpacerComplete:x}),w=ie(a),v=e.useRef(new Map),k=e.useMemo(()=>({itemsData:b,removeMessage:n,allowEditMessage:r,animationConfig:i,dynamicHeight:s,lastUserIndex:w,heightCacheRef:v}),[b,n,r,i,s,w]),S=e.useCallback(({index:e,style:s,ariaAttributes:a,...n})=>{const{itemsData:r,removeMessage:i,allowEditMessage:o,animationConfig:c,dynamicHeight:l,lastUserIndex:d,heightCacheRef:u}=n;return t.jsx("div",{style:s,ref:t=>{if(t){const s=r[e],a=s?.uniqueKey||s?.messageId||e;u.current.has(a)||requestAnimationFrame(()=>{const s=t.getBoundingClientRect().height;s!==l.getRowHeight(e)&&(l.setRowHeight(e,s),u.current.set(a,s))})}},...a,children:oe({item:r[e],index:e,lastUserIndex:d,removeMessage:i,isLastItem:e===r.length-1,allowEditMessage:o,animationConfig:c,instanceId:y})})},[]);return t.jsx("div",{style:{height:c,width:l,overflow:"hidden"},children:t.jsx(o.List,{listRef:u,rowComponent:S,rowCount:b.length,rowHeight:s,rowProps:k,overscanCount:d})})},de=({itemsData:t,scrollToBottom:s,shouldAutoScrollRef:a,isStreaming:n})=>{const r=e.useRef(0),i=e.useRef(!1);e.useEffect(()=>{!i.current&&t.length>0&&(i.current=!0,requestAnimationFrame(()=>{requestAnimationFrame(()=>{s(!1)})}))},[]),e.useEffect(()=>{t.length>r.current&&(r.current=t.length,!1!==a?.current&&s(!0))},[t.length,s,a]),e.useEffect(()=>{if(!n)return;const e=setInterval(()=>{!1!==a?.current&&s(!1)},100);return()=>clearInterval(e)},[n,s,a])},ue=({messages:s,removeMessage:a,allowEditMessage:n,animationConfig:r,height:i,width:o,isStreaming:l,shouldAutoScrollRef:d,instanceId:u})=>{const h=e.useRef(null),g=[{type:"empty-message",messageId:"empty-message"},...s],m=ie(s),p=e.useCallback(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 a=t.text||t.content||"",n=a.length;if(0===n)return s;s+=24*Math.ceil(n/90),"thinking"===t.type?s+=40:"status"===t.type&&(s+=30);const r=(a.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=c.useVirtualizer({count:g.length,getScrollElement:()=>h.current,estimateSize:p,overscan:10}),{handleScroll:x}=(t=>{const s=e.useRef(!1),a=e.useRef(null),n=e.useCallback(e=>{a.current&&clearTimeout(a.current),s.current=!0,a.current=setTimeout(()=>{s.current=!1},150),e&&t&&(t.current=50>Math.abs(e.scrollHeight-e.scrollTop-e.clientHeight))},[t]);return{isUserScrollingRef:s,handleScroll:n}})(d),y=e.useCallback((e=!0)=>{const t=h.current;t&&t.scrollTo({top:t.scrollHeight,behavior:e?"smooth":"auto"})},[]);de({itemsData:g,scrollToBottom:y,shouldAutoScrollRef:d,isStreaming:l});const b=f.getVirtualItems();return t.jsx("div",{ref:h,onScroll:()=>x(h.current),className:"tanstack-virtual-container",style:{height:i,width:o,overflowY:"auto",contain:"strict"},children:t.jsx("div",{style:{height:f.getTotalSize()+"px",width:"100%",position:"relative"},children:b.map(e=>t.jsx("div",{"data-index":e.index,ref:f.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${e.start}px)`},children:oe({item:g[e.index],index:e.index,lastUserIndex:m,removeMessage:a,allowEditMessage:n,animationConfig:r,isLastItem:e.index===g.length-1,instanceId:u,isFirstItem:0===e.index})},e.key))})})},he=({messages:e,removeMessage:s,allowEditMessage:a,animationConfig:n,scrollToBottom:r,shouldAutoScrollRef:i,isStreaming:o,scrollContainerRef:c,height:l,width:d,isLoading:u,isResponseStarted:h,showLoadingIndicator:g,showSpacer:m,spacerKey:p,onSpacerComplete:f,instanceId:x})=>{const y=re({messages:e,isLoading:u,isResponseStarted:h,showLoadingIndicator:g,showSpacer:m,spacerKey:p,onSpacerComplete:f}),b=ie(e);return de({itemsData:y,scrollToBottom:e=>r(),shouldAutoScrollRef:i,isStreaming:o}),t.jsx("div",{ref:c,className:"react-chat-core-simple-container overflow-y-auto scrollbar-hide",style:{height:l,width:d,overflowY:"auto"},children:y.map((e,r)=>e?t.jsx("div",{children:oe({item:e,index:r,lastUserIndex:b,removeMessage:s,allowEditMessage:a,animationConfig:n,instanceId:x})},e.uniqueKey||e.messageId||r):null)})},ge=e.forwardRef(({virtualization:s="tanstack",estimateSize:a=150,overscan:n=10,isDark:r=!1,className:i="",containerStyle:c={},useGradientMask:l=!0,gradientMaskStyle:d="linear-gradient(to bottom, transparent 6.5%, black 18%)",allowEditMessage:u=!1,showWelcome:h=!0,showLoadMore:g=!0,showLoadingIndicator:m=!0,keepUserMessageInView:p=!0,initialAnimation:f=null,height:x="100%",width:y="100%"},b)=>{const[w,v]=e.useState(!1),[k,S]=e.useState(!1),C=e.useRef(null),{sendMsg:j,messages:I,messageManager:M,isLoading:N,isStreaming:T,isPanelOpen:R,error:E,isInitialLoading:A,isResponseStarted:F,abort:H,loadMoreMessages:L,isLoadingMore:_,hasMoreMessages:q,animationConfig:O,instanceId:P}=z(),B=D(P,"loading"),{showSpacer:$,spacerKey:J,triggerSpacer:K,handleSpacerComplete:X}=(()=>{const[t,s]=e.useState(!1),[a,n]=e.useState(0);return{showSpacer:t,spacerKey:a,triggerSpacer:()=>{s(!0),n(e=>e+1)},handleSpacerComplete:()=>{s(!1)}}})(),{scrollContainerRef:G,shouldAutoScrollRef:Q,scrollToBottom:V,isAtBottom:Z}=(({onGradientChange:t,isStreaming:s})=>{const a=e.useRef(null),n=e.useRef(!0),r=e.useRef(!1),i=e.useCallback(()=>{const e=a.current;e&&(e.scrollTop=e.scrollHeight)},[]),o=e.useCallback(()=>{const e=a.current;return!!e&&50>e.scrollHeight-e.scrollTop-e.clientHeight},[]),c=e.useCallback(()=>{const e=a.current;if(!e)return;const s=e.scrollTop>20;s!==r.current&&(r.current=s,t&&t(s)),n.current=o()},[o,t]),l=e.useCallback((e=>{let t=0;return function(...s){const a=Date.now();100>a-t||(t=a,e(...s))}})(c),[c]);return e.useEffect(()=>{const e=a.current;if(e)return e.addEventListener("scroll",l),()=>e.removeEventListener("scroll",l)},[l]),e.useEffect(()=>{if(!s)return;const e=setInterval(()=>{n.current&&i()},100);return()=>clearInterval(e)},[s,i]),{scrollContainerRef:a,shouldAutoScrollRef:n,scrollToBottom:i,isAtBottom:o}})({onGradientChange:v,isStreaming:"none"===s&&T}),ee="react-window"===s?(({estimateSize:e})=>o.useDynamicRowHeight({defaultRowHeight:e}))({estimateSize:a}):null,te=e.useCallback(()=>{"virtuoso"!==s&&"tanstack"!==s&&("react-window"===s&&C.current?.scrollToBottomCustom?C.current.scrollToBottomCustom():"none"===s&&V())},[s,V]),se=e.useCallback(()=>{p&&setTimeout(()=>{K()},200)},[p,K]),{removeMessage:ae,handleSendMessage:ne}=(({messageManager:t,sendMsg:s,shouldAutoScrollRef:a,onUserMessageSent:n})=>({removeMessage:e.useCallback(e=>{t?.removeMessage&&t.removeMessage(e)},[t]),handleSendMessage:e.useCallback(async e=>{a&&(a.current=!0),n&&n(),await s(e)},[s,a,n])}))({messageManager:M,sendMsg:j,scrollToBottom:te,shouldAutoScrollRef:Q,onUserMessageSent:se});return e.useEffect(()=>{if(A)S(!1);else{if(I&&I.length>0&&!k){const e=setTimeout(()=>{S(!0)},100);return()=>clearTimeout(e)}I&&0!==I.length||S(!0)}},[A,I,k]),e.useImperativeHandle(b,()=>({scrollToBottom:te,isAtBottom:Z,scrollContainer:G.current,dynamicHeight:ee,listRef:C.current,sendMessage:ne,abort:H,isStreaming:T,isLoading:N,messages:I,messageManager:M}),[te,Z,ee,ne,H,T,N,I,M]),t.jsx("div",{className:"react-ai-agent-chat-core "+i,"data-theme":r?"dark":"light",style:{WebkitMaskImage:d,...c},children:A?t.jsx(B||Y,{}):I&&0!==I.length?t.jsxs("div",{className:"react-chat-core-messages h-full w-full",style:{opacity:k?1:0,transition:"opacity 0.3s ease-out"},children:[t.jsx(U,{showLoadMore:g,enableHistory:!0,hasMoreMessages:q,messagesLength:I.length,error:E,isInitialLoading:A,loadMoreMessages:L,isLoadingMore:_}),(()=>{const e={messages:I,removeMessage:ae,allowEditMessage:u,animationConfig:O,isLoading:N,isResponseStarted:F,showLoadingIndicator:m,isStreaming:T,showSpacer:p&&$,spacerKey:J,onSpacerComplete:X};switch(s){case"virtuoso":return t.jsx(ce,{height:x,width:y,listRef:C,shouldAutoScrollRef:Q,...e});case"react-window":return t.jsx(le,{dynamicHeight:ee,height:x,width:y,overscan:n,listRef:C,isStreaming:T,shouldAutoScrollRef:Q,...e});case"tanstack":return t.jsx(ue,{height:x,width:y,isStreaming:T,shouldAutoScrollRef:Q,...e});default:return t.jsx(he,{scrollToBottom:te,shouldAutoScrollRef:Q,isStreaming:T,scrollContainerRef:G,height:x,width:y,...e})}})()]}):h&&t.jsx("div",{style:{opacity:k?1:0,height:"100%",width:"100%",transition:"opacity 0.3s ease-out"},children:t.jsx(W,{error:E,isPanelOpen:R,instanceId:P})})})});ge.displayName="ChatCore";var me=e.memo(ge);const pe=({todos:e=[]})=>e&&0!==e?.length?t.jsx("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:t.jsxs("div",{className:"react-ai-agent-queue-manager-wrapper flex items-center w-full relative bottom-0",children:[t.jsx("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] "}),t.jsx("div",{className:"react-ai-agent-queue-manager-content flex items-center gap-2 w-full p-1 py-[5px] z-99"})]})}):null,fe=({children:e,content:s,visible:a})=>a?t.jsxs("div",{className:"react-ai-agent-tooltip-wrapper relative",children:[e,t.jsxs("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:[t.jsx("div",{className:"react-ai-agent-tooltip-content text-theme-secondary text-sm space-y-2",children:s}),t.jsx("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,xe=()=>{const[s,a]=e.useState(!1),{sessionMetrics:n,usedTokens:r,contextLimit:i}=z(),o=(100*(r/i||0)).toFixed(2),c=e=>e?1e6>e?1e3>e?""+e:(e/1e3).toFixed(1)+"K":(e/1e6).toFixed(1)+"M":"0",l=t.jsxs("div",{className:"space-y-2",children:[t.jsx("div",{className:"font-medium text-theme-primary border-b border-theme-tertiary pb-1",children:"Session Info"}),t.jsxs("div",{className:"space-y-1 text-xs",children:[t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-theme-quaternary",children:"Context size:"}),t.jsxs("span",{children:[c(n?.contextUsed)," / ",c(n?.contextLimit)]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-theme-quaternary",children:"Session Tokens:"}),t.jsx("span",{children:c(n?.tokensUsed)})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-theme-quaternary",children:"All time tokens:"}),t.jsx("span",{children:c(n?.allTimeTokens)})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsx("span",{className:"text-theme-quaternary",children:"Requests:"}),t.jsx("span",{children:c(n?.requests)})]})]})]});return t.jsx(fe,{content:l,visible:s,children:t.jsxs("div",{className:"react-ai-agent-progress-bar flex items-center gap-2 cursor-pointer",onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[t.jsxs("span",{className:"react-ai-agent-progress-percentage text-theme-ghost font-light text-[12px] leading-[18px]",children:[o,"%"]}),t.jsxs("div",{className:"react-ai-agent-progress-circle-wrapper relative w-4 h-4 flex items-center justify-center",children:[t.jsx("div",{className:"react-ai-agent-progress-circle-bg absolute inset-0 rounded-full bg-theme-muted"}),t.jsx("div",{className:"react-ai-agent-progress-circle-fill absolute inset-0 rounded-full",style:{background:`conic-gradient(var(--rca-text-faint) ${o}%, transparent 0)`}}),t.jsx("div",{className:"react-ai-agent-progress-circle-inner absolute inset-0.5 rounded-full bg-secondary"})]})]})})},ye=({attachedFiles:e=[],removeFile:s})=>{const{currentSelectedFile:a,setIsHoldEnabled:n,setCurrentSelectedFile:r,manuallyAddedFiles:i=[],setManuallyAddedFiles:o=()=>{}}=z(),c=[...a?[a]:[],...i,...e];return t.jsxs("div",{className:"react-ai-agent-chat-bar flex items-center w-full mb-2 justify-between",children:[t.jsxs("div",{className:"react-ai-agent-chat-bar-left flex items-center",children:[c.length>0&&t.jsx(we,{files:c,handleRemoveFile:e=>{"object"==typeof e&&e.id?s&&s(e.id):e===a?(r(null),n(!1)):o(t=>t.filter(t=>t!==e))}}),t.jsxs("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:[t.jsx("span",{className:"react-ai-agent-context-button-icon",children:B("add",20,"currentColor",{marginLeft:"-5px"})}),0===c.length&&t.jsx("span",{className:"react-ai-agent-context-button-label",children:"Context"})]})]}),t.jsx("div",{className:"react-ai-agent-chat-bar-right",children:t.jsx(xe,{})})]})},be=({file:s,handleRemoveFile:a})=>{const[n,r]=e.useState(!1),i="object"==typeof s&&s.id,o=i?s.name:s.split("/").pop(),c=i?s.id:s;return t.jsxs("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:()=>r(!0),onMouseLeave:()=>r(!1),children:[n?t.jsx("button",{className:"react-ai-agent-file-item-remove w-[16px] opacity-50 hover:opacity-100 -ml-[2px] -mr-[2px] h-[16px]",onClick:e=>{e.stopPropagation(),a(s)},children:t.jsx("span",{className:"react-ai-agent-file-item-remove-icon",children:B("close",16,"currentColor")})}):t.jsx("div",{className:"react-ai-agent-file-item-icon-wrapper",children:i&&s.preview?t.jsx("img",{src:s.preview,alt:o,className:"react-ai-agent-file-item-preview w-3 h-4 object-cover rounded",style:{marginRight:0,width:"12px",height:"16px"}}):t.jsx(FileIcon,{fileName:o,style:{marginRight:0,width:"12px",height:"16px"}})}),t.jsx("div",{className:"react-ai-agent-file-item-name text-theme-quaternary hover:text-theme-primary text-[12px] leading-relaxed whitespace-nowrap truncate max-w-[100px]",children:o})]},c)},we=({files:e,handleRemoveFile:s})=>t.jsx("div",{className:"react-ai-agent-file-items flex items-center gap-2 mr-2",children:e.map(e=>t.jsx(be,{file:e,handleRemoveFile:s},"object"==typeof e&&e.id?e.id:e))}),ve=()=>{const[s,a]=e.useState(0),n=e.useRef(),r=e.useRef(0),i=e.useRef(0),o=e.useRef(null),c=e.useRef(1);return e.useEffect(()=>{const e=()=>{if(o.current){const{width:e,height:t}=o.current.getBoundingClientRect();c.current=e/t}};e();const t=new ResizeObserver(e);return o.current&&t.observe(o.current),()=>{t.disconnect()}},[]),e.useEffect(()=>{i.current=performance.now(),r.current=s;const e=t=>{const o=t-i.current;i.current=t,r.current+=o/1e3*360,360>r.current||(r.current-=360);const l=r.current*(Math.PI/180),d=c.current,u=Math.round((Math.atan2(Math.sin(l),Math.cos(l)/d)*(180/Math.PI)+360)%360);3>Math.abs(u-s)||a(u),n.current=requestAnimationFrame(e)};return n.current=requestAnimationFrame(e),()=>{n.current&&(cancelAnimationFrame(n.current),n.current=null)}},[]),t.jsx("div",{ref:o,className:"react-ai-agent-loader-animation w-full h-full absolute inset-0 rounded-[inherit]",children:t.jsx("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":s,display:"flex"},children:t.jsx("div",{className:"style_glow__i4Qpo"})})})},ke="image/*,video/*,audio/*,.pdf,.doc,.docx,.txt,.md,.json,.js,.ts,.jsx,.tsx,.py,.html,.css,.xml,.csv";function Se(){const[t,s]=e.useState([]),a=e.useRef(null),n=e.useCallback(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=e.useCallback(async e=>{const a=[];for(const s of e){if(t.some(e=>e.name===s.name&&e.size===s.size&&e.type===s.type))continue;let e=!1;if(5242880>s.size)try{const r=await n(s);t.some(e=>e.hash===r)||(a.push({file:s,id:Date.now()+Math.random(),name:s.name,size:s.size,type:s.type,hash:r,preview:s.type.startsWith("image/")?URL.createObjectURL(s):null}),e=!0)}catch(r){}e||a.push({file:s,id:Date.now()+Math.random(),name:s.name,size:s.size,type:s.type,preview:s.type.startsWith("image/")?URL.createObjectURL(s):null})}a.length>0&&s(e=>[...e,...a])},[t,n]),i=e.useCallback(e=>{const t=Array.from(e.target.files||[]);t.length>0&&r(t),e.target.value=""},[r]),o=e.useCallback(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]),c=e.useCallback(e=>{s(t=>{const s=t.filter(t=>t.id!==e),a=t.find(t=>t.id===e);return a?.preview&&URL.revokeObjectURL(a.preview),s})},[]),l=e.useCallback(()=>{s(e=>(e.forEach(e=>{e.preview&&URL.revokeObjectURL(e.preview)}),[]))},[]);return{attachedFiles:t,fileInputRef:a,onFileSelect:i,onPaste:o,removeFile:c,clearFiles:l}}const Ce=()=>{const{streamError:s,clearStreamError:a,retryLastMessage:n,sendRequestCallback:r,triggerLoadingStates:i}=z(),[o]=e.useState(s?.choices||[{id:"retry",label:"Retry"},{id:"cancel",label:"Cancel"}]);return s?t.jsx("div",{className:"react-ai-agent-stream-error w-full mb-3",children:t.jsxs("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:[t.jsx("div",{className:"react-ai-agent-error-message-wrapper",children:t.jsx("div",{className:"react-ai-agent-error-message text-[12px] text-theme-primary font-medium",children:s.message||"An error occurred during streaming"})}),t.jsx("div",{className:"react-ai-agent-error-actions flex gap-2 items-center",children:o&&o.length>0&&o.map(e=>t.jsx("button",{onClick:()=>(async e=>{"retry"===e?"connection_error"===s.errorType?await n():(i(),r({type:"stream_error",callback:"retry",requestId:s.requestId})):"cancel"===e&&(s.requestId&&r({type:"stream_error",callback:"cancel",requestId:s.requestId}),a())})(e.id),className:`react-ai-agent-error-action react-ai-agent-error-action-${e.id} text-[11px] font-medium px-3 py-1 rounded-md transition-all duration-200\n ${"retry"===e.id?"text-theme-primary hover:text-theme-secondary underline underline-offset-2":"cancel"===e.id?"text-theme-subtle hover:text-theme-tertiary":"text-theme-tertiary hover:text-theme-primary"}\n `,children:e.label},e.id))})]})}):null},je=({agents:s=[],selectedAgentId:a,onAgentChange:n,disabled:r=!1})=>{const[i,o]=e.useState(!1),c=e.useRef(null),l=s.find(e=>e.id===a)||s[0],[d,u]=e.useState(l?.id||s[0]?.id);e.useEffect(()=>{const e=e=>{c.current&&!c.current.contains(e.target)&&o(!1)};return i&&document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[i]);const h=s.find(e=>e.id===d)||l||s[0];return h?t.jsxs("div",{className:"react-ai-agent-switch relative",ref:c,children:[t.jsxs("button",{type:"button",onClick:()=>!r&&o(!i),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:i?"var(--rca-bg-muted)":"transparent"},children:[t.jsx("span",{className:"mr-2",children:B("brain",18,"currentColor")}),t.jsx("span",{className:"react-ai-agent-switch-label text-[13px] mr-2 text-theme-primary font-[400]",children:h.name||h.model||"Agent"}),t.jsx("span",{style:{transform:i?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease",display:"inline-flex",opacity:.6},children:B("arrowDown",14,"currentColor")})]}),i&&s.length>0&&t.jsx("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:t.jsx("div",{className:"react-ai-agent-switch-dropdown-content max-h-[320px] overflow-y-auto py-1",children:s.map(e=>{const s=e.id===d;return t.jsxs("button",{type:"button",onClick:()=>(e=>{r||e.id===d||(u(e.id),n?.(e)),o(!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:s?"var(--rca-bg-subtle)":"transparent",color:s?"var(--rca-text-primary)":"var(--rca-text-secondary)"},onMouseEnter:e=>{s||(e.currentTarget.style.background="var(--rca-bg-hover)")},onMouseLeave:e=>{s||(e.currentTarget.style.background="transparent")},children:[t.jsx("span",{className:"flex-shrink-0",style:{opacity:.8},children:B("brain",18,"currentColor")}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("div",{className:"flex items-center gap-2",children:t.jsx("div",{className:"react-ai-agent-switch-option-name text-[13px] font-medium",children:e.name})}),e.description&&t.jsx("div",{className:"react-ai-agent-switch-option-description text-[11px] mt-0.5 truncate",style:{color:"var(--text-quaternary)"},children:e.description})]}),s&&t.jsx("span",{className:"react-ai-agent-switch-option-check flex-shrink-0",style:{color:"var(--rca-text-accent)"},children:B("check",16,"currentColor")})]},e.id)})})})]}):null},Ie=e.forwardRef(({onSendMessage:s,isStreaming:a,abort:n,mode:r="advanced",todos:i=[],agents:o=[],selectedAgentId:c,onAgentChange:l},d)=>{const[u,h]=e.useState(""),g=e.useRef(null),{attachedFiles:m,fileInputRef:p,onFileSelect:f,onPaste:x,removeFile:y,clearFiles:b}=Se();e.useEffect(()=>{g.current&&(g.current.style.height="auto",g.current.style.height=Math.min(g.current.scrollHeight,150)+"px")},[u]),e.useImperativeHandle(d,()=>({focus:()=>{g.current?.focus()}}),[]);const w=e=>{e.preventDefault(),(u.trim()||m.length>0)&&(s({message:u,attachedFiles:m}),h(""),b(),g.current&&(g.current.style.height="auto"))},v="advanced"===r,k=o&&o.length>0;return t.jsx("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:t.jsxs("div",{className:"react-ai-agent-input-wrapper mx-auto relative "+("advanced"===r?"min-h-[120px]":"min-h-[100px]"),children:[a&&t.jsx("div",{className:"absolute inset-0 pointer-events-none rounded-[15px]",style:{zIndex:1},children:t.jsx(ve,{})}),t.jsx("div",{className:"react-ai-agent-input-backdrop backdrop-blur-[20px] w-full h-full z-0 absolute bg-theme-overlay rounded-[15px]"}),t.jsxs("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:[v&&t.jsxs(t.Fragment,{children:[t.jsx(pe,{todos:i}),t.jsx(Ce,{}),t.jsx(ye,{attachedFiles:m,removeFile:y})]}),t.jsx("div",{className:`react-ai-agent-input-textarea-wrapper relative pb-[${"advanced"===r?"50px":"0px"}]`,children:t.jsx("textarea",{autoSave:"off",autoFocus:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false","data-form-type":"other",ref:g,value:u,onChange:e=>h(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),w(e))},onPaste:x,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})}),t.jsxs("div",{className:"react-ai-agent-input-actions flex items-center justify-between mt-auto bottom-[15px] absolute w-[calc(100%-40px)]",children:[t.jsx("input",{ref:p,type:"file",multiple:!0,accept:ke,onChange:f,className:"react-ai-agent-file-input hidden"}),t.jsx("div",{className:"react-ai-agent-input-actions-left flex items-center gap-2",children:"default"===r&&m.length>0?t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(we,{files:m,handleRemoveFile:e=>y(e.id)}),t.jsx("button",{type:"button",onClick:()=>p.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:B("add",20,"currentColor")})]}):t.jsxs("button",{type:"button",onClick:()=>p.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:[B("attach",18,"currentColor"),t.jsx("span",{className:"react-ai-agent-attach-label text-[14px] ml-2 font-[300]",children:"Attach"})]})}),t.jsxs("div",{className:"react-ai-agent-input-actions-right flex items-center",children:[k&&t.jsx(je,{agents:o,selectedAgentId:c,onAgentChange:l,disabled:a}),t.jsx("button",{type:"button",onClick:e=>{a?n():w(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:!u.trim()&&!a,children:B(a?"square":"send",a?15:20,"currentColor")})]})]})]})]})})});Ie.displayName="ChatInputDefault";var Me=e.memo(Ie);const Ne=({isDark:s=!1,onCreateSession:a,onClose:n,showCloseButton:r=!1})=>{const[i,o]=e.useState(!1),[c,l]=e.useState(!1),{instanceId:d}=z(),u=D(d,"header");return u?u():t.jsxs("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:[t.jsxs("div",{className:"react-ai-agent-header-left flex items-center gap-4 opacity-50",children:[t.jsx("button",{className:"react-ai-agent-header-new-chat flex items-center cursor-pointer hover:opacity-80",style:{opacity:i?.5:1,cursor:i?"progress":"pointer"},disabled:i,onClick:async({replace:e=!1}={})=>{if(o(!0),a)try{await a({replace:e})}catch(t){}finally{o(!1)}else setTimeout(()=>{o(!1)},1e3)},children:B("add",25,s?"#fff":"#000")}),t.jsx("div",{className:"react-ai-agent-header-history flex items-center cursor-pointer hover:opacity-80",onClick:c?()=>l(!1):()=>l(!0),children:B(c?"close":"history",18,s?"#fff":"#000")})]}),r&&n?t.jsx("button",{className:"react-ai-agent-header-close flex items-center cursor-pointer hover:opacity-80 opacity-50 transition-opacity",onClick:n,"aria-label":"Close panel",children:B("close",24,s?"#fff":"#000")}):t.jsx("div",{className:"react-ai-agent-header-right w-[80px]"})]})};var Te=e.memo(Ne);const Re=e.memo(({coreRef:e,isDark:s,allowEditMessage:a,onCreateSession:n,handleSendMessage:r,isStreaming:i,abort:o,coreProps:c,inputProps:l,children:d,onClose:u,showCloseButton:h=!1,className:g=""})=>t.jsxs("div",{className:"react-ai-agent flex flex-col h-full relative chat-panel "+g,"data-theme":s?"dark":"light",children:[t.jsx(Te,{isDark:s,onCreateSession:n,onClose:u,showCloseButton:h}),t.jsxs("div",{className:"relative flex-grow w-full max-w-[600px] mx-auto h-full min-w-[300px]",children:[t.jsx(me,{ref:e,isDark:s,allowEditMessage:a,className:"px-[15px]",...c}),t.jsx(Me,{onSendMessage:r,isStreaming:i,abort:o,...l})]}),d]}));Re.displayName="ChatPanelContent";const Ee=({isOpen:e,isDragging:s,isDark:a=!0})=>t.jsx("div",{className:`\n w-16 h-16 rounded-full flex items-center justify-center\n transition-all duration-300 ease-out\n ${s?"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:B(e?"close%20remove-8-1662452248.png":"chat%20intelligence-48-1686045820.png",32,"currentColor")}),Ae=e.memo(({onClick:s,isDark:a=!1,isOpen:n=!1,onPositionChange:r,livePositionUpdate:i=!0,edgeOffset:o=20,ContentComponent:c=Ee,onOpen:l,onClose:u,onDrag:h})=>{const g="react-ai-agent-floating-button-position",m=e.useRef(null),[p,f]=e.useState({width:64,height:64}),x="number"==typeof o?o:o?.x??20,y="number"==typeof o?o:o?.y??20,b=e.useCallback(()=>"undefined"==typeof window?{minX:x,minY:y,maxX:1024-p.width-x,maxY:768-p.height-y,width:1024,height:768}:{minX:x,minY:y,maxX:window.innerWidth-p.width-x,maxY:window.innerHeight-p.height-y,width:window.innerWidth,height:window.innerHeight},[p,x,y]),w=e.useCallback((e,t)=>{const s=b();return{x:Math.max(s.minX,Math.min(e,s.maxX)),y:Math.max(s.minY,Math.min(t,s.maxY))}},[b]),v=e.useCallback(e=>{const t=b();return!(t.minX>e.x||t.minY>e.y||e.x>t.maxX||e.y>t.maxY)},[b]),k=e.useCallback(()=>{const e=b(),{width:t,minX:s,minY:a,maxX:n,maxY:r}=e;return[{x:s,y:a,name:"top-left"},{x:(t-p.width)/2,y:a,name:"top-center"},{x:n,y:a,name:"top-right"},{x:s,y:r,name:"bottom-left"},{x:(t-p.width)/2,y:r,name:"bottom-center"},{x:n,y:r,name:"bottom-right"}]},[p,b]),S=e.useCallback(()=>{if("undefined"==typeof window)return k()[5];try{const e=localStorage.getItem(g);if(e){const t=JSON.parse(e);if(v(t))return t}}catch(e){}return k()[5]},[k,v]),[C,j]=e.useState(()=>"undefined"==typeof window?{x:0,y:0,name:"bottom-right"}:S()),[I,M]=e.useState(!1),[N,T]=e.useState(!1),[R,E]=e.useState({x:0,y:0}),[A,F]=e.useState({x:0,y:0}),[H,z]=e.useState(!1);e.useEffect(()=>{if("undefined"!=typeof window&&!H){z(!0);const e=S();e&&void 0!==e.x&&void 0!==e.y&&j(e)}},[H,S]);const L=e.useCallback((e,t)=>{const s=k();let a=s[0],n=1/0;return s.forEach(s=>{const r=Math.sqrt(Math.pow(s.x-e,2)+Math.pow(s.y-t,2));n>r&&(n=r,a=s)}),a},[k]),_=e.useCallback(e=>{if(0!==e.button)return;e.preventDefault();const t=m.current.getBoundingClientRect(),s=e.clientX-t.left,a=e.clientY-t.top;E({x:e.clientX,y:e.clientY}),F({x:s,y:a}),M(!0),T(!1),h?.(!0),m.current&&m.current.setPointerCapture(e.pointerId)},[h]),D=e.useCallback(e=>{if(!I)return;e.preventDefault(),Math.sqrt(Math.pow(e.clientX-R.x,2)+Math.pow(e.clientY-R.y,2))>5&&T(!0);const t=w(e.clientX-A.x,e.clientY-A.y);j(t),i&&r&&r(t,!0,p)},[I,A,R,w,r,i,p]),q=e.useCallback(e=>{if("undefined"!=typeof window)try{localStorage.setItem(g,JSON.stringify(e))}catch(t){}},[]),O=e.useCallback(e=>{if(I)if(e.preventDefault(),m.current&&m.current.releasePointerCapture(e.pointerId),M(!1),h?.(!1),N){const e=L(C.x,C.y);j(e),setTimeout(()=>{q(e)},0),r?.(e,!1,p)}else s?.()},[I,N,C,L,s,q,r,h,p]);return e.useEffect(()=>{if(I){const e=e=>D(e),t=e=>O(e);return document.addEventListener("pointermove",e,{passive:!1}),document.addEventListener("pointerup",t,{passive:!1}),document.addEventListener("pointercancel",t,{passive:!1}),document.body.style.userSelect="none",document.body.style.cursor="grabbing",()=>{document.removeEventListener("pointermove",e),document.removeEventListener("pointerup",t),document.removeEventListener("pointercancel",t),document.body.style.userSelect="",document.body.style.cursor=""}}},[I,D,O]),e.useEffect(()=>{if("undefined"==typeof window)return;const e=()=>{if(v(C)){const e=L(C.x,C.y);j(e),setTimeout(()=>{q(e)},0),r?.(e,!1,p)}else{const e=w(C.x,C.y),t=L(e.x,e.y);j(t),setTimeout(()=>{q(t)},0),r?.(t,!1,p)}};return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[C,L,q,v,w,r]),e.useEffect(()=>{if("undefined"==typeof window||!m.current||!H)return;const e=()=>{if(m.current){const e=m.current.getBoundingClientRect(),t={width:e.width,height:e.height};f(e=>e.width===t.width&&e.height===t.height?e:t)}},t=setTimeout(()=>{e()},0),s=new ResizeObserver(()=>{e()});return s.observe(m.current),()=>{clearTimeout(t),s.disconnect()}},[H]),e.useEffect(()=>{if("undefined"==typeof window||!C)return;const e=w(C.x,C.y);e.x===C.x&&e.y===C.y||(j(e),setTimeout(()=>{q(e)},0),r?.(e,!1,p))},[p,w,r,C,q]),e.useEffect(()=>{C&&r&&requestAnimationFrame(()=>{r(C,!1,p)})},[]),t.jsx("div",{ref:m,className:"fixed z-[9999] select-none",style:{left:C.x+"px",top:C.y+"px",transition:I?"none":"all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",cursor:I?"grabbing":"grab",willChange:I?"transform":"auto",transform:"translate3d(0, 0, 0)"},onPointerDown:_,children:d.default.isValidElement(c)?d.default.cloneElement(c,{isOpen:n,isDragging:I,isDark:a,onOpen:l,onClose:u,onDrag:h}):c?t.jsx(c,{isOpen:n,isDragging:I,isDark:a,onOpen:l,onClose:u,onDrag:h}):t.jsx(Ee,{isOpen:n,isDragging:I,isDark:a})})},(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});Ae.displayName="FloatingAIButton";const Fe=({isDark:s=!1,allowEditMessage:a=!1,children:n,onCreateSession:r,className:i="h-full w-full",coreProps:o={},inputProps:c={},mode:l="popup",livePositionUpdate:d=!0,popupOptions:u={},popupContainerClassName:h="",popupContainerStyle:g={},floatingButtonEdgeOffset:m=25,ContentComponent:p,onOpen:f,onClose:x,onDrag:y})=>{const b=e.useMemo(()=>({width:u.width??400,height:u.height??600,gap:u.gap??16,verticalPadding:u.verticalPadding??24}),[u.width,u.height,u.gap,u.verticalPadding]),w=e.useRef(null),v=e.useRef(null),[k,S]=e.useState("default"===l),[C,j]=e.useState(!1),[I,M]=e.useState(null),[N,T]=e.useState({width:64,height:64}),[R,E]=e.useState(!1),[A,F]=e.useState("right"),[H,L]=e.useState("bottom"),{sendMsg:_,isStreaming:D,abort:q}=z(),O=e.useCallback(async e=>{w.current?.sendMessage?await w.current.sendMessage(e):(await _(e),setTimeout(()=>{w.current?.scrollToBottom()},100))},[_]),P=e.useCallback(()=>{v.current&&clearTimeout(v.current),j(!0),S(!0),f?.(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{j(!1)})})},[f]),B=e.useCallback(()=>{v.current&&clearTimeout(v.current),S(!1),x?.(),j(!0),v.current=setTimeout(()=>{j(!1),v.current=null},450)},[x]),U=e.useCallback(()=>{k?B():P()},[k,P,B]),$=e.useCallback((e,t=!1,s={width:64,height:64})=>{if(E(t),M(e),T(s),!t&&"undefined"!=typeof window){const t=window.innerWidth,a=window.innerHeight,n=e.x+s.width/2;let r,i;r=t/3>n?"left":n>2*t/3?"right":"center",i=a/2>e.y+s.height/2?"top":"bottom",F(r),L(i)}},[]);e.useEffect(()=>()=>{v.current&&clearTimeout(v.current)},[]);const W=e.useMemo(()=>{if(!I||"undefined"==typeof window)return{bottom:"96px",left:"50%"};const e=window.innerHeight;let t;return t="bottom"===H?e-I.y+b.gap:e-(I.y+N.height)-b.height-b.gap,{bottom:t+"px",left:I.x+N.width/2+"px"}},[I,N,H,b.gap,b.height]),Y=e.useMemo(()=>{if("undefined"==typeof window||!I)return"translateX(-50%) translateY(0)";const e=window.innerWidth,t=window.innerHeight,s=I.x+N.width/2,a=N.width/2;let n,r;r="left"===A?s-a:"right"===A?s+a-b.width:s-b.width/2,n=0>r?-s+"px":r+b.width>e?e-s-b.width+"px":"left"===A?-a+"px":"right"===A?`calc(-100% + ${a}px)`:"-50%";let i=0;if(!R)if("bottom"===H){const e=I.y-b.gap-b.height;b.verticalPadding>e&&(i=b.verticalPadding-e)}else{const e=I.y+N.height+b.gap+b.height;e>t-b.verticalPadding&&(i=t-b.verticalPadding-e)}return`translateX(${n}) translateY(${i}px)`},[A,H,I,N,R,b.width,b.gap,b.height,b.verticalPadding]);e.useEffect(()=>{if("default"!==l&&"undefined"!=typeof window){const e=e=>{"Escape"===e.key&&k&&B()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)}},[l,k,B]);const J=e.useMemo(()=>({coreRef:w,isDark:s,allowEditMessage:a,onCreateSession:r,handleSendMessage:O,isStreaming:D,abort:q,coreProps:o,inputProps:c,children:n}),[s,a,r,O,D,q,o,c,n]);return"default"===l?t.jsx(Re,{...J,className:i}):t.jsxs(t.Fragment,"sliding"===l?{children:[k&&t.jsx("div",{className:"fixed inset-0 bg-black/50 z-[9990]",style:{backdropFilter:"blur(4px)",opacity:C?0:1,transition:"opacity 400ms cubic-bezier(0.4, 0, 0.2, 1)"},onClick:B}),t.jsx("div",{className:"fixed top-0 right-0 h-full z-[9995] shadow-2xl",style:{width:"min(600px, 100vw)",maxWidth:"100vw",backgroundColor:s?"#1a1a1a":"#ffffff",transform:k?"translateX(0)":"translateX(100%)",transition:"transform 400ms cubic-bezier(0.4, 0, 0.2, 1)"},children:t.jsx(Re,{...J,className:i,onClose:B,showCloseButton:!0})}),!k&&t.jsx(Ae,{onClick:P,isDark:s,onPositionChange:$,livePositionUpdate:d,edgeOffset:m,ContentComponent:p,onOpen:f,onClose:x,onDrag:y})]}:{children:[(k||C)&&t.jsx("div",{className:"fixed z-[9995]",style:{bottom:W.bottom,left:W.left,transition:R?"none":"bottom 200ms cubic-bezier(0.4, 0, 0.2, 1), left 200ms cubic-bezier(0.4, 0, 0.2, 1)",willChange:R?"bottom, left":"auto",pointerEvents:k?"auto":"none"},children:t.jsx("div",{className:("rounded-2xl shadow-2xl overflow-hidden "+h).trim(),style:{width:`min(${b.width}px, calc(100vw - 48px))`,height:`min(${b.height}px, calc(100vh - 160px))`,backgroundColor:s?"#1a1a1a":"#ffffff",transform:C?Y+" translateY(30px) rotateX(15deg)":Y+" rotateX(0deg)",transformOrigin:"bottom center",transformStyle:"preserve-3d",opacity:C?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",...g},children:t.jsx(Re,{...J,className:i,onClose:B,showCloseButton:!0})})}),t.jsx(Ae,{onClick:U,isDark:s,isOpen:k,onPositionChange:$,livePositionUpdate:d,edgeOffset:m,ContentComponent:p,onOpen:f,onClose:x,onDrag:y})]})};var He=e.memo(Fe);const ze={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}},Le=e.forwardRef(({onSendMessage:s,miniMode:a=!1,isStreaming:n,abort:r,todos:i,variant:o="default",placeholder:c="Type a message...",collapsed:l=!1,onExpand:d,position:u="bottom-center",compact:h},g)=>{const[m,p]=e.useState(""),[f,x]=e.useState(!1),y=e.useRef(null),{attachedFiles:b,fileInputRef:w,onFileSelect:v,onPaste:k,removeFile:S,clearFiles:C}=Se();e.useEffect(()=>{!l&&y.current&&(y.current.style.height="auto",y.current.style.height=Math.min(y.current.scrollHeight,150)+"px")},[m,l]),e.useImperativeHandle(g,()=>({focus:()=>{y.current?.focus()}}),[]);const j=e=>{e.preventDefault(),(m.trim()||b.length>0)&&(s({message:m,attachedFiles:b}),p(""),C(),!l&&y.current&&(y.current.style.height="auto"))},I=h?l?ze.collapsedCompact:ze.expandedCompact:l?ze.collapsed:ze.expanded;return t.jsxs("div",{className:"react-ai-agent-input-morph",style:{width:I.width,transition:"width 0.4s cubic-bezier(0.4, 0, 0.2, 1)"},"data-theme":"dark",children:[n&&!l&&t.jsx("div",{className:"absolute inset-0 pointer-events-none",style:{height:I.height,minHeight:I.minHeight||I.height,borderRadius:I.borderRadius,zIndex:1,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s, border-radius "+(l?"0.15s cubic-bezier(0.4, 0, 0.2, 1) 0.3s":"0.15s cubic-bezier(0.4, 0, 0.2, 1)")},children:t.jsx(ve,{})}),t.jsxs("div",{className:"react-ai-agent-input-wrapper relative",style:{height:I.height,minHeight:I.minHeight||I.height,zIndex:2,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s",overflow:"hidden"},children:[t.jsx("div",{className:"react-ai-agent-input-backdrop backdrop-blur-[20px] w-full h-full z-0 absolute bg-theme-overlay",style:{borderRadius:I.borderRadius,transition:l?"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)"}}),t.jsxs("div",{className:"relative z-10 h-full "+I.padding,style:{transition:"padding 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s"},children:[I.showTopContent&&t.jsxs("div",{style:{opacity:l?0:1,height:l?0:"auto",overflow:"hidden",pointerEvents:l?"none":"auto",transition:l?"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:[t.jsx(pe,{todos:i}),t.jsx(Ce,{}),t.jsx(ye,{attachedFiles:b,removeFile:S})]}),t.jsxs("div",{className:"flex items-center w-full "+(I.compact||l?I.gap:""),style:{position:I.compact||l?"relative":"static"},children:[t.jsx("input",{ref:w,type:"file",multiple:!0,accept:ke,onChange:v,className:"react-ai-agent-file-input hidden"}),I.compact&&I.showAttach&&t.jsx("div",{className:"flex-shrink-0",style:{opacity:l?0:1,width:l?0:"auto",overflow:"hidden",pointerEvents:l?"none":"auto",transition:l?"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:t.jsx("button",{type:"button",onClick:()=>w.current?.click(),className:(I.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:B("attach",I.compact?20:18,"currentColor")})}),t.jsx("div",{className:I.compact||l?"flex-1":"relative pb-[50px] w-full",style:{transition:"padding 0.3s ease-out 0.15s",marginTop:l&&!I.compact?"2px":void 0},children:t.jsx("textarea",{autoSave:"off",autoFocus:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false","data-form-type":"other",ref:y,value:m,onChange:e=>p(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),j(e))},onPaste:k,onFocus:()=>{x(!0),l&&d&&d()},onBlur:()=>{x(!1)},placeholder:c,className:"text-[14px] text-theme-primary resize-none outline-none bg-transparent "+(I.compact||l?"w-full pr-0 pl-3":"w-full min-h-[40px] max-h-[150px] pr-12"),style:{overflow:"auto",height:I.compact||l?"30px":void 0,maxHeight:I.compact||l?"30px":void 0,paddingTop:I.compact||l?"7px":void 0,paddingBottom:I.compact||l?"3px":void 0,lineHeight:I.compact||l?"16px":void 0,transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s"},rows:1})}),t.jsxs("div",{className:"flex items-center "+(I.compact||l?"flex-shrink-0":"justify-between"),style:{position:I.compact||l?"static":"absolute",bottom:I.compact||l?"auto":"15px",left:I.compact||l?"auto":"20px",right:I.compact||l?"auto":"20px",width:I.compact||l?"auto":"calc(100% - 40px)"},children:[!I.compact&&t.jsx("div",{className:"react-ai-agent-input-actions-left flex items-center",style:{opacity:l||!I.showAttach?0:1,width:l||!I.showAttach?0:"auto",overflow:"hidden",pointerEvents:l||!I.showAttach?"none":"auto",transition:l?"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:t.jsxs("button",{type:"button",onClick:()=>w.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:[B("attach",18,"currentColor"),t.jsx("span",{className:"react-ai-agent-attach-label text-[14px] ml-2 font-[300]",children:"Attach"})]})}),t.jsxs("div",{className:"react-ai-agent-input-actions-right flex items-center",children:[t.jsx("div",{style:{opacity:l||!I.showAgent?0:1,width:l||!I.showAgent?0:"auto",overflow:"hidden",transition:l?"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:I.showAgent&&t.jsxs("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:[B("brain",18,"currentColor"),t.jsx("span",{className:"react-ai-agent-agent-label text-[12px] mx-2 text-theme-quaternary font-[300] -mt-[2px]",children:"Agent"}),B("arrowDown",16,"currentColor",{transform:"rotate(180deg)"})]})}),t.jsx("button",{type:"button",onClick:e=>{n?r():j(e)},className:"react-ai-agent-send-button flex justify-center items-center cursor-pointer bg-inverse text-inverse rounded-full hover:scale-110",disabled:!m.trim()&&!n,style:{width:I.sendButtonSize+"px",height:I.sendButtonSize+"px",transition:"all 0.3s cubic-bezier(0.4, 0, 0.2, 1) 0.15s, transform 0.2s ease-out"},children:B(n?"square":"send",n?15:l?18:20,"currentColor")})]})]})]})]})]})]})});Le.displayName="ChatInput";var _e=e.memo(Le);const De=({allowEditMessage:s=!1,children:a,placeholder:n="Ask me anything...",position:r="bottom-center",isDark:i,compact:o,coreProps:c={},inputProps:l={},onExpand:d,onClose:u,bottomBlur:h})=>{const[g,m]=e.useState(!1),[p,f]=e.useState(!1),[x,y]=e.useState(!1),[b,w]=e.useState(!1),v=e.useRef(null),k=e.useRef(null),S=e.useRef([]),[C,j]=e.useState(i),{isStreaming:I,abort:M}=z(),N=e.useCallback(()=>{S.current.forEach(e=>clearTimeout(e)),S.current=[]},[]),T=e.useCallback(async e=>{v.current?.sendMessage?await v.current.sendMessage(e):setTimeout(()=>{v.current?.scrollToBottom()},100)},[]),R=e.useCallback(()=>{N(),f(!1),y(!1),m(!0),w(!1),d?.(),j(!0);const e=setTimeout(()=>{w(!0)},350);S.current.push(e);const t=setTimeout(()=>{k.current?.focus()},400);S.current.push(t)},[N]),E=e.useCallback(()=>{N(),f(!0),m(!1),setTimeout(()=>{u?.(),j(i)},500);const e=setTimeout(()=>{y(!0)},250);S.current.push(e);const t=setTimeout(()=>{w(!1),f(!1),y(!1)},500);S.current.push(t)},[N]);e.useEffect(()=>{const e=e=>{"Escape"===e.key&&g&&E()};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[g,E]),e.useEffect(()=>()=>{N()},[N]);const A=g||p;return t.jsxs("div",{className:"container",children:[A&&t.jsx("div",{className:"fixed inset-0 bg-black/80 z-40 transition-opacity duration-300 ease-in-out "+(x?"opacity-0":"opacity-100"),style:{backdropFilter:"blur(20px)"},onClick:E}),A&&t.jsx("div",{className:"fixed inset-0 z-45 flex items-center justify-center p-8 react-ai-agent",style:{pointerEvents:"none"},"data-theme":"dark",children:t.jsxs("div",{className:"relative w-full max-w-3xl rounded-3xl floating-panel",style:{height:"100vh",pointerEvents:"auto"},children:[t.jsx("div",{className:"mt-2 absolute",children:t.jsx(Te,{isDark:!0})}),b&&t.jsx("div",{className:"absolute inset-0 px-4 py-4 rounded-3xl",style:{opacity:p?0:1,transition:"opacity 0.25s ease-out"},children:t.jsx(me,{ref:v,isDark:i,allowEditMessage:s,className:"h-full w-full",...c})}),a]})}),A&&h&&t.jsxs("div",{className:"shader-blur absolute bottom-0 left-0 w-full",style:{height:"150px",transform:"scaleY(-1)",zIndex:99},children:[t.jsx("div",{}),t.jsx("div",{}),t.jsx("div",{}),t.jsx("div",{}),t.jsx("div",{}),t.jsx("div",{})]}),t.jsx("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":C?"dark":"light",children:t.jsx(_e,{ref:k,collapsed:!g,onExpand:R,onSendMessage:T,isStreaming:I,abort:M,variant:g?"pill":"collapsed",placeholder:n,position:r,compact:o,...l})})]})};var qe=e.memo(De);function Oe(e,t){return JSON.stringify({event:e,data:t})}function Pe(e,t,s=!0){return Oe("ai_response",{messageId:e,content:t,isLive:s})}function Be(){return Oe("ai_response_end",{status:"end"})}exports.BaseApiHandler=h,exports.ChatCore=me,exports.ChatHeader=Te,exports.ChatInput=_e,exports.ChatInstanceContext=F,exports.ChatLoadingMock=Y,exports.ChatProvider=q,exports.DefaultApiHandler=g,exports.DefaultPanel=He,exports.FloatingPanel=qe,exports.ForwardingManager=E,exports.LoadingResponse=ne,exports.MessageItem=ae,exports.MessageManager=b,exports.ModeToggle=({modes:e=[],activeMode:s,onModeChange:a,isDark:n=!1})=>e&&e.length>1?t.jsx("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=>t.jsx("button",{onClick:()=>a(e.id),className:`react-ai-agent-mode-button ${s===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 ${s===e.id?"bg-background text-theme-primary":"text-theme-subtle hover:text-theme-tertiary hover:bg-theme-subtle"}\n `,children:t.jsxs("div",{className:"react-ai-agent-mode-button-content flex items-center gap-1.5",children:[t.jsx("span",{className:"react-ai-agent-mode-button-icon",children:e.icon}),t.jsx("span",{className:"react-ai-agent-mode-button-label",children:e.label})]})},e.id))}):null,exports.SessionManager=class{constructor(e){this.tokenManager=e||new y,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()}},exports.ShimmerText=te,exports.StartChat=$,exports.StatusBlock=se,exports.StatusHandlerRegistry=v,exports.StreamService=x,exports.TokenManager=y,exports.WebSocketService=m,exports.adaptHistoryMessages=function(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()}):[]},exports.adaptOpenAIStream=function(e,t){try{if(e.startsWith("data: ")){const s=e.slice(6);if("[DONE]"===s)return Be();const a=JSON.parse(s),n=a.choices[0]?.delta?.content;if(n)return Pe(t,n,!0)}}catch(s){}return null},exports.createAIResponse=Pe,exports.createEndEvent=Be,exports.createErrorEvent=function(e,t=""){return Oe("stream_error",{errorType:"error",error:e,message:t})},exports.createSSEEvent=Oe,exports.createStatusUpdate=function(e,t,s,a=null){return Oe("status_update",{messageId:e,action:t,status:s,data:a})},exports.createThinkingEvent=function(e,t,s=!0){return Oe("ai_thinking",{messageId:e,content:t,isLive:s})},exports.createToolCallEvent=function(e,t,s){return Oe("tool_call",{messageId:e,toolName:t,args:s})},exports.getGlobalForwardingManager=A,exports.getGlobalStatusRegistry=S,exports.parseSSEChunk=function(e){try{const t=e.startsWith("data:")?e.slice(5).trim():e.trim();return t?JSON.parse(t):null}catch(t){return null}},exports.resetGlobalForwardingManager=function(){R=null},exports.setGlobalForwardingManager=function(e){R=e},exports.useChatContext=z,exports.useForwarding=function(t,s,a={}){const n=A(),r=e.useRef(new Map),i=!("string"!=typeof t||s||a&&0!==Object.keys(a).length),o=i?t:a.instanceId||null,c=e.useRef(s),l=e.useRef(a);e.useEffect(()=>{c.current=s,l.current=a}),e.useEffect(()=>{if(i)return;const e=[];if("object"!=typeof t||s){if("string"==typeof t&&s){const s=n.register(t,(...e)=>c.current(...e),{mode:l.current.mode||"dual",animated:!1!==l.current.animated,subscriptionMode:l.current.subscriptionMode||"delta",instanceId:l.current.instanceId||o});e.push(s)}}else Object.entries(t).forEach(([t,s])=>{const a=n.register(t,(...e)=>s.handler(...e),{mode:s.mode||"dual",animated:!1!==s.animated,subscriptionMode:s.subscriptionMode||"delta",instanceId:s.instanceId||o});e.push(a)});return()=>{e.forEach(e=>e())}},[t,n,o]);const d=e.useCallback((e,t,s={})=>{const a={...s,instanceId:s.instanceId||o},i=n.register(e,t,a);return r.current.set(e,i),i},[n,o]),u=e.useCallback(e=>{const t=r.current.get(e);t&&(t(),r.current.delete(e))},[]),h=e.useCallback(()=>n.getActiveSessions(),[n]),g=e.useCallback(e=>n.handlers[e],[n]),m=e.useCallback(()=>Object.entries(n.handlers).map(([e,t])=>({action:e,...t})),[n]);return{register:d,unregister:u,getActiveSessions:h,getHandler:g,getAllHandlers:m}},exports.useStatusSubscription=function(t,s,a={}){const n=e.useContext(F),r=void 0!==a.instanceId?a.instanceId:n,i=r?{instanceId:r}:{},o=S(),c=e.useRef(s);e.useEffect(()=>{c.current=s},[s]),e.useEffect(()=>{const e=[];if("object"==typeof t&&null!==t)Object.entries(t).forEach(([t,s])=>{if("*"===t){const t=o.registerGlobal(s,i);e.push(t)}else{const a=o.register(t,s,i);e.push(a)}});else if("string"==typeof t){const s=e=>c.current?.(e);if("*"===t){const t=o.registerGlobal(s,i);e.push(t)}else{const a=o.register(t,s,i);e.push(a)}}return()=>{e.forEach(e=>e?.())}},[t,r])};
|