@superatomai/sdk-node 0.0.13 → 0.0.14-mds

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,16 @@
1
1
  import { z } from 'zod';
2
+ import Anthropic from '@anthropic-ai/sdk';
3
+
4
+ /**
5
+ * Unified UIBlock structure for database storage
6
+ * Used in both bookmarks and user-conversations tables
7
+ */
8
+ interface DBUIBlock {
9
+ id: string;
10
+ component: Record<string, any> | null;
11
+ analysis: string | null;
12
+ user_prompt: string;
13
+ }
2
14
 
3
15
  /**
4
16
  * Log levels in hierarchical order
@@ -47,7 +59,18 @@ declare class Logger {
47
59
  * Log debug message (only shown for verbose level)
48
60
  */
49
61
  debug(...args: any[]): void;
62
+ /**
63
+ * Write to log file
64
+ */
50
65
  file(...args: any[]): void;
66
+ /**
67
+ * Clear the log file (call at start of new user request)
68
+ */
69
+ clearFile(): void;
70
+ /**
71
+ * Log LLM method prompts with clear labeling
72
+ */
73
+ logLLMPrompt(methodName: string, promptType: 'system' | 'user', content: string | object | any[]): void;
51
74
  }
52
75
  declare const logger: Logger;
53
76
 
@@ -78,7 +101,27 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
78
101
  deps?: string[] | undefined;
79
102
  }>, "many">>;
80
103
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
81
- render: z.ZodType<any, z.ZodTypeDef, any>;
104
+ render: z.ZodOptional<z.ZodType<any, z.ZodTypeDef, any>>;
105
+ pages: z.ZodOptional<z.ZodArray<z.ZodObject<{
106
+ id: z.ZodString;
107
+ name: z.ZodString;
108
+ order: z.ZodNumber;
109
+ icon: z.ZodOptional<z.ZodString>;
110
+ render: z.ZodType<any, z.ZodTypeDef, any>;
111
+ }, "strip", z.ZodTypeAny, {
112
+ id: string;
113
+ name: string;
114
+ order: number;
115
+ icon?: string | undefined;
116
+ render?: any;
117
+ }, {
118
+ id: string;
119
+ name: string;
120
+ order: number;
121
+ icon?: string | undefined;
122
+ render?: any;
123
+ }>, "many">>;
124
+ defaultPageId: z.ZodOptional<z.ZodString>;
82
125
  query: z.ZodOptional<z.ZodObject<{
83
126
  graphql: z.ZodOptional<z.ZodString>;
84
127
  sql: z.ZodOptional<z.ZodString>;
@@ -117,6 +160,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
117
160
  dependencies?: string[] | undefined;
118
161
  } | undefined;
119
162
  props?: Record<string, any> | undefined;
163
+ render?: any;
120
164
  states?: Record<string, any> | undefined;
121
165
  methods?: Record<string, {
122
166
  fn: string;
@@ -127,7 +171,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
127
171
  deps?: string[] | undefined;
128
172
  }[] | undefined;
129
173
  data?: Record<string, any> | undefined;
130
- render?: any;
174
+ pages?: {
175
+ id: string;
176
+ name: string;
177
+ order: number;
178
+ icon?: string | undefined;
179
+ render?: any;
180
+ }[] | undefined;
181
+ defaultPageId?: string | undefined;
131
182
  }, {
132
183
  id: string;
133
184
  name?: string | undefined;
@@ -141,6 +192,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
141
192
  dependencies?: string[] | undefined;
142
193
  } | undefined;
143
194
  props?: Record<string, any> | undefined;
195
+ render?: any;
144
196
  states?: Record<string, any> | undefined;
145
197
  methods?: Record<string, {
146
198
  fn: string;
@@ -151,7 +203,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
151
203
  deps?: string[] | undefined;
152
204
  }[] | undefined;
153
205
  data?: Record<string, any> | undefined;
154
- render?: any;
206
+ pages?: {
207
+ id: string;
208
+ name: string;
209
+ order: number;
210
+ icon?: string | undefined;
211
+ render?: any;
212
+ }[] | undefined;
213
+ defaultPageId?: string | undefined;
155
214
  }>;
156
215
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
157
216
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -169,6 +228,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
169
228
  dependencies?: string[] | undefined;
170
229
  } | undefined;
171
230
  props?: Record<string, any> | undefined;
231
+ render?: any;
172
232
  states?: Record<string, any> | undefined;
173
233
  methods?: Record<string, {
174
234
  fn: string;
@@ -179,7 +239,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
179
239
  deps?: string[] | undefined;
180
240
  }[] | undefined;
181
241
  data?: Record<string, any> | undefined;
182
- render?: any;
242
+ pages?: {
243
+ id: string;
244
+ name: string;
245
+ order: number;
246
+ icon?: string | undefined;
247
+ render?: any;
248
+ }[] | undefined;
249
+ defaultPageId?: string | undefined;
183
250
  };
184
251
  data?: Record<string, any> | undefined;
185
252
  context?: Record<string, any> | undefined;
@@ -197,6 +264,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
197
264
  dependencies?: string[] | undefined;
198
265
  } | undefined;
199
266
  props?: Record<string, any> | undefined;
267
+ render?: any;
200
268
  states?: Record<string, any> | undefined;
201
269
  methods?: Record<string, {
202
270
  fn: string;
@@ -207,7 +275,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
207
275
  deps?: string[] | undefined;
208
276
  }[] | undefined;
209
277
  data?: Record<string, any> | undefined;
210
- render?: any;
278
+ pages?: {
279
+ id: string;
280
+ name: string;
281
+ order: number;
282
+ icon?: string | undefined;
283
+ render?: any;
284
+ }[] | undefined;
285
+ defaultPageId?: string | undefined;
211
286
  };
212
287
  data?: Record<string, any> | undefined;
213
288
  context?: Record<string, any> | undefined;
@@ -280,6 +355,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
280
355
  dependencies?: string[] | undefined;
281
356
  } | undefined;
282
357
  props?: Record<string, any> | undefined;
358
+ render?: any;
283
359
  states?: Record<string, any> | undefined;
284
360
  methods?: Record<string, {
285
361
  fn: string;
@@ -290,7 +366,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
290
366
  deps?: string[] | undefined;
291
367
  }[] | undefined;
292
368
  data?: Record<string, any> | undefined;
293
- render?: any;
294
369
  }, {
295
370
  id: string;
296
371
  name?: string | undefined;
@@ -304,6 +379,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
304
379
  dependencies?: string[] | undefined;
305
380
  } | undefined;
306
381
  props?: Record<string, any> | undefined;
382
+ render?: any;
307
383
  states?: Record<string, any> | undefined;
308
384
  methods?: Record<string, {
309
385
  fn: string;
@@ -314,7 +390,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
314
390
  deps?: string[] | undefined;
315
391
  }[] | undefined;
316
392
  data?: Record<string, any> | undefined;
317
- render?: any;
318
393
  }>;
319
394
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
320
395
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -332,6 +407,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
332
407
  dependencies?: string[] | undefined;
333
408
  } | undefined;
334
409
  props?: Record<string, any> | undefined;
410
+ render?: any;
335
411
  states?: Record<string, any> | undefined;
336
412
  methods?: Record<string, {
337
413
  fn: string;
@@ -342,7 +418,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
342
418
  deps?: string[] | undefined;
343
419
  }[] | undefined;
344
420
  data?: Record<string, any> | undefined;
345
- render?: any;
346
421
  };
347
422
  data?: Record<string, any> | undefined;
348
423
  context?: Record<string, any> | undefined;
@@ -360,6 +435,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
360
435
  dependencies?: string[] | undefined;
361
436
  } | undefined;
362
437
  props?: Record<string, any> | undefined;
438
+ render?: any;
363
439
  states?: Record<string, any> | undefined;
364
440
  methods?: Record<string, {
365
441
  fn: string;
@@ -370,7 +446,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
370
446
  deps?: string[] | undefined;
371
447
  }[] | undefined;
372
448
  data?: Record<string, any> | undefined;
373
- render?: any;
374
449
  };
375
450
  data?: Record<string, any> | undefined;
376
451
  context?: Record<string, any> | undefined;
