@aikaara/chat-sdk 0.1.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aikaara/chat-sdk",
3
- "version": "0.1.4",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "description": "Aikaara Chat SDK — embeddable chat widget and headless client",
6
6
  "license": "MIT",
@@ -34,6 +34,9 @@
34
34
  "preview": "vite preview",
35
35
  "prepare": "git config core.hooksPath .githooks"
36
36
  },
37
+ "dependencies": {
38
+ "mqtt": "^5.10.0"
39
+ },
37
40
  "devDependencies": {
38
41
  "typescript": "^5.7.0",
39
42
  "vite": "^7.3.1",
@@ -1,551 +0,0 @@
1
- class p {
2
- identifier;
3
- callbacks = {};
4
- sendFn;
5
- constructor(t, e) {
6
- this.identifier = t, this.sendFn = e;
7
- }
8
- onReceived(t) {
9
- return this.callbacks.received = t, this;
10
- }
11
- onConnected(t) {
12
- return this.callbacks.connected = t, this;
13
- }
14
- onDisconnected(t) {
15
- return this.callbacks.disconnected = t, this;
16
- }
17
- onRejected(t) {
18
- return this.callbacks.rejected = t, this;
19
- }
20
- perform(t, e = {}) {
21
- this.sendFn({ action: t, ...e });
22
- }
23
- /** @internal */
24
- _notifyReceived(t) {
25
- this.callbacks.received?.(t);
26
- }
27
- /** @internal */
28
- _notifyConnected() {
29
- this.callbacks.connected?.();
30
- }
31
- /** @internal */
32
- _notifyDisconnected() {
33
- this.callbacks.disconnected?.();
34
- }
35
- /** @internal */
36
- _notifyRejected() {
37
- this.callbacks.rejected?.();
38
- }
39
- }
40
- class g {
41
- ws = null;
42
- url;
43
- subscriptions = /* @__PURE__ */ new Map();
44
- welcomePromise = null;
45
- pendingSubscriptions = /* @__PURE__ */ new Map();
46
- constructor(t) {
47
- this.url = t;
48
- }
49
- connect() {
50
- return new Promise((t, e) => {
51
- this.welcomePromise = { resolve: t, reject: e }, this.ws = new WebSocket(this.url), this.ws.onopen = () => {
52
- }, this.ws.onmessage = (s) => {
53
- this.handleMessage(s);
54
- }, this.ws.onerror = () => {
55
- const s = new Error("WebSocket connection error");
56
- this.welcomePromise?.reject(s), this.welcomePromise = null;
57
- }, this.ws.onclose = () => {
58
- this.subscriptions.forEach((s) => s._notifyDisconnected());
59
- };
60
- });
61
- }
62
- disconnect() {
63
- this.ws && (this.ws.onclose = null, this.ws.close(), this.ws = null), this.subscriptions.forEach((t) => t._notifyDisconnected()), this.subscriptions.clear();
64
- }
65
- subscribe(t) {
66
- const e = JSON.stringify(t), s = new p(e, (n) => {
67
- this.send({
68
- command: "message",
69
- identifier: e,
70
- data: JSON.stringify(n)
71
- });
72
- });
73
- return this.subscriptions.set(e, s), this.send({
74
- command: "subscribe",
75
- identifier: e
76
- }), s;
77
- }
78
- subscribeAsync(t) {
79
- const e = this.subscribe(t), s = e.identifier;
80
- return new Promise((n, i) => {
81
- this.pendingSubscriptions.set(s, {
82
- resolve: () => n(e),
83
- reject: i
84
- }), setTimeout(() => {
85
- this.pendingSubscriptions.has(s) && (this.pendingSubscriptions.delete(s), i(new Error(`Subscription timeout for ${s}`)));
86
- }, 1e4);
87
- });
88
- }
89
- unsubscribe(t) {
90
- this.send({
91
- command: "unsubscribe",
92
- identifier: t
93
- }), this.subscriptions.delete(t);
94
- }
95
- perform(t, e, s = {}) {
96
- this.send({
97
- command: "message",
98
- identifier: t,
99
- data: JSON.stringify({ action: e, ...s })
100
- });
101
- }
102
- get isConnected() {
103
- return this.ws?.readyState === WebSocket.OPEN;
104
- }
105
- send(t) {
106
- this.ws?.readyState === WebSocket.OPEN && this.ws.send(JSON.stringify(t));
107
- }
108
- handleMessage(t) {
109
- let e;
110
- try {
111
- e = JSON.parse(t.data);
112
- } catch {
113
- return;
114
- }
115
- switch (e.type) {
116
- case "welcome":
117
- this.welcomePromise?.resolve(), this.welcomePromise = null;
118
- break;
119
- case "ping":
120
- break;
121
- case "confirm_subscription": {
122
- const s = e.identifier;
123
- this.subscriptions.get(s)?._notifyConnected();
124
- const i = this.pendingSubscriptions.get(s);
125
- i && (i.resolve(), this.pendingSubscriptions.delete(s));
126
- break;
127
- }
128
- case "reject_subscription": {
129
- const s = e.identifier;
130
- this.subscriptions.get(s)?._notifyRejected(), this.subscriptions.delete(s);
131
- const i = this.pendingSubscriptions.get(s);
132
- i && (i.reject(new Error(`Subscription rejected: ${s}`)), this.pendingSubscriptions.delete(s));
133
- break;
134
- }
135
- case "disconnect":
136
- this.subscriptions.forEach((s) => s._notifyDisconnected());
137
- break;
138
- default: {
139
- e.identifier && e.message !== void 0 && this.subscriptions.get(e.identifier)?._notifyReceived(e.message);
140
- break;
141
- }
142
- }
143
- }
144
- }
145
- class m {
146
- handlers = /* @__PURE__ */ new Map();
147
- on(t, e) {
148
- return this.handlers.has(t) || this.handlers.set(t, /* @__PURE__ */ new Set()), this.handlers.get(t).add(e), () => this.off(t, e);
149
- }
150
- off(t, e) {
151
- this.handlers.get(t)?.delete(e);
152
- }
153
- emit(t, e) {
154
- this.handlers.get(t)?.forEach((s) => {
155
- try {
156
- s(e);
157
- } catch (n) {
158
- console.error(`Error in event handler for "${t}":`, n);
159
- }
160
- });
161
- }
162
- removeAllListeners() {
163
- this.handlers.clear();
164
- }
165
- }
166
- const f = 1e3, b = 10, y = 400, I = 600, k = "#6366f1", E = 12, T = "system-ui, -apple-system, sans-serif", C = "Type a message...", M = "bottom-right", A = "light", O = { x: 20, y: 20 }, d = "aikaara_conversation_id";
167
- class _ extends m {
168
- client;
169
- config;
170
- state = "disconnected";
171
- reconnectAttempt = 0;
172
- reconnectTimer = null;
173
- constructor(t) {
174
- super(), this.config = t;
175
- const e = this.buildWsUrl(t.baseUrl, t.userToken);
176
- this.client = new g(e);
177
- }
178
- async connect() {
179
- this.setState("connecting");
180
- try {
181
- await this.client.connect(), this.setState("connected"), this.reconnectAttempt = 0;
182
- } catch (t) {
183
- if (this.setState("disconnected"), this.config.reconnect !== !1)
184
- this.scheduleReconnect();
185
- else
186
- throw t;
187
- }
188
- }
189
- async disconnect() {
190
- this.clearReconnectTimer(), this.client.disconnect(), this.setState("disconnected");
191
- }
192
- subscribeToConversation(t) {
193
- return this.client.subscribeAsync({
194
- channel: "ConversationChannel",
195
- conversation_id: t
196
- });
197
- }
198
- sendMessage(t, e) {
199
- const s = JSON.stringify({
200
- channel: "ConversationChannel",
201
- conversation_id: t
202
- });
203
- this.client.perform(s, "send_message", { content: e });
204
- }
205
- sendUserEvent(t, e, s, n) {
206
- const i = JSON.stringify({
207
- channel: "ConversationChannel",
208
- conversation_id: t
209
- });
210
- this.client.perform(i, "send_user_event", {
211
- event_key: e,
212
- ...s && { value: s },
213
- ...n && { source: n }
214
- });
215
- }
216
- get connectionState() {
217
- return this.state;
218
- }
219
- setState(t) {
220
- this.state !== t && (this.state = t, this.emit("connection:state", t));
221
- }
222
- scheduleReconnect() {
223
- const t = this.config.maxReconnectAttempts ?? b;
224
- if (this.reconnectAttempt >= t) {
225
- this.emit("error", new Error("Max reconnection attempts reached"));
226
- return;
227
- }
228
- this.setState("reconnecting");
229
- const s = (this.config.reconnectInterval ?? f) * Math.pow(2, this.reconnectAttempt);
230
- this.reconnectAttempt++, this.reconnectTimer = setTimeout(async () => {
231
- try {
232
- const n = this.buildWsUrl(this.config.baseUrl, this.config.userToken);
233
- this.client = new g(n), await this.connect();
234
- } catch {
235
- }
236
- }, s);
237
- }
238
- clearReconnectTimer() {
239
- this.reconnectTimer && (clearTimeout(this.reconnectTimer), this.reconnectTimer = null);
240
- }
241
- buildWsUrl(t, e) {
242
- if (this.config.wsUrl) {
243
- const n = this.config.wsUrl.includes("?") ? "&" : "?";
244
- return `${this.config.wsUrl}${n}token=${e}`;
245
- }
246
- return `${t.replace(/^http/, "ws")}/cable?token=${e}`;
247
- }
248
- }
249
- class S {
250
- baseUrl;
251
- apiKey;
252
- userToken;
253
- constructor(t, e, s) {
254
- this.baseUrl = t, this.userToken = e, this.apiKey = s;
255
- }
256
- async createConversation(t) {
257
- const e = {
258
- conversation: {
259
- ...t.extUid && { ext_uid: t.extUid },
260
- ...t.systemPromptId && { system_prompt_id: t.systemPromptId },
261
- ...t.channel && { channel: t.channel },
262
- ...t.title && { title: t.title }
263
- }
264
- };
265
- return this.request("POST", "/api/v1/conversations", e);
266
- }
267
- async getMessages(t) {
268
- return (await this.request(
269
- "GET",
270
- `/api/v1/conversations/${t}/messages`
271
- )).map(this.mapMessage);
272
- }
273
- mapMessage(t) {
274
- return {
275
- id: String(t.id),
276
- conversationId: String(t.conversation_id),
277
- role: t.role,
278
- content: t.content || "",
279
- toolCalls: t.tool_calls?.map((e) => ({
280
- id: e.id,
281
- type: e.type,
282
- function: e.function
283
- })),
284
- toolCallResults: t.tool_call_results,
285
- tokensInput: t.tokens_input,
286
- tokensOutput: t.tokens_output,
287
- metadata: t.metadata,
288
- createdAt: t.created_at,
289
- status: "complete"
290
- };
291
- }
292
- async request(t, e, s) {
293
- const n = {
294
- "Content-Type": "application/json",
295
- Accept: "application/json"
296
- };
297
- this.apiKey && (n["X-Api-Key"] = this.apiKey);
298
- const i = `${this.baseUrl}${e}`, l = { method: t, headers: n };
299
- s && (l.body = JSON.stringify(s));
300
- const c = await fetch(i, l);
301
- if (!c.ok) {
302
- const a = await c.text();
303
- let h;
304
- try {
305
- const u = JSON.parse(a);
306
- h = u.error || u.message || a;
307
- } catch {
308
- h = a;
309
- }
310
- throw new Error(`API error ${c.status}: ${h}`);
311
- }
312
- const r = await c.json();
313
- if (r && typeof r == "object" && "success" in r) {
314
- if (!r.success)
315
- throw new Error(`API error: ${r.message || "Request failed"}`);
316
- return r.data;
317
- }
318
- return r;
319
- }
320
- }
321
- class v {
322
- _messages = [];
323
- optimisticCounter = 0;
324
- get messages() {
325
- return [...this._messages];
326
- }
327
- addOptimistic(t, e, s) {
328
- const n = {
329
- id: `optimistic_${++this.optimisticCounter}`,
330
- conversationId: s,
331
- role: t,
332
- content: e,
333
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
334
- status: "sending"
335
- };
336
- return this._messages.push(n), n;
337
- }
338
- confirmOptimistic(t) {
339
- const e = this._messages.find((s) => s.id === t);
340
- e && (e.status = "sent");
341
- }
342
- addStreamingMessage(t) {
343
- const e = {
344
- id: `streaming_${Date.now()}`,
345
- conversationId: t,
346
- role: "assistant",
347
- content: "",
348
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
349
- status: "streaming"
350
- };
351
- return this._messages.push(e), e;
352
- }
353
- updateStreaming(t) {
354
- const e = this._messages.findLast((s) => s.status === "streaming");
355
- e && (e.content = t);
356
- }
357
- appendToStreaming(t) {
358
- const e = this._messages.findLast((s) => s.status === "streaming");
359
- e && (e.content += t);
360
- }
361
- get streamingContent() {
362
- return this._messages.findLast((e) => e.status === "streaming")?.content || "";
363
- }
364
- finalizeStreaming(t) {
365
- const e = this._messages.findLast((s) => s.status === "streaming");
366
- return e && (e.status = "complete", t && (e.tokensInput = t.tokensInput, e.tokensOutput = t.tokensOutput)), e;
367
- }
368
- addMessage(t) {
369
- this._messages.push(t);
370
- }
371
- setMessages(t) {
372
- this._messages = [...t];
373
- }
374
- clear() {
375
- this._messages = [];
376
- }
377
- }
378
- class w {
379
- _conversationId;
380
- persist;
381
- constructor(t, e = !0) {
382
- this.persist = e, this._conversationId = t || this.loadFromStorage();
383
- }
384
- get conversationId() {
385
- return this._conversationId;
386
- }
387
- set conversationId(t) {
388
- this._conversationId = t, this.persist && t && this.saveToStorage(t);
389
- }
390
- clear() {
391
- if (this._conversationId = null, this.persist)
392
- try {
393
- localStorage.removeItem(d);
394
- } catch {
395
- }
396
- }
397
- loadFromStorage() {
398
- if (!this.persist) return null;
399
- try {
400
- return localStorage.getItem(d);
401
- } catch {
402
- return null;
403
- }
404
- }
405
- saveToStorage(t) {
406
- try {
407
- localStorage.setItem(d, t);
408
- } catch {
409
- }
410
- }
411
- }
412
- class U extends m {
413
- connection;
414
- api;
415
- messageStore;
416
- conversationManager;
417
- subscription = null;
418
- config;
419
- constructor(t) {
420
- super(), this.config = t, this.connection = new _(t), this.api = new S(t.baseUrl, t.userToken, t.apiKey), this.messageStore = new v(), this.conversationManager = new w(t.conversationId), this.connection.on("connection:state", (e) => {
421
- this.emit("connection:state", e), this.config.onConnectionStateChange?.(e);
422
- }), this.connection.on("error", (e) => {
423
- this.emit("error", e), this.config.onError?.(e);
424
- });
425
- }
426
- async connect() {
427
- if (await this.connection.connect(), !this.conversationManager.conversationId) {
428
- const t = await this.api.createConversation({
429
- systemPromptId: this.config.systemPromptId,
430
- channel: this.config.channel || "widget",
431
- extUid: this.config.extUid
432
- });
433
- this.conversationManager.conversationId = String(t.id);
434
- }
435
- this.subscription = await this.connection.subscribeToConversation(
436
- this.conversationManager.conversationId
437
- ), this.subscription.onReceived((t) => {
438
- this.handleBroadcast(t);
439
- }), await this.loadHistory();
440
- }
441
- async sendMessage(t) {
442
- const e = this.conversationManager.conversationId;
443
- if (!e)
444
- throw new Error("No active conversation");
445
- const s = this.messageStore.addOptimistic("user", t, e);
446
- this.emit("message:sent", s), this.config.onMessage?.(s), this.connection.sendMessage(e, t);
447
- }
448
- async sendUserEvent(t, e, s) {
449
- const n = this.conversationManager.conversationId;
450
- if (!n)
451
- throw new Error("No active conversation");
452
- this.connection.sendUserEvent(n, t, e, s);
453
- }
454
- async loadHistory() {
455
- const t = this.conversationManager.conversationId;
456
- if (!t) return [];
457
- try {
458
- const e = await this.api.getMessages(t);
459
- return this.messageStore.setMessages(e), e;
460
- } catch {
461
- return [];
462
- }
463
- }
464
- get messages() {
465
- return this.messageStore.messages;
466
- }
467
- get conversationId() {
468
- return this.conversationManager.conversationId;
469
- }
470
- get isConnected() {
471
- return this.connection.connectionState === "connected";
472
- }
473
- async disconnect() {
474
- this.subscription && (this.subscription = null), await this.connection.disconnect();
475
- }
476
- handleBroadcast(t) {
477
- const e = this.conversationManager.conversationId;
478
- switch (t.type) {
479
- case "status": {
480
- const s = t.status;
481
- this.emit("status", s), this.config.onStatusChange?.(s), s === "processing" && this.emit("typing:start", void 0);
482
- break;
483
- }
484
- case "error": {
485
- const s = new Error(t.message || "Unknown error");
486
- this.emit("error", s), this.config.onError?.(s);
487
- break;
488
- }
489
- case "message_start": {
490
- if (t.role === "assistant") {
491
- const s = this.messageStore.addStreamingMessage(e);
492
- this.emit("stream:start", { messageId: s.id }), this.emit("typing:start", void 0);
493
- }
494
- break;
495
- }
496
- case "message_update": {
497
- const s = t.delta || "", n = t.content || "";
498
- n ? this.messageStore.updateStreaming(n) : s && this.messageStore.appendToStreaming(s);
499
- const i = this.messageStore.streamingContent;
500
- this.emit("stream:update", { delta: s, content: i }), this.config.onStreamUpdate?.(s, i);
501
- break;
502
- }
503
- case "message_end": {
504
- const s = t.usage, n = this.messageStore.finalizeStreaming(
505
- s ? { tokensInput: s.tokens_input || 0, tokensOutput: s.tokens_output || 0 } : void 0
506
- );
507
- this.emit("typing:stop", void 0), n && (this.emit("stream:end", {
508
- messageId: n.id,
509
- usage: s ? { tokensInput: s.tokens_input || 0, tokensOutput: s.tokens_output || 0 } : void 0
510
- }), this.emit("message:received", n), this.config.onMessage?.(n));
511
- break;
512
- }
513
- case "message_queued": {
514
- const s = this.messageStore.messages.findLast((n) => n.status === "sending");
515
- s && this.messageStore.confirmOptimistic(s.id);
516
- break;
517
- }
518
- case "tool_execution_start":
519
- case "tool_execution_update":
520
- case "tool_execution_end":
521
- case "agent_start":
522
- case "agent_end":
523
- case "turn_start":
524
- case "turn_end":
525
- case "auto_retry_start":
526
- case "auto_retry_end":
527
- case "cancelled":
528
- this.emit("status", t.type);
529
- break;
530
- }
531
- }
532
- }
533
- export {
534
- g as A,
535
- p as C,
536
- O as D,
537
- m as E,
538
- v as M,
539
- U as a,
540
- S as b,
541
- _ as c,
542
- w as d,
543
- C as e,
544
- E as f,
545
- T as g,
546
- I as h,
547
- y as i,
548
- M as j,
549
- k,
550
- A as l
551
- };
@@ -1 +0,0 @@
1
- "use strict";class p{identifier;callbacks={};sendFn;constructor(t,e){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){this.callbacks.received?.(t)}_notifyConnected(){this.callbacks.connected?.()}_notifyDisconnected(){this.callbacks.disconnected?.()}_notifyRejected(){this.callbacks.rejected?.()}}class l{ws=null;url;subscriptions=new Map;welcomePromise=null;pendingSubscriptions=new Map;constructor(t){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=()=>{const s=new Error("WebSocket connection error");this.welcomePromise?.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 p(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(){return this.ws?.readyState===WebSocket.OPEN}send(t){this.ws?.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify(t))}handleMessage(t){let e;try{e=JSON.parse(t.data)}catch{return}switch(e.type){case"welcome":this.welcomePromise?.resolve(),this.welcomePromise=null;break;case"ping":break;case"confirm_subscription":{const s=e.identifier;this.subscriptions.get(s)?._notifyConnected();const i=this.pendingSubscriptions.get(s);i&&(i.resolve(),this.pendingSubscriptions.delete(s));break}case"reject_subscription":{const s=e.identifier;this.subscriptions.get(s)?._notifyRejected(),this.subscriptions.delete(s);const i=this.pendingSubscriptions.get(s);i&&(i.reject(new Error(`Subscription rejected: ${s}`)),this.pendingSubscriptions.delete(s));break}case"disconnect":this.subscriptions.forEach(s=>s._notifyDisconnected());break;default:{e.identifier&&e.message!==void 0&&this.subscriptions.get(e.identifier)?._notifyReceived(e.message);break}}}}class u{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){this.handlers.get(t)?.delete(e)}emit(t,e){this.handlers.get(t)?.forEach(s=>{try{s(e)}catch(n){console.error(`Error in event handler for "${t}":`,n)}})}removeAllListeners(){this.handlers.clear()}}const v=1e3,w=10,y=400,E=600,T="#6366f1",I=12,A="system-ui, -apple-system, sans-serif",k="Type a message...",C="bottom-right",M="light",U={x:20,y:20},d="aikaara_conversation_id";class f extends u{client;config;state="disconnected";reconnectAttempt=0;reconnectTimer=null;constructor(t){super(),this.config=t;const e=this.buildWsUrl(t.baseUrl,t.userToken);this.client=new l(e)}async connect(){this.setState("connecting");try{await this.client.connect(),this.setState("connected"),this.reconnectAttempt=0}catch(t){if(this.setState("disconnected"),this.config.reconnect!==!1)this.scheduleReconnect();else throw t}}async disconnect(){this.clearReconnectTimer(),this.client.disconnect(),this.setState("disconnected")}subscribeToConversation(t){return this.client.subscribeAsync({channel:"ConversationChannel",conversation_id:t})}sendMessage(t,e){const s=JSON.stringify({channel:"ConversationChannel",conversation_id:t});this.client.perform(s,"send_message",{content:e})}sendUserEvent(t,e,s,n){const i=JSON.stringify({channel:"ConversationChannel",conversation_id:t});this.client.perform(i,"send_user_event",{event_key:e,...s&&{value:s},...n&&{source:n}})}get connectionState(){return this.state}setState(t){this.state!==t&&(this.state=t,this.emit("connection:state",t))}scheduleReconnect(){const t=this.config.maxReconnectAttempts??w;if(this.reconnectAttempt>=t){this.emit("error",new Error("Max reconnection attempts reached"));return}this.setState("reconnecting");const s=(this.config.reconnectInterval??v)*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 l(n),await this.connect()}catch{}},s)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}buildWsUrl(t,e){if(this.config.wsUrl){const n=this.config.wsUrl.includes("?")?"&":"?";return`${this.config.wsUrl}${n}token=${e}`}return`${t.replace(/^http/,"ws")}/cable?token=${e}`}}class _{baseUrl;apiKey;userToken;constructor(t,e,s){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){return{id:String(t.id),conversationId:String(t.conversation_id),role:t.role,content:t.content||"",toolCalls:t.tool_calls?.map(e=>({id:e.id,type:e.type,function:e.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}`,g={method:t,headers:n};s&&(g.body=JSON.stringify(s));const c=await fetch(i,g);if(!c.ok){const a=await c.text();let h;try{const m=JSON.parse(a);h=m.error||m.message||a}catch{h=a}throw new Error(`API error ${c.status}: ${h}`)}const r=await c.json();if(r&&typeof r=="object"&&"success"in r){if(!r.success)throw new Error(`API error: ${r.message||"Request failed"}`);return r.data}return r}}class b{_messages=[];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)}appendToStreaming(t){const e=this._messages.findLast(s=>s.status==="streaming");e&&(e.content+=t)}get streamingContent(){return this._messages.findLast(e=>e.status==="streaming")?.content||""}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 S{_conversationId;persist;constructor(t,e=!0){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(d)}catch{}}loadFromStorage(){if(!this.persist)return null;try{return localStorage.getItem(d)}catch{return null}}saveToStorage(t){try{localStorage.setItem(d,t)}catch{}}}class O extends u{connection;api;messageStore;conversationManager;subscription=null;config;constructor(t){super(),this.config=t,this.connection=new f(t),this.api=new _(t.baseUrl,t.userToken,t.apiKey),this.messageStore=new b,this.conversationManager=new S(t.conversationId),this.connection.on("connection:state",e=>{this.emit("connection:state",e),this.config.onConnectionStateChange?.(e)}),this.connection.on("error",e=>{this.emit("error",e),this.config.onError?.(e)})}async connect(){if(await this.connection.connect(),!this.conversationManager.conversationId){const t=await this.api.createConversation({systemPromptId:this.config.systemPromptId,channel:this.config.channel||"widget",extUid:this.config.extUid});this.conversationManager.conversationId=String(t.id)}this.subscription=await this.connection.subscribeToConversation(this.conversationManager.conversationId),this.subscription.onReceived(t=>{this.handleBroadcast(t)}),await this.loadHistory()}async sendMessage(t){const e=this.conversationManager.conversationId;if(!e)throw new Error("No active conversation");const s=this.messageStore.addOptimistic("user",t,e);this.emit("message:sent",s),this.config.onMessage?.(s),this.connection.sendMessage(e,t)}async sendUserEvent(t,e,s){const n=this.conversationManager.conversationId;if(!n)throw new Error("No active conversation");this.connection.sendUserEvent(n,t,e,s)}async loadHistory(){const t=this.conversationManager.conversationId;if(!t)return[];try{const e=await this.api.getMessages(t);return this.messageStore.setMessages(e),e}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(t){const e=this.conversationManager.conversationId;switch(t.type){case"status":{const s=t.status;this.emit("status",s),this.config.onStatusChange?.(s),s==="processing"&&this.emit("typing:start",void 0);break}case"error":{const s=new Error(t.message||"Unknown error");this.emit("error",s),this.config.onError?.(s);break}case"message_start":{if(t.role==="assistant"){const s=this.messageStore.addStreamingMessage(e);this.emit("stream:start",{messageId:s.id}),this.emit("typing:start",void 0)}break}case"message_update":{const s=t.delta||"",n=t.content||"";n?this.messageStore.updateStreaming(n):s&&this.messageStore.appendToStreaming(s);const i=this.messageStore.streamingContent;this.emit("stream:update",{delta:s,content:i}),this.config.onStreamUpdate?.(s,i);break}case"message_end":{const s=t.usage,n=this.messageStore.finalizeStreaming(s?{tokensInput:s.tokens_input||0,tokensOutput:s.tokens_output||0}:void 0);this.emit("typing:stop",void 0),n&&(this.emit("stream:end",{messageId:n.id,usage:s?{tokensInput:s.tokens_input||0,tokensOutput:s.tokens_output||0}:void 0}),this.emit("message:received",n),this.config.onMessage?.(n));break}case"message_queued":{const s=this.messageStore.messages.findLast(n=>n.status==="sending");s&&this.messageStore.confirmOptimistic(s.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",t.type);break}}}exports.ActionCableClient=l;exports.AikaaraChatClient=O;exports.ApiClient=_;exports.ChannelSubscription=p;exports.ConnectionManager=f;exports.ConversationManager=S;exports.DEFAULT_BORDER_RADIUS=I;exports.DEFAULT_FONT_FAMILY=A;exports.DEFAULT_OFFSET=U;exports.DEFAULT_PLACEHOLDER=k;exports.DEFAULT_POSITION=C;exports.DEFAULT_PRIMARY_COLOR=T;exports.DEFAULT_THEME=M;exports.DEFAULT_WIDGET_HEIGHT=E;exports.DEFAULT_WIDGET_WIDTH=y;exports.EventEmitter=u;exports.MessageStore=b;