@superatomai/sdk-node 0.0.11 → 0.0.12-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,22 +626,407 @@ 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>;
740
+ declare const ToolSchema: z.ZodObject<{
741
+ id: z.ZodString;
742
+ name: z.ZodString;
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>;
748
+ params: z.ZodRecord<z.ZodString, z.ZodString>;
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
+ }>>;
780
+ }, "strip", z.ZodTypeAny, {
781
+ id: string;
782
+ params: Record<string, string>;
783
+ name: string;
784
+ description: string;
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;
796
+ }, {
797
+ id: string;
798
+ params: Record<string, string>;
799
+ name: string;
800
+ description: string;
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;
812
+ }>;
813
+ type Tool$1 = z.infer<typeof ToolSchema>;
546
814
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
547
815
  type CollectionHandler<TParams = any, TResult = any> = (params: TParams) => Promise<TResult> | TResult;
548
- type LLMProvider = 'anthropic' | 'groq';
816
+ type LLMProvider = 'anthropic' | 'groq' | 'gemini' | 'openai';
549
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
+ }
550
842
  interface SuperatomSDKConfig {
551
843
  url?: string;
552
- apiKey: string;
844
+ apiKey?: string;
553
845
  projectId: string;
554
- userId?: string;
555
846
  type?: string;
556
847
  bundleDir?: string;
557
848
  promptsDir?: string;
849
+ databaseType?: DatabaseType;
558
850
  ANTHROPIC_API_KEY?: string;
559
851
  GROQ_API_KEY?: string;
852
+ GEMINI_API_KEY?: string;
853
+ OPENAI_API_KEY?: string;
560
854
  LLM_PROVIDERS?: LLMProvider[];
561
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
+
883
+ declare const KbNodesQueryFiltersSchema: z.ZodObject<{
884
+ query: z.ZodOptional<z.ZodString>;
885
+ category: z.ZodOptional<z.ZodString>;
886
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
887
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
888
+ createdBy: z.ZodOptional<z.ZodString>;
889
+ }, "strip", z.ZodTypeAny, {
890
+ type?: "query" | "user" | "global" | undefined;
891
+ query?: string | undefined;
892
+ category?: string | undefined;
893
+ createdBy?: string | undefined;
894
+ tags?: string[] | undefined;
895
+ }, {
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 KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
903
+ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
904
+ operation: z.ZodEnum<["create", "update", "delete", "getAll", "getOne", "search", "getByCategory", "getByUser", "getCategories", "getTags"]>;
905
+ data: z.ZodOptional<z.ZodObject<{
906
+ id: z.ZodOptional<z.ZodNumber>;
907
+ title: z.ZodOptional<z.ZodString>;
908
+ content: z.ZodOptional<z.ZodString>;
909
+ category: z.ZodOptional<z.ZodString>;
910
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
911
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
912
+ createdBy: z.ZodOptional<z.ZodString>;
913
+ updatedBy: z.ZodOptional<z.ZodString>;
914
+ userId: z.ZodOptional<z.ZodString>;
915
+ query: z.ZodOptional<z.ZodString>;
916
+ filters: z.ZodOptional<z.ZodObject<{
917
+ query: z.ZodOptional<z.ZodString>;
918
+ category: z.ZodOptional<z.ZodString>;
919
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
920
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
921
+ createdBy: z.ZodOptional<z.ZodString>;
922
+ }, "strip", z.ZodTypeAny, {
923
+ type?: "query" | "user" | "global" | undefined;
924
+ query?: string | undefined;
925
+ category?: string | undefined;
926
+ createdBy?: string | undefined;
927
+ tags?: string[] | undefined;
928
+ }, {
929
+ type?: "query" | "user" | "global" | undefined;
930
+ query?: string | undefined;
931
+ category?: string | undefined;
932
+ createdBy?: string | undefined;
933
+ tags?: string[] | undefined;
934
+ }>>;
935
+ limit: z.ZodOptional<z.ZodNumber>;
936
+ offset: z.ZodOptional<z.ZodNumber>;
937
+ }, "strip", z.ZodTypeAny, {
938
+ id?: number | undefined;
939
+ type?: "query" | "user" | "global" | undefined;
940
+ query?: string | undefined;
941
+ title?: string | undefined;
942
+ category?: string | undefined;
943
+ userId?: string | undefined;
944
+ limit?: number | undefined;
945
+ filters?: {
946
+ type?: "query" | "user" | "global" | undefined;
947
+ query?: string | undefined;
948
+ category?: string | undefined;
949
+ createdBy?: string | undefined;
950
+ tags?: string[] | undefined;
951
+ } | undefined;
952
+ createdBy?: string | undefined;
953
+ updatedBy?: string | undefined;
954
+ offset?: number | undefined;
955
+ tags?: string[] | undefined;
956
+ content?: string | undefined;
957
+ }, {
958
+ id?: number | undefined;
959
+ type?: "query" | "user" | "global" | undefined;
960
+ query?: string | undefined;
961
+ title?: string | undefined;
962
+ category?: string | undefined;
963
+ userId?: string | undefined;
964
+ limit?: number | undefined;
965
+ filters?: {
966
+ type?: "query" | "user" | "global" | undefined;
967
+ query?: string | undefined;
968
+ category?: string | undefined;
969
+ createdBy?: string | undefined;
970
+ tags?: string[] | undefined;
971
+ } | undefined;
972
+ createdBy?: string | undefined;
973
+ updatedBy?: string | undefined;
974
+ offset?: number | undefined;
975
+ tags?: string[] | undefined;
976
+ content?: string | undefined;
977
+ }>>;
978
+ }, "strip", z.ZodTypeAny, {
979
+ operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
980
+ data?: {
981
+ id?: number | undefined;
982
+ type?: "query" | "user" | "global" | undefined;
983
+ query?: string | undefined;
984
+ title?: string | undefined;
985
+ category?: string | undefined;
986
+ userId?: string | undefined;
987
+ limit?: number | undefined;
988
+ filters?: {
989
+ type?: "query" | "user" | "global" | undefined;
990
+ query?: string | undefined;
991
+ category?: string | undefined;
992
+ createdBy?: string | undefined;
993
+ tags?: string[] | undefined;
994
+ } | undefined;
995
+ createdBy?: string | undefined;
996
+ updatedBy?: string | undefined;
997
+ offset?: number | undefined;
998
+ tags?: string[] | undefined;
999
+ content?: string | undefined;
1000
+ } | undefined;
1001
+ }, {
1002
+ operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
1003
+ data?: {
1004
+ id?: number | undefined;
1005
+ type?: "query" | "user" | "global" | undefined;
1006
+ query?: string | undefined;
1007
+ title?: string | undefined;
1008
+ category?: string | undefined;
1009
+ userId?: string | undefined;
1010
+ limit?: number | undefined;
1011
+ filters?: {
1012
+ type?: "query" | "user" | "global" | undefined;
1013
+ query?: string | undefined;
1014
+ category?: string | undefined;
1015
+ createdBy?: string | undefined;
1016
+ tags?: string[] | undefined;
1017
+ } | undefined;
1018
+ createdBy?: string | undefined;
1019
+ updatedBy?: string | undefined;
1020
+ offset?: number | undefined;
1021
+ tags?: string[] | undefined;
1022
+ content?: string | undefined;
1023
+ } | undefined;
1024
+ }>;
1025
+ type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
1026
+ interface T_RESPONSE {
1027
+ success: boolean;
1028
+ data?: any;
1029
+ errors: string[];
562
1030
  }
563
1031
 
564
1032
  /**
@@ -820,9 +1288,11 @@ declare class ReportManager {
820
1288
  getReportCount(): number;
821
1289
  }
822
1290
 
1291
+ type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
823
1292
  interface LLMMessages {
824
- sys: string;
1293
+ sys: SystemPrompt;
825
1294
  user: string;
1295
+ prefill?: string;
826
1296
  }
827
1297
  interface LLMOptions {
828
1298
  model?: string;
@@ -845,6 +1315,18 @@ declare class LLM {
845
1315
  static text(messages: LLMMessages, options?: LLMOptions): Promise<string>;
846
1316
  static stream<T = string>(messages: LLMMessages, options?: LLMOptions, json?: boolean): Promise<T extends string ? string : any>;
847
1317
  static streamWithTools(messages: LLMMessages, tools: Tool[], toolHandler: (toolName: string, toolInput: any) => Promise<any>, options?: LLMOptions, maxIterations?: number): Promise<string>;
1318
+ /**
1319
+ * Normalize system prompt to Anthropic format
1320
+ * Converts string to array format if needed
1321
+ * @param sys - System prompt (string or array of blocks)
1322
+ * @returns Normalized system prompt for Anthropic API
1323
+ */
1324
+ private static _normalizeSystemPrompt;
1325
+ /**
1326
+ * Log cache usage metrics from Anthropic API response
1327
+ * Shows cache hits, costs, and savings
1328
+ */
1329
+ private static _logCacheUsage;
848
1330
  /**
849
1331
  * Parse model string to extract provider and model name
850
1332
  * @param modelString - Format: "provider/model-name" or just "model-name"
@@ -861,6 +1343,17 @@ declare class LLM {
861
1343
  private static _anthropicStreamWithTools;
862
1344
  private static _groqText;
863
1345
  private static _groqStream;
1346
+ private static _geminiText;
1347
+ private static _geminiStream;
1348
+ /**
1349
+ * Recursively strip unsupported JSON Schema properties for Gemini
1350
+ * Gemini doesn't support: additionalProperties, $schema, etc.
1351
+ */
1352
+ private static _cleanSchemaForGemini;
1353
+ private static _geminiStreamWithTools;
1354
+ private static _openaiText;
1355
+ private static _openaiStream;
1356
+ private static _openaiStreamWithTools;
864
1357
  /**
865
1358
  * Parse JSON string, handling markdown code blocks and surrounding text
866
1359
  * Enhanced version with jsonrepair to handle malformed JSON from LLMs
@@ -1276,15 +1769,17 @@ declare const STORAGE_CONFIG: {
1276
1769
  */
1277
1770
  MAX_ROWS_PER_BLOCK: number;
1278
1771
  /**
1279
- * Maximum size in bytes per UIBlock (1MB)
1772
+ * Maximum size in bytes per UIBlock (500KB - reduced to save memory)
1280
1773
  */
1281
1774
  MAX_SIZE_PER_BLOCK_BYTES: number;
1282
1775
  /**
1283
1776
  * Number of days to keep threads before cleanup
1777
+ * Note: This is for in-memory storage. Conversations are also persisted to database.
1284
1778
  */
1285
1779
  THREAD_RETENTION_DAYS: number;
1286
1780
  /**
1287
1781
  * Number of days to keep UIBlocks before cleanup
1782
+ * Note: This is for in-memory storage. Data is also persisted to database.
1288
1783
  */
1289
1784
  UIBLOCK_RETENTION_DAYS: number;
1290
1785
  };