@@ -383,6 +458,7 @@ declare const UserSchema: z.ZodObject<{
383
458
  password: z.ZodString;
384
459
  fullname: z.ZodOptional<z.ZodString>;
385
460
  role: z.ZodOptional<z.ZodString>;
461
+ userInfo: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
386
462
  wsIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
387
463
  }, "strip", z.ZodTypeAny, {
388
464
  username: string;
@@ -390,6 +466,7 @@ declare const UserSchema: z.ZodObject<{
390
466
  email?: string | undefined;
391
467
  fullname?: string | undefined;
392
468
  role?: string | undefined;
469
+ userInfo?: Record<string, unknown> | undefined;
393
470
  wsIds?: string[] | undefined;
394
471
  }, {
395
472
  username: string;
@@ -397,6 +474,7 @@ declare const UserSchema: z.ZodObject<{
397
474
  email?: string | undefined;
398
475
  fullname?: string | undefined;
399
476
  role?: string | undefined;
477
+ userInfo?: Record<string, unknown> | undefined;
400
478
  wsIds?: string[] | undefined;
401
479
  }>;
402
480
  type User = z.infer<typeof UserSchema>;
@@ -407,6 +485,7 @@ declare const UsersDataSchema: z.ZodObject<{
407
485
  password: z.ZodString;
408
486
  fullname: z.ZodOptional<z.ZodString>;
409
487
  role: z.ZodOptional<z.ZodString>;
488
+ userInfo: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
410
489
  wsIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
411
490
  }, "strip", z.ZodTypeAny, {
412
491
  username: string;
@@ -414,6 +493,7 @@ declare const UsersDataSchema: z.ZodObject<{
414
493
  email?: string | undefined;
415
494
  fullname?: string | undefined;
416
495
  role?: string | undefined;
496
+ userInfo?: Record<string, unknown> | undefined;
417
497
  wsIds?: string[] | undefined;
418
498
  }, {
419
499
  username: string;
@@ -421,6 +501,7 @@ declare const UsersDataSchema: z.ZodObject<{
421
501
  email?: string | undefined;
422
502
  fullname?: string | undefined;
423
503
  role?: string | undefined;
504
+ userInfo?: Record<string, unknown> | undefined;
424
505
  wsIds?: string[] | undefined;
425
506
  }>, "many">;
426
507
  }, "strip", z.ZodTypeAny, {
@@ -430,6 +511,7 @@ declare const UsersDataSchema: z.ZodObject<{
430
511
  email?: string | undefined;
431
512
  fullname?: string | undefined;
432
513
  role?: string | undefined;
514
+ userInfo?: Record<string, unknown> | undefined;
433
515
  wsIds?: string[] | undefined;
434
516
  }[];
435
517
  }, {
@@ -439,6 +521,7 @@ declare const UsersDataSchema: z.ZodObject<{
439
521
  email?: string | undefined;
440
522
  fullname?: string | undefined;
441
523
  role?: string | undefined;
524
+ userInfo?: Record<string, unknown> | undefined;
442
525
  wsIds?: string[] | undefined;
443
526
  }[];
444
527
  }>;
@@ -543,42 +626,413 @@ declare const IncomingMessageSchema: z.ZodObject<{
543
626
  payload?: unknown;
544
627
  }>;
545
628
  type IncomingMessage = z.infer<typeof IncomingMessageSchema>;
629
+ declare const ComponentSchema: z.ZodObject<{
630
+ id: z.ZodString;
631
+ name: z.ZodString;
632
+ displayName: z.ZodOptional<z.ZodString>;
633
+ isDisplayComp: z.ZodOptional<z.ZodBoolean>;
634
+ type: z.ZodString;
635
+ description: z.ZodString;
636
+ props: z.ZodObject<{
637
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
638
+ title: z.ZodOptional<z.ZodString>;
639
+ description: z.ZodOptional<z.ZodString>;
640
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
641
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
642
+ }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
643
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
644
+ title: z.ZodOptional<z.ZodString>;
645
+ description: z.ZodOptional<z.ZodString>;
646
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
647
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
648
+ }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
649
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
650
+ title: z.ZodOptional<z.ZodString>;
651
+ description: z.ZodOptional<z.ZodString>;
652
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
653
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
654
+ }, z.ZodTypeAny, "passthrough">>;
655
+ category: z.ZodOptional<z.ZodString>;
656
+ keywords: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
657
+ }, "strip", z.ZodTypeAny, {
658
+ id: string;
659
+ type: string;
660
+ name: string;
661
+ description: string;
662
+ props: {
663
+ description?: string | undefined;
664
+ query?: string | {} | null | undefined;
665
+ title?: string | undefined;
666
+ config?: Record<string, unknown> | undefined;
667
+ actions?: any[] | undefined;
668
+ } & {
669
+ [k: string]: unknown;
670
+ };
671
+ displayName?: string | undefined;
672
+ isDisplayComp?: boolean | undefined;
673
+ category?: string | undefined;
674
+ keywords?: string[] | undefined;
675
+ }, {
676
+ id: string;
677
+ type: string;
678
+ name: string;
679
+ description: string;
680
+ props: {
681
+ description?: string | undefined;
682
+ query?: string | {} | null | undefined;
683
+ title?: string | undefined;
684
+ config?: Record<string, unknown> | undefined;
685
+ actions?: any[] | undefined;
686
+ } & {
687
+ [k: string]: unknown;
688
+ };
689
+ displayName?: string | undefined;
690
+ isDisplayComp?: boolean | undefined;
691
+ category?: string | undefined;
692
+ keywords?: string[] | undefined;
693
+ }>;
694
+ type Component = z.infer<typeof ComponentSchema>;
695
+ declare const OutputFieldSchema: z.ZodObject<{
696
+ name: z.ZodString;
697
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
698
+ description: z.ZodString;
699
+ }, "strip", z.ZodTypeAny, {
700
+ type: "string" | "number" | "boolean" | "date";
701
+ name: string;
702
+ description: string;
703
+ }, {
704
+ type: "string" | "number" | "boolean" | "date";
705
+ name: string;
706
+ description: string;
707
+ }>;
708
+ type OutputField = z.infer<typeof OutputFieldSchema>;
709
+ declare const OutputSchema: z.ZodObject<{
710
+ description: z.ZodString;
711
+ fields: z.ZodArray<z.ZodObject<{
712
+ name: z.ZodString;
713
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
714
+ description: z.ZodString;
715
+ }, "strip", z.ZodTypeAny, {
716
+ type: "string" | "number" | "boolean" | "date";
717
+ name: string;
718
+ description: string;
719
+ }, {
720
+ type: "string" | "number" | "boolean" | "date";
721
+ name: string;
722
+ description: string;
723
+ }>, "many">;
724
+ }, "strip", z.ZodTypeAny, {
725
+ description: string;
726
+ fields: {
727
+ type: "string" | "number" | "boolean" | "date";
728
+ name: string;
729
+ description: string;
730
+ }[];
731
+ }, {
732
+ description: string;
733
+ fields: {
734
+ type: "string" | "number" | "boolean" | "date";
735
+ name: string;
736
+ description: string;
737
+ }[];
738
+ }>;
739
+ type ToolOutputSchema = z.infer<typeof OutputSchema>;
546
740
  declare const ToolSchema: z.ZodObject<{
547
741
  id: z.ZodString;
548
742
  name: z.ZodString;
549
743
  description: z.ZodString;
744
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
745
+ toolType: z.ZodOptional<z.ZodEnum<["source", "direct"]>>;
746
+ /** Full untruncated schema for source agent (all columns visible) */
747
+ fullSchema: z.ZodOptional<z.ZodString>;
550
748
  params: z.ZodRecord<z.ZodString, z.ZodString>;
551
749
  fn: z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodAny>;
750
+ outputSchema: z.ZodOptional<z.ZodObject<{
751
+ description: z.ZodString;
752
+ fields: z.ZodArray<z.ZodObject<{
753
+ name: z.ZodString;
754
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
755
+ description: z.ZodString;
756
+ }, "strip", z.ZodTypeAny, {
757
+ type: "string" | "number" | "boolean" | "date";
758
+ name: string;
759
+ description: string;
760
+ }, {
761
+ type: "string" | "number" | "boolean" | "date";
762
+ name: string;
763
+ description: string;
764
+ }>, "many">;
765
+ }, "strip", z.ZodTypeAny, {
766
+ description: string;
767
+ fields: {
768
+ type: "string" | "number" | "boolean" | "date";
769
+ name: string;
770
+ description: string;
771
+ }[];
772
+ }, {
773
+ description: string;
774
+ fields: {
775
+ type: "string" | "number" | "boolean" | "date";
776
+ name: string;
777
+ description: string;
778
+ }[];
779
+ }>>;
552
780
  }, "strip", z.ZodTypeAny, {
553
781
  id: string;
554
782
  params: Record<string, string>;
555
783
  name: string;
556
784
  description: string;
557
785
  fn: (args_0: any, ...args: unknown[]) => any;
786
+ toolType?: "source" | "direct" | undefined;
787
+ fullSchema?: string | undefined;
788
+ outputSchema?: {
789
+ description: string;
790
+ fields: {
791
+ type: "string" | "number" | "boolean" | "date";
792
+ name: string;
793
+ description: string;
794
+ }[];
795
+ } | undefined;
558
796
  }, {
559
797
  id: string;
560
798
  params: Record<string, string>;
561
799
  name: string;
562
800
  description: string;
563
801
  fn: (args_0: any, ...args: unknown[]) => any;
802
+ toolType?: "source" | "direct" | undefined;
803
+ fullSchema?: string | undefined;
804
+ outputSchema?: {
805
+ description: string;
806
+ fields: {
807
+ type: "string" | "number" | "boolean" | "date";
808
+ name: string;
809
+ description: string;
810
+ }[];
811
+ } | undefined;
564
812
  }>;
565
813
  type Tool$1 = z.infer<typeof ToolSchema>;
566
814
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
567
815
  type CollectionHandler<TParams = any, TResult = any> = (params: TParams) => Promise<TResult> | TResult;
568
- type LLMProvider = 'anthropic' | 'groq';
816
+ type LLMProvider = 'anthropic' | 'groq' | 'gemini' | 'openai';
569
817
 
818
+ type DatabaseType = 'postgresql' | 'mssql' | 'snowflake' | 'mysql';
819
+ /**
820
+ * Model strategy for controlling which models are used for different tasks
821
+ * - 'best': Use the best model (e.g., Sonnet) for all tasks - highest quality, higher cost
822
+ * - 'fast': Use the fast model (e.g., Haiku) for all tasks - lower quality, lower cost
823
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
824
+ */
825
+ type ModelStrategy = 'best' | 'fast' | 'balanced';
826
+ /**
827
+ * Model configuration for DASH_COMP flow (dashboard component picking)
828
+ * Allows separate control of models used for component selection
829
+ */
830
+ interface DashCompModelConfig {
831
+ /**
832
+ * Primary model for DASH_COMP requests
833
+ * Format: "provider/model-name" (e.g., "anthropic/claude-sonnet-4-5-20250929")
834
+ */
835
+ model?: string;
836
+ /**
837
+ * Fast model for simpler DASH_COMP tasks (optional)
838
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
839
+ */
840
+ fastModel?: string;
841
+ }
570
842
  interface SuperatomSDKConfig {
571
843
  url?: string;
572
- apiKey: string;
844
+ apiKey?: string;
573
845
  projectId: string;
574
- userId?: string;
575
846
  type?: string;
576
847
  bundleDir?: string;
577
848
  promptsDir?: string;
849
+ databaseType?: DatabaseType;
578
850
  ANTHROPIC_API_KEY?: string;
579
851
  GROQ_API_KEY?: string;
852
+ GEMINI_API_KEY?: string;
853
+ OPENAI_API_KEY?: string;
580
854
  LLM_PROVIDERS?: LLMProvider[];
581
855
  logLevel?: LogLevel;
856
+ /**
857
+ * Model selection strategy for LLM API calls:
858
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
859
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
860
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
861
+ */
862
+ modelStrategy?: ModelStrategy;
863
+ /**
864
+ * Separate model configuration for DASH_COMP flow (dashboard component picking)
865
+ * If not provided, falls back to provider-based model selection
866
+ */
867
+ dashCompModels?: DashCompModelConfig;
868
+ /**
869
+ * Similarity threshold for conversation search (semantic matching)
870
+ * Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
871
+ * Higher values require closer matches, lower values allow more distant matches
872
+ * Default: 0.8
873
+ */
874
+ conversationSimilarityThreshold?: number;
875
+ /**
876
+ * Query cache TTL (Time To Live) in minutes
877
+ * Cached query results expire after this duration
878
+ * Default: 5 minutes
879
+ */
880
+ queryCacheTTL?: number;
881
+ /**
882
+ * Dashboard conversation history TTL (Time To Live) in minutes
883
+ * Per-dashboard conversation histories expire after this duration
884
+ * Default: 30 minutes
885
+ */
886
+ dashboardHistoryTTL?: number;
887
+ }
888
+
889
+ declare const KbNodesQueryFiltersSchema: z.ZodObject<{
890
+ query: z.ZodOptional<z.ZodString>;
891
+ category: z.ZodOptional<z.ZodString>;
892
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
893
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
894
+ createdBy: z.ZodOptional<z.ZodString>;
895
+ }, "strip", z.ZodTypeAny, {
896
+ type?: "query" | "user" | "global" | undefined;
897
+ query?: string | undefined;
898
+ category?: string | undefined;
899
+ createdBy?: string | undefined;
900
+ tags?: string[] | undefined;
901
+ }, {
902
+ type?: "query" | "user" | "global" | undefined;
903
+ query?: string | undefined;
904
+ category?: string | undefined;
905
+ createdBy?: string | undefined;
906
+ tags?: string[] | undefined;
907
+ }>;
908
+ type KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
909
+ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
910
+ operation: z.ZodEnum<["create", "update", "delete", "getAll", "getOne", "search", "getByCategory", "getByUser", "getCategories", "getTags"]>;
911
+ data: z.ZodOptional<z.ZodObject<{
912
+ id: z.ZodOptional<z.ZodNumber>;
913
+ title: z.ZodOptional<z.ZodString>;
914
+ content: z.ZodOptional<z.ZodString>;
915
+ category: z.ZodOptional<z.ZodString>;
916
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
917
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
918
+ createdBy: z.ZodOptional<z.ZodString>;
919
+ updatedBy: z.ZodOptional<z.ZodString>;
920
+ userId: z.ZodOptional<z.ZodString>;
921
+ query: z.ZodOptional<z.ZodString>;
922
+ filters: z.ZodOptional<z.ZodObject<{
923
+ query: z.ZodOptional<z.ZodString>;
924
+ category: z.ZodOptional<z.ZodString>;
925
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
926
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
927
+ createdBy: z.ZodOptional<z.ZodString>;
928
+ }, "strip", z.ZodTypeAny, {
929
+ type?: "query" | "user" | "global" | undefined;
930
+ query?: string | undefined;
931
+ category?: string | undefined;
932
+ createdBy?: string | undefined;
933
+ tags?: string[] | undefined;
934
+ }, {
935
+ type?: "query" | "user" | "global" | undefined;
936
+ query?: string | undefined;
937
+ category?: string | undefined;
938
+ createdBy?: string | undefined;
939
+ tags?: string[] | undefined;
940
+ }>>;
941
+ limit: z.ZodOptional<z.ZodNumber>;
942
+ offset: z.ZodOptional<z.ZodNumber>;
943
+ }, "strip", z.ZodTypeAny, {
944
+ id?: number | undefined;
945
+ type?: "query" | "user" | "global" | undefined;
946
+ query?: string | undefined;
947
+ title?: string | undefined;
948
+ category?: string | undefined;
949
+ userId?: string | undefined;
950
+ limit?: number | undefined;
951
+ filters?: {
952
+ type?: "query" | "user" | "global" | undefined;
953
+ query?: string | undefined;
954
+ category?: string | undefined;
955
+ createdBy?: string | undefined;
956
+ tags?: string[] | undefined;
957
+ } | undefined;
958
+ createdBy?: string | undefined;
959
+ updatedBy?: string | undefined;
960
+ offset?: number | undefined;
961
+ tags?: string[] | undefined;
962
+ content?: string | undefined;
963
+ }, {
964
+ id?: number | undefined;
965
+ type?: "query" | "user" | "global" | undefined;
966
+ query?: string | undefined;
967
+ title?: string | undefined;
968
+ category?: string | undefined;
969
+ userId?: string | undefined;
970
+ limit?: number | undefined;
971
+ filters?: {
972
+ type?: "query" | "user" | "global" | undefined;
973
+ query?: string | undefined;
974
+ category?: string | undefined;
975
+ createdBy?: string | undefined;
976
+ tags?: string[] | undefined;
977
+ } | undefined;
978
+ createdBy?: string | undefined;
979
+ updatedBy?: string | undefined;
980
+ offset?: number | undefined;
981
+ tags?: string[] | undefined;
982
+ content?: string | undefined;
983
+ }>>;
984
+ }, "strip", z.ZodTypeAny, {
985
+ operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
986
+ data?: {
987
+ id?: number | undefined;
988
+ type?: "query" | "user" | "global" | undefined;
989
+ query?: string | undefined;
990
+ title?: string | undefined;
991
+ category?: string | undefined;
992
+ userId?: string | undefined;
993
+ limit?: number | undefined;
994
+ filters?: {
995
+ type?: "query" | "user" | "global" | undefined;
996
+ query?: string | undefined;
997
+ category?: string | undefined;
998
+ createdBy?: string | undefined;
999
+ tags?: string[] | undefined;
1000
+ } | undefined;
1001
+ createdBy?: string | undefined;
1002
+ updatedBy?: string | undefined;
1003
+ offset?: number | undefined;
1004
+ tags?: string[] | undefined;
1005
+ content?: string | undefined;
1006
+ } | undefined;
1007
+ }, {
1008
+ operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
1009
+ data?: {
1010
+ id?: number | undefined;
1011
+ type?: "query" | "user" | "global" | undefined;
1012
+ query?: string | undefined;
1013
+ title?: string | undefined;
1014
+ category?: string | undefined;
1015
+ userId?: string | undefined;
1016
+ limit?: number | undefined;
1017
+ filters?: {
1018
+ type?: "query" | "user" | "global" | undefined;
1019
+ query?: string | undefined;
1020
+ category?: string | undefined;
1021
+ createdBy?: string | undefined;
1022
+ tags?: string[] | undefined;
1023
+ } | undefined;
1024
+ createdBy?: string | undefined;
1025
+ updatedBy?: string | undefined;
1026
+ offset?: number | undefined;
1027
+ tags?: string[] | undefined;
1028
+ content?: string | undefined;
1029
+ } | undefined;
1030
+ }>;
1031
+ type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
1032
+ interface T_RESPONSE {
1033
+ success: boolean;
1034
+ data?: any;
1035
+ errors: string[];
582
1036
  }
