@aikaara/chat-sdk 0.1.0 → 0.1.2

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.
@@ -1,8 +1,8 @@
1
- var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o,h,p)=>h in o?te(o,h,{enumerable:!0,configurable:!0,writable:!0,value:p}):o[h]=p;var a=(o,h,p)=>se(o,typeof h!="symbol"?h+"":h,p);class h{constructor(t,e){a(this,"identifier");a(this,"callbacks",{});a(this,"sendFn");this.identifier=t,this.sendFn=e}onReceived(t){return this.callbacks.received=t,this}onConnected(t){return this.callbacks.connected=t,this}onDisconnected(t){return this.callbacks.disconnected=t,this}onRejected(t){return this.callbacks.rejected=t,this}perform(t,e={}){this.sendFn({action:t,...e})}_notifyReceived(t){var e,s;(s=(e=this.callbacks).received)==null||s.call(e,t)}_notifyConnected(){var t,e;(e=(t=this.callbacks).connected)==null||e.call(t)}_notifyDisconnected(){var t,e;(e=(t=this.callbacks).disconnected)==null||e.call(t)}_notifyRejected(){var t,e;(e=(t=this.callbacks).rejected)==null||e.call(t)}}class p{constructor(t){a(this,"ws",null);a(this,"url");a(this,"subscriptions",new Map);a(this,"welcomePromise",null);a(this,"pendingSubscriptions",new Map);this.url=t}connect(){return new Promise((t,e)=>{this.welcomePromise={resolve:t,reject:e},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=s=>{this.handleMessage(s)},this.ws.onerror=()=>{var i;const s=new Error("WebSocket connection error");(i=this.welcomePromise)==null||i.reject(s),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(s=>s._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(t=>t._notifyDisconnected()),this.subscriptions.clear()}subscribe(t){const e=JSON.stringify(t),s=new h(e,i=>{this.send({command:"message",identifier:e,data:JSON.stringify(i)})});return this.subscriptions.set(e,s),this.send({command:"subscribe",identifier:e}),s}subscribeAsync(t){const e=this.subscribe(t),s=e.identifier;return new Promise((i,n)=>{this.pendingSubscriptions.set(s,{resolve:()=>i(e),reject:n}),setTimeout(()=>{this.pendingSubscriptions.has(s)&&(this.pendingSubscriptions.delete(s),n(new Error(`Subscription timeout for ${s}`)))},1e4)})}unsubscribe(t){this.send({command:"unsubscribe",identifier:t}),this.subscriptions.delete(t)}perform(t,e,s={}){this.send({command:"message",identifier:t,data:JSON.stringify({action:e,...s})})}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}send(t){var e;((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}handleMessage(t){var s;let e;try{e=JSON.parse(t.data)}catch{return}switch(e.type){case"welcome":(s=this.welcomePromise)==null||s.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const i=e.identifier,n=this.subscriptions.get(i);n==null||n._notifyConnected();const c=this.pendingSubscriptions.get(i);c&&(c.resolve(),this.pendingSubscriptions.delete(i));break}case"reject_subscription":{const i=e.identifier,n=this.subscriptions.get(i);n==null||n._notifyRejected(),this.subscriptions.delete(i);const c=this.pendingSubscriptions.get(i);c&&(c.reject(new Error(`Subscription rejected: ${i}`)),this.pendingSubscriptions.delete(i));break}case"disconnect":this.subscriptions.forEach(i=>i._notifyDisconnected());break;default:{if(e.identifier&&e.message!==void 0){const i=this.subscriptions.get(e.identifier);i==null||i._notifyReceived(e.message)}break}}}}class y{constructor(){a(this,"handlers",new Map)}on(t,e){return this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.handlers.get(t))==null||s.delete(e)}emit(t,e){var s;(s=this.handlers.get(t))==null||s.forEach(i=>{try{i(e)}catch(n){console.error(`Error in event handler for "${t}":`,n)}})}removeAllListeners(){this.handlers.clear()}}const N=1e3,q=10,P=400,R=600,x="#6366f1",j=12,W="system-ui, -apple-system, sans-serif",S="Type a message...",K="bottom-right",J="light",Y={x:20,y:20},k="aikaara_conversation_id";class _ extends y{constructor(e){super();a(this,"client");a(this,"config");a(this,"state","disconnected");a(this,"reconnectAttempt",0);a(this,"reconnectTimer",null);this.config=e;const s=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new p(s)}async connect(){this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0}catch(e){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw e}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,s){const i=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(i,"send_message",{content:s})}sendUserEvent(e,s,i,n){const c=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(c,"send_user_event",{event_key:s,...i&&{value:i},...n&&{source:n}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??q;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const i=(this.config.reconnectInterval??N)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const n=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new p(n),await this.connect()}catch{}},i)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,s){return`${e.replace(/^http/,"ws")}/cable?token=${s}`}}class C{constructor(t,e,s){a(this,"baseUrl");a(this,"apiKey");a(this,"userToken");this.baseUrl=t,this.userToken=e,this.apiKey=s}async createConversation(t){const e={conversation:{...t.systemPromptId&&{system_prompt_id:t.systemPromptId},...t.channel&&{channel:t.channel},...t.title&&{title:t.title}}};return this.request("POST","/api/v1/conversations",e)}async getMessages(t){return(await this.request("GET",`/api/v1/conversations/${t}/messages`)).map(this.mapMessage)}mapMessage(t){var e;return{id:String(t.id),conversationId:String(t.conversation_id),role:t.role,content:t.content||"",toolCalls:(e=t.tool_calls)==null?void 0:e.map(s=>({id:s.id,type:s.type,function:s.function})),toolCallResults:t.tool_call_results,tokensInput:t.tokens_input,tokensOutput:t.tokens_output,metadata:t.metadata,createdAt:t.created_at,status:"complete"}}async request(t,e,s){const i={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(i["X-Api-Key"]=this.apiKey);const n=`${this.baseUrl}${e}`,c={method:t,headers:i};s&&(c.body=JSON.stringify(s));const d=await fetch(n,c);if(!d.ok){const g=await d.text();let b;try{const v=JSON.parse(g);b=v.error||v.message||g}catch{b=g}throw new Error(`API error ${d.status}: ${b}`)}return d.json()}}class T{constructor(){a(this,"_messages",[]);a(this,"optimisticCounter",0)}get messages(){return[...this._messages]}addOptimistic(t,e,s){const i={id:`optimistic_${++this.optimisticCounter}`,conversationId:s,role:t,content:e,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(i),i}confirmOptimistic(t){const e=this._messages.find(s=>s.id===t);e&&(e.status="sent")}addStreamingMessage(t){const e={id:`streaming_${Date.now()}`,conversationId:t,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(e),e}updateStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");e&&(e.content=t)}finalizeStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");return e&&(e.status="complete",t&&(e.tokensInput=t.tokensInput,e.tokensOutput=t.tokensOutput)),e}addMessage(t){this._messages.push(t)}setMessages(t){this._messages=[...t]}clear(){this._messages=[]}}class M{constructor(t,e=!0){a(this,"_conversationId");a(this,"persist");this.persist=e,this._conversationId=t||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(t){this._conversationId=t,this.persist&&t&&this.saveToStorage(t)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem(k)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(k)}catch{return null}}saveToStorage(t){try{localStorage.setItem(k,t)}catch{}}}class A extends y{constructor(e){super();a(this,"connection");a(this,"api");a(this,"messageStore");a(this,"conversationManager");a(this,"subscription",null);a(this,"config");this.config=e,this.connection=new _(e),this.api=new C(e.baseUrl,e.userToken,e.apiKey),this.messageStore=new T,this.conversationManager=new M(e.conversationId),this.connection.on("connection:state",s=>{var i,n;this.emit("connection:state",s),(n=(i=this.config).onConnectionStateChange)==null||n.call(i,s)}),this.connection.on("error",s=>{var i,n;this.emit("error",s),(n=(i=this.config).onError)==null||n.call(i,s)})}async connect(){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget"});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}async sendMessage(e){var n,c;const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");const i=this.messageStore.addOptimistic("user",e,s);this.emit("message:sent",i),(c=(n=this.config).onMessage)==null||c.call(n,i),this.connection.sendMessage(s,e)}async sendUserEvent(e,s,i){const n=this.conversationManager.conversationId;if(!n)throw new Error("No active conversation");this.connection.sendUserEvent(n,e,s,i)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const s=await this.api.getMessages(e);return this.messageStore.setMessages(s),s}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){return this.connection.connectionState==="connected"}async disconnect(){this.subscription&&(this.subscription=null),await this.connection.disconnect()}handleBroadcast(e){var i,n,c,d,g,b,v,D;const s=this.conversationManager.conversationId;switch(e.type){case"status":{const l=e.status;this.emit("status",l),(n=(i=this.config).onStatusChange)==null||n.call(i,l),l==="processing"&&this.emit("typing:start",void 0);break}case"error":{const l=new Error(e.message||"Unknown error");this.emit("error",l),(d=(c=this.config).onError)==null||d.call(c,l);break}case"message_start":{if(e.role==="assistant"){const l=this.messageStore.addStreamingMessage(s);this.emit("stream:start",{messageId:l.id}),this.emit("typing:start",void 0)}break}case"message_update":{const l=e.content||"",u=e.delta||"";this.messageStore.updateStreaming(l),this.emit("stream:update",{delta:u,content:l}),(b=(g=this.config).onStreamUpdate)==null||b.call(g,u,l);break}case"message_end":{const l=e.usage,u=this.messageStore.finalizeStreaming(l?{tokensInput:l.tokens_input||0,tokensOutput:l.tokens_output||0}:void 0);this.emit("typing:stop",void 0),u&&(this.emit("stream:end",{messageId:u.id,usage:l?{tokensInput:l.tokens_input||0,tokensOutput:l.tokens_output||0}:void 0}),this.emit("message:received",u),(D=(v=this.config).onMessage)==null||D.call(v,u));break}case"message_queued":{const l=this.messageStore.messages.findLast(u=>u.status==="sending");l&&this.messageStore.confirmOptimistic(l.id);break}case"tool_execution_start":case"tool_execution_update":case"tool_execution_end":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class G{constructor(t,e){a(this,"client");a(this,"panel");a(this,"bubble");a(this,"header");a(this,"messageList");a(this,"input");a(this,"errorBanner");a(this,"isOpen",!1);this.client=new A(t),this.bubble=e.querySelector("aikaara-chat-bubble"),this.panel=e.querySelector(".aikaara-panel"),this.header=e.querySelector("aikaara-chat-header"),this.messageList=e.querySelector("aikaara-message-list"),this.input=e.querySelector("aikaara-chat-input"),this.errorBanner=e.querySelector("aikaara-error-banner"),t.welcomeMessage&&this.messageList.setWelcomeMessage(t.welcomeMessage),t.showTimestamps!==void 0&&this.messageList.setShowTimestamps(t.showTimestamps),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble.addEventListener("toggle",()=>{this.togglePanel()}),this.header.addEventListener("close",()=>{this.togglePanel(!1)}),this.input.addEventListener("send",(t=>{this.handleSend(t.detail.content)})),this.client.on("message:sent",t=>{this.messageList.addMessage(t)}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const t=this.client.messages[this.client.messages.length-1];t&&this.messageList.addMessage(t)}),this.client.on("stream:update",({content:t})=>{this.messageList.updateStreamingContent(t)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const t=this.client.messages,e=t[t.length-1];(!e||e.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",t=>{this.header.setStatus(t),t==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):t==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):t==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",t=>{this.errorBanner.show(t.message,5e3)})}async handleSend(t){try{await this.client.sendMessage(t)}catch{this.errorBanner.show("Failed to send message",3e3)}}togglePanel(t){this.isOpen=t!==void 0?t:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200))}}class E extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"controller",null);a(this,"_config",{});this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["base-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url"]}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){var e;(e=this.controller)==null||e.disconnect()}attributeChangedCallback(e,s,i){s!==i&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||J,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||x,position:this.getAttribute("position")||this._config.position||K,width:Number(this.getAttribute("width"))||this._config.width||P,height:Number(this.getAttribute("height"))||this._config.height||R,fontFamily:this._config.fontFamily||W,borderRadius:this._config.borderRadius??j,placeholder:this.getAttribute("placeholder")||this._config.placeholder||S,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showBubble:this._config.showBubble??!0,offset:this._config.offset||Y,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange}}render(){var s,i;const e=this.getConfig();this.shadow.innerHTML=`
1
+ var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o,h,g)=>h in o?te(o,h,{enumerable:!0,configurable:!0,writable:!0,value:g}):o[h]=g;var a=(o,h,g)=>se(o,typeof h!="symbol"?h+"":h,g);class h{constructor(t,e){a(this,"identifier");a(this,"callbacks",{});a(this,"sendFn");this.identifier=t,this.sendFn=e}onReceived(t){return this.callbacks.received=t,this}onConnected(t){return this.callbacks.connected=t,this}onDisconnected(t){return this.callbacks.disconnected=t,this}onRejected(t){return this.callbacks.rejected=t,this}perform(t,e={}){this.sendFn({action:t,...e})}_notifyReceived(t){var e,s;(s=(e=this.callbacks).received)==null||s.call(e,t)}_notifyConnected(){var t,e;(e=(t=this.callbacks).connected)==null||e.call(t)}_notifyDisconnected(){var t,e;(e=(t=this.callbacks).disconnected)==null||e.call(t)}_notifyRejected(){var t,e;(e=(t=this.callbacks).rejected)==null||e.call(t)}}class g{constructor(t){a(this,"ws",null);a(this,"url");a(this,"subscriptions",new Map);a(this,"welcomePromise",null);a(this,"pendingSubscriptions",new Map);this.url=t}connect(){return new Promise((t,e)=>{this.welcomePromise={resolve:t,reject:e},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=s=>{this.handleMessage(s)},this.ws.onerror=()=>{var i;const s=new Error("WebSocket connection error");(i=this.welcomePromise)==null||i.reject(s),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(s=>s._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(t=>t._notifyDisconnected()),this.subscriptions.clear()}subscribe(t){const e=JSON.stringify(t),s=new h(e,i=>{this.send({command:"message",identifier:e,data:JSON.stringify(i)})});return this.subscriptions.set(e,s),this.send({command:"subscribe",identifier:e}),s}subscribeAsync(t){const e=this.subscribe(t),s=e.identifier;return new Promise((i,n)=>{this.pendingSubscriptions.set(s,{resolve:()=>i(e),reject:n}),setTimeout(()=>{this.pendingSubscriptions.has(s)&&(this.pendingSubscriptions.delete(s),n(new Error(`Subscription timeout for ${s}`)))},1e4)})}unsubscribe(t){this.send({command:"unsubscribe",identifier:t}),this.subscriptions.delete(t)}perform(t,e,s={}){this.send({command:"message",identifier:t,data:JSON.stringify({action:e,...s})})}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}send(t){var e;((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}handleMessage(t){var s;let e;try{e=JSON.parse(t.data)}catch{return}switch(e.type){case"welcome":(s=this.welcomePromise)==null||s.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const i=e.identifier,n=this.subscriptions.get(i);n==null||n._notifyConnected();const c=this.pendingSubscriptions.get(i);c&&(c.resolve(),this.pendingSubscriptions.delete(i));break}case"reject_subscription":{const i=e.identifier,n=this.subscriptions.get(i);n==null||n._notifyRejected(),this.subscriptions.delete(i);const c=this.pendingSubscriptions.get(i);c&&(c.reject(new Error(`Subscription rejected: ${i}`)),this.pendingSubscriptions.delete(i));break}case"disconnect":this.subscriptions.forEach(i=>i._notifyDisconnected());break;default:{if(e.identifier&&e.message!==void 0){const i=this.subscriptions.get(e.identifier);i==null||i._notifyReceived(e.message)}break}}}}class k{constructor(){a(this,"handlers",new Map)}on(t,e){return this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.handlers.get(t))==null||s.delete(e)}emit(t,e){var s;(s=this.handlers.get(t))==null||s.forEach(i=>{try{i(e)}catch(n){console.error(`Error in event handler for "${t}":`,n)}})}removeAllListeners(){this.handlers.clear()}}const N=1e3,q=10,P=400,R=600,S="#6366f1",j=12,W="system-ui, -apple-system, sans-serif",_="Type a message...",K="bottom-right",J="light",Y={x:20,y:20},w="aikaara_conversation_id";class C extends k{constructor(e){super();a(this,"client");a(this,"config");a(this,"state","disconnected");a(this,"reconnectAttempt",0);a(this,"reconnectTimer",null);this.config=e;const s=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new g(s)}async connect(){this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0}catch(e){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw e}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,s){const i=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(i,"send_message",{content:s})}sendUserEvent(e,s,i,n){const c=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(c,"send_user_event",{event_key:s,...i&&{value:i},...n&&{source:n}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??q;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const i=(this.config.reconnectInterval??N)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const n=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new g(n),await this.connect()}catch{}},i)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,s){return`${e.replace(/^http/,"ws")}/cable?token=${s}`}}class T{constructor(t,e,s){a(this,"baseUrl");a(this,"apiKey");a(this,"userToken");this.baseUrl=t,this.userToken=e,this.apiKey=s}async createConversation(t){const e={conversation:{...t.extUid&&{ext_uid:t.extUid},...t.systemPromptId&&{system_prompt_id:t.systemPromptId},...t.channel&&{channel:t.channel},...t.title&&{title:t.title}}};return this.request("POST","/api/v1/conversations",e)}async getMessages(t){return(await this.request("GET",`/api/v1/conversations/${t}/messages`)).map(this.mapMessage)}mapMessage(t){var e;return{id:String(t.id),conversationId:String(t.conversation_id),role:t.role,content:t.content||"",toolCalls:(e=t.tool_calls)==null?void 0:e.map(s=>({id:s.id,type:s.type,function:s.function})),toolCallResults:t.tool_call_results,tokensInput:t.tokens_input,tokensOutput:t.tokens_output,metadata:t.metadata,createdAt:t.created_at,status:"complete"}}async request(t,e,s){const i={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(i["X-Api-Key"]=this.apiKey);const n=`${this.baseUrl}${e}`,c={method:t,headers:i};s&&(c.body=JSON.stringify(s));const d=await fetch(n,c);if(!d.ok){const b=await d.text();let m;try{const y=JSON.parse(b);m=y.error||y.message||b}catch{m=b}throw new Error(`API error ${d.status}: ${m}`)}const u=await d.json();if(u&&typeof u=="object"&&"success"in u){if(!u.success)throw new Error(`API error: ${u.message||"Request failed"}`);return u.data}return u}}class M{constructor(){a(this,"_messages",[]);a(this,"optimisticCounter",0)}get messages(){return[...this._messages]}addOptimistic(t,e,s){const i={id:`optimistic_${++this.optimisticCounter}`,conversationId:s,role:t,content:e,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(i),i}confirmOptimistic(t){const e=this._messages.find(s=>s.id===t);e&&(e.status="sent")}addStreamingMessage(t){const e={id:`streaming_${Date.now()}`,conversationId:t,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(e),e}updateStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");e&&(e.content=t)}finalizeStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");return e&&(e.status="complete",t&&(e.tokensInput=t.tokensInput,e.tokensOutput=t.tokensOutput)),e}addMessage(t){this._messages.push(t)}setMessages(t){this._messages=[...t]}clear(){this._messages=[]}}class A{constructor(t,e=!0){a(this,"_conversationId");a(this,"persist");this.persist=e,this._conversationId=t||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(t){this._conversationId=t,this.persist&&t&&this.saveToStorage(t)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem(w)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(w)}catch{return null}}saveToStorage(t){try{localStorage.setItem(w,t)}catch{}}}class E extends k{constructor(e){super();a(this,"connection");a(this,"api");a(this,"messageStore");a(this,"conversationManager");a(this,"subscription",null);a(this,"config");this.config=e,this.connection=new C(e),this.api=new T(e.baseUrl,e.userToken,e.apiKey),this.messageStore=new M,this.conversationManager=new A(e.conversationId),this.connection.on("connection:state",s=>{var i,n;this.emit("connection:state",s),(n=(i=this.config).onConnectionStateChange)==null||n.call(i,s)}),this.connection.on("error",s=>{var i,n;this.emit("error",s),(n=(i=this.config).onError)==null||n.call(i,s)})}async connect(){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}async sendMessage(e){var n,c;const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");const i=this.messageStore.addOptimistic("user",e,s);this.emit("message:sent",i),(c=(n=this.config).onMessage)==null||c.call(n,i),this.connection.sendMessage(s,e)}async sendUserEvent(e,s,i){const n=this.conversationManager.conversationId;if(!n)throw new Error("No active conversation");this.connection.sendUserEvent(n,e,s,i)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const s=await this.api.getMessages(e);return this.messageStore.setMessages(s),s}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){return this.connection.connectionState==="connected"}async disconnect(){this.subscription&&(this.subscription=null),await this.connection.disconnect()}handleBroadcast(e){var i,n,c,d,u,b,m,y;const s=this.conversationManager.conversationId;switch(e.type){case"status":{const l=e.status;this.emit("status",l),(n=(i=this.config).onStatusChange)==null||n.call(i,l),l==="processing"&&this.emit("typing:start",void 0);break}case"error":{const l=new Error(e.message||"Unknown error");this.emit("error",l),(d=(c=this.config).onError)==null||d.call(c,l);break}case"message_start":{if(e.role==="assistant"){const l=this.messageStore.addStreamingMessage(s);this.emit("stream:start",{messageId:l.id}),this.emit("typing:start",void 0)}break}case"message_update":{const l=e.content||"",p=e.delta||"";this.messageStore.updateStreaming(l),this.emit("stream:update",{delta:p,content:l}),(b=(u=this.config).onStreamUpdate)==null||b.call(u,p,l);break}case"message_end":{const l=e.usage,p=this.messageStore.finalizeStreaming(l?{tokensInput:l.tokens_input||0,tokensOutput:l.tokens_output||0}:void 0);this.emit("typing:stop",void 0),p&&(this.emit("stream:end",{messageId:p.id,usage:l?{tokensInput:l.tokens_input||0,tokensOutput:l.tokens_output||0}:void 0}),this.emit("message:received",p),(y=(m=this.config).onMessage)==null||y.call(m,p));break}case"message_queued":{const l=this.messageStore.messages.findLast(p=>p.status==="sending");l&&this.messageStore.confirmOptimistic(l.id);break}case"tool_execution_start":case"tool_execution_update":case"tool_execution_end":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}class G{constructor(t,e){a(this,"client");a(this,"panel");a(this,"bubble");a(this,"header");a(this,"messageList");a(this,"input");a(this,"errorBanner");a(this,"isOpen",!1);this.client=new E(t),this.bubble=e.querySelector("aikaara-chat-bubble"),this.panel=e.querySelector(".aikaara-panel"),this.header=e.querySelector("aikaara-chat-header"),this.messageList=e.querySelector("aikaara-message-list"),this.input=e.querySelector("aikaara-chat-input"),this.errorBanner=e.querySelector("aikaara-error-banner"),t.welcomeMessage&&this.messageList.setWelcomeMessage(t.welcomeMessage),t.showTimestamps!==void 0&&this.messageList.setShowTimestamps(t.showTimestamps),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble.addEventListener("toggle",()=>{this.togglePanel()}),this.header.addEventListener("close",()=>{this.togglePanel(!1)}),this.input.addEventListener("send",(t=>{this.handleSend(t.detail.content)})),this.client.on("message:sent",t=>{this.messageList.addMessage(t)}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const t=this.client.messages[this.client.messages.length-1];t&&this.messageList.addMessage(t)}),this.client.on("stream:update",({content:t})=>{this.messageList.updateStreamingContent(t)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const t=this.client.messages,e=t[t.length-1];(!e||e.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",t=>{this.header.setStatus(t),t==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):t==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):t==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",t=>{this.errorBanner.show(t.message,5e3)})}async handleSend(t){try{await this.client.sendMessage(t)}catch{this.errorBanner.show("Failed to send message",3e3)}}togglePanel(t){this.isOpen=t!==void 0?t:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200))}}class L extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"controller",null);a(this,"_config",{});this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["base-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url"]}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){var e;(e=this.controller)==null||e.disconnect()}attributeChangedCallback(e,s,i){s!==i&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||J,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||S,position:this.getAttribute("position")||this._config.position||K,width:Number(this.getAttribute("width"))||this._config.width||P,height:Number(this.getAttribute("height"))||this._config.height||R,fontFamily:this._config.fontFamily||W,borderRadius:this._config.borderRadius??j,placeholder:this.getAttribute("placeholder")||this._config.placeholder||_,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showBubble:this._config.showBubble??!0,offset:this._config.offset||Y,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange}}render(){var s,i;const e=this.getConfig();this.shadow.innerHTML=`
2
2
  <style>
3
3
  :host {
4
4
  --aikaara-primary: ${e.primaryColor};
5
- --aikaara-primary-hover: ${this.darkenColor(e.primaryColor||x)};
5
+ --aikaara-primary-hover: ${this.darkenColor(e.primaryColor||S)};
6
6
  --aikaara-bg: #ffffff;
7
7
  --aikaara-bg-secondary: #f9fafb;
8
8
  --aikaara-text: #1f2937;
@@ -63,10 +63,10 @@ var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o
63
63
  ${e.avatarUrl?`avatar-url="${e.avatarUrl}"`:""}
64
64
  ></aikaara-chat-header>
65
65
  <aikaara-message-list></aikaara-message-list>
66
- <aikaara-chat-input placeholder="${e.placeholder||S}"></aikaara-chat-input>
66
+ <aikaara-chat-input placeholder="${e.placeholder||_}"></aikaara-chat-input>
67
67
  <aikaara-error-banner></aikaara-error-banner>
68
68
  </div>
69
- `}async initController(){var s;const e=this.getConfig();!e.baseUrl||!e.userToken||((s=this.controller)==null||s.disconnect(),this.controller=new G(e,this.shadow),await this.controller.connect())}darkenColor(e){try{const s=parseInt(e.replace("#",""),16),i=Math.max(0,(s>>16)-20),n=Math.max(0,(s>>8&255)-20),c=Math.max(0,(s&255)-20);return`#${(i<<16|n<<8|c).toString(16).padStart(6,"0")}`}catch{return e}}}class L extends HTMLElement{constructor(){super();a(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){var e;this.render(),(e=this.shadow.querySelector(".bubble"))==null||e.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("toggle",{bubbles:!0,composed:!0}))})}render(){this.shadow.innerHTML=`
69
+ `}async initController(){var s;const e=this.getConfig();!e.baseUrl||!e.userToken||((s=this.controller)==null||s.disconnect(),this.controller=new G(e,this.shadow),await this.controller.connect())}darkenColor(e){try{const s=parseInt(e.replace("#",""),16),i=Math.max(0,(s>>16)-20),n=Math.max(0,(s>>8&255)-20),c=Math.max(0,(s&255)-20);return`#${(i<<16|n<<8|c).toString(16).padStart(6,"0")}`}catch{return e}}}class I extends HTMLElement{constructor(){super();a(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){var e;this.render(),(e=this.shadow.querySelector(".bubble"))==null||e.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("toggle",{bubbles:!0,composed:!0}))})}render(){this.shadow.innerHTML=`
70
70
  <style>
71
71
  .bubble {
72
72
  width: var(--aikaara-bubble-size, 60px);
@@ -101,7 +101,7 @@ var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o
101
101
  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
102
102
  </svg>
103
103
  </button>
104
- `}setIcon(e){const s=this.shadow.querySelector(".bubble");s&&(s.innerHTML=e)}}class I extends HTMLElement{constructor(){super();a(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["title","subtitle","avatar-url","status"]}connectedCallback(){var e;this.render(),(e=this.shadow.querySelector(".close-btn"))==null||e.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("close",{bubbles:!0,composed:!0}))})}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("title")||"Chat",s=this.getAttribute("subtitle")||"",i=this.getAttribute("avatar-url"),n=this.getAttribute("status")||"connected",c=n==="connected"?"#10b981":n==="connecting"||n==="reconnecting"?"#f59e0b":"#ef4444";this.shadow.innerHTML=`
104
+ `}setIcon(e){const s=this.shadow.querySelector(".bubble");s&&(s.innerHTML=e)}}class $ extends HTMLElement{constructor(){super();a(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["title","subtitle","avatar-url","status"]}connectedCallback(){var e;this.render(),(e=this.shadow.querySelector(".close-btn"))==null||e.addEventListener("click",()=>{this.dispatchEvent(new CustomEvent("close",{bubbles:!0,composed:!0}))})}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("title")||"Chat",s=this.getAttribute("subtitle")||"",i=this.getAttribute("avatar-url"),n=this.getAttribute("status")||"connected",c=n==="connected"?"#10b981":n==="connecting"||n==="reconnecting"?"#f59e0b":"#ef4444";this.shadow.innerHTML=`
105
105
  <style>
106
106
  .header {
107
107
  display: flex;
@@ -195,7 +195,7 @@ var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o
195
195
  </svg>
196
196
  </button>
197
197
  </div>
198
- `}setStatus(e){this.setAttribute("status",e)}}function m(r){let t=V(r);return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(e,s,i)=>`<pre><code>${i.trim()}</code></pre>`),t=t.replace(/`([^`]+)`/g,"<code>$1</code>"),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),t=t.replace(/\n/g,"<br>"),t}function V(r){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return r.replace(/[&<>"']/g,e=>t[e])}const X=new Set(["p","br","strong","em","code","pre","a","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div"]),Q={a:new Set(["href","target","rel"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function f(r){const t=document.createElement("template");return t.innerHTML=r,$(t.content),t.innerHTML}function $(r){const t=Array.from(r.childNodes);for(const e of t)if(e.nodeType===Node.ELEMENT_NODE){const s=e,i=s.tagName.toLowerCase();if(!X.has(i)){const d=document.createTextNode(s.textContent||"");r.replaceChild(d,e);continue}const n=Q[i]||new Set,c=Array.from(s.attributes);for(const d of c)n.has(d.name)||s.removeAttribute(d.name);if(s.hasAttribute("href")){const d=s.getAttribute("href")||"";!d.startsWith("http://")&&!d.startsWith("https://")&&!d.startsWith("/")&&s.removeAttribute("href")}$(e)}}class O extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"container");a(this,"welcomeMessage","");a(this,"showTimestamps",!0);this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
198
+ `}setStatus(e){this.setAttribute("status",e)}}function f(r){let t=V(r);return t=t.replace(/```(\w*)\n([\s\S]*?)```/g,(e,s,i)=>`<pre><code>${i.trim()}</code></pre>`),t=t.replace(/`([^`]+)`/g,"<code>$1</code>"),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),t=t.replace(/\n/g,"<br>"),t}function V(r){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return r.replace(/[&<>"']/g,e=>t[e])}const X=new Set(["p","br","strong","em","code","pre","a","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div"]),Q={a:new Set(["href","target","rel"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function v(r){const t=document.createElement("template");return t.innerHTML=r,O(t.content),t.innerHTML}function O(r){const t=Array.from(r.childNodes);for(const e of t)if(e.nodeType===Node.ELEMENT_NODE){const s=e,i=s.tagName.toLowerCase();if(!X.has(i)){const d=document.createTextNode(s.textContent||"");r.replaceChild(d,e);continue}const n=Q[i]||new Set,c=Array.from(s.attributes);for(const d of c)n.has(d.name)||s.removeAttribute(d.name);if(s.hasAttribute("href")){const d=s.getAttribute("href")||"";!d.startsWith("http://")&&!d.startsWith("https://")&&!d.startsWith("/")&&s.removeAttribute("href")}O(e)}}class U extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"container");a(this,"welcomeMessage","");a(this,"showTimestamps",!0);this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
199
199
  <style>
200
200
  .message-list {
201
201
  flex: 1;
@@ -298,7 +298,7 @@ var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o
298
298
  }
299
299
  </style>
300
300
  <div class="message-list"></div>
301
- `,this.container=this.shadow.querySelector(".message-list")}setWelcomeMessage(e){this.welcomeMessage=e}setShowTimestamps(e){this.showTimestamps=e}renderMessages(e){if(this.container){if(this.container.innerHTML="",e.length===0&&this.welcomeMessage){this.container.innerHTML=`<div class="welcome">${f(m(this.welcomeMessage))}</div>`;return}for(const s of e)this.appendMessageElement(s);this.scrollToBottom()}}addMessage(e){const s=this.container.querySelector(".welcome");s&&s.remove(),this.appendMessageElement(e),this.scrollToBottom()}updateStreamingContent(e){const s=this.container.querySelector('[data-streaming="true"] .bubble');s&&(s.innerHTML=f(m(e)),s.classList.add("streaming-cursor"),this.scrollToBottom())}finalizeStreaming(){const e=this.container.querySelector('[data-streaming="true"]');if(e){e.removeAttribute("data-streaming");const s=e.querySelector(".bubble");s==null||s.classList.remove("streaming-cursor")}}showTypingIndicator(){this.removeTypingIndicator();const e=document.createElement("div");e.classList.add("typing-indicator"),e.setAttribute("data-typing","true"),e.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',this.container.appendChild(e),this.scrollToBottom()}removeTypingIndicator(){var e;(e=this.container.querySelector('[data-typing="true"]'))==null||e.remove()}appendMessageElement(e){const s=document.createElement("div");s.classList.add("message-wrap",e.role),e.status==="streaming"&&s.setAttribute("data-streaming","true");const i=document.createElement("div");if(i.classList.add("bubble",e.role),e.role==="user"?i.textContent=e.content:(i.innerHTML=f(m(e.content||"")),e.status==="streaming"&&i.classList.add("streaming-cursor")),s.appendChild(i),this.showTimestamps&&e.createdAt){const n=document.createElement("div");n.classList.add("timestamp"),n.textContent=this.formatTime(e.createdAt),s.appendChild(n)}this.container.appendChild(s)}scrollToBottom(){requestAnimationFrame(()=>{this.container.scrollTop=this.container.scrollHeight})}formatTime(e){try{return new Date(e).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}catch{return""}}}class H extends HTMLElement{constructor(){super();a(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["role","content","timestamp"]}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("role")||"user",s=this.getAttribute("content")||"",i=this.getAttribute("timestamp")||"",n=e==="user"?document.createTextNode(s).textContent||"":f(m(s));this.shadow.innerHTML=`
301
+ `,this.container=this.shadow.querySelector(".message-list")}setWelcomeMessage(e){this.welcomeMessage=e}setShowTimestamps(e){this.showTimestamps=e}renderMessages(e){if(this.container){if(this.container.innerHTML="",e.length===0&&this.welcomeMessage){this.container.innerHTML=`<div class="welcome">${v(f(this.welcomeMessage))}</div>`;return}for(const s of e)this.appendMessageElement(s);this.scrollToBottom()}}addMessage(e){const s=this.container.querySelector(".welcome");s&&s.remove(),this.appendMessageElement(e),this.scrollToBottom()}updateStreamingContent(e){const s=this.container.querySelector('[data-streaming="true"] .bubble');s&&(s.innerHTML=v(f(e)),s.classList.add("streaming-cursor"),this.scrollToBottom())}finalizeStreaming(){const e=this.container.querySelector('[data-streaming="true"]');if(e){e.removeAttribute("data-streaming");const s=e.querySelector(".bubble");s==null||s.classList.remove("streaming-cursor")}}showTypingIndicator(){this.removeTypingIndicator();const e=document.createElement("div");e.classList.add("typing-indicator"),e.setAttribute("data-typing","true"),e.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',this.container.appendChild(e),this.scrollToBottom()}removeTypingIndicator(){var e;(e=this.container.querySelector('[data-typing="true"]'))==null||e.remove()}appendMessageElement(e){const s=document.createElement("div");s.classList.add("message-wrap",e.role),e.status==="streaming"&&s.setAttribute("data-streaming","true");const i=document.createElement("div");if(i.classList.add("bubble",e.role),e.role==="user"?i.textContent=e.content:(i.innerHTML=v(f(e.content||"")),e.status==="streaming"&&i.classList.add("streaming-cursor")),s.appendChild(i),this.showTimestamps&&e.createdAt){const n=document.createElement("div");n.classList.add("timestamp"),n.textContent=this.formatTime(e.createdAt),s.appendChild(n)}this.container.appendChild(s)}scrollToBottom(){requestAnimationFrame(()=>{this.container.scrollTop=this.container.scrollHeight})}formatTime(e){try{return new Date(e).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}catch{return""}}}class H extends HTMLElement{constructor(){super();a(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["role","content","timestamp"]}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("role")||"user",s=this.getAttribute("content")||"",i=this.getAttribute("timestamp")||"",n=e==="user"?document.createTextNode(s).textContent||"":v(f(s));this.shadow.innerHTML=`
302
302
  <style>
303
303
  :host { display: flex; flex-direction: column; }
304
304
  :host([role="user"]) { align-items: flex-end; }
@@ -330,7 +330,7 @@ var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o
330
330
  </style>
331
331
  <div class="bubble ${e}">${n}</div>
332
332
  ${i?`<div class="timestamp">${i}</div>`:""}
333
- `}}class U extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"textarea");a(this,"sendBtn");a(this,"_disabled",!1);this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...";this.shadow.innerHTML=`
333
+ `}}class B extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"textarea");a(this,"sendBtn");a(this,"_disabled",!1);this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...";this.shadow.innerHTML=`
334
334
  <style>
335
335
  .input-container {
336
336
  display: flex;
@@ -388,7 +388,7 @@ var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o
388
388
  </svg>
389
389
  </button>
390
390
  </div>
391
- `,this.textarea=this.shadow.querySelector("textarea"),this.sendBtn=this.shadow.querySelector(".send-btn"),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.sendBtn.disabled=this._disabled||!this.textarea.value.trim()}),this.textarea.addEventListener("keydown",s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),this.handleSend())}),this.sendBtn.addEventListener("click",()=>this.handleSend())}set disabled(e){var s;this._disabled=e,this.textarea&&(this.textarea.disabled=e),this.sendBtn&&(this.sendBtn.disabled=e||!((s=this.textarea)!=null&&s.value.trim()))}get disabled(){return this._disabled}focus(){var e;(e=this.textarea)==null||e.focus()}clear(){this.textarea&&(this.textarea.value="",this.textarea.style.height="auto",this.sendBtn.disabled=!0)}handleSend(){const e=this.textarea.value.trim();!e||this._disabled||(this.dispatchEvent(new CustomEvent("send",{detail:{content:e},bubbles:!0,composed:!0})),this.clear(),this.textarea.focus())}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+"px"}}class B extends HTMLElement{constructor(){super();a(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
391
+ `,this.textarea=this.shadow.querySelector("textarea"),this.sendBtn=this.shadow.querySelector(".send-btn"),this.textarea.addEventListener("input",()=>{this.autoGrow(),this.sendBtn.disabled=this._disabled||!this.textarea.value.trim()}),this.textarea.addEventListener("keydown",s=>{s.key==="Enter"&&!s.shiftKey&&(s.preventDefault(),this.handleSend())}),this.sendBtn.addEventListener("click",()=>this.handleSend())}set disabled(e){var s;this._disabled=e,this.textarea&&(this.textarea.disabled=e),this.sendBtn&&(this.sendBtn.disabled=e||!((s=this.textarea)!=null&&s.value.trim()))}get disabled(){return this._disabled}focus(){var e;(e=this.textarea)==null||e.focus()}clear(){this.textarea&&(this.textarea.value="",this.textarea.style.height="auto",this.sendBtn.disabled=!0)}handleSend(){const e=this.textarea.value.trim();!e||this._disabled||(this.dispatchEvent(new CustomEvent("send",{detail:{content:e},bubbles:!0,composed:!0})),this.clear(),this.textarea.focus())}autoGrow(){this.textarea.style.height="auto",this.textarea.style.height=Math.min(this.textarea.scrollHeight,120)+"px"}}class z extends HTMLElement{constructor(){super();a(this,"shadow");this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
392
392
  <style>
393
393
  :host { display: none; }
394
394
  :host([visible]) { display: block; }
@@ -422,7 +422,7 @@ var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o
422
422
  <span class="dot"></span>
423
423
  <span class="dot"></span>
424
424
  </div>
425
- `}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class z extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"bubble");this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
425
+ `}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}}class F extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"bubble");this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.shadow.innerHTML=`
426
426
  <style>
427
427
  :host {
428
428
  display: flex;
@@ -471,7 +471,7 @@ var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o
471
471
  }
472
472
  </style>
473
473
  <div class="bubble cursor"></div>
474
- `,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=f(m(e)),this.bubble.classList.add("cursor"))}finalize(){var e;(e=this.bubble)==null||e.classList.remove("cursor")}}class F extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"container");a(this,"dismissTimer",null);this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){var e;this.shadow.innerHTML=`
474
+ `,this.bubble=this.shadow.querySelector(".bubble")}updateContent(e){this.bubble&&(this.bubble.innerHTML=v(f(e)),this.bubble.classList.add("cursor"))}finalize(){var e;(e=this.bubble)==null||e.classList.remove("cursor")}}class D extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"container");a(this,"dismissTimer",null);this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){var e;this.shadow.innerHTML=`
475
475
  <style>
476
476
  .banner {
477
477
  display: none;
@@ -499,4 +499,4 @@ var AikaaraChat=(function(o){"use strict";var te=Object.defineProperty;var se=(o
499
499
  <span class="message"></span>
500
500
  <button class="dismiss">Dismiss</button>
501
501
  </div>
502
- `,this.container=this.shadow.querySelector(".banner"),(e=this.shadow.querySelector(".dismiss"))==null||e.addEventListener("click",()=>this.hide())}show(e,s){const i=this.container.querySelector(".message");i&&(i.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),s&&(this.dismissTimer=setTimeout(()=>this.hide(),s))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}function w(){const r=[["aikaara-chat-widget",E],["aikaara-chat-bubble",L],["aikaara-chat-header",I],["aikaara-message-list",O],["aikaara-message-bubble",H],["aikaara-chat-input",U],["aikaara-typing-indicator",B],["aikaara-streaming-message",z],["aikaara-error-banner",F]];for(const[t,e]of r)customElements.get(t)||customElements.define(t,e)}w();function Z(r){w();const t=document.createElement("aikaara-chat-widget"),e={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[s,i]of Object.entries(e)){const n=r[s];n!=null&&t.setAttribute(i,String(n))}return t.configure(r),document.body.appendChild(t),t}function ee(){const r=document.querySelector("aikaara-chat-widget");r&&r.remove()}return o.ActionCableClient=p,o.AikaaraChatBubble=L,o.AikaaraChatClient=A,o.AikaaraChatHeader=I,o.AikaaraChatInput=U,o.AikaaraChatWidget=E,o.AikaaraErrorBanner=F,o.AikaaraMessageBubble=H,o.AikaaraMessageList=O,o.AikaaraStreamingMessage=z,o.AikaaraTypingIndicator=B,o.ApiClient=C,o.ChannelSubscription=h,o.ConnectionManager=_,o.ConversationManager=M,o.EventEmitter=y,o.MessageStore=T,o.mount=Z,o.registerComponents=w,o.unmount=ee,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),o})({});
502
+ `,this.container=this.shadow.querySelector(".banner"),(e=this.shadow.querySelector(".dismiss"))==null||e.addEventListener("click",()=>this.hide())}show(e,s){const i=this.container.querySelector(".message");i&&(i.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),s&&(this.dismissTimer=setTimeout(()=>this.hide(),s))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}function x(){const r=[["aikaara-chat-widget",L],["aikaara-chat-bubble",I],["aikaara-chat-header",$],["aikaara-message-list",U],["aikaara-message-bubble",H],["aikaara-chat-input",B],["aikaara-typing-indicator",z],["aikaara-streaming-message",F],["aikaara-error-banner",D]];for(const[t,e]of r)customElements.get(t)||customElements.define(t,e)}x();function Z(r){x();const t=document.createElement("aikaara-chat-widget"),e={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[s,i]of Object.entries(e)){const n=r[s];n!=null&&t.setAttribute(i,String(n))}return t.configure(r),document.body.appendChild(t),t}function ee(){const r=document.querySelector("aikaara-chat-widget");r&&r.remove()}return o.ActionCableClient=g,o.AikaaraChatBubble=I,o.AikaaraChatClient=E,o.AikaaraChatHeader=$,o.AikaaraChatInput=B,o.AikaaraChatWidget=L,o.AikaaraErrorBanner=D,o.AikaaraMessageBubble=H,o.AikaaraMessageList=U,o.AikaaraStreamingMessage=F,o.AikaaraTypingIndicator=z,o.ApiClient=T,o.ChannelSubscription=h,o.ConnectionManager=C,o.ConversationManager=A,o.EventEmitter=k,o.MessageStore=M,o.mount=Z,o.registerComponents=x,o.unmount=ee,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),o})({});
@@ -181,8 +181,8 @@ class _ {
181
181
  this.handlers.clear();
182
182
  }
183
183
  }
184
- const y = 1e3, w = 10, A = 400, C = 600, O = "#6366f1", U = 12, D = "system-ui, -apple-system, sans-serif", R = "Type a message...", N = "bottom-right", F = "light", L = { x: 20, y: 20 }, m = "aikaara_conversation_id";
185
- class k extends _ {
184
+ const y = 1e3, w = 10, A = 400, C = 600, O = "#6366f1", U = 12, D = "system-ui, -apple-system, sans-serif", R = "Type a message...", N = "bottom-right", P = "light", F = { x: 20, y: 20 }, p = "aikaara_conversation_id";
185
+ class I extends _ {
186
186
  constructor(e) {
187
187
  super();
188
188
  o(this, "client");
@@ -261,7 +261,7 @@ class k extends _ {
261
261
  return `${e.replace(/^http/, "ws")}/cable?token=${s}`;
262
262
  }
263
263
  }
264
- class I {
264
+ class k {
265
265
  constructor(t, e, s) {
266
266
  o(this, "baseUrl");
267
267
  o(this, "apiKey");
@@ -271,6 +271,7 @@ class I {
271
271
  async createConversation(t) {
272
272
  const e = {
273
273
  conversation: {
274
+ ...t.extUid && { ext_uid: t.extUid },
274
275
  ...t.systemPromptId && { system_prompt_id: t.systemPromptId },
275
276
  ...t.channel && { channel: t.channel },
276
277
  ...t.title && { title: t.title }
@@ -312,19 +313,25 @@ class I {
312
313
  this.apiKey && (n["X-Api-Key"] = this.apiKey);
313
314
  const i = `${this.baseUrl}${e}`, c = { method: t, headers: n };
314
315
  s && (c.body = JSON.stringify(s));
315
- const d = await fetch(i, c);
316
- if (!d.ok) {
317
- const l = await d.text();
318
- let u;
316
+ const l = await fetch(i, c);
317
+ if (!l.ok) {
318
+ const u = await l.text();
319
+ let g;
319
320
  try {
320
- const g = JSON.parse(l);
321
- u = g.error || g.message || l;
321
+ const m = JSON.parse(u);
322
+ g = m.error || m.message || u;
322
323
  } catch {
323
- u = l;
324
+ g = u;
324
325
  }
325
- throw new Error(`API error ${d.status}: ${u}`);
326
+ throw new Error(`API error ${l.status}: ${g}`);
326
327
  }
327
- return d.json();
328
+ const h = await l.json();
329
+ if (h && typeof h == "object" && "success" in h) {
330
+ if (!h.success)
331
+ throw new Error(`API error: ${h.message || "Request failed"}`);
332
+ return h.data;
333
+ }
334
+ return h;
328
335
  }
329
336
  }
330
337
  class E {
@@ -394,26 +401,26 @@ class T {
394
401
  clear() {
395
402
  if (this._conversationId = null, this.persist)
396
403
  try {
397
- localStorage.removeItem(m);
404
+ localStorage.removeItem(p);
398
405
  } catch {
399
406
  }
400
407
  }
401
408
  loadFromStorage() {
402
409
  if (!this.persist) return null;
403
410
  try {
404
- return localStorage.getItem(m);
411
+ return localStorage.getItem(p);
405
412
  } catch {
406
413
  return null;
407
414
  }
408
415
  }
409
416
  saveToStorage(t) {
410
417
  try {
411
- localStorage.setItem(m, t);
418
+ localStorage.setItem(p, t);
412
419
  } catch {
413
420
  }
414
421
  }
415
422
  }
416
- class P extends _ {
423
+ class L extends _ {
417
424
  constructor(e) {
418
425
  super();
419
426
  o(this, "connection");
@@ -422,7 +429,7 @@ class P extends _ {
422
429
  o(this, "conversationManager");
423
430
  o(this, "subscription", null);
424
431
  o(this, "config");
425
- this.config = e, this.connection = new k(e), this.api = new I(e.baseUrl, e.userToken, e.apiKey), this.messageStore = new E(), this.conversationManager = new T(e.conversationId), this.connection.on("connection:state", (s) => {
432
+ this.config = e, this.connection = new I(e), this.api = new k(e.baseUrl, e.userToken, e.apiKey), this.messageStore = new E(), this.conversationManager = new T(e.conversationId), this.connection.on("connection:state", (s) => {
426
433
  var n, i;
427
434
  this.emit("connection:state", s), (i = (n = this.config).onConnectionStateChange) == null || i.call(n, s);
428
435
  }), this.connection.on("error", (s) => {
@@ -434,7 +441,8 @@ class P extends _ {
434
441
  if (await this.connection.connect(), !this.conversationManager.conversationId) {
435
442
  const e = await this.api.createConversation({
436
443
  systemPromptId: this.config.systemPromptId,
437
- channel: this.config.channel || "widget"
444
+ channel: this.config.channel || "widget",
445
+ extUid: this.config.extUid
438
446
  });
439
447
  this.conversationManager.conversationId = String(e.id);
440
448
  }
@@ -481,7 +489,7 @@ class P extends _ {
481
489
  this.subscription && (this.subscription = null), await this.connection.disconnect();
482
490
  }
483
491
  handleBroadcast(e) {
484
- var n, i, c, d, l, u, g, p;
492
+ var n, i, c, l, h, u, g, m;
485
493
  const s = this.conversationManager.conversationId;
486
494
  switch (e.type) {
487
495
  case "status": {
@@ -491,7 +499,7 @@ class P extends _ {
491
499
  }
492
500
  case "error": {
493
501
  const r = new Error(e.message || "Unknown error");
494
- this.emit("error", r), (d = (c = this.config).onError) == null || d.call(c, r);
502
+ this.emit("error", r), (l = (c = this.config).onError) == null || l.call(c, r);
495
503
  break;
496
504
  }
497
505
  case "message_start": {
@@ -502,22 +510,22 @@ class P extends _ {
502
510
  break;
503
511
  }
504
512
  case "message_update": {
505
- const r = e.content || "", h = e.delta || "";
506
- this.messageStore.updateStreaming(r), this.emit("stream:update", { delta: h, content: r }), (u = (l = this.config).onStreamUpdate) == null || u.call(l, h, r);
513
+ const r = e.content || "", d = e.delta || "";
514
+ this.messageStore.updateStreaming(r), this.emit("stream:update", { delta: d, content: r }), (u = (h = this.config).onStreamUpdate) == null || u.call(h, d, r);
507
515
  break;
508
516
  }
509
517
  case "message_end": {
510
- const r = e.usage, h = this.messageStore.finalizeStreaming(
518
+ const r = e.usage, d = this.messageStore.finalizeStreaming(
511
519
  r ? { tokensInput: r.tokens_input || 0, tokensOutput: r.tokens_output || 0 } : void 0
512
520
  );
513
- this.emit("typing:stop", void 0), h && (this.emit("stream:end", {
514
- messageId: h.id,
521
+ this.emit("typing:stop", void 0), d && (this.emit("stream:end", {
522
+ messageId: d.id,
515
523
  usage: r ? { tokensInput: r.tokens_input || 0, tokensOutput: r.tokens_output || 0 } : void 0
516
- }), this.emit("message:received", h), (p = (g = this.config).onMessage) == null || p.call(g, h));
524
+ }), this.emit("message:received", d), (m = (g = this.config).onMessage) == null || m.call(g, d));
517
525
  break;
518
526
  }
519
527
  case "message_queued": {
520
- const r = this.messageStore.messages.findLast((h) => h.status === "sending");
528
+ const r = this.messageStore.messages.findLast((d) => d.status === "sending");
521
529
  r && this.messageStore.confirmOptimistic(r.id);
522
530
  break;
523
531
  }
@@ -539,12 +547,12 @@ class P extends _ {
539
547
  export {
540
548
  f as A,
541
549
  S as C,
542
- L as D,
550
+ F as D,
543
551
  _ as E,
544
552
  E as M,
545
- P as a,
546
- I as b,
547
- k as c,
553
+ L as a,
554
+ k as b,
555
+ I as c,
548
556
  T as d,
549
557
  R as e,
550
558
  U as f,
@@ -553,5 +561,5 @@ export {
553
561
  A as i,
554
562
  N as j,
555
563
  O as k,
556
- F as l
564
+ P as l
557
565
  };
@@ -0,0 +1 @@
1
+ "use strict";var E=Object.defineProperty;var T=(a,t,e)=>t in a?E(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e;var o=(a,t,e)=>T(a,typeof t!="symbol"?t+"":t,e);class b{constructor(t,e){o(this,"identifier");o(this,"callbacks",{});o(this,"sendFn");this.identifier=t,this.sendFn=e}onReceived(t){return this.callbacks.received=t,this}onConnected(t){return this.callbacks.connected=t,this}onDisconnected(t){return this.callbacks.disconnected=t,this}onRejected(t){return this.callbacks.rejected=t,this}perform(t,e={}){this.sendFn({action:t,...e})}_notifyReceived(t){var e,s;(s=(e=this.callbacks).received)==null||s.call(e,t)}_notifyConnected(){var t,e;(e=(t=this.callbacks).connected)==null||e.call(t)}_notifyDisconnected(){var t,e;(e=(t=this.callbacks).disconnected)==null||e.call(t)}_notifyRejected(){var t,e;(e=(t=this.callbacks).rejected)==null||e.call(t)}}class f{constructor(t){o(this,"ws",null);o(this,"url");o(this,"subscriptions",new Map);o(this,"welcomePromise",null);o(this,"pendingSubscriptions",new Map);this.url=t}connect(){return new Promise((t,e)=>{this.welcomePromise={resolve:t,reject:e},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=s=>{this.handleMessage(s)},this.ws.onerror=()=>{var n;const s=new Error("WebSocket connection error");(n=this.welcomePromise)==null||n.reject(s),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(s=>s._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(t=>t._notifyDisconnected()),this.subscriptions.clear()}subscribe(t){const e=JSON.stringify(t),s=new b(e,n=>{this.send({command:"message",identifier:e,data:JSON.stringify(n)})});return this.subscriptions.set(e,s),this.send({command:"subscribe",identifier:e}),s}subscribeAsync(t){const e=this.subscribe(t),s=e.identifier;return new Promise((n,i)=>{this.pendingSubscriptions.set(s,{resolve:()=>n(e),reject:i}),setTimeout(()=>{this.pendingSubscriptions.has(s)&&(this.pendingSubscriptions.delete(s),i(new Error(`Subscription timeout for ${s}`)))},1e4)})}unsubscribe(t){this.send({command:"unsubscribe",identifier:t}),this.subscriptions.delete(t)}perform(t,e,s={}){this.send({command:"message",identifier:t,data:JSON.stringify({action:e,...s})})}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}send(t){var e;((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}handleMessage(t){var s;let e;try{e=JSON.parse(t.data)}catch{return}switch(e.type){case"welcome":(s=this.welcomePromise)==null||s.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const n=e.identifier,i=this.subscriptions.get(n);i==null||i._notifyConnected();const c=this.pendingSubscriptions.get(n);c&&(c.resolve(),this.pendingSubscriptions.delete(n));break}case"reject_subscription":{const n=e.identifier,i=this.subscriptions.get(n);i==null||i._notifyRejected(),this.subscriptions.delete(n);const c=this.pendingSubscriptions.get(n);c&&(c.reject(new Error(`Subscription rejected: ${n}`)),this.pendingSubscriptions.delete(n));break}case"disconnect":this.subscriptions.forEach(n=>n._notifyDisconnected());break;default:{if(e.identifier&&e.message!==void 0){const n=this.subscriptions.get(e.identifier);n==null||n._notifyReceived(e.message)}break}}}}class _{constructor(){o(this,"handlers",new Map)}on(t,e){return this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.handlers.get(t))==null||s.delete(e)}emit(t,e){var s;(s=this.handlers.get(t))==null||s.forEach(n=>{try{n(e)}catch(i){console.error(`Error in event handler for "${t}":`,i)}})}removeAllListeners(){this.handlers.clear()}}const I=1e3,A=10,k=400,C=600,M="#6366f1",O=12,U="system-ui, -apple-system, sans-serif",D="Type a message...",F="bottom-right",L="light",R={x:20,y:20},p="aikaara_conversation_id";class S extends _{constructor(e){super();o(this,"client");o(this,"config");o(this,"state","disconnected");o(this,"reconnectAttempt",0);o(this,"reconnectTimer",null);this.config=e;const s=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new f(s)}async connect(){this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0}catch(e){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw e}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,s){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_message",{content:s})}sendUserEvent(e,s,n,i){const c=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(c,"send_user_event",{event_key:s,...n&&{value:n},...i&&{source:i}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??A;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const n=(this.config.reconnectInterval??I)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const i=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new f(i),await this.connect()}catch{}},n)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,s){return`${e.replace(/^http/,"ws")}/cable?token=${s}`}}class v{constructor(t,e,s){o(this,"baseUrl");o(this,"apiKey");o(this,"userToken");this.baseUrl=t,this.userToken=e,this.apiKey=s}async createConversation(t){const e={conversation:{...t.extUid&&{ext_uid:t.extUid},...t.systemPromptId&&{system_prompt_id:t.systemPromptId},...t.channel&&{channel:t.channel},...t.title&&{title:t.title}}};return this.request("POST","/api/v1/conversations",e)}async getMessages(t){return(await this.request("GET",`/api/v1/conversations/${t}/messages`)).map(this.mapMessage)}mapMessage(t){var e;return{id:String(t.id),conversationId:String(t.conversation_id),role:t.role,content:t.content||"",toolCalls:(e=t.tool_calls)==null?void 0:e.map(s=>({id:s.id,type:s.type,function:s.function})),toolCallResults:t.tool_call_results,tokensInput:t.tokens_input,tokensOutput:t.tokens_output,metadata:t.metadata,createdAt:t.created_at,status:"complete"}}async request(t,e,s){const n={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(n["X-Api-Key"]=this.apiKey);const i=`${this.baseUrl}${e}`,c={method:t,headers:n};s&&(c.body=JSON.stringify(s));const l=await fetch(i,c);if(!l.ok){const u=await l.text();let g;try{const m=JSON.parse(u);g=m.error||m.message||u}catch{g=u}throw new Error(`API error ${l.status}: ${g}`)}const h=await l.json();if(h&&typeof h=="object"&&"success"in h){if(!h.success)throw new Error(`API error: ${h.message||"Request failed"}`);return h.data}return h}}class y{constructor(){o(this,"_messages",[]);o(this,"optimisticCounter",0)}get messages(){return[...this._messages]}addOptimistic(t,e,s){const n={id:`optimistic_${++this.optimisticCounter}`,conversationId:s,role:t,content:e,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(n),n}confirmOptimistic(t){const e=this._messages.find(s=>s.id===t);e&&(e.status="sent")}addStreamingMessage(t){const e={id:`streaming_${Date.now()}`,conversationId:t,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(e),e}updateStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");e&&(e.content=t)}finalizeStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");return e&&(e.status="complete",t&&(e.tokensInput=t.tokensInput,e.tokensOutput=t.tokensOutput)),e}addMessage(t){this._messages.push(t)}setMessages(t){this._messages=[...t]}clear(){this._messages=[]}}class w{constructor(t,e=!0){o(this,"_conversationId");o(this,"persist");this.persist=e,this._conversationId=t||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(t){this._conversationId=t,this.persist&&t&&this.saveToStorage(t)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem(p)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(p)}catch{return null}}saveToStorage(t){try{localStorage.setItem(p,t)}catch{}}}class N extends _{constructor(e){super();o(this,"connection");o(this,"api");o(this,"messageStore");o(this,"conversationManager");o(this,"subscription",null);o(this,"config");this.config=e,this.connection=new S(e),this.api=new v(e.baseUrl,e.userToken,e.apiKey),this.messageStore=new y,this.conversationManager=new w(e.conversationId),this.connection.on("connection:state",s=>{var n,i;this.emit("connection:state",s),(i=(n=this.config).onConnectionStateChange)==null||i.call(n,s)}),this.connection.on("error",s=>{var n,i;this.emit("error",s),(i=(n=this.config).onError)==null||i.call(n,s)})}async connect(){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}async sendMessage(e){var i,c;const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");const n=this.messageStore.addOptimistic("user",e,s);this.emit("message:sent",n),(c=(i=this.config).onMessage)==null||c.call(i,n),this.connection.sendMessage(s,e)}async sendUserEvent(e,s,n){const i=this.conversationManager.conversationId;if(!i)throw new Error("No active conversation");this.connection.sendUserEvent(i,e,s,n)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const s=await this.api.getMessages(e);return this.messageStore.setMessages(s),s}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){return this.connection.connectionState==="connected"}async disconnect(){this.subscription&&(this.subscription=null),await this.connection.disconnect()}handleBroadcast(e){var n,i,c,l,h,u,g,m;const s=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),(i=(n=this.config).onStatusChange)==null||i.call(n,r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),(l=(c=this.config).onError)==null||l.call(c,r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(s);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.content||"",d=e.delta||"";this.messageStore.updateStreaming(r),this.emit("stream:update",{delta:d,content:r}),(u=(h=this.config).onStreamUpdate)==null||u.call(h,d,r);break}case"message_end":{const r=e.usage,d=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),d&&(this.emit("stream:end",{messageId:d.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",d),(m=(g=this.config).onMessage)==null||m.call(g,d));break}case"message_queued":{const r=this.messageStore.messages.findLast(d=>d.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":case"tool_execution_update":case"tool_execution_end":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}exports.ActionCableClient=f;exports.AikaaraChatClient=N;exports.ApiClient=v;exports.ChannelSubscription=b;exports.ConnectionManager=S;exports.ConversationManager=w;exports.DEFAULT_BORDER_RADIUS=O;exports.DEFAULT_FONT_FAMILY=U;exports.DEFAULT_OFFSET=R;exports.DEFAULT_PLACEHOLDER=D;exports.DEFAULT_POSITION=F;exports.DEFAULT_PRIMARY_COLOR=M;exports.DEFAULT_THEME=L;exports.DEFAULT_WIDGET_HEIGHT=C;exports.DEFAULT_WIDGET_WIDTH=k;exports.EventEmitter=_;exports.MessageStore=y;
package/dist/headless.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./headless-CjIUiswe.cjs");exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatClient=e.AikaaraChatClient;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./headless-DDmLD-ag.cjs");exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatClient=e.AikaaraChatClient;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;
@@ -57,6 +57,7 @@ export declare class ApiClient {
57
57
  systemPromptId?: number;
58
58
  channel?: string;
59
59
  title?: string;
60
+ extUid?: string;
60
61
  }): Promise<CreateConversationResponse>;
61
62
  getMessages(conversationId: string): Promise<Message[]>;
62
63
  private mapMessage;
@@ -81,6 +82,7 @@ export declare class ChannelSubscription {
81
82
 
82
83
  export declare interface ChatClientConfig extends ConnectionConfig {
83
84
  apiKey?: string;
85
+ extUid?: string;
84
86
  conversationId?: string;
85
87
  systemPromptId?: number;
86
88
  channel?: 'widget' | 'api';
package/dist/headless.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as n, a as t, b as s, C as i, c as o, d as r, E as C, M as l } from "./headless-DzI-CcOZ.mjs";
1
+ import { A as n, a as t, b as s, C as i, c as o, d as r, E as C, M as l } from "./headless-CXRux2Q-.mjs";
2
2
  export {
3
3
  n as ActionCableClient,
4
4
  t as AikaaraChatClient,
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./headless-CjIUiswe.cjs"),a=require("./ui.cjs");function l(t){a.registerComponents();const r=document.createElement("aikaara-chat-widget"),n={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[o,s]of Object.entries(n)){const i=t[o];i!=null&&r.setAttribute(s,String(i))}return r.configure(t),document.body.appendChild(r),r}function u(){const t=document.querySelector("aikaara-chat-widget");t&&t.remove()}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatClient=e.AikaaraChatClient;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.AikaaraChatBubble=a.AikaaraChatBubble;exports.AikaaraChatHeader=a.AikaaraChatHeader;exports.AikaaraChatInput=a.AikaaraChatInput;exports.AikaaraChatWidget=a.AikaaraChatWidget;exports.AikaaraErrorBanner=a.AikaaraErrorBanner;exports.AikaaraMessageBubble=a.AikaaraMessageBubble;exports.AikaaraMessageList=a.AikaaraMessageList;exports.AikaaraStreamingMessage=a.AikaaraStreamingMessage;exports.AikaaraTypingIndicator=a.AikaaraTypingIndicator;exports.registerComponents=a.registerComponents;exports.mount=l;exports.unmount=u;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./headless-DDmLD-ag.cjs"),a=require("./ui.cjs");function l(t){a.registerComponents();const r=document.createElement("aikaara-chat-widget"),n={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[o,s]of Object.entries(n)){const i=t[o];i!=null&&r.setAttribute(s,String(i))}return r.configure(t),document.body.appendChild(r),r}function u(){const t=document.querySelector("aikaara-chat-widget");t&&t.remove()}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatClient=e.AikaaraChatClient;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.AikaaraChatBubble=a.AikaaraChatBubble;exports.AikaaraChatHeader=a.AikaaraChatHeader;exports.AikaaraChatInput=a.AikaaraChatInput;exports.AikaaraChatWidget=a.AikaaraChatWidget;exports.AikaaraErrorBanner=a.AikaaraErrorBanner;exports.AikaaraMessageBubble=a.AikaaraMessageBubble;exports.AikaaraMessageList=a.AikaaraMessageList;exports.AikaaraStreamingMessage=a.AikaaraStreamingMessage;exports.AikaaraTypingIndicator=a.AikaaraTypingIndicator;exports.registerComponents=a.registerComponents;exports.mount=l;exports.unmount=u;
package/dist/index.d.ts CHANGED
@@ -162,6 +162,7 @@ export declare class ApiClient {
162
162
  systemPromptId?: number;
163
163
  channel?: string;
164
164
  title?: string;
165
+ extUid?: string;
165
166
  }): Promise<CreateConversationResponse>;
166
167
  getMessages(conversationId: string): Promise<Message[]>;
167
168
  private mapMessage;
@@ -186,6 +187,7 @@ export declare class ChannelSubscription {
186
187
 
187
188
  export declare interface ChatClientConfig extends ConnectionConfig {
188
189
  apiKey?: string;
190
+ extUid?: string;
189
191
  conversationId?: string;
190
192
  systemPromptId?: number;
191
193
  channel?: 'widget' | 'api';
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as p, a as d, b as g, C as h, c as k, d as C, E as b, M as A } from "./headless-DzI-CcOZ.mjs";
1
+ import { A as p, a as d, b as g, C as h, c as k, d as C, E as b, M as A } from "./headless-CXRux2Q-.mjs";
2
2
  import { registerComponents as n } from "./ui.mjs";
3
3
  import { AikaaraChatBubble as M, AikaaraChatHeader as w, AikaaraChatInput as y, AikaaraChatWidget as v, AikaaraErrorBanner as E, AikaaraMessageBubble as S, AikaaraMessageList as x, AikaaraStreamingMessage as B, AikaaraTypingIndicator as I } from "./ui.mjs";
4
4
  function l(a) {
package/dist/ui.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var T=Object.defineProperty;var L=(s,t,e)=>t in s?T(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var i=(s,t,e)=>L(s,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./headless-CjIUiswe.cjs");class C{constructor(t,e){i(this,"client");i(this,"panel");i(this,"bubble");i(this,"header");i(this,"messageList");i(this,"input");i(this,"errorBanner");i(this,"isOpen",!1);this.client=new o.AikaaraChatClient(t),this.bubble=e.querySelector("aikaara-chat-bubble"),this.panel=e.querySelector(".aikaara-panel"),this.header=e.querySelector("aikaara-chat-header"),this.messageList=e.querySelector("aikaara-message-list"),this.input=e.querySelector("aikaara-chat-input"),this.errorBanner=e.querySelector("aikaara-error-banner"),t.welcomeMessage&&this.messageList.setWelcomeMessage(t.welcomeMessage),t.showTimestamps!==void 0&&this.messageList.setShowTimestamps(t.showTimestamps),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble.addEventListener("toggle",()=>{this.togglePanel()}),this.header.addEventListener("close",()=>{this.togglePanel(!1)}),this.input.addEventListener("send",(t=>{this.handleSend(t.detail.content)})),this.client.on("message:sent",t=>{this.messageList.addMessage(t)}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const t=this.client.messages[this.client.messages.length-1];t&&this.messageList.addMessage(t)}),this.client.on("stream:update",({content:t})=>{this.messageList.updateStreamingContent(t)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const t=this.client.messages,e=t[t.length-1];(!e||e.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",t=>{this.header.setStatus(t),t==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):t==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):t==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",t=>{this.errorBanner.show(t.message,5e3)})}async handleSend(t){try{await this.client.sendMessage(t)}catch{this.errorBanner.show("Failed to send message",3e3)}}togglePanel(t){this.isOpen=t!==void 0?t:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200))}}class b extends HTMLElement{constructor(){super();i(this,"shadow");i(this,"controller",null);i(this,"_config",{});this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["base-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url"]}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){var e;(e=this.controller)==null||e.disconnect()}attributeChangedCallback(e,a,r){a!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||o.DEFAULT_THEME,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||o.DEFAULT_PRIMARY_COLOR,position:this.getAttribute("position")||this._config.position||o.DEFAULT_POSITION,width:Number(this.getAttribute("width"))||this._config.width||o.DEFAULT_WIDGET_WIDTH,height:Number(this.getAttribute("height"))||this._config.height||o.DEFAULT_WIDGET_HEIGHT,fontFamily:this._config.fontFamily||o.DEFAULT_FONT_FAMILY,borderRadius:this._config.borderRadius??o.DEFAULT_BORDER_RADIUS,placeholder:this.getAttribute("placeholder")||this._config.placeholder||o.DEFAULT_PLACEHOLDER,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showBubble:this._config.showBubble??!0,offset:this._config.offset||o.DEFAULT_OFFSET,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange}}render(){var a,r;const e=this.getConfig();this.shadow.innerHTML=`
1
+ "use strict";var T=Object.defineProperty;var L=(s,t,e)=>t in s?T(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var i=(s,t,e)=>L(s,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./headless-DDmLD-ag.cjs");class C{constructor(t,e){i(this,"client");i(this,"panel");i(this,"bubble");i(this,"header");i(this,"messageList");i(this,"input");i(this,"errorBanner");i(this,"isOpen",!1);this.client=new o.AikaaraChatClient(t),this.bubble=e.querySelector("aikaara-chat-bubble"),this.panel=e.querySelector(".aikaara-panel"),this.header=e.querySelector("aikaara-chat-header"),this.messageList=e.querySelector("aikaara-message-list"),this.input=e.querySelector("aikaara-chat-input"),this.errorBanner=e.querySelector("aikaara-error-banner"),t.welcomeMessage&&this.messageList.setWelcomeMessage(t.welcomeMessage),t.showTimestamps!==void 0&&this.messageList.setShowTimestamps(t.showTimestamps),this.wireEvents()}async connect(){try{await this.client.connect(),this.messageList.renderMessages(this.client.messages)}catch{this.errorBanner.show("Failed to connect. Retrying...",5e3)}}async disconnect(){await this.client.disconnect()}wireEvents(){this.bubble.addEventListener("toggle",()=>{this.togglePanel()}),this.header.addEventListener("close",()=>{this.togglePanel(!1)}),this.input.addEventListener("send",(t=>{this.handleSend(t.detail.content)})),this.client.on("message:sent",t=>{this.messageList.addMessage(t)}),this.client.on("stream:start",()=>{this.messageList.removeTypingIndicator();const t=this.client.messages[this.client.messages.length-1];t&&this.messageList.addMessage(t)}),this.client.on("stream:update",({content:t})=>{this.messageList.updateStreamingContent(t)}),this.client.on("stream:end",()=>{this.messageList.finalizeStreaming()}),this.client.on("typing:start",()=>{const t=this.client.messages,e=t[t.length-1];(!e||e.status!=="streaming")&&this.messageList.showTypingIndicator()}),this.client.on("typing:stop",()=>{this.messageList.removeTypingIndicator()}),this.client.on("connection:state",t=>{this.header.setStatus(t),t==="connected"?(this.errorBanner.hide(),this.input.disabled=!1):t==="reconnecting"?(this.errorBanner.show("Connection lost. Reconnecting..."),this.input.disabled=!0):t==="disconnected"&&(this.input.disabled=!0)}),this.client.on("error",t=>{this.errorBanner.show(t.message,5e3)})}async handleSend(t){try{await this.client.sendMessage(t)}catch{this.errorBanner.show("Failed to send message",3e3)}}togglePanel(t){this.isOpen=t!==void 0?t:!this.isOpen,this.isOpen?(this.panel.removeAttribute("hidden"),requestAnimationFrame(()=>{this.panel.classList.remove("entering"),this.panel.classList.add("visible"),this.input.focus()})):(this.panel.classList.remove("visible"),this.panel.classList.add("entering"),setTimeout(()=>{this.panel.setAttribute("hidden","")},200))}}class b extends HTMLElement{constructor(){super();i(this,"shadow");i(this,"controller",null);i(this,"_config",{});this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["base-url","user-token","api-key","title","subtitle","theme","primary-color","position","width","height","placeholder","welcome-message","avatar-url"]}connectedCallback(){this.render(),this.initController()}disconnectedCallback(){var e;(e=this.controller)==null||e.disconnect()}attributeChangedCallback(e,a,r){a!==r&&this.controller&&(this.render(),this.initController())}configure(e){this._config={...this._config,...e}}getConfig(){return{baseUrl:this.getAttribute("base-url")||this._config.baseUrl||"",userToken:this.getAttribute("user-token")||this._config.userToken||"",apiKey:this.getAttribute("api-key")||this._config.apiKey,title:this.getAttribute("title")||this._config.title||"Chat",subtitle:this.getAttribute("subtitle")||this._config.subtitle,theme:this.getAttribute("theme")||this._config.theme||o.DEFAULT_THEME,primaryColor:this.getAttribute("primary-color")||this._config.primaryColor||o.DEFAULT_PRIMARY_COLOR,position:this.getAttribute("position")||this._config.position||o.DEFAULT_POSITION,width:Number(this.getAttribute("width"))||this._config.width||o.DEFAULT_WIDGET_WIDTH,height:Number(this.getAttribute("height"))||this._config.height||o.DEFAULT_WIDGET_HEIGHT,fontFamily:this._config.fontFamily||o.DEFAULT_FONT_FAMILY,borderRadius:this._config.borderRadius??o.DEFAULT_BORDER_RADIUS,placeholder:this.getAttribute("placeholder")||this._config.placeholder||o.DEFAULT_PLACEHOLDER,welcomeMessage:this.getAttribute("welcome-message")||this._config.welcomeMessage,avatarUrl:this.getAttribute("avatar-url")||this._config.avatarUrl,showTimestamps:this._config.showTimestamps??!0,persistConversation:this._config.persistConversation??!0,showBubble:this._config.showBubble??!0,offset:this._config.offset||o.DEFAULT_OFFSET,conversationId:this._config.conversationId,systemPromptId:this._config.systemPromptId,channel:this._config.channel,onMessage:this._config.onMessage,onStatusChange:this._config.onStatusChange,onError:this._config.onError,onStreamUpdate:this._config.onStreamUpdate,onConnectionStateChange:this._config.onConnectionStateChange}}render(){var a,r;const e=this.getConfig();this.shadow.innerHTML=`
2
2
  <style>
3
3
  :host {
4
4
  --aikaara-primary: ${e.primaryColor};
package/dist/ui.d.ts CHANGED
@@ -105,6 +105,7 @@ export declare class AikaaraTypingIndicator extends HTMLElement {
105
105
 
106
106
  declare interface ChatClientConfig extends ConnectionConfig {
107
107
  apiKey?: string;
108
+ extUid?: string;
108
109
  conversationId?: string;
109
110
  systemPromptId?: number;
110
111
  channel?: 'widget' | 'api';
package/dist/ui.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  var u = Object.defineProperty;
2
2
  var g = (s, t, e) => t in s ? u(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
3
3
  var i = (s, t, e) => g(s, typeof t != "symbol" ? t + "" : t, e);
4
- import { a as m, D as f, e as h, f as x, g as k, h as y, i as v, j as w, k as b, l as T } from "./headless-DzI-CcOZ.mjs";
4
+ import { a as m, D as f, e as h, f as x, g as k, h as y, i as v, j as w, k as b, l as T } from "./headless-CXRux2Q-.mjs";
5
5
  class L {
6
6
  constructor(t, e) {
7
7
  i(this, "client");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aikaara/chat-sdk",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "description": "Aikaara Chat SDK — embeddable chat widget and headless client",
6
6
  "license": "MIT",
@@ -31,7 +31,8 @@
31
31
  "build:cdn": "vite build --config vite.iife.config.ts",
32
32
  "build:all": "npm run build && npm run build:cdn",
33
33
  "typecheck": "tsc --noEmit",
34
- "preview": "vite preview"
34
+ "preview": "vite preview",
35
+ "prepare": "git config core.hooksPath .githooks"
35
36
  },
36
37
  "devDependencies": {
37
38
  "typescript": "^5.7.0",
@@ -1 +0,0 @@
1
- "use strict";var w=Object.defineProperty;var T=(a,t,e)=>t in a?w(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e;var o=(a,t,e)=>T(a,typeof t!="symbol"?t+"":t,e);class b{constructor(t,e){o(this,"identifier");o(this,"callbacks",{});o(this,"sendFn");this.identifier=t,this.sendFn=e}onReceived(t){return this.callbacks.received=t,this}onConnected(t){return this.callbacks.connected=t,this}onDisconnected(t){return this.callbacks.disconnected=t,this}onRejected(t){return this.callbacks.rejected=t,this}perform(t,e={}){this.sendFn({action:t,...e})}_notifyReceived(t){var e,s;(s=(e=this.callbacks).received)==null||s.call(e,t)}_notifyConnected(){var t,e;(e=(t=this.callbacks).connected)==null||e.call(t)}_notifyDisconnected(){var t,e;(e=(t=this.callbacks).disconnected)==null||e.call(t)}_notifyRejected(){var t,e;(e=(t=this.callbacks).rejected)==null||e.call(t)}}class p{constructor(t){o(this,"ws",null);o(this,"url");o(this,"subscriptions",new Map);o(this,"welcomePromise",null);o(this,"pendingSubscriptions",new Map);this.url=t}connect(){return new Promise((t,e)=>{this.welcomePromise={resolve:t,reject:e},this.ws=new WebSocket(this.url),this.ws.onopen=()=>{},this.ws.onmessage=s=>{this.handleMessage(s)},this.ws.onerror=()=>{var n;const s=new Error("WebSocket connection error");(n=this.welcomePromise)==null||n.reject(s),this.welcomePromise=null},this.ws.onclose=()=>{this.subscriptions.forEach(s=>s._notifyDisconnected())}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close(),this.ws=null),this.subscriptions.forEach(t=>t._notifyDisconnected()),this.subscriptions.clear()}subscribe(t){const e=JSON.stringify(t),s=new b(e,n=>{this.send({command:"message",identifier:e,data:JSON.stringify(n)})});return this.subscriptions.set(e,s),this.send({command:"subscribe",identifier:e}),s}subscribeAsync(t){const e=this.subscribe(t),s=e.identifier;return new Promise((n,i)=>{this.pendingSubscriptions.set(s,{resolve:()=>n(e),reject:i}),setTimeout(()=>{this.pendingSubscriptions.has(s)&&(this.pendingSubscriptions.delete(s),i(new Error(`Subscription timeout for ${s}`)))},1e4)})}unsubscribe(t){this.send({command:"unsubscribe",identifier:t}),this.subscriptions.delete(t)}perform(t,e,s={}){this.send({command:"message",identifier:t,data:JSON.stringify({action:e,...s})})}get isConnected(){var t;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN}send(t){var e;((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}handleMessage(t){var s;let e;try{e=JSON.parse(t.data)}catch{return}switch(e.type){case"welcome":(s=this.welcomePromise)==null||s.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const n=e.identifier,i=this.subscriptions.get(n);i==null||i._notifyConnected();const c=this.pendingSubscriptions.get(n);c&&(c.resolve(),this.pendingSubscriptions.delete(n));break}case"reject_subscription":{const n=e.identifier,i=this.subscriptions.get(n);i==null||i._notifyRejected(),this.subscriptions.delete(n);const c=this.pendingSubscriptions.get(n);c&&(c.reject(new Error(`Subscription rejected: ${n}`)),this.pendingSubscriptions.delete(n));break}case"disconnect":this.subscriptions.forEach(n=>n._notifyDisconnected());break;default:{if(e.identifier&&e.message!==void 0){const n=this.subscriptions.get(e.identifier);n==null||n._notifyReceived(e.message)}break}}}}class _{constructor(){o(this,"handlers",new Map)}on(t,e){return this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e),()=>this.off(t,e)}off(t,e){var s;(s=this.handlers.get(t))==null||s.delete(e)}emit(t,e){var s;(s=this.handlers.get(t))==null||s.forEach(n=>{try{n(e)}catch(i){console.error(`Error in event handler for "${t}":`,i)}})}removeAllListeners(){this.handlers.clear()}}const I=1e3,A=10,k=400,C=600,M="#6366f1",O=12,D="system-ui, -apple-system, sans-serif",U="Type a message...",F="bottom-right",L="light",R={x:20,y:20},m="aikaara_conversation_id";class S extends _{constructor(e){super();o(this,"client");o(this,"config");o(this,"state","disconnected");o(this,"reconnectAttempt",0);o(this,"reconnectTimer",null);this.config=e;const s=this.buildWsUrl(e.baseUrl,e.userToken);this.client=new p(s)}async connect(){this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0}catch(e){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw e}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(e){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:e})}sendMessage(e,s){const n=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(n,"send_message",{content:s})}sendUserEvent(e,s,n,i){const c=JSON.stringify({channel:"ConversationChannel",conversation_id:e});this.client.perform(c,"send_user_event",{event_key:s,...n&&{value:n},...i&&{source:i}})}get connectionState(){return this.state}setState(e){this.state!==e&&(this.state=e,this.emit("connection:state",e))}scheduleReconnect(){const e=this.config.maxReconnectAttempts??A;if(this.reconnectAttempt>=e){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const n=(this.config.reconnectInterval??I)*Math.pow(2,this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{try{const i=this.buildWsUrl(this.config.baseUrl,this.config.userToken);this.client=new p(i),await this.connect()}catch{}},n)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(e,s){return`${e.replace(/^http/,"ws")}/cable?token=${s}`}}class v{constructor(t,e,s){o(this,"baseUrl");o(this,"apiKey");o(this,"userToken");this.baseUrl=t,this.userToken=e,this.apiKey=s}async createConversation(t){const e={conversation:{...t.systemPromptId&&{system_prompt_id:t.systemPromptId},...t.channel&&{channel:t.channel},...t.title&&{title:t.title}}};return this.request("POST","/api/v1/conversations",e)}async getMessages(t){return(await this.request("GET",`/api/v1/conversations/${t}/messages`)).map(this.mapMessage)}mapMessage(t){var e;return{id:String(t.id),conversationId:String(t.conversation_id),role:t.role,content:t.content||"",toolCalls:(e=t.tool_calls)==null?void 0:e.map(s=>({id:s.id,type:s.type,function:s.function})),toolCallResults:t.tool_call_results,tokensInput:t.tokens_input,tokensOutput:t.tokens_output,metadata:t.metadata,createdAt:t.created_at,status:"complete"}}async request(t,e,s){const n={"Content-Type":"application/json",Accept:"application/json"};this.apiKey&&(n["X-Api-Key"]=this.apiKey);const i=`${this.baseUrl}${e}`,c={method:t,headers:n};s&&(c.body=JSON.stringify(s));const d=await fetch(i,c);if(!d.ok){const l=await d.text();let u;try{const g=JSON.parse(l);u=g.error||g.message||l}catch{u=l}throw new Error(`API error ${d.status}: ${u}`)}return d.json()}}class y{constructor(){o(this,"_messages",[]);o(this,"optimisticCounter",0)}get messages(){return[...this._messages]}addOptimistic(t,e,s){const n={id:`optimistic_${++this.optimisticCounter}`,conversationId:s,role:t,content:e,createdAt:new Date().toISOString(),status:"sending"};return this._messages.push(n),n}confirmOptimistic(t){const e=this._messages.find(s=>s.id===t);e&&(e.status="sent")}addStreamingMessage(t){const e={id:`streaming_${Date.now()}`,conversationId:t,role:"assistant",content:"",createdAt:new Date().toISOString(),status:"streaming"};return this._messages.push(e),e}updateStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");e&&(e.content=t)}finalizeStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");return e&&(e.status="complete",t&&(e.tokensInput=t.tokensInput,e.tokensOutput=t.tokensOutput)),e}addMessage(t){this._messages.push(t)}setMessages(t){this._messages=[...t]}clear(){this._messages=[]}}class E{constructor(t,e=!0){o(this,"_conversationId");o(this,"persist");this.persist=e,this._conversationId=t||this.loadFromStorage()}get conversationId(){return this._conversationId}set conversationId(t){this._conversationId=t,this.persist&&t&&this.saveToStorage(t)}clear(){if(this._conversationId=null,this.persist)try{localStorage.removeItem(m)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(m)}catch{return null}}saveToStorage(t){try{localStorage.setItem(m,t)}catch{}}}class N extends _{constructor(e){super();o(this,"connection");o(this,"api");o(this,"messageStore");o(this,"conversationManager");o(this,"subscription",null);o(this,"config");this.config=e,this.connection=new S(e),this.api=new v(e.baseUrl,e.userToken,e.apiKey),this.messageStore=new y,this.conversationManager=new E(e.conversationId),this.connection.on("connection:state",s=>{var n,i;this.emit("connection:state",s),(i=(n=this.config).onConnectionStateChange)==null||i.call(n,s)}),this.connection.on("error",s=>{var n,i;this.emit("error",s),(i=(n=this.config).onError)==null||i.call(n,s)})}async connect(){if(await this.connection.connect(),!this.conversationManager.conversationId){const e=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget"});this.conversationManager.conversationId=String(e.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(e=>{this.handleBroadcast(e)}),await this.loadHistory()}async sendMessage(e){var i,c;const s=this.conversationManager.conversationId;if(!s)throw new Error("No active conversation");const n=this.messageStore.addOptimistic("user",e,s);this.emit("message:sent",n),(c=(i=this.config).onMessage)==null||c.call(i,n),this.connection.sendMessage(s,e)}async sendUserEvent(e,s,n){const i=this.conversationManager.conversationId;if(!i)throw new Error("No active conversation");this.connection.sendUserEvent(i,e,s,n)}async loadHistory(){const e=this.conversationManager.conversationId;if(!e)return[];try{const s=await this.api.getMessages(e);return this.messageStore.setMessages(s),s}catch{return[]}}get messages(){return this.messageStore.messages}get conversationId(){return this.conversationManager.conversationId}get isConnected(){return this.connection.connectionState==="connected"}async disconnect(){this.subscription&&(this.subscription=null),await this.connection.disconnect()}handleBroadcast(e){var n,i,c,d,l,u,g,f;const s=this.conversationManager.conversationId;switch(e.type){case"status":{const r=e.status;this.emit("status",r),(i=(n=this.config).onStatusChange)==null||i.call(n,r),r==="processing"&&this.emit("typing:start",void 0);break}case"error":{const r=new Error(e.message||"Unknown error");this.emit("error",r),(d=(c=this.config).onError)==null||d.call(c,r);break}case"message_start":{if(e.role==="assistant"){const r=this.messageStore.addStreamingMessage(s);this.emit("stream:start",{messageId:r.id}),this.emit("typing:start",void 0)}break}case"message_update":{const r=e.content||"",h=e.delta||"";this.messageStore.updateStreaming(r),this.emit("stream:update",{delta:h,content:r}),(u=(l=this.config).onStreamUpdate)==null||u.call(l,h,r);break}case"message_end":{const r=e.usage,h=this.messageStore.finalizeStreaming(r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0);this.emit("typing:stop",void 0),h&&(this.emit("stream:end",{messageId:h.id,usage:r?{tokensInput:r.tokens_input||0,tokensOutput:r.tokens_output||0}:void 0}),this.emit("message:received",h),(f=(g=this.config).onMessage)==null||f.call(g,h));break}case"message_queued":{const r=this.messageStore.messages.findLast(h=>h.status==="sending");r&&this.messageStore.confirmOptimistic(r.id);break}case"tool_execution_start":case"tool_execution_update":case"tool_execution_end":case"agent_start":case"agent_end":case"turn_start":case"turn_end":case"auto_retry_start":case"auto_retry_end":case"cancelled":this.emit("status",e.type);break}}}exports.ActionCableClient=p;exports.AikaaraChatClient=N;exports.ApiClient=v;exports.ChannelSubscription=b;exports.ConnectionManager=S;exports.ConversationManager=E;exports.DEFAULT_BORDER_RADIUS=O;exports.DEFAULT_FONT_FAMILY=D;exports.DEFAULT_OFFSET=R;exports.DEFAULT_PLACEHOLDER=U;exports.DEFAULT_POSITION=F;exports.DEFAULT_PRIMARY_COLOR=M;exports.DEFAULT_THEME=L;exports.DEFAULT_WIDGET_HEIGHT=C;exports.DEFAULT_WIDGET_WIDTH=k;exports.EventEmitter=_;exports.MessageStore=y;