@@ -1301,14 +1796,632 @@ declare const CONTEXT_CONFIG: {
1301
1796
  MAX_CONVERSATION_CONTEXT_BLOCKS: number;
1302
1797
  };
1303
1798
 
1304
- declare const SDK_VERSION = "0.0.8";
1799
+ /**
1800
+ * LLM Usage Logger - Tracks token usage, costs, and timing for all LLM API calls
1801
+ */
1802
+ interface LLMUsageEntry {
1803
+ timestamp: string;
1804
+ requestId: string;
1805
+ provider: string;
1806
+ model: string;
1807
+ method: string;
1808
+ inputTokens: number;
1809
+ outputTokens: number;
1810
+ cacheReadTokens?: number;
1811
+ cacheWriteTokens?: number;
1812
+ totalTokens: number;
1813
+ costUSD: number;
1814
+ durationMs: number;
1815
+ toolCalls?: number;
1816
+ success: boolean;
1817
+ error?: string;
1818
+ }
1819
+ declare class LLMUsageLogger {
1820
+ private logStream;
1821
+ private logPath;
1822
+ private enabled;
1823
+ private sessionStats;
1824
+ constructor();
1825
+ private initLogStream;
1826
+ private writeHeader;
1827
+ /**
1828
+ * Calculate cost based on token usage and model
1829
+ */
1830
+ calculateCost(model: string, inputTokens: number, outputTokens: number, cacheReadTokens?: number, cacheWriteTokens?: number): number;
1831
+ /**
1832
+ * Log an LLM API call
1833
+ */
1834
+ log(entry: LLMUsageEntry): void;
1835
+ /**
1836
+ * Log session summary (call at end of request)
1837
+ */
1838
+ logSessionSummary(requestContext?: string): void;
1839
+ /**
1840
+ * Reset session stats (call at start of new user request)
1841
+ */
1842
+ resetSession(): void;
1843
+ /**
1844
+ * Reset the log file for a new request (clears previous logs)
1845
+ * Call this at the start of each USER_PROMPT_REQ
1846
+ */
1847
+ resetLogFile(requestContext?: string): void;
1848
+ /**
1849
+ * Get current session stats
1850
+ */
1851
+ getSessionStats(): {
1852
+ totalCalls: number;
1853
+ totalInputTokens: number;
1854
+ totalOutputTokens: number;
1855
+ totalCacheReadTokens: number;
1856
+ totalCacheWriteTokens: number;
1857
+ totalCostUSD: number;
1858
+ totalDurationMs: number;
1859
+ };
1860
+ /**
1861
+ * Generate a unique request ID
1862
+ */
1863
+ generateRequestId(): string;
1864
+ }
1865
+ declare const llmUsageLogger: LLMUsageLogger;
1866
+
1867
+ /**
1868
+ * User Prompt Error Logger - Captures detailed errors for USER_PROMPT_REQ
1869
+ * Logs full error details including raw strings for parse failures
1870
+ */
1871
+ declare class UserPromptErrorLogger {
1872
+ private logStream;
1873
+ private logPath;
1874
+ private enabled;
1875
+ private hasErrors;
1876
+ constructor();
1877
+ /**
1878
+ * Reset the error log file for a new request
1879
+ */
1880
+ resetLogFile(requestContext?: string): void;
1881
+ /**
1882
+ * Log a JSON parse error with the raw string that failed
1883
+ */
1884
+ logJsonParseError(context: string, rawString: string, error: Error): void;
1885
+ /**
1886
+ * Log a general error with full details
1887
+ */
1888
+ logError(context: string, error: Error | string, additionalData?: Record<string, any>): void;
1889
+ /**
1890
+ * Log a SQL query error with the full query
1891
+ */
1892
+ logSqlError(query: string, error: Error | string, params?: any[]): void;
1893
+ /**
1894
+ * Log an LLM API error
1895
+ */
1896
+ logLlmError(provider: string, model: string, method: string, error: Error | string, requestData?: any): void;
1897
+ /**
1898
+ * Log tool execution error
1899
+ */
1900
+ logToolError(toolName: string, toolInput: any, error: Error | string): void;
1901
+ /**
1902
+ * Write final summary if there were errors
1903
+ */
1904
+ writeSummary(): void;
1905
+ /**
1906
+ * Check if any errors were logged
1907
+ */
1908
+ hadErrors(): boolean;
1909
+ private write;
1910
+ }
1911
+ declare const userPromptErrorLogger: UserPromptErrorLogger;
1912
+
1913
+ /**
1914
+ * BM25L Reranker for hybrid semantic search
1915
+ *
1916
+ * BM25L is an improved variant of BM25 that provides better handling of
1917
+ * long documents and term frequency saturation. This implementation is
1918
+ * designed to rerank semantic search results from ChromaDB.
1919
+ *
1920
+ * The hybrid approach combines:
1921
+ * 1. Semantic similarity from ChromaDB embeddings (dense vectors)
1922
+ * 2. Lexical matching from BM25L (sparse, keyword-based)
1923
+ *
1924
+ * This addresses the weakness of pure semantic search which may miss
1925
+ * exact keyword matches that are important for user intent.
1926
+ */
1927
+ interface BM25LOptions {
1928
+ /** Term frequency saturation parameter (default: 1.5) */
1929
+ k1?: number;
1930
+ /** Length normalization parameter (default: 0.75) */
1931
+ b?: number;
1932
+ /** Lower-bound adjustment from BM25L paper (default: 0.5) */
1933
+ delta?: number;
1934
+ }
1935
+ interface RerankedResult<T> {
1936
+ item: T;
1937
+ originalIndex: number;
1938
+ semanticScore: number;
1939
+ bm25Score: number;
1940
+ hybridScore: number;
1941
+ }
1942
+ interface HybridSearchOptions extends BM25LOptions {
1943
+ /** Weight for semantic score (0-1, default: 0.7) */
1944
+ semanticWeight?: number;
1945
+ /** Weight for BM25 score (0-1, default: 0.3) */
1946
+ bm25Weight?: number;
1947
+ /** Minimum hybrid score threshold (0-1, default: 0) */
1948
+ minScore?: number;
1949
+ }
1950
+ /**
1951
+ * BM25L implementation for lexical scoring
1952
+ */
1953
+ declare class BM25L {
1954
+ private k1;
1955
+ private b;
1956
+ private delta;
1957
+ private documents;
1958
+ private docLengths;
1959
+ private avgDocLength;
1960
+ private termDocFreq;
1961
+ /**
1962
+ * @param documents - Array of raw documents (strings)
1963
+ * @param opts - Optional BM25L parameters
1964
+ */
1965
+ constructor(documents?: string[], opts?: BM25LOptions);
1966
+ /**
1967
+ * Tokenize text into lowercase alphanumeric tokens
1968
+ */
1969
+ tokenize(text: string): string[];
1970
+ /**
1971
+ * Compute IDF (Inverse Document Frequency) with smoothing
1972
+ */
1973
+ private idf;
1974
+ /**
1975
+ * Compute BM25L score for a single document
1976
+ */
1977
+ score(query: string, docIndex: number): number;
1978
+ /**
1979
+ * Search and rank all documents
1980
+ */
1981
+ search(query: string): Array<{
1982
+ index: number;
1983
+ score: number;
1984
+ }>;
1985
+ }
1986
+ /**
1987
+ * Hybrid reranker that combines semantic and BM25L scores
1988
+ *
1989
+ * @param query - The search query
1990
+ * @param items - Array of items to rerank
1991
+ * @param getDocument - Function to extract document text from an item
1992
+ * @param getSemanticScore - Function to extract semantic similarity score from an item
1993
+ * @param options - Hybrid search options
1994
+ * @returns Reranked items with hybrid scores
1995
+ */
1996
+ declare function hybridRerank<T>(query: string, items: T[], getDocument: (item: T) => string, getSemanticScore: (item: T) => number, options?: HybridSearchOptions): RerankedResult<T>[];
1997
+ /**
1998
+ * Simple reranking function for ChromaDB results
1999
+ *
2000
+ * This is a convenience wrapper for reranking ChromaDB query results
2001
+ * that follow the standard { ids, documents, metadatas, distances } format.
2002
+ *
2003
+ * @param query - The search query
2004
+ * @param chromaResults - ChromaDB query results
2005
+ * @param options - Hybrid search options
2006
+ * @returns Reranked results with hybrid scores
2007
+ */
2008
+ declare function rerankChromaResults(query: string, chromaResults: {
2009
+ ids: string[][];
2010
+ documents: (string | null)[][];
2011
+ metadatas: Record<string, any>[][];
2012
+ distances: number[][];
2013
+ }, options?: HybridSearchOptions): Array<{
2014
+ id: string;
2015
+ document: string | null;
2016
+ metadata: Record<string, any>;
2017
+ distance: number;
2018
+ semanticScore: number;
2019
+ bm25Score: number;
2020
+ hybridScore: number;
2021
+ }>;
2022
+ /**
2023
+ * Rerank conversation search results specifically
2024
+ *
2025
+ * This function is designed to work with the conversation-history.search collection
2026
+ * where we need to fetch more results initially and then rerank them.
2027
+ *
2028
+ * @param query - The user's search query
2029
+ * @param results - Array of conversation search results from ChromaDB
2030
+ * @param options - Hybrid search options
2031
+ * @returns Reranked results sorted by hybrid score
2032
+ */
2033
+ declare function rerankConversationResults<T extends {
2034
+ userPrompt?: string;
2035
+ similarity?: number;
2036
+ }>(query: string, results: T[], options?: HybridSearchOptions): Array<T & {
2037
+ hybridScore: number;
2038
+ bm25Score: number;
2039
+ }>;
2040
+
2041
+ /**
2042
+ * QueryExecutionService - Handles all query execution, validation, and retry logic
2043
+ * Extracted from BaseLLM for better separation of concerns
2044
+ */
2045
+
2046
+ /**
2047
+ * Context for component when requesting query fix
2048
+ */
2049
+ interface ComponentContext {
2050
+ name: string;
2051
+ type: string;
2052
+ title?: string;
2053
+ }
2054
+ /**
2055
+ * Result of query validation
2056
+ */
2057
+ interface QueryValidationResult {
2058
+ component: Component | null;
2059
+ queryKey: string;
2060
+ result: any;
2061
+ validated: boolean;
2062
+ }
2063
+ /**
2064
+ * Result of batch query validation
2065
+ */
2066
+ interface BatchValidationResult {
2067
+ components: Component[];
2068
+ queryResults: Map<string, any>;
2069
+ }
2070
+ /**
2071
+ * Configuration for QueryExecutionService
2072
+ */
2073
+ interface QueryExecutionServiceConfig {
2074
+ defaultLimit: number;
2075
+ getModelForTask: (taskType: 'simple' | 'complex') => string;
2076
+ getApiKey: (apiKey?: string) => string | undefined;
2077
+ providerName: string;
2078
+ }
2079
+ /**
2080
+ * QueryExecutionService handles all query-related operations
2081
+ */
2082
+ declare class QueryExecutionService {
2083
+ private config;
2084
+ constructor(config: QueryExecutionServiceConfig);
2085
+ /**
2086
+ * Get the cache key for a query
2087
+ * This ensures the cache key matches what the frontend will send
2088
+ */
2089
+ getQueryCacheKey(query: any): string;
2090
+ /**
2091
+ * Execute a query against the database
2092
+ * @param query - The SQL query to execute (string or object with sql/values)
2093
+ * @param collections - Collections object containing database execute function
2094
+ * @returns Object with result data and cache key
2095
+ */
2096
+ executeQuery(query: any, collections: any): Promise<{
2097
+ result: any;
2098
+ cacheKey: string;
2099
+ }>;
2100
+ /**
2101
+ * Request the LLM to fix a failed SQL query
2102
+ * @param failedQuery - The query that failed execution
2103
+ * @param errorMessage - The error message from the failed execution
2104
+ * @param componentContext - Context about the component
2105
+ * @param apiKey - Optional API key
2106
+ * @returns Fixed query string
2107
+ */
2108
+ requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
2109
+ /**
2110
+ * Validate a single component's query with retry logic
2111
+ * @param component - The component to validate
2112
+ * @param collections - Collections object containing database execute function
2113
+ * @param apiKey - Optional API key for LLM calls
2114
+ * @returns Validation result with component, query key, and result
2115
+ */
2116
+ validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
2117
+ /**
2118
+ * Validate multiple component queries in parallel
2119
+ * @param components - Array of components with potential queries
2120
+ * @param collections - Collections object containing database execute function
2121
+ * @param apiKey - Optional API key for LLM calls
2122
+ * @returns Object with validated components and query results map
2123
+ */
2124
+ validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
2125
+ }
2126
+
2127
+ /**
2128
+ * Task types for model selection
2129
+ * - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
2130
+ * - 'simple': Classification, action generation (uses fast model in balanced mode)
2131
+ */
2132
+ type TaskType = 'complex' | 'simple';
2133
+ interface BaseLLMConfig {
2134
+ model?: string;
2135
+ fastModel?: string;
2136
+ defaultLimit?: number;
2137
+ apiKey?: string;
2138
+ /**
2139
+ * Model selection strategy:
2140
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
2141
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
2142
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
2143
+ */
2144
+ modelStrategy?: ModelStrategy;
2145
+ conversationSimilarityThreshold?: number;
2146
+ }
2147
+ /**
2148
+ * BaseLLM abstract class for AI-powered component generation and matching
2149
+ * Provides common functionality for all LLM providers
2150
+ */
2151
+ declare abstract class BaseLLM {
2152
+ protected model: string;
2153
+ protected fastModel: string;
2154
+ protected defaultLimit: number;
2155
+ protected apiKey?: string;
2156
+ protected modelStrategy: ModelStrategy;
2157
+ protected conversationSimilarityThreshold: number;
2158
+ protected queryService: QueryExecutionService;
2159
+ constructor(config?: BaseLLMConfig);
2160
+ /**
2161
+ * Get the appropriate model based on task type and model strategy
2162
+ * @param taskType - 'complex' for text generation/matching, 'simple' for classification/actions
2163
+ * @returns The model string to use for this task
2164
+ */
2165
+ protected getModelForTask(taskType: TaskType): string;
2166
+ /**
2167
+ * Set the model strategy at runtime
2168
+ * @param strategy - 'best', 'fast', or 'balanced'
2169
+ */
2170
+ setModelStrategy(strategy: ModelStrategy): void;
2171
+ /**
2172
+ * Get the current model strategy
2173
+ * @returns The current model strategy
2174
+ */
2175
+ getModelStrategy(): ModelStrategy;
2176
+ /**
2177
+ * Set the conversation similarity threshold at runtime
2178
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2179
+ */
2180
+ setConversationSimilarityThreshold(threshold: number): void;
2181
+ /**
2182
+ * Get the current conversation similarity threshold
2183
+ * @returns The current threshold value
2184
+ */
2185
+ getConversationSimilarityThreshold(): number;
2186
+ /**
2187
+ * Get the default model for this provider (used for complex tasks like text generation)
2188
+ */
2189
+ protected abstract getDefaultModel(): string;
2190
+ /**
2191
+ * Get the default fast model for this provider (used for simple tasks: classification, matching, actions)
2192
+ * Should return a cheaper/faster model like Haiku for Anthropic
2193
+ */
2194
+ protected abstract getDefaultFastModel(): string;
2195
+ /**
2196
+ * Get the default API key from environment
2197
+ */
2198
+ protected abstract getDefaultApiKey(): string | undefined;
2199
+ /**
2200
+ * Get the provider name (for logging)
2201
+ */
2202
+ protected abstract getProviderName(): string;
2203
+ /**
2204
+ * Get the API key (from instance, parameter, or environment)
2205
+ */
2206
+ protected getApiKey(apiKey?: string): string | undefined;
2207
+ /**
2208
+ * Check if a component contains a Form (data_modification component)
2209
+ * Forms have hardcoded defaultValues that become stale when cached
2210
+ * This checks both single Form components and Forms inside MultiComponentContainer
2211
+ */
2212
+ protected containsFormComponent(component: any): boolean;
2213
+ /**
2214
+ * Match components from text response suggestions and generate follow-up questions
2215
+ * Takes a text response with component suggestions (c1:type format) and matches with available components
2216
+ * Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
2217
+ * All components are placed in a default MultiComponentContainer layout
2218
+ * @param analysisContent - The text response containing component suggestions
2219
+ * @param components - List of available components
2220
+ * @param apiKey - Optional API key
2221
+ * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
2222
+ * @returns Object containing matched components, layout title/description, and follow-up actions
2223
+ */
2224
+ matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
2225
+ components: Component[];
2226
+ layoutTitle: string;
2227
+ layoutDescription: string;
2228
+ actions: Action[];
2229
+ }>;
2230
+ /**
2231
+ * Classify user question into category and detect external tools needed
2232
+ * Determines if question is for data analysis, requires external tools, or needs text response
2233
+ */
2234
+ classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
2235
+ category: 'data_analysis' | 'data_modification' | 'general';
2236
+ externalTools: Array<{
2237
+ type: string;
2238
+ name: string;
2239
+ description: string;
2240
+ parameters: Record<string, any>;
2241
+ }>;
2242
+ dataAnalysisType?: 'visualization' | 'calculation' | 'comparison' | 'trend';
2243
+ reasoning: string;
2244
+ confidence: number;
2245
+ }>;
2246
+ /**
2247
+ * Adapt UI block parameters based on current user question
2248
+ * Takes a matched UI block from semantic search and modifies its props to answer the new question
2249
+ * Also adapts the cached text response to match the new question
2250
+ */
2251
+ adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
2252
+ success: boolean;
2253
+ adaptedComponent?: Component;
2254
+ adaptedTextResponse?: string;
2255
+ parametersChanged?: Array<{
2256
+ field: string;
2257
+ reason: string;
2258
+ }>;
2259
+ explanation: string;
2260
+ }>;
2261
+ /**
2262
+ * Generate text-based response for user question
2263
+ * This provides conversational text responses instead of component generation
2264
+ * Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
2265
+ * After generating text response, if components are provided, matches suggested components
2266
+ */
2267
+ 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>;
2268
+ /**
2269
+ * Main orchestration function with semantic search and multi-step classification
2270
+ * NEW FLOW (Recommended):
2271
+ * 1. Semantic search: Check previous conversations (>60% match)
2272
+ * - If match found → Adapt UI block parameters and return
2273
+ * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
2274
+ * 3. Route appropriately based on category and response mode
2275
+ */
2276
+ 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>;
2277
+ /**
2278
+ * Generate next questions that the user might ask based on the original prompt and generated component
2279
+ * This helps provide intelligent suggestions for follow-up queries
2280
+ * For general/conversational questions without components, pass textResponse instead
2281
+ */
2282
+ generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string): Promise<string[]>;
2283
+ }
2284
+
2285
+ interface AnthropicLLMConfig extends BaseLLMConfig {
2286
+ }
2287
+ /**
2288
+ * AnthropicLLM class for handling AI-powered component generation and matching using Anthropic Claude
2289
+ */
2290
+ declare class AnthropicLLM extends BaseLLM {
2291
+ constructor(config?: AnthropicLLMConfig);
2292
+ protected getDefaultModel(): string;
2293
+ protected getDefaultFastModel(): string;
2294
+ protected getDefaultApiKey(): string | undefined;
2295
+ protected getProviderName(): string;
2296
+ }
2297
+ declare const anthropicLLM: AnthropicLLM;
2298
+
2299
+ interface GroqLLMConfig extends BaseLLMConfig {
2300
+ }
2301
+ /**
2302
+ * GroqLLM class for handling AI-powered component generation and matching using Groq
2303
+ */
2304
+ declare class GroqLLM extends BaseLLM {
2305
+ constructor(config?: GroqLLMConfig);
2306
+ protected getDefaultModel(): string;
2307
+ protected getDefaultFastModel(): string;
2308
+ protected getDefaultApiKey(): string | undefined;
2309
+ protected getProviderName(): string;
2310
+ }
2311
+ declare const groqLLM: GroqLLM;
2312
+
2313
+ interface GeminiLLMConfig extends BaseLLMConfig {
2314
+ }
2315
+ /**
2316
+ * GeminiLLM class for handling AI-powered component generation and matching using Google Gemini
2317
+ */
2318
+ declare class GeminiLLM extends BaseLLM {
2319
+ constructor(config?: GeminiLLMConfig);
2320
+ protected getDefaultModel(): string;
2321
+ protected getDefaultFastModel(): string;
2322
+ protected getDefaultApiKey(): string | undefined;
2323
+ protected getProviderName(): string;
2324
+ }
2325
+ declare const geminiLLM: GeminiLLM;
2326
+
2327
+ interface OpenAILLMConfig extends BaseLLMConfig {
2328
+ }
2329
+ /**
2330
+ * OpenAILLM class for handling AI-powered component generation and matching using OpenAI GPT models
2331
+ */
2332
+ declare class OpenAILLM extends BaseLLM {
2333
+ constructor(config?: OpenAILLMConfig);
2334
+ protected getDefaultModel(): string;
2335
+ protected getDefaultFastModel(): string;
2336
+ protected getDefaultApiKey(): string | undefined;
2337
+ protected getProviderName(): string;
2338
+ }
2339
+ declare const openaiLLM: OpenAILLM;
2340
+
2341
+ /**
2342
+ * Query Cache - Stores query results with configurable TTL
2343
+ * Used to avoid re-executing queries that were already validated
2344
+ */
2345
+ declare class QueryCache {
2346
+ private cache;
2347
+ private queryIdCache;
2348
+ private ttlMs;
2349
+ private cleanupInterval;
2350
+ constructor();
2351
+ /**
2352
+ * Set the cache TTL (Time To Live)
2353
+ * @param minutes - TTL in minutes (default: 5)
2354
+ */
2355
+ setTTL(minutes: number): void;
2356
+ /**
2357
+ * Get the current TTL in minutes
2358
+ */
2359
+ getTTL(): number;
2360
+ /**
2361
+ * Store query result in cache
2362
+ * Key is the exact query string (or JSON for parameterized queries)
2363
+ */
2364
+ set(query: string, data: any): void;
2365
+ /**
2366
+ * Get cached result if exists and not expired
2367
+ */
2368
+ get(query: string): any | null;
2369
+ /**
2370
+ * Check if query exists in cache (not expired)
2371
+ */
2372
+ has(query: string): boolean;
2373
+ /**
2374
+ * Remove a specific query from cache
2375
+ */
2376
+ delete(query: string): void;
2377
+ /**
2378
+ * Clear all cached entries
2379
+ */
2380
+ clear(): void;
2381
+ /**
2382
+ * Get cache statistics
2383
+ */
2384
+ getStats(): {
2385
+ size: number;
2386
+ oldestEntryAge: number | null;
2387
+ };
2388
+ /**
2389
+ * Start periodic cleanup of expired entries
2390
+ */
2391
+ private startCleanup;
2392
+ /**
2393
+ * Generate a unique query ID
2394
+ */
2395
+ private generateQueryId;
2396
+ /**
2397
+ * Store a query by ID. Returns the generated queryId.
2398
+ * The query is stored server-side; only the queryId is sent to the frontend.
2399
+ */
2400
+ storeQuery(query: any, data?: any): string;
2401
+ /**
2402
+ * Get a stored query by its ID (not expired)
2403
+ */
2404
+ getQuery(queryId: string): {
2405
+ query: any;
2406
+ data: any;
2407
+ } | null;
2408
+ /**
2409
+ * Update cached data for a queryId
2410
+ */
2411
+ setQueryData(queryId: string, data: any): void;
2412
+ /**
2413
+ * Stop cleanup interval (for graceful shutdown)
2414
+ */
2415
+ destroy(): void;
2416
+ }
2417
+ declare const queryCache: QueryCache;
2418
+
1305
2419
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
1306
2420
  declare class SuperatomSDK {
1307
2421
  private ws;
1308
2422
  private url;
1309
- private apiKey;
2423
+ private apiKey?;
1310
2424
  private projectId;
1311
- private userId;
1312
2425
  private type;
1313
2426
  private bundleDir;
1314
2427
  private messageHandlers;
@@ -1318,12 +2431,22 @@ declare class SuperatomSDK {
1318
2431
  private maxReconnectAttempts;
1319
2432
  private collections;
1320
2433
  private components;
2434
+ private tools;
1321
2435
  private anthropicApiKey;
1322
2436
  private groqApiKey;
2437
+ private geminiApiKey;
2438
+ private openaiApiKey;
1323
2439
  private llmProviders;
2440
+ private databaseType;
2441
+ private modelStrategy;
2442
+ private conversationSimilarityThreshold;
1324
2443
  private userManager;
1325
2444
  private dashboardManager;
1326
2445
  private reportManager;
2446
+ private pingInterval;
2447
+ private lastPong;
2448
+ private readonly PING_INTERVAL_MS;
2449
+ private readonly PONG_TIMEOUT_MS;
1327
2450
  constructor(config: SuperatomSDKConfig);
1328
2451
  /**
1329
2452
  * Initialize PromptLoader and load prompts into memory
@@ -1363,9 +2486,11 @@ declare class SuperatomSDK {
1363
2486
  */
1364
2487
  private handleMessage;
1365
2488
  /**
1366
- * Send a message to the Superatom service
2489
+ * Send a message to the Superatom service.
2490
+ * Returns true if the message was sent, false if the WebSocket is not connected.
2491
+ * Does NOT throw on closed connections — callers can check the return value if needed.
1367
2492
  */
1368
- send(message: Message): void;
2493
+ send(message: Message): boolean;
1369
2494
  /**
1370
2495
  * Register a message handler to receive all messages
1371
2496
  */
@@ -1391,7 +2516,56 @@ declare class SuperatomSDK {
1391
2516
  */
1392
2517
  addCollection<TParams = any, TResult = any>(collectionName: string, operation: CollectionOperation | string, handler: CollectionHandler<TParams, TResult>): void;
1393
2518
  private handleReconnect;
2519
+ /**
2520
+ * Start heartbeat to keep WebSocket connection alive
2521
+ * Sends PING every 3 minutes to prevent idle timeout from cloud infrastructure
2522
+ */
2523
+ private startHeartbeat;
2524
+ /**
2525
+ * Stop the heartbeat interval
2526
+ */
2527
+ private stopHeartbeat;
2528
+ /**
2529
+ * Handle PONG response from server
2530
+ */
2531
+ private handlePong;
1394
2532
  private storeComponents;
2533
+ /**
2534
+ * Set tools for the SDK instance
2535
+ */
2536
+ setTools(tools: Tool$1[]): void;
2537
+ /**
2538
+ * Get the stored tools
2539
+ */
2540
+ getTools(): Tool$1[];
2541
+ /**
2542
+ * Apply model strategy to all LLM provider singletons
2543
+ * @param strategy - 'best', 'fast', or 'balanced'
2544
+ */
2545
+ private applyModelStrategy;
2546
+ /**
2547
+ * Set model strategy at runtime
2548
+ * @param strategy - 'best', 'fast', or 'balanced'
2549
+ */
2550
+ setModelStrategy(strategy: ModelStrategy): void;
2551
+ /**
2552
+ * Get current model strategy
2553
+ */
2554
+ getModelStrategy(): ModelStrategy;
2555
+ /**
2556
+ * Apply conversation similarity threshold to all LLM provider singletons
2557
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2558
+ */
2559
+ private applyConversationSimilarityThreshold;
2560
+ /**
2561
+ * Set conversation similarity threshold at runtime
2562
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2563
+ */
2564
+ setConversationSimilarityThreshold(threshold: number): void;
2565
+ /**
2566
+ * Get current conversation similarity threshold
2567
+ */
2568
+ getConversationSimilarityThreshold(): number;
1395
2569
  }
1396
2570
 
1397
- 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, UIBlock, UILogCollector, type User, UserManager, type UsersData, logger };
2571
+ export { type Action, BM25L, type BM25LOptions, type BaseLLMConfig, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, 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, geminiLLM, groqLLM, hybridRerank, llmUsageLogger, logger, openaiLLM, queryCache, rerankChromaResults, rerankConversationResults, userPromptErrorLogger };