583
1037
 
584
1038
  /**
@@ -840,9 +1294,11 @@ declare class ReportManager {
840
1294
  getReportCount(): number;
841
1295
  }
842
1296
 
1297
+ type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
843
1298
  interface LLMMessages {
844
- sys: string;
1299
+ sys: SystemPrompt;
845
1300
  user: string;
1301
+ prefill?: string;
846
1302
  }
847
1303
  interface LLMOptions {
848
1304
  model?: string;
@@ -865,6 +1321,18 @@ declare class LLM {
865
1321
  static text(messages: LLMMessages, options?: LLMOptions): Promise<string>;
866
1322
  static stream<T = string>(messages: LLMMessages, options?: LLMOptions, json?: boolean): Promise<T extends string ? string : any>;
867
1323
  static streamWithTools(messages: LLMMessages, tools: Tool[], toolHandler: (toolName: string, toolInput: any) => Promise<any>, options?: LLMOptions, maxIterations?: number): Promise<string>;
1324
+ /**
1325
+ * Normalize system prompt to Anthropic format
1326
+ * Converts string to array format if needed
1327
+ * @param sys - System prompt (string or array of blocks)
1328
+ * @returns Normalized system prompt for Anthropic API
1329
+ */
1330
+ private static _normalizeSystemPrompt;
1331
+ /**
1332
+ * Log cache usage metrics from Anthropic API response
1333
+ * Shows cache hits, costs, and savings
1334
+ */
1335
+ private static _logCacheUsage;
868
1336
  /**
869
1337
  * Parse model string to extract provider and model name
870
1338
  * @param modelString - Format: "provider/model-name" or just "model-name"
@@ -881,6 +1349,17 @@ declare class LLM {
881
1349
  private static _anthropicStreamWithTools;
882
1350
  private static _groqText;
883
1351
  private static _groqStream;
1352
+ private static _geminiText;
1353
+ private static _geminiStream;
1354
+ /**
1355
+ * Recursively strip unsupported JSON Schema properties for Gemini
1356
+ * Gemini doesn't support: additionalProperties, $schema, etc.
1357
+ */
1358
+ private static _cleanSchemaForGemini;
1359
+ private static _geminiStreamWithTools;
1360
+ private static _openaiText;
1361
+ private static _openaiStream;
1362
+ private static _openaiStreamWithTools;
884
1363
  /**
885
1364
  * Parse JSON string, handling markdown code blocks and surrounding text
886
1365
  * Enhanced version with jsonrepair to handle malformed JSON from LLMs
@@ -1296,15 +1775,17 @@ declare const STORAGE_CONFIG: {
1296
1775
  */
