@aikaara/chat-sdk 0.2.0 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -33,14 +33,45 @@ export declare type AgentEventType = 'status' | 'error' | 'agent_start' | 'agent
33
33
 
34
34
  export declare class AikaaraChatClient extends EventEmitter<ChatEvents> {
35
35
  private connection;
36
+ private tiledesk;
36
37
  private api;
37
38
  private messageStore;
38
39
  private conversationManager;
39
40
  private subscription;
40
41
  private config;
41
- constructor(config: ChatClientConfig);
42
+ private mode;
43
+ private uploadAdapter;
44
+ private historyAdapter;
45
+ private tiledeskUnsubs;
46
+ constructor(config: ChatClientConfig, opts?: {
47
+ uploadAdapter?: UploadAdapter;
48
+ historyAdapter?: ConversationHistoryAdapter;
49
+ });
50
+ private usesAikaara;
51
+ private usesTiledesk;
52
+ private initTiledeskTransport;
42
53
  connect(): Promise<void>;
43
- sendMessage(content: string): Promise<void>;
54
+ private hydrateTiledeskHistory;
55
+ sendMessage(content: string, opts?: {
56
+ attributes?: Record<string, unknown>;
57
+ metadata?: Record<string, unknown>;
58
+ }): Promise<void>;
59
+ /**
60
+ * Upload a file via the configured UploadAdapter (client-side: file goes
61
+ * to the tenant's own backend, never through Aikaara). Then publish the
62
+ * Tiledesk file-message envelope so hooks_controller picks it up.
63
+ */
64
+ sendFile(file: File | Blob, opts?: {
65
+ caption?: string;
66
+ }): Promise<void>;
67
+ /**
68
+ * Trigger Tiledesk's CHAT_INITIATED event — required to kick off a bot flow
69
+ * for newly-created Tiledesk request groups.
70
+ */
71
+ initiateTiledeskChat(extraAttributes?: Record<string, unknown>): void;
72
+ /** Mark a Tiledesk message as read (publishes status=300 update). */
73
+ markTiledeskRead(messageId: string): void;
74
+ setUploadAdapter(adapter: UploadAdapter): void;
44
75
  sendUserEvent(eventKey: string, value?: object, source?: string): Promise<void>;
45
76
  loadHistory(): Promise<Message[]>;
46
77
  get messages(): Message[];
@@ -65,6 +96,85 @@ export declare class AikaaraChatClient extends EventEmitter<ChatEvents> {
65
96
  */
66
97
  setContext(context: AppContext): Promise<void>;
67
98
  disconnect(): Promise<void>;
99
+ private handleTiledeskMessage;
100
+ private handleTiledeskStatusUpdate;
101
+ /**
102
+ * Parse structured action results from tool execution output.
103
+ * When the agent calls tools like `edit_current_entity`, `save_current_entity`,
104
+ * `navigate_to`, or `test_tool_by_id`, the result contains an action payload
105
+ * that the SDK emits as a typed event for the host app to handle.
106
+ */
107
+ private parseActionResult;
108
+ private handleBroadcast;
109
+ }
110
+
111
+ declare class AikaaraChatClient_2 extends EventEmitter_2<ChatEvents_2> {
112
+ private connection;
113
+ private tiledesk;
114
+ private api;
115
+ private messageStore;
116
+ private conversationManager;
117
+ private subscription;
118
+ private config;
119
+ private mode;
120
+ private uploadAdapter;
121
+ private historyAdapter;
122
+ private tiledeskUnsubs;
123
+ constructor(config: ChatClientConfig_2, opts?: {
124
+ uploadAdapter?: UploadAdapter_2;
125
+ historyAdapter?: ConversationHistoryAdapter_2;
126
+ });
127
+ private usesAikaara;
128
+ private usesTiledesk;
129
+ private initTiledeskTransport;
130
+ connect(): Promise<void>;
131
+ private hydrateTiledeskHistory;
132
+ sendMessage(content: string, opts?: {
133
+ attributes?: Record<string, unknown>;
134
+ metadata?: Record<string, unknown>;
135
+ }): Promise<void>;
136
+ /**
137
+ * Upload a file via the configured UploadAdapter (client-side: file goes
138
+ * to the tenant's own backend, never through Aikaara). Then publish the
139
+ * Tiledesk file-message envelope so hooks_controller picks it up.
140
+ */
141
+ sendFile(file: File | Blob, opts?: {
142
+ caption?: string;
143
+ }): Promise<void>;
144
+ /**
145
+ * Trigger Tiledesk's CHAT_INITIATED event — required to kick off a bot flow
146
+ * for newly-created Tiledesk request groups.
147
+ */
148
+ initiateTiledeskChat(extraAttributes?: Record<string, unknown>): void;
149
+ /** Mark a Tiledesk message as read (publishes status=300 update). */
150
+ markTiledeskRead(messageId: string): void;
151
+ setUploadAdapter(adapter: UploadAdapter_2): void;
152
+ sendUserEvent(eventKey: string, value?: object, source?: string): Promise<void>;
153
+ loadHistory(): Promise<Message_2[]>;
154
+ get messages(): Message_2[];
155
+ get conversationId(): string | null;
156
+ get isConnected(): boolean;
157
+ /**
158
+ * Update the agent's context with information about the host app's current state.
159
+ * Call this on route changes so the agent knows what page/entity the user is viewing.
160
+ *
161
+ * The context is stored in conversation metadata and interpolated into the system prompt.
162
+ *
163
+ * @example
164
+ * ```typescript
165
+ * // On route change
166
+ * client.setContext({
167
+ * currentPage: '/products/42',
168
+ * entityType: 'product',
169
+ * entityId: '42',
170
+ * availableRoutes: { products: '/products', orders: '/orders' },
171
+ * });
172
+ * ```
173
+ */
174
+ setContext(context: AppContext_2): Promise<void>;
175
+ disconnect(): Promise<void>;
176
+ private handleTiledeskMessage;
177
+ private handleTiledeskStatusUpdate;
68
178
  /**
69
179
  * Parse structured action results from tool execution output.
70
180
  * When the agent calls tools like `edit_current_entity`, `save_current_entity`,
@@ -75,6 +185,26 @@ export declare class AikaaraChatClient extends EventEmitter<ChatEvents> {
75
185
  private handleBroadcast;
76
186
  }
77
187
 
188
+ declare class AikaaraChatWidget extends HTMLElement {
189
+ private shadow;
190
+ private controller;
191
+ private _config;
192
+ static get observedAttributes(): string[];
193
+ constructor();
194
+ connectedCallback(): void;
195
+ disconnectedCallback(): void;
196
+ attributeChangedCallback(_name: string, oldVal: string, newVal: string): void;
197
+ configure(config: Partial<WidgetConfig>): void;
198
+ private getConfig;
199
+ setUploadAdapter(adapter: UploadAdapter): void;
200
+ setHistoryAdapter(adapter: ConversationHistoryAdapter): void;
201
+ private render;
202
+ private initController;
203
+ sendUserEvent(eventKey: string, value?: Record<string, unknown>, source?: string): void;
204
+ getClient(): AikaaraChatClient_2 | null;
205
+ private darkenColor;
206
+ }
207
+
78
208
  export declare class ApiClient {
79
209
  private baseUrl;
80
210
  private apiKey?;
@@ -108,6 +238,21 @@ export declare interface AppContext {
108
238
  custom?: Record<string, unknown>;
109
239
  }
110
240
 
241
+ declare interface AppContext_2 {
242
+ /** Current page/route path in the host app (e.g., '/products/42') */
243
+ currentPage: string;
244
+ /** Entity type on the current page (e.g., 'product', 'agent') */
245
+ entityType?: string;
246
+ /** Entity ID on the current page */
247
+ entityId?: string | number;
248
+ /** Project/workspace ID if applicable */
249
+ projectId?: string | number;
250
+ /** Routes the agent can navigate to — map of label → path */
251
+ availableRoutes?: Record<string, string>;
252
+ /** Additional context for the agent (e.g., form field names, entity schema) */
253
+ custom?: Record<string, unknown>;
254
+ }
255
+
111
256
  export declare class ChannelSubscription {
112
257
  readonly identifier: string;
113
258
  private callbacks;
@@ -131,11 +276,77 @@ export declare interface ChatClientConfig extends ConnectionConfig {
131
276
  conversationId?: string;
132
277
  systemPromptId?: number;
133
278
  channel?: 'widget' | 'api' | 'sidekick';
279
+ /**
280
+ * Transport selection.
281
+ * - `aikaara` (default): ActionCable to Aikaara Rails (AI streaming).
282
+ * - `tiledesk`: MQTT direct to a self-hosted Tiledesk + chat21 stack.
283
+ * - `dual`: both — Aikaara cable for AI, Tiledesk MQTT for live-agent + file events.
284
+ */
285
+ transport?: TransportMode;
286
+ /**
287
+ * Tiledesk-side identity. Required when `transport` is `tiledesk` or `dual`.
288
+ * `userId` here is the Tiledesk user `_id` and is also used as the SDK conversation
289
+ * subject — Aikaara conversations bound to this user via ext_uid mapping.
290
+ */
291
+ tiledeskIdentity?: {
292
+ userId: string;
293
+ userName?: string;
294
+ departmentId?: string;
295
+ senderFullname?: string;
296
+ };
297
+ /**
298
+ * Tenant-level defaults merged into the `action` object of every template
299
+ * postback (e.g. submit-action click). Useful for app-specific keys like
300
+ * `serviceType: 'ITR'` that the bot expects on every form submission.
301
+ * Per-submit values from the form take precedence over these defaults.
302
+ */
303
+ templateActionAttributes?: Record<string, unknown>;
134
304
  onMessage?: (message: Message) => void;
135
305
  onStatusChange?: (status: string) => void;
136
306
  onError?: (error: Error) => void;
137
307
  onStreamUpdate?: (delta: string, fullContent: string) => void;
138
308
  onConnectionStateChange?: (state: ConnectionState) => void;
309
+ onTemplateMessage?: (template: TemplateMessageEvent) => void;
310
+ }
311
+
312
+ declare interface ChatClientConfig_2 extends ConnectionConfig_2 {
313
+ apiKey?: string;
314
+ authToken?: string;
315
+ extUid?: string;
316
+ conversationId?: string;
317
+ systemPromptId?: number;
318
+ channel?: 'widget' | 'api' | 'sidekick';
319
+ /**
320
+ * Transport selection.
321
+ * - `aikaara` (default): ActionCable to Aikaara Rails (AI streaming).
322
+ * - `tiledesk`: MQTT direct to a self-hosted Tiledesk + chat21 stack.
323
+ * - `dual`: both — Aikaara cable for AI, Tiledesk MQTT for live-agent + file events.
324
+ */
325
+ transport?: TransportMode_2;
326
+ /**
327
+ * Tiledesk-side identity. Required when `transport` is `tiledesk` or `dual`.
328
+ * `userId` here is the Tiledesk user `_id` and is also used as the SDK conversation
329
+ * subject — Aikaara conversations bound to this user via ext_uid mapping.
330
+ */
331
+ tiledeskIdentity?: {
332
+ userId: string;
333
+ userName?: string;
334
+ departmentId?: string;
335
+ senderFullname?: string;
336
+ };
337
+ /**
338
+ * Tenant-level defaults merged into the `action` object of every template
339
+ * postback (e.g. submit-action click). Useful for app-specific keys like
340
+ * `serviceType: 'ITR'` that the bot expects on every form submission.
341
+ * Per-submit values from the form take precedence over these defaults.
342
+ */
343
+ templateActionAttributes?: Record<string, unknown>;
344
+ onMessage?: (message: Message_2) => void;
345
+ onStatusChange?: (status: string) => void;
346
+ onError?: (error: Error) => void;
347
+ onStreamUpdate?: (delta: string, fullContent: string) => void;
348
+ onConnectionStateChange?: (state: ConnectionState_2) => void;
349
+ onTemplateMessage?: (template: TemplateMessageEvent_2) => void;
139
350
  }
140
351
 
141
352
  export declare interface ChatEvents {
@@ -176,6 +387,46 @@ export declare interface ChatEvents {
176
387
  };
177
388
  }
178
389
 
390
+ declare interface ChatEvents_2 {
391
+ 'connection:state': ConnectionState_2;
392
+ 'message:received': Message_2;
393
+ 'message:updated': Message_2;
394
+ 'message:sent': Message_2;
395
+ 'stream:start': {
396
+ messageId: string;
397
+ };
398
+ 'stream:update': {
399
+ delta: string;
400
+ content: string;
401
+ };
402
+ 'stream:end': {
403
+ messageId: string;
404
+ usage?: {
405
+ tokensInput: number;
406
+ tokensOutput: number;
407
+ };
408
+ };
409
+ 'typing:start': void;
410
+ 'typing:stop': void;
411
+ 'error': Error;
412
+ 'status': string;
413
+ 'action:edit_entity': EditEntityAction_2;
414
+ 'action:save_entity': SaveEntityAction_2;
415
+ 'action:test_tool': TestToolAction_2;
416
+ 'action:navigate': NavigateAction_2;
417
+ 'tool:start': {
418
+ toolName: string;
419
+ args: Record<string, unknown>;
420
+ };
421
+ 'tool:end': {
422
+ toolName: string;
423
+ result: unknown;
424
+ isError: boolean;
425
+ };
426
+ }
427
+
428
+ export declare function clearPersistedConversationId(userId: string, projectId: string): void;
429
+
179
430
  export declare interface ConnectionConfig {
180
431
  baseUrl: string;
181
432
  wsUrl?: string;
@@ -186,6 +437,16 @@ export declare interface ConnectionConfig {
186
437
  reconnectInterval?: number;
187
438
  }
188
439
 
440
+ declare interface ConnectionConfig_2 {
441
+ baseUrl: string;
442
+ wsUrl?: string;
443
+ userToken: string;
444
+ tiledesk?: TiledeskTransportConfig_2;
445
+ reconnect?: boolean;
446
+ maxReconnectAttempts?: number;
447
+ reconnectInterval?: number;
448
+ }
449
+
189
450
  export declare class ConnectionManager extends EventEmitter<ChatEvents> {
190
451
  private client;
191
452
  private config;
@@ -207,6 +468,34 @@ export declare class ConnectionManager extends EventEmitter<ChatEvents> {
207
468
 
208
469
  export declare type ConnectionState = 'disconnected' | 'connecting' | 'connected' | 'reconnecting';
209
470
 
471
+ declare type ConnectionState_2 = 'disconnected' | 'connecting' | 'connected' | 'reconnecting';
472
+
473
+ /**
474
+ * Pluggable adapter that hydrates prior conversation messages on connect.
475
+ * The SDK calls this once after MQTT subscribes so the user sees existing
476
+ * history before any new live messages arrive.
477
+ */
478
+ export declare interface ConversationHistoryAdapter {
479
+ fetchMessages(conversationId: string, ctx: {
480
+ userId: string;
481
+ appId?: string;
482
+ projectId?: string;
483
+ }): Promise<TiledeskMessage[]>;
484
+ }
485
+
486
+ /**
487
+ * Pluggable adapter that hydrates prior conversation messages on connect.
488
+ * The SDK calls this once after MQTT subscribes so the user sees existing
489
+ * history before any new live messages arrive.
490
+ */
491
+ declare interface ConversationHistoryAdapter_2 {
492
+ fetchMessages(conversationId: string, ctx: {
493
+ userId: string;
494
+ appId?: string;
495
+ projectId?: string;
496
+ }): Promise<TiledeskMessage_2[]>;
497
+ }
498
+
210
499
  export declare class ConversationManager {
211
500
  private _conversationId;
212
501
  private persist;
@@ -223,6 +512,10 @@ declare interface CreateConversationResponse {
223
512
  status: string;
224
513
  }
225
514
 
515
+ export declare function createFetchUploadAdapter(config: FetchUploadAdapterConfig): UploadAdapter;
516
+
517
+ export declare function createTiledeskHistoryAdapter(config: TiledeskHistoryAdapterConfig): ConversationHistoryAdapter;
518
+
226
519
  export declare interface EditEntityAction {
227
520
  action: 'edit_entity';
228
521
  entity_type: string;
@@ -230,6 +523,13 @@ export declare interface EditEntityAction {
230
523
  fields: FieldUpdate[];
231
524
  }
232
525
 
526
+ declare interface EditEntityAction_2 {
527
+ action: 'edit_entity';
528
+ entity_type: string;
529
+ entity_id: string | number;
530
+ fields: FieldUpdate_2[];
531
+ }
532
+
233
533
  export declare class EventEmitter<Events extends Record<string, any>> {
234
534
  private handlers;
235
535
  on<K extends keyof Events & string>(event: K, handler: (data: Events[K]) => void): () => void;
@@ -238,12 +538,38 @@ export declare class EventEmitter<Events extends Record<string, any>> {
238
538
  removeAllListeners(): void;
239
539
  }
240
540
 
541
+ declare class EventEmitter_2<Events extends Record<string, any>> {
542
+ private handlers;
543
+ on<K extends keyof Events & string>(event: K, handler: (data: Events[K]) => void): () => void;
544
+ off<K extends keyof Events & string>(event: K, handler: (data: Events[K]) => void): void;
545
+ emit<K extends keyof Events & string>(event: K, data: Events[K]): void;
546
+ removeAllListeners(): void;
547
+ }
548
+
549
+ export declare function extractTiledeskFileEnvelope(message: TiledeskMessage): TiledeskFileEnvelope | null;
550
+
551
+ export declare interface FetchUploadAdapterConfig {
552
+ endpoint: string;
553
+ method?: 'POST' | 'PUT';
554
+ fieldName?: string;
555
+ headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
556
+ credentials?: RequestCredentials;
557
+ extraFields?: Record<string, string> | ((ctx: UploadAdapterContext) => Record<string, string>);
558
+ parseResponse?: (raw: unknown, ctx: UploadAdapterContext) => UploadAdapterResult;
559
+ }
560
+
241
561
  export declare interface FieldUpdate {
242
562
  field: string;
243
563
  value: unknown;
244
564
  previousValue?: unknown;
245
565
  }
246
566
 
567
+ declare interface FieldUpdate_2 {
568
+ field: string;
569
+ value: unknown;
570
+ previousValue?: unknown;
571
+ }
572
+
247
573
  export declare class FormBridge extends EventEmitter<FormBridgeEvents> {
248
574
  private registration;
249
575
  private pendingEdits;
@@ -360,10 +686,19 @@ export declare interface FormRegistration {
360
686
  getCurrentValues: () => Record<string, unknown>;
361
687
  }
362
688
 
689
+ export declare function inferTiledeskRole(message: TiledeskMessage, cfg: TiledeskRoleConfig): TiledeskRole;
690
+
691
+ /**
692
+ * Self-echo detector — Tiledesk fans the user's outgoing publish back
693
+ * as a `clientadded` event on the same connection. UI must dedupe against
694
+ * the optimistic local message rather than rendering twice.
695
+ */
696
+ export declare function isTiledeskSelfEcho(message: TiledeskMessage, userId: string): boolean;
697
+
363
698
  export declare interface Message {
364
699
  id: string;
365
700
  conversationId: string;
366
- role: 'user' | 'assistant' | 'system' | 'tool';
701
+ role: 'user' | 'assistant' | 'system' | 'tool' | 'agent';
367
702
  content: string;
368
703
  toolCalls?: ToolCall[];
369
704
  toolCallResults?: ToolCallResult;
@@ -371,7 +706,45 @@ export declare interface Message {
371
706
  tokensOutput?: number;
372
707
  metadata?: Record<string, unknown>;
373
708
  createdAt: string;
374
- status?: 'sending' | 'sent' | 'streaming' | 'complete' | 'error';
709
+ status?: 'sending' | 'sent' | 'delivered' | 'read' | 'streaming' | 'complete' | 'error';
710
+ externalId?: string;
711
+ template?: {
712
+ contentType?: string;
713
+ templateId?: string;
714
+ payload?: unknown;
715
+ };
716
+ attachments?: Array<{
717
+ fileName: string;
718
+ fileUrl: string;
719
+ cloudFileId?: string;
720
+ contentType?: string;
721
+ }>;
722
+ }
723
+
724
+ declare interface Message_2 {
725
+ id: string;
726
+ conversationId: string;
727
+ role: 'user' | 'assistant' | 'system' | 'tool' | 'agent';
728
+ content: string;
729
+ toolCalls?: ToolCall_2[];
730
+ toolCallResults?: ToolCallResult_2;
731
+ tokensInput?: number;
732
+ tokensOutput?: number;
733
+ metadata?: Record<string, unknown>;
734
+ createdAt: string;
735
+ status?: 'sending' | 'sent' | 'delivered' | 'read' | 'streaming' | 'complete' | 'error';
736
+ externalId?: string;
737
+ template?: {
738
+ contentType?: string;
739
+ templateId?: string;
740
+ payload?: unknown;
741
+ };
742
+ attachments?: Array<{
743
+ fileName: string;
744
+ fileUrl: string;
745
+ cloudFileId?: string;
746
+ contentType?: string;
747
+ }>;
375
748
  }
376
749
 
377
750
  export declare class MessageStore {
@@ -379,6 +752,22 @@ export declare class MessageStore {
379
752
  private optimisticCounter;
380
753
  get messages(): Message[];
381
754
  addOptimistic(role: 'user', content: string, conversationId: string): Message;
755
+ /**
756
+ * Reconcile a remote message against an outstanding optimistic message.
757
+ * Tiledesk fans the user's outgoing publish back as an inbound clientadded —
758
+ * dedupe by exact content + recency window so the optimistic bubble keeps
759
+ * its position and we don't render duplicates.
760
+ */
761
+ reconcileOptimistic(remote: Message, recencyMs?: number): Message | null;
762
+ /**
763
+ * Append a remote-originated message (e.g. from Tiledesk MQTT). If a matching
764
+ * optimistic message exists it is reconciled in place; otherwise appended.
765
+ */
766
+ upsertRemoteMessage(remote: Message): {
767
+ message: Message;
768
+ deduped: boolean;
769
+ };
770
+ updateMessageStatus(externalId: string, status: Message['status']): Message | undefined;
382
771
  confirmOptimistic(tempId: string): void;
383
772
  addStreamingMessage(conversationId: string): Message;
384
773
  updateStreaming(content: string): void;
@@ -393,54 +782,325 @@ export declare class MessageStore {
393
782
  clear(): void;
394
783
  }
395
784
 
785
+ export declare interface MountedTenantWidget {
786
+ widget: AikaaraChatWidget;
787
+ requestId: string;
788
+ config: WidgetConfig;
789
+ destroy: () => void;
790
+ }
791
+
792
+ /**
793
+ * Standard tenant mount. Fetches the descriptor (when `configUrl` is set),
794
+ * merges per-mount overrides, builds default adapters from the descriptor's
795
+ * endpoint URLs (when no override is supplied), and mounts the widget.
796
+ */
797
+ export declare function mountTenantWidget(opts: TenantMountOptions): Promise<MountedTenantWidget>;
798
+
396
799
  export declare interface NavigateAction {
397
800
  navigate_to: string;
398
801
  }
399
802
 
803
+ declare interface NavigateAction_2 {
804
+ navigate_to: string;
805
+ }
806
+
807
+ export declare function parseTiledeskTemplate(message: TiledeskMessage): TiledeskParsedTemplate;
808
+
400
809
  export declare interface SaveEntityAction {
401
810
  action: 'save_entity';
402
811
  }
403
812
 
813
+ declare interface SaveEntityAction_2 {
814
+ action: 'save_entity';
815
+ }
816
+
404
817
  declare type SubscriptionCallback = (data: unknown) => void;
405
818
 
819
+ declare interface TemplateMessageEvent {
820
+ messageId: string;
821
+ conversationId: string;
822
+ role: 'user' | 'assistant' | 'system' | 'agent';
823
+ contentType?: string;
824
+ templateId?: string;
825
+ payload?: unknown;
826
+ innerMessage?: string;
827
+ raw: unknown;
828
+ }
829
+
830
+ declare interface TemplateMessageEvent_2 {
831
+ messageId: string;
832
+ conversationId: string;
833
+ role: 'user' | 'assistant' | 'system' | 'agent';
834
+ contentType?: string;
835
+ templateId?: string;
836
+ payload?: unknown;
837
+ innerMessage?: string;
838
+ raw: unknown;
839
+ }
840
+
841
+ export declare interface TenantMountOptions {
842
+ container: HTMLElement;
843
+ /** Fetched from this URL when `config` is omitted. */
844
+ configUrl?: string;
845
+ /** Pre-resolved descriptor — skip the fetch. */
846
+ config?: WidgetConfigDescriptor;
847
+ /** Headers attached when fetching `configUrl` (e.g. tenant-API auth). */
848
+ configHeaders?: Record<string, string>;
849
+ identity: {
850
+ userId: string;
851
+ userName?: string;
852
+ departmentId?: string;
853
+ senderFullname?: string;
854
+ };
855
+ /** Returns a raw Tiledesk JWT (no Bearer/JWT prefix) for MQTT password. */
856
+ tokenProvider: () => Promise<string>;
857
+ /** Authorization value for the history fetch. Defaults to `tokenProvider()`. */
858
+ historyTokenProvider?: () => Promise<string>;
859
+ /**
860
+ * Optional override adapters. If omitted and the descriptor specifies the
861
+ * matching endpoint, the SDK builds default fetch-based adapters.
862
+ */
863
+ uploadAdapter?: UploadAdapter;
864
+ historyAdapter?: ConversationHistoryAdapter;
865
+ /**
866
+ * Pin a conversationId. When omitted we look up
867
+ * `aikaara_chat:requestId:{userId}:{projectId}` in localStorage and reuse
868
+ * any persisted value; only mint a fresh `requestId` when nothing is stored.
869
+ */
870
+ conversationId?: string;
871
+ forceNewConversation?: boolean;
872
+ /** Per-mount overrides that take precedence over the descriptor. */
873
+ overrides?: Partial<WidgetConfigDescriptor>;
874
+ /** Surfaced from the SDK. */
875
+ onError?: (err: Error) => void;
876
+ }
877
+
406
878
  export declare interface TestToolAction {
407
879
  action: 'test_tool';
408
880
  tool_id: number;
409
881
  parameters: Record<string, unknown>;
410
882
  }
411
883
 
884
+ declare interface TestToolAction_2 {
885
+ action: 'test_tool';
886
+ tool_id: number;
887
+ parameters: Record<string, unknown>;
888
+ }
889
+
890
+ export declare interface TiledeskFileEnvelope {
891
+ fileName?: string;
892
+ fileUrl?: string;
893
+ cloudFileId?: string;
894
+ templateId?: string;
895
+ }
896
+
897
+ export declare interface TiledeskFileMessageInput {
898
+ fileName: string;
899
+ fileUrl: string;
900
+ cloudFileId?: string;
901
+ templateId?: string;
902
+ headerImgSrc?: string;
903
+ type?: 'link' | 'image';
904
+ isDeepLink?: boolean;
905
+ description?: string;
906
+ attributes?: Record<string, unknown>;
907
+ metadata?: Record<string, unknown>;
908
+ }
909
+
910
+ export declare interface TiledeskFileTemplateConfig {
911
+ templateId: string;
912
+ headerImgSrc?: string;
913
+ type?: 'link' | 'image';
914
+ isDeepLink?: boolean;
915
+ }
916
+
917
+ declare interface TiledeskFileTemplateConfig_2 {
918
+ templateId: string;
919
+ headerImgSrc?: string;
920
+ type?: 'link' | 'image';
921
+ isDeepLink?: boolean;
922
+ }
923
+
924
+ export declare interface TiledeskHistoryAdapterConfig {
925
+ /**
926
+ * Base URL of the Tiledesk chat API, e.g. `https://uat-tiledesk.taxbuddy.com/chatapi/api`
927
+ * (no trailing slash). Final URL is composed as
928
+ * `{apiBase}/tilechat/{userId}/conversations/{conversationId}/messages?pageSize={pageSize}`
929
+ */
930
+ apiBase: string;
931
+ pageSize?: number;
932
+ /**
933
+ * Async getter for the bearer token. Most Tiledesk-fronted gateways accept
934
+ * the same JWT used for the MQTT connection. Return `null` to omit the
935
+ * `Authorization` header.
936
+ */
937
+ getToken?: () => string | null | Promise<string | null>;
938
+ /** Override the path template. Default mirrors bandhan's chatapi route. */
939
+ pathTemplate?: string;
940
+ /** Extra static headers to attach (e.g. `partnerid`, `environment`). */
941
+ extraHeaders?: Record<string, string>;
942
+ /**
943
+ * Optional response shape mapper. Default expects
944
+ * `{ success: true, result: TiledeskMessage[] }`
945
+ * which matches the bandhan `/chatapi/api/tilechat/.../messages` response.
946
+ */
947
+ parseResponse?: (raw: unknown) => TiledeskMessage[];
948
+ }
949
+
412
950
  export declare interface TiledeskMessage {
413
951
  text?: string;
414
952
  type?: string;
415
953
  sender?: string;
416
954
  senderFullname?: string;
955
+ sender_fullname?: string;
417
956
  recipient?: string;
957
+ recipient_fullname?: string;
958
+ channel_type?: string;
418
959
  timestamp?: number;
960
+ app_id?: string;
961
+ message_id?: string;
962
+ status?: number;
419
963
  attributes?: Record<string, unknown>;
420
964
  metadata?: Record<string, unknown>;
421
965
  [key: string]: unknown;
422
966
  }
423
967
 
968
+ declare interface TiledeskMessage_2 {
969
+ text?: string;
970
+ type?: string;
971
+ sender?: string;
972
+ senderFullname?: string;
973
+ sender_fullname?: string;
974
+ recipient?: string;
975
+ recipient_fullname?: string;
976
+ channel_type?: string;
977
+ timestamp?: number;
978
+ app_id?: string;
979
+ message_id?: string;
980
+ status?: number;
981
+ attributes?: Record<string, unknown>;
982
+ metadata?: Record<string, unknown>;
983
+ [key: string]: unknown;
984
+ }
985
+
986
+ export declare interface TiledeskMessageContext {
987
+ topic: string;
988
+ conversationId?: string;
989
+ messageId?: string;
990
+ kind: 'clientadded' | 'update' | 'unknown';
991
+ }
992
+
993
+ export declare interface TiledeskMessageDefaults {
994
+ channelType?: string;
995
+ channel?: string;
996
+ requestChannel?: string;
997
+ platform?: string;
998
+ medium?: string;
999
+ departmentId?: string;
1000
+ attributes?: Record<string, unknown>;
1001
+ }
1002
+
1003
+ declare interface TiledeskMessageDefaults_2 {
1004
+ channelType?: string;
1005
+ channel?: string;
1006
+ requestChannel?: string;
1007
+ platform?: string;
1008
+ medium?: string;
1009
+ departmentId?: string;
1010
+ attributes?: Record<string, unknown>;
1011
+ }
1012
+
1013
+ export declare interface TiledeskParsedTemplate {
1014
+ contentType?: string;
1015
+ templateId?: string;
1016
+ payload?: unknown;
1017
+ innerMessage?: string;
1018
+ raw: TiledeskMessage;
1019
+ }
1020
+
1021
+ export declare type TiledeskRole = 'user' | 'assistant' | 'system' | 'agent';
1022
+
1023
+ export declare interface TiledeskRoleConfig {
1024
+ userId: string;
1025
+ systemSenders?: string[];
1026
+ botSenderPrefix?: string;
1027
+ }
1028
+
1029
+ export declare interface TiledeskStatusUpdate {
1030
+ conversationId: string;
1031
+ messageId: string;
1032
+ status: number;
1033
+ raw: Record<string, unknown>;
1034
+ }
1035
+
1036
+ export declare interface TiledeskTopicTemplates {
1037
+ inbound?: string;
1038
+ inboundUpdate?: string;
1039
+ outbound?: string;
1040
+ presence?: string;
1041
+ wildcardSubscribe?: string;
1042
+ }
1043
+
1044
+ declare interface TiledeskTopicTemplates_2 {
1045
+ inbound?: string;
1046
+ inboundUpdate?: string;
1047
+ outbound?: string;
1048
+ presence?: string;
1049
+ wildcardSubscribe?: string;
1050
+ }
1051
+
424
1052
  export declare class TiledeskTransport {
425
1053
  private client;
426
1054
  private config;
1055
+ private currentToken;
1056
+ private clientId;
1057
+ private appId;
1058
+ private topics;
427
1059
  private messageHandlers;
428
1060
  private stateHandlers;
1061
+ private statusUpdateHandlers;
429
1062
  private subscribedTopics;
430
1063
  private reconnectAttempt;
431
1064
  private maxReconnectAttempts;
1065
+ private reconnectMaxDelayMs;
432
1066
  private disposed;
1067
+ private reconnectTimer;
1068
+ private inboundRegex;
1069
+ private inboundUpdateRegex;
433
1070
  constructor(config: TiledeskTransportConfig);
434
1071
  connect(): Promise<void>;
1072
+ private debugLog;
1073
+ subscribeWildcard(): void;
435
1074
  subscribeToConversation(conversationId: string): void;
436
1075
  unsubscribeFromConversation(conversationId: string): void;
437
- publishMessage(conversationId: string, text: string): void;
1076
+ publishMessage(conversationId: string, text: string, overrides?: Partial<TiledeskMessage>): void;
1077
+ publishFileMessage(conversationId: string, file: TiledeskFileMessageInput): void;
1078
+ publishRaw(conversationId: string, message: TiledeskMessage): void;
1079
+ /**
1080
+ * Send a read receipt for a message. Tiledesk widgets publish
1081
+ * `{"status":300}` to apps/{appId}/users/{userId}/messages/{convId}/{msgId}/update.
1082
+ */
1083
+ publishReadReceipt(conversationId: string, messageId: string, status?: number): void;
1084
+ /**
1085
+ * Trigger conversation kickoff. Tiledesk bot routing waits for the
1086
+ * widget to publish a CHAT_INITIATED event before the bot replies.
1087
+ */
1088
+ publishChatInitiated(conversationId: string, extraAttributes?: Record<string, unknown>): void;
438
1089
  onMessage(handler: TransportMessageHandler): () => void;
439
1090
  onStateChange(handler: TransportStateHandler): () => void;
1091
+ onStatusUpdate(handler: TransportStatusUpdateHandler): () => void;
440
1092
  disconnect(): void;
441
1093
  get isConnected(): boolean;
442
1094
  private scheduleReconnect;
443
1095
  private notifyStateChange;
1096
+ private dispatchInbound;
1097
+ private buildOutgoingEnvelope;
1098
+ private publishEnvelope;
1099
+ private renderInboundTopic;
1100
+ private renderOutboundTopic;
1101
+ private renderPresenceTopic;
1102
+ private renderTemplate;
1103
+ private buildTopicRegex;
444
1104
  }
445
1105
 
446
1106
  export declare interface TiledeskTransportConfig {
@@ -449,6 +1109,86 @@ export declare interface TiledeskTransportConfig {
449
1109
  userId: string;
450
1110
  userName?: string;
451
1111
  projectId: string;
1112
+ appId?: string;
1113
+ clientId?: string;
1114
+ protocolVersion?: 3 | 4 | 5;
1115
+ protocolId?: 'MQIsdp' | 'MQTT';
1116
+ mqttUsername?: string;
1117
+ connectTimeoutMs?: number;
1118
+ keepAliveSec?: number;
1119
+ maxReconnectAttempts?: number;
1120
+ reconnectMaxDelayMs?: number;
1121
+ tokenProvider?: () => Promise<string>;
1122
+ wildcardSubscribe?: boolean;
1123
+ subscribeQos?: 0 | 1 | 2;
1124
+ publishQos?: 0 | 1 | 2;
1125
+ publishRetain?: boolean;
1126
+ enablePresence?: boolean;
1127
+ presencePayloadConnected?: Record<string, unknown>;
1128
+ presencePayloadDisconnected?: Record<string, unknown>;
1129
+ topicTemplates?: TiledeskTopicTemplates;
1130
+ messageDefaults?: TiledeskMessageDefaults;
1131
+ fileTemplate?: TiledeskFileTemplateConfig;
1132
+ recipientFullnameResolver?: (conversationId: string) => string | undefined;
1133
+ senderFullname?: string;
1134
+ /**
1135
+ * If true (default), AikaaraChatClient publishes a `CHAT_INITIATED` event
1136
+ * to the conversation's outbound topic on first connect — but only when
1137
+ * the conversation history is empty (so reload of an in-flight chat
1138
+ * doesn't replay the kickoff).
1139
+ */
1140
+ autoInitiateOnEmpty?: boolean;
1141
+ /** Extra attributes merged into the auto-fired CHAT_INITIATED envelope. */
1142
+ chatInitiatedAttributes?: Record<string, unknown>;
1143
+ /**
1144
+ * Log decoded MQTT frames to console as they're sent/received.
1145
+ * Off by default — set true for debugging Tiledesk wire traffic.
1146
+ */
1147
+ debug?: boolean;
1148
+ }
1149
+
1150
+ declare interface TiledeskTransportConfig_2 {
1151
+ mqttEndpoint: string;
1152
+ jwtToken: string;
1153
+ userId: string;
1154
+ userName?: string;
1155
+ projectId: string;
1156
+ appId?: string;
1157
+ clientId?: string;
1158
+ protocolVersion?: 3 | 4 | 5;
1159
+ protocolId?: 'MQIsdp' | 'MQTT';
1160
+ mqttUsername?: string;
1161
+ connectTimeoutMs?: number;
1162
+ keepAliveSec?: number;
1163
+ maxReconnectAttempts?: number;
1164
+ reconnectMaxDelayMs?: number;
1165
+ tokenProvider?: () => Promise<string>;
1166
+ wildcardSubscribe?: boolean;
1167
+ subscribeQos?: 0 | 1 | 2;
1168
+ publishQos?: 0 | 1 | 2;
1169
+ publishRetain?: boolean;
1170
+ enablePresence?: boolean;
1171
+ presencePayloadConnected?: Record<string, unknown>;
1172
+ presencePayloadDisconnected?: Record<string, unknown>;
1173
+ topicTemplates?: TiledeskTopicTemplates_2;
1174
+ messageDefaults?: TiledeskMessageDefaults_2;
1175
+ fileTemplate?: TiledeskFileTemplateConfig_2;
1176
+ recipientFullnameResolver?: (conversationId: string) => string | undefined;
1177
+ senderFullname?: string;
1178
+ /**
1179
+ * If true (default), AikaaraChatClient publishes a `CHAT_INITIATED` event
1180
+ * to the conversation's outbound topic on first connect — but only when
1181
+ * the conversation history is empty (so reload of an in-flight chat
1182
+ * doesn't replay the kickoff).
1183
+ */
1184
+ autoInitiateOnEmpty?: boolean;
1185
+ /** Extra attributes merged into the auto-fired CHAT_INITIATED envelope. */
1186
+ chatInitiatedAttributes?: Record<string, unknown>;
1187
+ /**
1188
+ * Log decoded MQTT frames to console as they're sent/received.
1189
+ * Off by default — set true for debugging Tiledesk wire traffic.
1190
+ */
1191
+ debug?: boolean;
452
1192
  }
453
1193
 
454
1194
  export declare interface ToolCall {
@@ -460,15 +1200,77 @@ export declare interface ToolCall {
460
1200
  };
461
1201
  }
462
1202
 
1203
+ declare interface ToolCall_2 {
1204
+ id: string;
1205
+ type: 'function';
1206
+ function: {
1207
+ name: string;
1208
+ arguments: string;
1209
+ };
1210
+ }
1211
+
463
1212
  export declare interface ToolCallResult {
464
1213
  tool_call_id: string;
465
1214
  content: string;
466
1215
  }
467
1216
 
468
- export declare type TransportMessageHandler = (message: TiledeskMessage) => void;
1217
+ declare interface ToolCallResult_2 {
1218
+ tool_call_id: string;
1219
+ content: string;
1220
+ }
1221
+
1222
+ export declare type TransportMessageHandler = (message: TiledeskMessage, ctx: TiledeskMessageContext) => void;
1223
+
1224
+ declare type TransportMode = 'aikaara' | 'tiledesk' | 'dual';
1225
+
1226
+ declare type TransportMode_2 = 'aikaara' | 'tiledesk' | 'dual';
469
1227
 
470
1228
  export declare type TransportStateHandler = (connected: boolean) => void;
471
1229
 
1230
+ export declare type TransportStatusUpdateHandler = (update: TiledeskStatusUpdate) => void;
1231
+
1232
+ export declare interface UploadAdapter {
1233
+ upload(file: File | Blob, ctx: UploadAdapterContext): Promise<UploadAdapterResult>;
1234
+ }
1235
+
1236
+ declare interface UploadAdapter_2 {
1237
+ upload(file: File | Blob, ctx: UploadAdapterContext_2): Promise<UploadAdapterResult_2>;
1238
+ }
1239
+
1240
+ export declare interface UploadAdapterContext {
1241
+ conversationId: string;
1242
+ userId: string;
1243
+ projectId?: string;
1244
+ appId?: string;
1245
+ }
1246
+
1247
+ declare interface UploadAdapterContext_2 {
1248
+ conversationId: string;
1249
+ userId: string;
1250
+ projectId?: string;
1251
+ appId?: string;
1252
+ }
1253
+
1254
+ export declare interface UploadAdapterResult {
1255
+ url: string;
1256
+ fileName: string;
1257
+ cloudFileId?: string;
1258
+ relativePath?: string;
1259
+ contentType?: string;
1260
+ byteSize?: number;
1261
+ meta?: Record<string, unknown>;
1262
+ }
1263
+
1264
+ declare interface UploadAdapterResult_2 {
1265
+ url: string;
1266
+ fileName: string;
1267
+ cloudFileId?: string;
1268
+ relativePath?: string;
1269
+ contentType?: string;
1270
+ byteSize?: number;
1271
+ meta?: Record<string, unknown>;
1272
+ }
1273
+
472
1274
  export declare interface WidgetConfig extends ChatClientConfig {
473
1275
  position?: 'bottom-right' | 'bottom-left';
474
1276
  offset?: {
@@ -491,6 +1293,71 @@ export declare interface WidgetConfig extends ChatClientConfig {
491
1293
  showBubble?: boolean;
492
1294
  bubbleText?: string;
493
1295
  bubbleIcon?: string;
1296
+ uploadAdapter?: UploadAdapter;
1297
+ historyAdapter?: ConversationHistoryAdapter;
1298
+ /**
1299
+ * Display mode:
1300
+ * - `popup` (default): floating bubble in the corner, click to open panel.
1301
+ * - `embed`: render the chat panel inline at the host element's location,
1302
+ * filling its container. Bubble + open/close animation are skipped.
1303
+ */
1304
+ display?: 'popup' | 'embed';
1305
+ }
1306
+
1307
+ export declare interface WidgetConfigDescriptor {
1308
+ /** Visuals */
1309
+ display?: 'popup' | 'embed';
1310
+ position?: 'bottom-right' | 'bottom-left';
1311
+ primaryColor?: string;
1312
+ title?: string;
1313
+ subtitle?: string;
1314
+ avatarUrl?: string;
1315
+ width?: number;
1316
+ height?: number;
1317
+ borderRadius?: number;
1318
+ fontFamily?: string;
1319
+ welcomeMessage?: string;
1320
+ placeholder?: string;
1321
+ showTimestamps?: boolean;
1322
+ persistConversation?: boolean;
1323
+ /** Transport selection */
1324
+ transport?: TransportMode;
1325
+ /** Tiledesk wire config (JSON-serializable subset of TiledeskTransportConfig) */
1326
+ tiledesk?: {
1327
+ mqttEndpoint: string;
1328
+ appId?: string;
1329
+ projectId: string;
1330
+ mqttUsername?: string;
1331
+ protocolId?: 'MQIsdp' | 'MQTT';
1332
+ protocolVersion?: 3 | 4 | 5;
1333
+ keepAliveSec?: number;
1334
+ connectTimeoutMs?: number;
1335
+ maxReconnectAttempts?: number;
1336
+ reconnectMaxDelayMs?: number;
1337
+ wildcardSubscribe?: boolean;
1338
+ enablePresence?: boolean;
1339
+ autoInitiateOnEmpty?: boolean;
1340
+ chatInitiatedAttributes?: Record<string, unknown>;
1341
+ messageDefaults?: TiledeskMessageDefaults;
1342
+ fileTemplate?: TiledeskFileTemplateConfig;
1343
+ topicTemplates?: TiledeskTopicTemplates;
1344
+ debug?: boolean;
1345
+ /**
1346
+ * Pattern for `support-group-…` requestId minted on first chat. Use
1347
+ * `{projectId}` and `{uuid}` placeholders. Defaults to bandhan's
1348
+ * `support-group-{projectId}-{uuid}`.
1349
+ */
1350
+ requestIdTemplate?: string;
1351
+ };
1352
+ /** Defaults merged into every form-action postback */
1353
+ templateActionAttributes?: Record<string, unknown>;
1354
+ /** Adapter endpoints — SDK builds the actual fetch calls */
1355
+ uploadEndpoint?: string;
1356
+ uploadFieldName?: string;
1357
+ uploadExtraFields?: Record<string, string>;
1358
+ historyApiBase?: string;
1359
+ historyPageSize?: number;
1360
+ historyPathTemplate?: string;
494
1361
  }
495
1362
 
496
1363
  export { }