1297
1776
  MAX_ROWS_PER_BLOCK: number;
1298
1777
  /**
1299
- * Maximum size in bytes per UIBlock (1MB)
1778
+ * Maximum size in bytes per UIBlock (500KB - reduced to save memory)
1300
1779
  */
1301
1780
  MAX_SIZE_PER_BLOCK_BYTES: number;
1302
1781
  /**
1303
1782
  * Number of days to keep threads before cleanup
1783
+ * Note: This is for in-memory storage. Conversations are also persisted to database.
1304
1784
  */
1305
1785
  THREAD_RETENTION_DAYS: number;
1306
1786
  /**
1307
1787
  * Number of days to keep UIBlocks before cleanup
1788
+ * Note: This is for in-memory storage. Data is also persisted to database.
1308
1789
  */
1309
1790
  UIBLOCK_RETENTION_DAYS: number;
1310
1791
  };
@@ -1321,14 +1802,936 @@ declare const CONTEXT_CONFIG: {
1321
1802
  MAX_CONVERSATION_CONTEXT_BLOCKS: number;
1322
1803
  };
1323
1804
 
1324
- declare const SDK_VERSION = "0.0.8";
1805
+ /**
1806
+ * LLM Usage Logger - Tracks token usage, costs, and timing for all LLM API calls
1807
+ */
1808
+ interface LLMUsageEntry {
1809
+ timestamp: string;
1810
+ requestId: string;
1811
+ provider: string;
1812
+ model: string;
1813
+ method: string;
1814
+ inputTokens: number;
1815
+ outputTokens: number;
1816
+ cacheReadTokens?: number;
1817
+ cacheWriteTokens?: number;
1818
+ totalTokens: number;
1819
+ costUSD: number;
1820
+ durationMs: number;
1821
+ toolCalls?: number;
1822
+ success: boolean;
1823
+ error?: string;
1824
+ }
1825
+ declare class LLMUsageLogger {
1826
+ private logStream;
1827
+ private logPath;
1828
+ private enabled;
1829
+ private sessionStats;
1830
+ constructor();
1831
+ private initLogStream;
1832
+ private writeHeader;
1833
+ /**
1834
+ * Calculate cost based on token usage and model
1835
+ */
1836
+ calculateCost(model: string, inputTokens: number, outputTokens: number, cacheReadTokens?: number, cacheWriteTokens?: number): number;
1837
+ /**
1838
+ * Log an LLM API call
1839
+ */
1840
+ log(entry: LLMUsageEntry): void;
1841
+ /**
1842
+ * Log session summary (call at end of request)
1843
+ */
1844
+ logSessionSummary(requestContext?: string): void;
1845
+ /**
1846
+ * Reset session stats (call at start of new user request)
1847
+ */
1848
+ resetSession(): void;
1849
+ /**
1850
+ * Reset the log file for a new request (clears previous logs)
1851
+ * Call this at the start of each USER_PROMPT_REQ
1852
+ */
1853
+ resetLogFile(requestContext?: string): void;
1854
+ /**
1855
+ * Get current session stats
1856
+ */
1857
+ getSessionStats(): {
1858
+ totalCalls: number;
1859
+ totalInputTokens: number;
1860
+ totalOutputTokens: number;
1861
+ totalCacheReadTokens: number;
1862
+ totalCacheWriteTokens: number;
1863
+ totalCostUSD: number;
1864
+ totalDurationMs: number;
1865
+ };
1866
+ /**
1867
+ * Generate a unique request ID
1868
+ */
1869
+ generateRequestId(): string;
1870
+ }
1871
+ declare const llmUsageLogger: LLMUsageLogger;
1872
+
1873
+ /**
1874
+ * User Prompt Error Logger - Captures detailed errors for USER_PROMPT_REQ
1875
+ * Logs full error details including raw strings for parse failures
1876
+ */
1877
+ declare class UserPromptErrorLogger {
1878
+ private logStream;
1879
+ private logPath;
1880
+ private enabled;
1881
+ private hasErrors;
1882
+ constructor();
1883
+ /**
1884
+ * Reset the error log file for a new request
1885
+ */
1886
+ resetLogFile(requestContext?: string): void;
1887
+ /**
1888
+ * Log a JSON parse error with the raw string that failed
1889
+ */
1890
+ logJsonParseError(context: string, rawString: string, error: Error): void;
1891
+ /**
1892
+ * Log a general error with full details
1893
+ */
1894
+ logError(context: string, error: Error | string, additionalData?: Record<string, any>): void;
1895
+ /**
1896
+ * Log a SQL query error with the full query
1897
+ */
1898
+ logSqlError(query: string, error: Error | string, params?: any[]): void;
1899
+ /**
1900
+ * Log an LLM API error
1901
+ */
1902
+ logLlmError(provider: string, model: string, method: string, error: Error | string, requestData?: any): void;
1903
+ /**
1904
+ * Log tool execution error
1905
+ */
1906
+ logToolError(toolName: string, toolInput: any, error: Error | string): void;
1907
+ /**
1908
+ * Write final summary if there were errors
1909
+ */
1910
+ writeSummary(): void;
1911
+ /**
1912
+ * Check if any errors were logged
1913
+ */
1914
+ hadErrors(): boolean;
1915
+ private write;
1916
+ }
1917
+ declare const userPromptErrorLogger: UserPromptErrorLogger;
1918
+
1919
+ /**
1920
+ * BM25L Reranker for hybrid semantic search
1921
+ *
1922
+ * BM25L is an improved variant of BM25 that provides better handling of
1923
+ * long documents and term frequency saturation. This implementation is
1924
+ * designed to rerank semantic search results from ChromaDB.
1925
+ *
1926
+ * The hybrid approach combines:
1927
+ * 1. Semantic similarity from ChromaDB embeddings (dense vectors)
1928
+ * 2. Lexical matching from BM25L (sparse, keyword-based)
1929
+ *
1930
+ * This addresses the weakness of pure semantic search which may miss
1931
+ * exact keyword matches that are important for user intent.
1932
+ */
1933
+ interface BM25LOptions {
1934
+ /** Term frequency saturation parameter (default: 1.5) */
1935
+ k1?: number;
1936
+ /** Length normalization parameter (default: 0.75) */
1937
+ b?: number;
1938
+ /** Lower-bound adjustment from BM25L paper (default: 0.5) */
1939
+ delta?: number;
1940
+ }
1941
+ interface RerankedResult<T> {
1942
+ item: T;
1943
+ originalIndex: number;
1944
+ semanticScore: number;
1945
+ bm25Score: number;
1946
+ hybridScore: number;
1947
+ }
1948
+ interface HybridSearchOptions extends BM25LOptions {
1949
+ /** Weight for semantic score (0-1, default: 0.7) */
1950
+ semanticWeight?: number;
1951
+ /** Weight for BM25 score (0-1, default: 0.3) */
1952
+ bm25Weight?: number;
1953
+ /** Minimum hybrid score threshold (0-1, default: 0) */
1954
+ minScore?: number;
1955
+ }
1956
+ /**
1957
+ * BM25L implementation for lexical scoring
1958
+ */
1959
+ declare class BM25L {
1960
+ private k1;
1961
+ private b;
1962
+ private delta;
1963
+ private documents;
1964
+ private docLengths;
1965
+ private avgDocLength;
1966
+ private termDocFreq;
1967
+ /**
1968
+ * @param documents - Array of raw documents (strings)
1969
+ * @param opts - Optional BM25L parameters
1970
+ */
1971
+ constructor(documents?: string[], opts?: BM25LOptions);
1972
+ /**
1973
+ * Tokenize text into lowercase alphanumeric tokens
1974
+ */
1975
+ tokenize(text: string): string[];
1976
+ /**
1977
+ * Compute IDF (Inverse Document Frequency) with smoothing
1978
+ */
1979
+ private idf;
1980
+ /**
1981
+ * Compute BM25L score for a single document
1982
+ */
1983
+ score(query: string, docIndex: number): number;
1984
+ /**
1985
+ * Search and rank all documents
1986
+ */
1987
+ search(query: string): Array<{
1988
+ index: number;
1989
+ score: number;
1990
+ }>;
1991
+ }
1992
+ /**
1993
+ * Hybrid reranker that combines semantic and BM25L scores
1994
+ *
1995
+ * @param query - The search query
1996
+ * @param items - Array of items to rerank
1997
+ * @param getDocument - Function to extract document text from an item
1998
+ * @param getSemanticScore - Function to extract semantic similarity score from an item
1999
+ * @param options - Hybrid search options
2000
+ * @returns Reranked items with hybrid scores
2001
+ */
2002
+ declare function hybridRerank<T>(query: string, items: T[], getDocument: (item: T) => string, getSemanticScore: (item: T) => number, options?: HybridSearchOptions): RerankedResult<T>[];
2003
+ /**
2004
+ * Simple reranking function for ChromaDB results
2005
+ *
2006
+ * This is a convenience wrapper for reranking ChromaDB query results
2007
+ * that follow the standard { ids, documents, metadatas, distances } format.
2008
+ *
2009
+ * @param query - The search query
2010
+ * @param chromaResults - ChromaDB query results
2011
+ * @param options - Hybrid search options
2012
+ * @returns Reranked results with hybrid scores
2013
+ */
2014
+ declare function rerankChromaResults(query: string, chromaResults: {
2015
+ ids: string[][];
2016
+ documents: (string | null)[][];
2017
+ metadatas: Record<string, any>[][];
2018
+ distances: number[][];
2019
+ }, options?: HybridSearchOptions): Array<{
2020
+ id: string;
2021
+ document: string | null;
2022
+ metadata: Record<string, any>;
2023
+ distance: number;
2024
+ semanticScore: number;
2025
+ bm25Score: number;
2026
+ hybridScore: number;
2027
+ }>;
2028
+ /**
2029
+ * Rerank conversation search results specifically
2030
+ *
2031
+ * This function is designed to work with the conversation-history.search collection
2032
+ * where we need to fetch more results initially and then rerank them.
2033
+ *
2034
+ * @param query - The user's search query
2035
+ * @param results - Array of conversation search results from ChromaDB
2036
+ * @param options - Hybrid search options
2037
+ * @returns Reranked results sorted by hybrid score
2038
+ */
2039
+ declare function rerankConversationResults<T extends {
2040
+ userPrompt?: string;
2041
+ similarity?: number;
2042
+ }>(query: string, results: T[], options?: HybridSearchOptions): Array<T & {
2043
+ hybridScore: number;
2044
+ bm25Score: number;
2045
+ }>;
2046
+
2047
+ /**
2048
+ * QueryExecutionService - Handles all query execution, validation, and retry logic
2049
+ * Extracted from BaseLLM for better separation of concerns
2050
+ */
2051
+
2052
+ /**
2053
+ * Context for component when requesting query fix
2054
+ */
2055
+ interface ComponentContext {
2056
+ name: string;
2057
+ type: string;
2058
+ title?: string;
2059
+ }
2060
+ /**
2061
+ * Result of query validation
2062
+ */
2063
+ interface QueryValidationResult {
2064
+ component: Component | null;
2065
+ queryKey: string;
2066
+ result: any;
2067
+ validated: boolean;
2068
+ }
2069
+ /**
2070
+ * Result of batch query validation
2071
+ */
2072
+ interface BatchValidationResult {
2073
+ components: Component[];
2074
+ queryResults: Map<string, any>;
2075
+ }
2076
+ /**
2077
+ * Configuration for QueryExecutionService
2078
+ */
2079
+ interface QueryExecutionServiceConfig {
2080
+ defaultLimit: number;
2081
+ getModelForTask: (taskType: 'simple' | 'complex') => string;
2082
+ getApiKey: (apiKey?: string) => string | undefined;
2083
+ providerName: string;
2084
+ }
2085
+ /**
2086
+ * QueryExecutionService handles all query-related operations
2087
+ */
2088
+ declare class QueryExecutionService {
2089
+ private config;
2090
+ constructor(config: QueryExecutionServiceConfig);
2091
+ /**
2092
+ * Get the cache key for a query
2093
+ * This ensures the cache key matches what the frontend will send
2094
+ */
2095
+ getQueryCacheKey(query: any): string;
2096
+ /**
2097
+ * Execute a query against the database
2098
+ * @param query - The SQL query to execute (string or object with sql/values)
2099
+ * @param collections - Collections object containing database execute function
2100
+ * @returns Object with result data and cache key
2101
+ */
2102
+ executeQuery(query: any, collections: any): Promise<{
2103
+ result: any;
2104
+ cacheKey: string;
2105
+ }>;
2106
+ /**
2107
+ * Request the LLM to fix a failed SQL query
2108
+ * @param failedQuery - The query that failed execution
2109
+ * @param errorMessage - The error message from the failed execution
2110
+ * @param componentContext - Context about the component
2111
+ * @param apiKey - Optional API key
2112
+ * @returns Fixed query string
2113
+ */
2114
+ requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
2115
+ /**
2116
+ * Validate a single component's query with retry logic
2117
+ * @param component - The component to validate
2118
+ * @param collections - Collections object containing database execute function
2119
+ * @param apiKey - Optional API key for LLM calls
2120
+ * @returns Validation result with component, query key, and result
2121
+ */
2122
+ validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
2123
+ /**
2124
+ * Validate multiple component queries in parallel
2125
+ * @param components - Array of components with potential queries
2126
+ * @param collections - Collections object containing database execute function
2127
+ * @param apiKey - Optional API key for LLM calls
2128
+ * @returns Object with validated components and query results map
2129
+ */
2130
+ validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
2131
+ }
2132
+
2133
+ /**
2134
+ * StreamBuffer - Buffered streaming utility for smoother text delivery
2135
+ * Batches small chunks together and flushes at regular intervals
2136
+ */
2137
+ type StreamCallback = (chunk: string) => void;
2138
+ /**
2139
+ * StreamBuffer class for managing buffered streaming output
2140
+ * Provides smooth text delivery by batching small chunks
2141
+ */
2142
+ declare class StreamBuffer {
2143
+ private buffer;
2144
+ private flushTimer;
2145
+ private callback;
2146
+ private fullText;
2147
+ constructor(callback?: StreamCallback);
2148
+ /**
2149
+ * Check if the buffer has a callback configured
2150
+ */
2151
+ hasCallback(): boolean;
2152
+ /**
2153
+ * Get all text that has been written (including already flushed)
2154
+ */
2155
+ getFullText(): string;
2156
+ /**
2157
+ * Write a chunk to the buffer
2158
+ * Large chunks or chunks with newlines are flushed immediately
2159
+ * Small chunks are batched and flushed after a short interval
2160
+ *
2161
+ * @param chunk - Text chunk to write
2162
+ */
2163
+ write(chunk: string): void;
2164
+ /**
2165
+ * Flush the buffer immediately
2166
+ * Call this before tool execution or other operations that need clean output
2167
+ */
2168
+ flush(): void;
2169
+ /**
2170
+ * Internal flush implementation
2171
+ */
2172
+ private flushNow;
2173
+ /**
2174
+ * Clean up resources
2175
+ * Call this when done with the buffer
2176
+ */
2177
+ dispose(): void;
2178
+ }
2179
+
2180
+ /**
2181
+ * ToolExecutorService - Handles execution of SQL queries and external tools
2182
+ * Extracted from BaseLLM.generateTextResponse for better separation of concerns
2183
+ */
2184
+
2185
+ /**
2186
+ * External tool definition
2187
+ */
2188
+ interface ExternalTool {
2189
+ id: string;
2190
+ name: string;
2191
+ description?: string;
2192
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
2193
+ toolType?: 'source' | 'direct';
2194
+ /** Full untruncated schema for source agent (all columns visible) */
2195
+ fullSchema?: string;
2196
+ fn: (input: any) => Promise<any>;
2197
+ limit?: number;
2198
+ outputSchema?: any;
2199
+ executionType?: 'immediate' | 'deferred';
2200
+ userProvidedData?: any;
2201
+ }
2202
+ /**
2203
+ * Executed tool tracking info
2204
+ */
2205
+ interface ExecutedToolInfo {
2206
+ id: string;
2207
+ name: string;
2208
+ params: any;
2209
+ result: {
2210
+ _totalRecords: number;
2211
+ _recordsShown: number;
2212
+ _metadata?: any;
2213
+ _sampleData: any[];
2214
+ };
2215
+ outputSchema?: any;
2216
+ sourceSchema?: string;
2217
+ sourceType?: string;
2218
+ }
2219
+
2220
+ /**
2221
+ * Task types for model selection
2222
+ * - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
2223
+ * - 'simple': Classification, action generation (uses fast model in balanced mode)
2224
+ */
2225
+ type TaskType = 'complex' | 'simple';
2226
+ interface BaseLLMConfig {
2227
+ model?: string;
2228
+ fastModel?: string;
2229
+ defaultLimit?: number;
2230
+ apiKey?: string;
2231
+ /**
2232
+ * Model selection strategy:
2233
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
2234
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
2235
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
2236
+ */
2237
+ modelStrategy?: ModelStrategy;
2238
+ conversationSimilarityThreshold?: number;
2239
+ }
2240
+ /**
2241
+ * BaseLLM abstract class for AI-powered component generation and matching
2242
+ * Provides common functionality for all LLM providers
2243
+ */
2244
+ declare abstract class BaseLLM {
2245
+ protected model: string;
2246
+ protected fastModel: string;
2247
+ protected defaultLimit: number;
2248
+ protected apiKey?: string;
2249
+ protected modelStrategy: ModelStrategy;
2250
+ protected conversationSimilarityThreshold: number;
2251
+ protected queryService: QueryExecutionService;
2252
+ constructor(config?: BaseLLMConfig);
2253
+ /**
2254
+ * Get the appropriate model based on task type and model strategy
2255
+ * @param taskType - 'complex' for text generation/matching, 'simple' for classification/actions
2256
+ * @returns The model string to use for this task
2257
+ */
2258
+ protected getModelForTask(taskType: TaskType): string;
2259
+ /**
2260
+ * Set the model strategy at runtime
2261
+ * @param strategy - 'best', 'fast', or 'balanced'
2262
+ */
2263
+ setModelStrategy(strategy: ModelStrategy): void;
2264
+ /**
2265
+ * Get the current model strategy
2266
+ * @returns The current model strategy
2267
+ */
2268
+ getModelStrategy(): ModelStrategy;
2269
+ /**
2270
+ * Set the conversation similarity threshold at runtime
2271
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2272
+ */
2273
+ setConversationSimilarityThreshold(threshold: number): void;
2274
+ /**
2275
+ * Get the current conversation similarity threshold
2276
+ * @returns The current threshold value
2277
+ */
2278
+ getConversationSimilarityThreshold(): number;
2279
+ /**
2280
+ * Get the default model for this provider (used for complex tasks like text generation)
2281
+ */
2282
+ protected abstract getDefaultModel(): string;
2283
+ /**
2284
+ * Get the default fast model for this provider (used for simple tasks: classification, matching, actions)
2285
+ * Should return a cheaper/faster model like Haiku for Anthropic
2286
+ */
2287
+ protected abstract getDefaultFastModel(): string;
2288
+ /**
2289
+ * Get the default API key from environment
2290
+ */
2291
+ protected abstract getDefaultApiKey(): string | undefined;
2292
+ /**
2293
+ * Get the provider name (for logging)
2294
+ */
2295
+ protected abstract getProviderName(): string;
2296
+ /**
2297
+ * Get the API key (from instance, parameter, or environment)
2298
+ */
2299
+ protected getApiKey(apiKey?: string): string | undefined;
2300
+ /**
2301
+ * Check if a component contains a Form (data_modification component)
2302
+ * Forms have hardcoded defaultValues that become stale when cached
2303
+ * This checks both single Form components and Forms inside MultiComponentContainer
2304
+ */
2305
+ protected containsFormComponent(component: any): boolean;
2306
+ /**
2307
+ * Match components from text response suggestions and generate follow-up questions
2308
+ * Takes a text response with component suggestions (c1:type format) and matches with available components
2309
+ * Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
2310
+ * All components are placed in a default MultiComponentContainer layout
2311
+ * @param analysisContent - The text response containing component suggestions
2312
+ * @param components - List of available components
2313
+ * @param apiKey - Optional API key
2314
+ * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
2315
+ * @returns Object containing matched components, layout title/description, and follow-up actions
2316
+ */
2317
+ matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
2318
+ components: Component[];
2319
+ layoutTitle: string;
2320
+ layoutDescription: string;
2321
+ actions: Action[];
2322
+ }>;
2323
+ /**
2324
+ * Classify user question into category and detect external tools needed
2325
+ * Determines if question is for data analysis, requires external tools, or needs text response
2326
+ */
2327
+ classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
2328
+ category: 'data_analysis' | 'data_modification' | 'general';
2329
+ externalTools: Array<{
2330
+ type: string;
2331
+ name: string;
2332
+ description: string;
2333
+ parameters: Record<string, any>;
2334
+ }>;
2335
+ dataAnalysisType?: 'visualization' | 'calculation' | 'comparison' | 'trend';
2336
+ reasoning: string;
2337
+ confidence: number;
2338
+ }>;
2339
+ /**
2340
+ * Adapt UI block parameters based on current user question
2341
+ * Takes a matched UI block from semantic search and modifies its props to answer the new question
2342
+ * Also adapts the cached text response to match the new question
2343
+ */
2344
+ adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
2345
+ success: boolean;
2346
+ adaptedComponent?: Component;
2347
+ adaptedTextResponse?: string;
2348
+ parametersChanged?: Array<{
2349
+ field: string;
2350
+ reason: string;
2351
+ }>;
2352
+ explanation: string;
2353
+ }>;
2354
+ /**
2355
+ * Generate text-based response for user question
2356
+ * This provides conversational text responses instead of component generation
2357
+ * Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
2358
+ * After generating text response, if components are provided, matches suggested components
2359
+ */
2360
+ generateTextResponse(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, collections?: any, components?: Component[], externalTools?: any[], category?: 'data_analysis' | 'data_modification' | 'general', userId?: string): Promise<T_RESPONSE>;
2361
+ /**
2362
+ * Main orchestration function with semantic search and multi-step classification
2363
+ * NEW FLOW (Recommended):
2364
+ * 1. Semantic search: Check previous conversations (>60% match)
2365
+ * - If match found → Adapt UI block parameters and return
2366
+ * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
2367
+ * 3. Route appropriately based on category and response mode
2368
+ */
2369
+ handleUserRequest(userPrompt: string, components: Component[], apiKey?: string, conversationHistory?: string, responseMode?: 'component' | 'text', streamCallback?: (chunk: string) => void, collections?: any, externalTools?: any[], userId?: string): Promise<T_RESPONSE>;
2370
+ /**
2371
+ * Generate next questions that the user might ask based on the original prompt and generated component
2372
+ * This helps provide intelligent suggestions for follow-up queries
2373
+ * For general/conversational questions without components, pass textResponse instead
2374
+ */
2375
+ generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string): Promise<string[]>;
2376
+ }
2377
+
2378
+ interface AnthropicLLMConfig extends BaseLLMConfig {
2379
+ }
2380
+ /**
2381
+ * AnthropicLLM class for handling AI-powered component generation and matching using Anthropic Claude
2382
+ */
2383
+ declare class AnthropicLLM extends BaseLLM {
2384
+ constructor(config?: AnthropicLLMConfig);
2385
+ protected getDefaultModel(): string;
2386
+ protected getDefaultFastModel(): string;
2387
+ protected getDefaultApiKey(): string | undefined;
2388
+ protected getProviderName(): string;
2389
+ }
2390
+ declare const anthropicLLM: AnthropicLLM;
2391
+
2392
+ interface GroqLLMConfig extends BaseLLMConfig {
2393
+ }
2394
+ /**
2395
+ * GroqLLM class for handling AI-powered component generation and matching using Groq
2396
+ */
2397
+ declare class GroqLLM extends BaseLLM {
2398
+ constructor(config?: GroqLLMConfig);
2399
+ protected getDefaultModel(): string;
2400
+ protected getDefaultFastModel(): string;
2401
+ protected getDefaultApiKey(): string | undefined;
2402
+ protected getProviderName(): string;
2403
+ }
2404
+ declare const groqLLM: GroqLLM;
2405
+
2406
+ interface GeminiLLMConfig extends BaseLLMConfig {
2407
+ }
2408
+ /**
2409
+ * GeminiLLM class for handling AI-powered component generation and matching using Google Gemini
2410
+ */
2411
+ declare class GeminiLLM extends BaseLLM {
2412
+ constructor(config?: GeminiLLMConfig);
2413
+ protected getDefaultModel(): string;
2414
+ protected getDefaultFastModel(): string;
2415
+ protected getDefaultApiKey(): string | undefined;
2416
+ protected getProviderName(): string;
2417
+ }
2418
+ declare const geminiLLM: GeminiLLM;
2419
+
2420
+ interface OpenAILLMConfig extends BaseLLMConfig {
2421
+ }
2422
+ /**
2423
+ * OpenAILLM class for handling AI-powered component generation and matching using OpenAI GPT models
2424
+ */
2425
+ declare class OpenAILLM extends BaseLLM {
2426
+ constructor(config?: OpenAILLMConfig);
2427
+ protected getDefaultModel(): string;
2428
+ protected getDefaultFastModel(): string;
2429
+ protected getDefaultApiKey(): string | undefined;
2430
+ protected getProviderName(): string;
2431
+ }
2432
+ declare const openaiLLM: OpenAILLM;
2433
+
2434
+ /**
2435
+ * Query Cache - Stores query results with configurable TTL
2436
+ * Used to avoid re-executing queries that were already validated
2437
+ */
2438
+ declare class QueryCache {
2439
+ private cache;
2440
+ private queryIdCache;
2441
+ private ttlMs;
2442
+ private cleanupInterval;
2443
+ constructor();
2444
+ /**
2445
+ * Set the cache TTL (Time To Live)
2446
+ * @param minutes - TTL in minutes (default: 5)
2447
+ */
2448
+ setTTL(minutes: number): void;
2449
+ /**
2450
+ * Get the current TTL in minutes
2451
+ */
2452
+ getTTL(): number;
2453
+ /**
2454
+ * Store query result in cache
2455
+ * Key is the exact query string (or JSON for parameterized queries)
2456
+ */
2457
+ set(query: string, data: any): void;
2458
+ /**
2459
+ * Get cached result if exists and not expired
2460
+ */
2461
+ get(query: string): any | null;
2462
+ /**
2463
+ * Check if query exists in cache (not expired)
2464
+ */
2465
+ has(query: string): boolean;
2466
+ /**
2467
+ * Remove a specific query from cache
2468
+ */
2469
+ delete(query: string): void;
2470
+ /**
2471
+ * Clear all cached entries
2472
+ */
2473
+ clear(): void;
2474
+ /**
2475
+ * Get cache statistics
2476
+ */
2477
+ getStats(): {
2478
+ size: number;
2479
+ oldestEntryAge: number | null;
2480
+ };
2481
+ /**
2482
+ * Start periodic cleanup of expired entries
2483
+ */
2484
+ private startCleanup;
2485
+ /**
2486
+ * Generate a unique query ID
2487
+ */
2488
+ private generateQueryId;
2489
+ /**
2490
+ * Store a query by ID. Returns the generated queryId.
2491
+ * The query is stored server-side; only the queryId is sent to the frontend.
2492
+ */
2493
+ storeQuery(query: any, data?: any): string;
2494
+ /**
2495
+ * Get a stored query by its ID (not expired)
2496
+ */
2497
+ getQuery(queryId: string): {
2498
+ query: any;
2499
+ data: any;
2500
+ } | null;
2501
+ /**
2502
+ * Update cached data for a queryId
2503
+ */
2504
+ setQueryData(queryId: string, data: any): void;
2505
+ /**
2506
+ * Stop cleanup interval (for graceful shutdown)
2507
+ */
2508
+ destroy(): void;
2509
+ }
2510
+ declare const queryCache: QueryCache;
2511
+
2512
+ /**
2513
+ * Manages conversation history scoped per user + dashboard.
2514
+ * Each user-dashboard pair has its own isolated history that expires after a configurable TTL.
2515
+ */
2516
+ declare class DashboardConversationHistory {
2517
+ private histories;
2518
+ private ttlMs;
2519
+ private maxEntries;
2520
+ private cleanupInterval;
2521
+ constructor();
2522
+ /**
2523
+ * Set the TTL for dashboard histories
2524
+ * @param minutes - TTL in minutes
2525
+ */
2526
+ setTTL(minutes: number): void;
2527
+ /**
2528
+ * Set max entries per dashboard
2529
+ */
2530
+ setMaxEntries(max: number): void;
2531
+ /**
2532
+ * Add a conversation entry for a user's dashboard
2533
+ */
2534
+ addEntry(dashboardId: string, userPrompt: string, componentSummary: string, userId?: string): void;
2535
+ /**
2536
+ * Get formatted conversation history for a user's dashboard
2537
+ */
2538
+ getHistory(dashboardId: string, userId?: string): string;
2539
+ /**
2540
+ * Clear history for a specific user's dashboard
2541
+ */
2542
+ clearDashboard(dashboardId: string, userId?: string): void;
2543
+ /**
2544
+ * Clear all dashboard histories
2545
+ */
2546
+ clearAll(): void;
2547
+ /**
2548
+ * Start periodic cleanup of expired histories
2549
+ */
2550
+ private startCleanup;
2551
+ /**
2552
+ * Stop cleanup interval (for graceful shutdown)
2553
+ */
2554
+ destroy(): void;
2555
+ }
2556
+ declare const dashboardConversationHistory: DashboardConversationHistory;
2557
+
2558
+ /**
2559
+ * Multi-Agent Architecture Types
2560
+ *
2561
+ * Defines interfaces for the hierarchical agent system:
2562
+ * - Main Agent: ONE LLM.streamWithTools() call with source agent tools
2563
+ * - Source Agents: independent agents that query individual data sources
2564
+ *
2565
+ * The main agent sees only source summaries. When it calls a source tool,
2566
+ * the SourceAgent runs independently (own LLM, own retries) and returns clean data.
2567
+ */
2568
+
2569
+ /**
2570
+ * Per-entity detail: name, row count, and column names.
2571
+ * Gives the main agent enough context to route to the right source.
2572
+ */
2573
+ interface EntityDetail {
2574
+ /** Entity name (table, sheet, endpoint) */
2575
+ name: string;
2576
+ /** Approximate row count */
2577
+ rowCount?: number;
2578
+ /** Column/field names */
2579
+ columns: string[];
2580
+ }
2581
+ /**
2582
+ * Representation of a data source for the main agent.
2583
+ * Contains entity names WITH column names so the LLM can route accurately.
2584
+ */
2585
+ interface SourceSummary {
2586
+ /** Source ID (matches tool ID prefix) */
2587
+ id: string;
2588
+ /** Human-readable source name */
2589
+ name: string;
2590
+ /** Source type: postgres, excel, rest_api, etc. */
2591
+ type: string;
2592
+ /** Brief description of what data this source contains */
2593
+ description: string;
2594
+ /** Detailed entity info with column names for routing */
2595
+ entityDetails: EntityDetail[];
2596
+ /** The tool ID associated with this source */
2597
+ toolId: string;
2598
+ }
2599
+ /**
2600
+ * What a source agent returns after querying its data source.
2601
+ * The main agent uses this to analyze and compose the final response.
2602
+ */
2603
+ interface SourceAgentResult {
2604
+ /** Source ID */
2605
+ sourceId: string;
2606
+ /** Source name */
2607
+ sourceName: string;
2608
+ /** Whether the query succeeded */
2609
+ success: boolean;
2610
+ /** Result data rows */
2611
+ data: any[];
2612
+ /** Metadata about the query execution */
2613
+ metadata: SourceAgentMetadata;
2614
+ /** Tool execution info (reused for component generation) */
2615
+ executedTool: ExecutedToolInfo;
2616
+ /** Error message if failed */
2617
+ error?: string;
2618
+ }
2619
+ interface SourceAgentMetadata {
2620
+ /** Total rows that matched the query (before limit) */
2621
+ totalRowsMatched: number;
2622
+ /** Rows actually returned (after limit) */
2623
+ rowsReturned: number;
2624
+ /** Whether the result was truncated by the row limit */
2625
+ isLimited: boolean;
2626
+ /** The query/params that were executed */
2627
+ queryExecuted?: string;
2628
+ /** Execution time in milliseconds */
2629
+ executionTimeMs: number;
2630
+ }
2631
+ /**
2632
+ * The complete response from the multi-agent system.
2633
+ * Contains everything needed for text display + component generation.
2634
+ */
2635
+ interface AgentResponse {
2636
+ /** Generated text response (analysis of the data) */
2637
+ text: string;
2638
+ /** All executed tools across all source agents (for component generation) */
2639
+ executedTools: ExecutedToolInfo[];
2640
+ /** Individual results from each source agent */
2641
+ sourceResults: SourceAgentResult[];
2642
+ }
2643
+ /**
2644
+ * Configuration for the multi-agent system.
2645
+ * Controls limits, models, and behavior.
2646
+ */
2647
+ interface AgentConfig {
2648
+ /** Max rows a source agent can return (default: 50) */
2649
+ maxRowsPerSource: number;
2650
+ /** Model for the main agent (routing + analysis in one LLM call) */
2651
+ mainAgentModel: string;
2652
+ /** Model for source agent query generation */
2653
+ sourceAgentModel: string;
2654
+ /** API key for LLM calls */
2655
+ apiKey?: string;
2656
+ /** Max retry attempts per source agent */
2657
+ maxRetries: number;
2658
+ /** Max tool calling iterations for the main agent loop */
2659
+ maxIterations: number;
2660
+ /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
2661
+ globalKnowledgeBase?: string;
2662
+ /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
2663
+ knowledgeBaseContext?: string;
2664
+ }
2665
+ /**
2666
+ * Default agent configuration
2667
+ */
2668
+ declare const DEFAULT_AGENT_CONFIG: AgentConfig;
2669
+
2670
+ /**
2671
+ * Main Agent (Orchestrator)
2672
+ *
2673
+ * A single LLM.streamWithTools() call that handles everything:
2674
+ * - Routing: decides which source(s) to query based on summaries
2675
+ * - Querying: calls source tools (each wraps an independent SourceAgent)
2676
+ * - Direct tools: calls pre-built function tools directly with LLM-provided params
2677
+ * - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
2678
+ * - Analysis: generates final text response from the data
2679
+ *
2680
+ * Two tool types:
2681
+ * - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
2682
+ * - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
2683
+ */
2684
+
2685
+ declare class MainAgent {
2686
+ private externalTools;
2687
+ private config;
2688
+ private streamBuffer;
2689
+ constructor(externalTools: ExternalTool[], config: AgentConfig, streamBuffer?: StreamBuffer);
2690
+ /**
2691
+ * Handle a user question using the multi-agent system.
2692
+ *
2693
+ * This is ONE LLM.streamWithTools() call. The LLM:
2694
+ * 1. Sees source summaries + direct tool descriptions in system prompt
2695
+ * 2. Decides which tool(s) to call (routing)
2696
+ * 3. Source tools → SourceAgent runs independently → returns data
2697
+ * 4. Direct tools → fn() called directly with LLM params → returns data
2698
+ * 5. Generates final analysis text
2699
+ */
2700
+ handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void): Promise<AgentResponse>;
2701
+ /**
2702
+ * Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
2703
+ */
2704
+ private handleDirectTool;
2705
+ /**
2706
+ * Build the main agent's system prompt with source summaries and direct tool descriptions.
2707
+ */
2708
+ private buildSystemPrompt;
2709
+ /**
2710
+ * Build tool definitions for source tools — summary-only descriptions.
2711
+ * The full schema is inside the SourceAgent which runs independently.
2712
+ */
2713
+ private buildSourceToolDefinitions;
2714
+ /**
2715
+ * Build tool definitions for direct tools — expose their actual params.
2716
+ * These are called directly by the main agent LLM, no SourceAgent.
2717
+ */
2718
+ private buildDirectToolDefinitions;
2719
+ /**
2720
+ * Format a source agent's result as a clean string for the main agent LLM.
2721
+ */
2722
+ private formatResultForMainAgent;
2723
+ /**
2724
+ * Get source summaries (for external inspection/debugging).
2725
+ */
2726
+ getSourceSummaries(): SourceSummary[];
2727
+ }
2728
+
1325
2729
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
1326
2730
  declare class SuperatomSDK {
1327
2731
  private ws;
1328
2732
  private url;
1329
- private apiKey;
2733
+ private apiKey?;
1330
2734
  private projectId;
1331
- private userId;
1332
2735
  private type;
1333
2736
  private bundleDir;
1334
2737
  private messageHandlers;
@@ -1341,10 +2744,19 @@ declare class SuperatomSDK {
1341
2744
  private tools;
1342
2745
  private anthropicApiKey;
1343
2746
  private groqApiKey;
2747
+ private geminiApiKey;
2748
+ private openaiApiKey;
1344
2749
  private llmProviders;
2750
+ private databaseType;
2751
+ private modelStrategy;
2752
+ private conversationSimilarityThreshold;
1345
2753
  private userManager;
1346
2754
  private dashboardManager;
1347
2755
  private reportManager;
2756
+ private pingInterval;
2757
+ private lastPong;
2758
+ private readonly PING_INTERVAL_MS;
2759
+ private readonly PONG_TIMEOUT_MS;
1348
2760
  constructor(config: SuperatomSDKConfig);
1349
2761
  /**
1350
2762
  * Initialize PromptLoader and load prompts into memory
@@ -1384,9 +2796,11 @@ declare class SuperatomSDK {
1384
2796
  */
1385
2797
  private handleMessage;
1386
2798
  /**
1387
- * Send a message to the Superatom service
2799
+ * Send a message to the Superatom service.
2800
+ * Returns true if the message was sent, false if the WebSocket is not connected.
2801
+ * Does NOT throw on closed connections — callers can check the return value if needed.
1388
2802
  */
1389
- send(message: Message): void;
2803
+ send(message: Message): boolean;
1390
2804
  /**
1391
2805
  * Register a message handler to receive all messages
1392
2806
  */
@@ -1412,6 +2826,19 @@ declare class SuperatomSDK {
1412
2826
  */
1413
2827
  addCollection<TParams = any, TResult = any>(collectionName: string, operation: CollectionOperation | string, handler: CollectionHandler<TParams, TResult>): void;
1414
2828
  private handleReconnect;
2829
+ /**
2830
+ * Start heartbeat to keep WebSocket connection alive
2831
+ * Sends PING every 3 minutes to prevent idle timeout from cloud infrastructure
2832
+ */
2833
+ private startHeartbeat;
2834
+ /**
2835
+ * Stop the heartbeat interval
2836
+ */
2837
+ private stopHeartbeat;
2838
+ /**
2839
+ * Handle PONG response from server
2840
+ */
2841
+ private handlePong;
1415
2842
  private storeComponents;
1416
2843
  /**
1417
2844
  * Set tools for the SDK instance
@@ -1421,6 +2848,34 @@ declare class SuperatomSDK {
1421
2848
  * Get the stored tools
1422
2849
  */
1423
2850
  getTools(): Tool$1[];
2851
+ /**
2852
+ * Apply model strategy to all LLM provider singletons
2853
+ * @param strategy - 'best', 'fast', or 'balanced'
2854
+ */
2855
+ private applyModelStrategy;
2856
+ /**
2857
+ * Set model strategy at runtime
2858
+ * @param strategy - 'best', 'fast', or 'balanced'
2859
+ */
2860
+ setModelStrategy(strategy: ModelStrategy): void;
2861
+ /**
2862
+ * Get current model strategy
2863
+ */
2864
+ getModelStrategy(): ModelStrategy;
2865
+ /**
2866
+ * Apply conversation similarity threshold to all LLM provider singletons
2867
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2868
+ */
2869
+ private applyConversationSimilarityThreshold;
2870
+ /**
2871
+ * Set conversation similarity threshold at runtime
2872
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2873
+ */
2874
+ setConversationSimilarityThreshold(threshold: number): void;
2875
+ /**
2876
+ * Get current conversation similarity threshold
2877
+ */
2878
+ getConversationSimilarityThreshold(): number;
1424
2879
  }
1425
2880
 
1426
- export { type Action, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type IncomingMessage, LLM, type LogLevel, type Message, SDK_VERSION, STORAGE_CONFIG, SuperatomSDK, type SuperatomSDKConfig, Thread, ThreadManager, type Tool$1 as Tool, UIBlock, UILogCollector, type User, UserManager, type UsersData, logger };
2881
+ export { type Action, type AgentConfig, type AgentResponse, BM25L, type BM25LOptions, type BaseLLMConfig, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, DEFAULT_AGENT_CONFIG, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, MainAgent, type Message, type ModelStrategy, type OutputField, type RerankedResult, STORAGE_CONFIG, SuperatomSDK, type SuperatomSDKConfig, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, type ToolOutputSchema, UIBlock, UILogCollector, type User, UserManager, type UsersData, anthropicLLM, dashboardConversationHistory, geminiLLM, groqLLM, hybridRerank, llmUsageLogger, logger, openaiLLM, queryCache, rerankChromaResults, rerankConversationResults, userPromptErrorLogger };