@superatomai/sdk-node 0.0.5 → 0.0.6-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,6 +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
+ */
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;
50
74
  }
51
75
  declare const logger: Logger;
52
76
 
@@ -77,7 +101,27 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
77
101
  deps?: string[] | undefined;
78
102
  }>, "many">>;
79
103
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
80
- 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>;
81
125
  query: z.ZodOptional<z.ZodObject<{
82
126
  graphql: z.ZodOptional<z.ZodString>;
83
127
  sql: z.ZodOptional<z.ZodString>;
@@ -116,6 +160,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
116
160
  dependencies?: string[] | undefined;
117
161
  } | undefined;
118
162
  props?: Record<string, any> | undefined;
163
+ render?: any;
119
164
  states?: Record<string, any> | undefined;
120
165
  methods?: Record<string, {
121
166
  fn: string;
@@ -126,7 +171,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
126
171
  deps?: string[] | undefined;
127
172
  }[] | undefined;
128
173
  data?: Record<string, any> | undefined;
129
- 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;
130
182
  }, {
131
183
  id: string;
132
184
  name?: string | undefined;
@@ -140,6 +192,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
140
192
  dependencies?: string[] | undefined;
141
193
  } | undefined;
142
194
  props?: Record<string, any> | undefined;
195
+ render?: any;
143
196
  states?: Record<string, any> | undefined;
144
197
  methods?: Record<string, {
145
198
  fn: string;
@@ -150,7 +203,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
150
203
  deps?: string[] | undefined;
151
204
  }[] | undefined;
152
205
  data?: Record<string, any> | undefined;
153
- 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;
154
214
  }>;
155
215
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
156
216
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -168,6 +228,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
168
228
  dependencies?: string[] | undefined;
169
229
  } | undefined;
170
230
  props?: Record<string, any> | undefined;
231
+ render?: any;
171
232
  states?: Record<string, any> | undefined;
172
233
  methods?: Record<string, {
173
234
  fn: string;
@@ -178,7 +239,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
178
239
  deps?: string[] | undefined;
179
240
  }[] | undefined;
180
241
  data?: Record<string, any> | undefined;
181
- 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;
182
250
  };
183
251
  data?: Record<string, any> | undefined;
184
252
  context?: Record<string, any> | undefined;
@@ -196,6 +264,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
196
264
  dependencies?: string[] | undefined;
197
265
  } | undefined;
198
266
  props?: Record<string, any> | undefined;
267
+ render?: any;
199
268
  states?: Record<string, any> | undefined;
200
269
  methods?: Record<string, {
201
270
  fn: string;
@@ -206,7 +275,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
206
275
  deps?: string[] | undefined;
207
276
  }[] | undefined;
208
277
  data?: Record<string, any> | undefined;
209
- 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;
210
286
  };
211
287
  data?: Record<string, any> | undefined;
212
288
  context?: Record<string, any> | undefined;
@@ -279,6 +355,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
279
355
  dependencies?: string[] | undefined;
280
356
  } | undefined;
281
357
  props?: Record<string, any> | undefined;
358
+ render?: any;
282
359
  states?: Record<string, any> | undefined;
283
360
  methods?: Record<string, {
284
361
  fn: string;
@@ -289,7 +366,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
289
366
  deps?: string[] | undefined;
290
367
  }[] | undefined;
291
368
  data?: Record<string, any> | undefined;
292
- render?: any;
293
369
  }, {
294
370
  id: string;
295
371
  name?: string | undefined;
@@ -303,6 +379,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
303
379
  dependencies?: string[] | undefined;
304
380
  } | undefined;
305
381
  props?: Record<string, any> | undefined;
382
+ render?: any;
306
383
  states?: Record<string, any> | undefined;
307
384
  methods?: Record<string, {
308
385
  fn: string;
@@ -313,7 +390,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
313
390
  deps?: string[] | undefined;
314
391
  }[] | undefined;
315
392
  data?: Record<string, any> | undefined;
316
- render?: any;
317
393
  }>;
318
394
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
319
395
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -331,6 +407,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
331
407
  dependencies?: string[] | undefined;
332
408
  } | undefined;
333
409
  props?: Record<string, any> | undefined;
410
+ render?: any;
334
411
  states?: Record<string, any> | undefined;
335
412
  methods?: Record<string, {
336
413
  fn: string;
@@ -341,7 +418,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
341
418
  deps?: string[] | undefined;
342
419
  }[] | undefined;
343
420
  data?: Record<string, any> | undefined;
344
- render?: any;
345
421
  };
346
422
  data?: Record<string, any> | undefined;
347
423
  context?: Record<string, any> | undefined;
@@ -359,6 +435,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
359
435
  dependencies?: string[] | undefined;
360
436
  } | undefined;
361
437
  props?: Record<string, any> | undefined;
438
+ render?: any;
362
439
  states?: Record<string, any> | undefined;
363
440
  methods?: Record<string, {
364
441
  fn: string;
@@ -369,7 +446,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
369
446
  deps?: string[] | undefined;
370
447
  }[] | undefined;
371
448
  data?: Record<string, any> | undefined;
372
- render?: any;
373
449
  };
374
450
  data?: Record<string, any> | undefined;
375
451
  context?: Record<string, any> | undefined;
@@ -382,6 +458,7 @@ declare const UserSchema: z.ZodObject<{
382
458
  password: z.ZodString;
383
459
  fullname: z.ZodOptional<z.ZodString>;
384
460
  role: z.ZodOptional<z.ZodString>;
461
+ userInfo: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
385
462
  wsIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
386
463
  }, "strip", z.ZodTypeAny, {
387
464
  username: string;
@@ -389,6 +466,7 @@ declare const UserSchema: z.ZodObject<{
389
466
  email?: string | undefined;
390
467
  fullname?: string | undefined;
391
468
  role?: string | undefined;
469
+ userInfo?: Record<string, unknown> | undefined;
392
470
  wsIds?: string[] | undefined;
393
471
  }, {
394
472
  username: string;
@@ -396,6 +474,7 @@ declare const UserSchema: z.ZodObject<{
396
474
  email?: string | undefined;
397
475
  fullname?: string | undefined;
398
476
  role?: string | undefined;
477
+ userInfo?: Record<string, unknown> | undefined;
399
478
  wsIds?: string[] | undefined;
400
479
  }>;
401
480
  type User = z.infer<typeof UserSchema>;
@@ -406,6 +485,7 @@ declare const UsersDataSchema: z.ZodObject<{
406
485
  password: z.ZodString;
407
486
  fullname: z.ZodOptional<z.ZodString>;
408
487
  role: z.ZodOptional<z.ZodString>;
488
+ userInfo: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
409
489
  wsIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
410
490
  }, "strip", z.ZodTypeAny, {
411
491
  username: string;
@@ -413,6 +493,7 @@ declare const UsersDataSchema: z.ZodObject<{
413
493
  email?: string | undefined;
414
494
  fullname?: string | undefined;
415
495
  role?: string | undefined;
496
+ userInfo?: Record<string, unknown> | undefined;
416
497
  wsIds?: string[] | undefined;
417
498
  }, {
418
499
  username: string;
@@ -420,6 +501,7 @@ declare const UsersDataSchema: z.ZodObject<{
420
501
  email?: string | undefined;
421
502
  fullname?: string | undefined;
422
503
  role?: string | undefined;
504
+ userInfo?: Record<string, unknown> | undefined;
423
505
  wsIds?: string[] | undefined;
424
506
  }>, "many">;
425
507
  }, "strip", z.ZodTypeAny, {
@@ -429,6 +511,7 @@ declare const UsersDataSchema: z.ZodObject<{
429
511
  email?: string | undefined;
430
512
  fullname?: string | undefined;
431
513
  role?: string | undefined;
514
+ userInfo?: Record<string, unknown> | undefined;
432
515
  wsIds?: string[] | undefined;
433
516
  }[];
434
517
  }, {
@@ -438,6 +521,7 @@ declare const UsersDataSchema: z.ZodObject<{
438
521
  email?: string | undefined;
439
522
  fullname?: string | undefined;
440
523
  role?: string | undefined;
524
+ userInfo?: Record<string, unknown> | undefined;
441
525
  wsIds?: string[] | undefined;
442
526
  }[];
443
527
  }>;
@@ -542,22 +626,399 @@ declare const IncomingMessageSchema: z.ZodObject<{
542
626
  payload?: unknown;
543
627
  }>;
544
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
+ params: z.ZodRecord<z.ZodString, z.ZodString>;
745
+ fn: z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodAny>;
746
+ outputSchema: z.ZodOptional<z.ZodObject<{
747
+ description: z.ZodString;
748
+ fields: z.ZodArray<z.ZodObject<{
749
+ name: z.ZodString;
750
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
751
+ description: z.ZodString;
752
+ }, "strip", z.ZodTypeAny, {
753
+ type: "string" | "number" | "boolean" | "date";
754
+ name: string;
755
+ description: string;
756
+ }, {
757
+ type: "string" | "number" | "boolean" | "date";
758
+ name: string;
759
+ description: string;
760
+ }>, "many">;
761
+ }, "strip", z.ZodTypeAny, {
762
+ description: string;
763
+ fields: {
764
+ type: "string" | "number" | "boolean" | "date";
765
+ name: string;
766
+ description: string;
767
+ }[];
768
+ }, {
769
+ description: string;
770
+ fields: {
771
+ type: "string" | "number" | "boolean" | "date";
772
+ name: string;
773
+ description: string;
774
+ }[];
775
+ }>>;
776
+ }, "strip", z.ZodTypeAny, {
777
+ id: string;
778
+ params: Record<string, string>;
779
+ name: string;
780
+ description: string;
781
+ fn: (args_0: any, ...args: unknown[]) => any;
782
+ outputSchema?: {
783
+ description: string;
784
+ fields: {
785
+ type: "string" | "number" | "boolean" | "date";
786
+ name: string;
787
+ description: string;
788
+ }[];
789
+ } | undefined;
790
+ }, {
791
+ id: string;
792
+ params: Record<string, string>;
793
+ name: string;
794
+ description: string;
795
+ fn: (args_0: any, ...args: unknown[]) => any;
796
+ outputSchema?: {
797
+ description: string;
798
+ fields: {
799
+ type: "string" | "number" | "boolean" | "date";
800
+ name: string;
801
+ description: string;
802
+ }[];
803
+ } | undefined;
804
+ }>;
805
+ type Tool$1 = z.infer<typeof ToolSchema>;
545
806
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
546
807
  type CollectionHandler<TParams = any, TResult = any> = (params: TParams) => Promise<TResult> | TResult;
547
- type LLMProvider = 'anthropic' | 'groq';
808
+ type LLMProvider = 'anthropic' | 'groq' | 'gemini' | 'openai';
548
809
 
810
+ type DatabaseType = 'postgresql' | 'mssql' | 'snowflake' | 'mysql';
811
+ /**
812
+ * Model strategy for controlling which models are used for different tasks
813
+ * - 'best': Use the best model (e.g., Sonnet) for all tasks - highest quality, higher cost
814
+ * - 'fast': Use the fast model (e.g., Haiku) for all tasks - lower quality, lower cost
815
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
816
+ */
817
+ type ModelStrategy = 'best' | 'fast' | 'balanced';
818
+ /**
819
+ * Model configuration for DASH_COMP flow (dashboard component picking)
820
+ * Allows separate control of models used for component selection
821
+ */
822
+ interface DashCompModelConfig {
823
+ /**
824
+ * Primary model for DASH_COMP requests
825
+ * Format: "provider/model-name" (e.g., "anthropic/claude-sonnet-4-5-20250929")
826
+ */
827
+ model?: string;
828
+ /**
829
+ * Fast model for simpler DASH_COMP tasks (optional)
830
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
831
+ */
832
+ fastModel?: string;
833
+ }
549
834
  interface SuperatomSDKConfig {
550
835
  url?: string;
551
- apiKey: string;
836
+ apiKey?: string;
552
837
  projectId: string;
553
- userId?: string;
554
838
  type?: string;
555
839
  bundleDir?: string;
556
840
  promptsDir?: string;
841
+ databaseType?: DatabaseType;
557
842
  ANTHROPIC_API_KEY?: string;
558
843
  GROQ_API_KEY?: string;
844
+ GEMINI_API_KEY?: string;
845
+ OPENAI_API_KEY?: string;
559
846
  LLM_PROVIDERS?: LLMProvider[];
560
847
  logLevel?: LogLevel;
848
+ /**
849
+ * Model selection strategy for LLM API calls:
850
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
851
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
852
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
853
+ */
854
+ modelStrategy?: ModelStrategy;
855
+ /**
856
+ * Separate model configuration for DASH_COMP flow (dashboard component picking)
857
+ * If not provided, falls back to provider-based model selection
858
+ */
859
+ dashCompModels?: DashCompModelConfig;
860
+ /**
861
+ * Similarity threshold for conversation search (semantic matching)
862
+ * Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
863
+ * Higher values require closer matches, lower values allow more distant matches
864
+ * Default: 0.8
865
+ */
866
+ conversationSimilarityThreshold?: number;
867
+ /**
868
+ * Query cache TTL (Time To Live) in minutes
869
+ * Cached query results expire after this duration
870
+ * Default: 5 minutes
871
+ */
872
+ queryCacheTTL?: number;
873
+ }
874
+
875
+ declare const KbNodesQueryFiltersSchema: z.ZodObject<{
876
+ query: z.ZodOptional<z.ZodString>;
877
+ category: z.ZodOptional<z.ZodString>;
878
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
879
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
880
+ createdBy: z.ZodOptional<z.ZodNumber>;
881
+ }, "strip", z.ZodTypeAny, {
882
+ type?: "query" | "user" | "global" | undefined;
883
+ query?: string | undefined;
884
+ category?: string | undefined;
885
+ createdBy?: number | undefined;
886
+ tags?: string[] | undefined;
887
+ }, {
888
+ type?: "query" | "user" | "global" | undefined;
889
+ query?: string | undefined;
890
+ category?: string | undefined;
891
+ createdBy?: number | undefined;
892
+ tags?: string[] | undefined;
893
+ }>;
894
+ type KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
895
+ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
896
+ operation: z.ZodEnum<["create", "update", "delete", "getAll", "getOne", "search", "getByCategory", "getByUser", "getCategories", "getTags"]>;
897
+ data: z.ZodOptional<z.ZodObject<{
898
+ id: z.ZodOptional<z.ZodNumber>;
899
+ title: z.ZodOptional<z.ZodString>;
900
+ content: z.ZodOptional<z.ZodString>;
901
+ category: z.ZodOptional<z.ZodString>;
902
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
903
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
904
+ createdBy: z.ZodOptional<z.ZodNumber>;
905
+ updatedBy: z.ZodOptional<z.ZodNumber>;
906
+ userId: z.ZodOptional<z.ZodNumber>;
907
+ query: z.ZodOptional<z.ZodString>;
908
+ filters: z.ZodOptional<z.ZodObject<{
909
+ query: z.ZodOptional<z.ZodString>;
910
+ category: z.ZodOptional<z.ZodString>;
911
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
912
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
913
+ createdBy: z.ZodOptional<z.ZodNumber>;
914
+ }, "strip", z.ZodTypeAny, {
915
+ type?: "query" | "user" | "global" | undefined;
916
+ query?: string | undefined;
917
+ category?: string | undefined;
918
+ createdBy?: number | undefined;
919
+ tags?: string[] | undefined;
920
+ }, {
921
+ type?: "query" | "user" | "global" | undefined;
922
+ query?: string | undefined;
923
+ category?: string | undefined;
924
+ createdBy?: number | undefined;
925
+ tags?: string[] | undefined;
926
+ }>>;
927
+ limit: z.ZodOptional<z.ZodNumber>;
928
+ offset: z.ZodOptional<z.ZodNumber>;
929
+ }, "strip", z.ZodTypeAny, {
930
+ id?: number | undefined;
931
+ type?: "query" | "user" | "global" | undefined;
932
+ query?: string | undefined;
933
+ title?: string | undefined;
934
+ category?: string | undefined;
935
+ userId?: number | undefined;
936
+ limit?: number | undefined;
937
+ filters?: {
938
+ type?: "query" | "user" | "global" | undefined;
939
+ query?: string | undefined;
940
+ category?: string | undefined;
941
+ createdBy?: number | undefined;
942
+ tags?: string[] | undefined;
943
+ } | undefined;
944
+ createdBy?: number | undefined;
945
+ updatedBy?: number | undefined;
946
+ offset?: number | undefined;
947
+ tags?: string[] | undefined;
948
+ content?: string | undefined;
949
+ }, {
950
+ id?: number | undefined;
951
+ type?: "query" | "user" | "global" | undefined;
952
+ query?: string | undefined;
953
+ title?: string | undefined;
954
+ category?: string | undefined;
955
+ userId?: number | undefined;
956
+ limit?: number | undefined;
957
+ filters?: {
958
+ type?: "query" | "user" | "global" | undefined;
959
+ query?: string | undefined;
960
+ category?: string | undefined;
961
+ createdBy?: number | undefined;
962
+ tags?: string[] | undefined;
963
+ } | undefined;
964
+ createdBy?: number | undefined;
965
+ updatedBy?: number | undefined;
966
+ offset?: number | undefined;
967
+ tags?: string[] | undefined;
968
+ content?: string | undefined;
969
+ }>>;
970
+ }, "strip", z.ZodTypeAny, {
971
+ operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
972
+ data?: {
973
+ id?: number | undefined;
974
+ type?: "query" | "user" | "global" | undefined;
975
+ query?: string | undefined;
976
+ title?: string | undefined;
977
+ category?: string | undefined;
978
+ userId?: number | undefined;
979
+ limit?: number | undefined;
980
+ filters?: {
981
+ type?: "query" | "user" | "global" | undefined;
982
+ query?: string | undefined;
983
+ category?: string | undefined;
984
+ createdBy?: number | undefined;
985
+ tags?: string[] | undefined;
986
+ } | undefined;
987
+ createdBy?: number | undefined;
988
+ updatedBy?: number | undefined;
989
+ offset?: number | undefined;
990
+ tags?: string[] | undefined;
991
+ content?: string | undefined;
992
+ } | undefined;
993
+ }, {
994
+ operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
995
+ data?: {
996
+ id?: number | undefined;
997
+ type?: "query" | "user" | "global" | undefined;
998
+ query?: string | undefined;
999
+ title?: string | undefined;
1000
+ category?: string | undefined;
1001
+ userId?: number | undefined;
1002
+ limit?: number | undefined;
1003
+ filters?: {
1004
+ type?: "query" | "user" | "global" | undefined;
1005
+ query?: string | undefined;
1006
+ category?: string | undefined;
1007
+ createdBy?: number | undefined;
1008
+ tags?: string[] | undefined;
1009
+ } | undefined;
1010
+ createdBy?: number | undefined;
1011
+ updatedBy?: number | undefined;
1012
+ offset?: number | undefined;
1013
+ tags?: string[] | undefined;
1014
+ content?: string | undefined;
1015
+ } | undefined;
1016
+ }>;
1017
+ type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
1018
+ interface T_RESPONSE {
1019
+ success: boolean;
1020
+ data?: any;
1021
+ errors: string[];
561
1022
  }
562
1023
 
563
1024
  /**
@@ -819,9 +1280,11 @@ declare class ReportManager {
819
1280
  getReportCount(): number;
820
1281
  }
821
1282
 
1283
+ type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
822
1284
  interface LLMMessages {
823
- sys: string;
1285
+ sys: SystemPrompt;
824
1286
  user: string;
1287
+ prefill?: string;
825
1288
  }
826
1289
  interface LLMOptions {
827
1290
  model?: string;
@@ -831,9 +1294,31 @@ interface LLMOptions {
831
1294
  apiKey?: string;
832
1295
  partial?: (chunk: string) => void;
833
1296
  }
1297
+ interface Tool {
1298
+ name: string;
1299
+ description: string;
1300
+ input_schema: {
1301
+ type: string;
1302
+ properties: Record<string, any>;
1303
+ required?: string[];
1304
+ };
1305
+ }
834
1306
  declare class LLM {
835
1307
  static text(messages: LLMMessages, options?: LLMOptions): Promise<string>;
836
1308
  static stream<T = string>(messages: LLMMessages, options?: LLMOptions, json?: boolean): Promise<T extends string ? string : any>;
1309
+ static streamWithTools(messages: LLMMessages, tools: Tool[], toolHandler: (toolName: string, toolInput: any) => Promise<any>, options?: LLMOptions, maxIterations?: number): Promise<string>;
1310
+ /**
1311
+ * Normalize system prompt to Anthropic format
1312
+ * Converts string to array format if needed
1313
+ * @param sys - System prompt (string or array of blocks)
1314
+ * @returns Normalized system prompt for Anthropic API
1315
+ */
1316
+ private static _normalizeSystemPrompt;
1317
+ /**
1318
+ * Log cache usage metrics from Anthropic API response
1319
+ * Shows cache hits, costs, and savings
1320
+ */
1321
+ private static _logCacheUsage;
837
1322
  /**
838
1323
  * Parse model string to extract provider and model name
839
1324
  * @param modelString - Format: "provider/model-name" or just "model-name"
@@ -847,13 +1332,25 @@ declare class LLM {
847
1332
  private static _parseModel;
848
1333
  private static _anthropicText;
849
1334
  private static _anthropicStream;
1335
+ private static _anthropicStreamWithTools;
850
1336
  private static _groqText;
851
1337
  private static _groqStream;
1338
+ private static _geminiText;
1339
+ private static _geminiStream;
1340
+ /**
1341
+ * Recursively strip unsupported JSON Schema properties for Gemini
1342
+ * Gemini doesn't support: additionalProperties, $schema, etc.
1343
+ */
1344
+ private static _cleanSchemaForGemini;
1345
+ private static _geminiStreamWithTools;
1346
+ private static _openaiText;
1347
+ private static _openaiStream;
1348
+ private static _openaiStreamWithTools;
852
1349
  /**
853
1350
  * Parse JSON string, handling markdown code blocks and surrounding text
854
- * Enhanced version from anthropic.ts implementation
1351
+ * Enhanced version with jsonrepair to handle malformed JSON from LLMs
855
1352
  * @param text - Text that may contain JSON wrapped in ```json...``` or with surrounding text
856
- * @returns Parsed JSON object
1353
+ * @returns Parsed JSON object or array
857
1354
  */
858
1355
  private static _parseJSON;
859
1356
  }
@@ -985,6 +1482,7 @@ declare class UIBlock {
985
1482
  * Get component metadata
986
1483
  */
987
1484
  getComponentMetadata(): Record<string, any>;
1485
+ getTextResponse(): string;
988
1486
  /**
989
1487
  * Set or update component metadata
990
1488
  */
@@ -1013,10 +1511,6 @@ declare class UIBlock {
1013
1511
  * Set or update component data with size and row limits
1014
1512
  */
1015
1513
  setComponentData(data: Record<string, any>): void;
1016
- /**
1017
- * Get text response
1018
- */
1019
- getTextResponse(): string | null;
1020
1514
  /**
1021
1515
  * Set or update text response
1022
1516
  */
@@ -1033,6 +1527,10 @@ declare class UIBlock {
1033
1527
  * @returns Promise resolving to Action[]
1034
1528
  */
1035
1529
  getOrFetchActions(generateFn: () => Promise<Action[]>): Promise<Action[]>;
1530
+ /**
1531
+ * Set or replace all actions
1532
+ */
1533
+ setActions(actions: Action[]): void;
1036
1534
  /**
1037
1535
  * Add a single action (only if actions are resolved)
1038
1536
  */
@@ -1263,15 +1761,17 @@ declare const STORAGE_CONFIG: {
1263
1761
  */
1264
1762
  MAX_ROWS_PER_BLOCK: number;
1265
1763
  /**
1266
- * Maximum size in bytes per UIBlock (1MB)
1764
+ * Maximum size in bytes per UIBlock (500KB - reduced to save memory)
1267
1765
  */
1268
1766
  MAX_SIZE_PER_BLOCK_BYTES: number;
1269
1767
  /**
1270
1768
  * Number of days to keep threads before cleanup
1769
+ * Note: This is for in-memory storage. Conversations are also persisted to database.
1271
1770
  */
1272
1771
  THREAD_RETENTION_DAYS: number;
1273
1772
  /**
1274
1773
  * Number of days to keep UIBlocks before cleanup
1774
+ * Note: This is for in-memory storage. Data is also persisted to database.
1275
1775
  */
1276
1776
  UIBLOCK_RETENTION_DAYS: number;
1277
1777
  };
@@ -1288,14 +1788,632 @@ declare const CONTEXT_CONFIG: {
1288
1788
  MAX_CONVERSATION_CONTEXT_BLOCKS: number;
1289
1789
  };
1290
1790
 
1291
- declare const SDK_VERSION = "0.0.8";
1791
+ /**
1792
+ * LLM Usage Logger - Tracks token usage, costs, and timing for all LLM API calls
1793
+ */
1794
+ interface LLMUsageEntry {
1795
+ timestamp: string;
1796
+ requestId: string;
1797
+ provider: string;
1798
+ model: string;
1799
+ method: string;
1800
+ inputTokens: number;
1801
+ outputTokens: number;
1802
+ cacheReadTokens?: number;
1803
+ cacheWriteTokens?: number;
1804
+ totalTokens: number;
1805
+ costUSD: number;
1806
+ durationMs: number;
1807
+ toolCalls?: number;
1808
+ success: boolean;
1809
+ error?: string;
1810
+ }
1811
+ declare class LLMUsageLogger {
1812
+ private logStream;
1813
+ private logPath;
1814
+ private enabled;
1815
+ private sessionStats;
1816
+ constructor();
1817
+ private initLogStream;
1818
+ private writeHeader;
1819
+ /**
1820
+ * Calculate cost based on token usage and model
1821
+ */
1822
+ calculateCost(model: string, inputTokens: number, outputTokens: number, cacheReadTokens?: number, cacheWriteTokens?: number): number;
1823
+ /**
1824
+ * Log an LLM API call
1825
+ */
1826
+ log(entry: LLMUsageEntry): void;
1827
+ /**
1828
+ * Log session summary (call at end of request)
1829
+ */
1830
+ logSessionSummary(requestContext?: string): void;
1831
+ /**
1832
+ * Reset session stats (call at start of new user request)
1833
+ */
1834
+ resetSession(): void;
1835
+ /**
1836
+ * Reset the log file for a new request (clears previous logs)
1837
+ * Call this at the start of each USER_PROMPT_REQ
1838
+ */
1839
+ resetLogFile(requestContext?: string): void;
1840
+ /**
1841
+ * Get current session stats
1842
+ */
1843
+ getSessionStats(): {
1844
+ totalCalls: number;
1845
+ totalInputTokens: number;
1846
+ totalOutputTokens: number;
1847
+ totalCacheReadTokens: number;
1848
+ totalCacheWriteTokens: number;
1849
+ totalCostUSD: number;
1850
+ totalDurationMs: number;
1851
+ };
1852
+ /**
1853
+ * Generate a unique request ID
1854
+ */
1855
+ generateRequestId(): string;
1856
+ }
1857
+ declare const llmUsageLogger: LLMUsageLogger;
1858
+
1859
+ /**
1860
+ * User Prompt Error Logger - Captures detailed errors for USER_PROMPT_REQ
1861
+ * Logs full error details including raw strings for parse failures
1862
+ */
1863
+ declare class UserPromptErrorLogger {
1864
+ private logStream;
1865
+ private logPath;
1866
+ private enabled;
1867
+ private hasErrors;
1868
+ constructor();
1869
+ /**
1870
+ * Reset the error log file for a new request
1871
+ */
1872
+ resetLogFile(requestContext?: string): void;
1873
+ /**
1874
+ * Log a JSON parse error with the raw string that failed
1875
+ */
1876
+ logJsonParseError(context: string, rawString: string, error: Error): void;
1877
+ /**
1878
+ * Log a general error with full details
1879
+ */
1880
+ logError(context: string, error: Error | string, additionalData?: Record<string, any>): void;
1881
+ /**
1882
+ * Log a SQL query error with the full query
1883
+ */
1884
+ logSqlError(query: string, error: Error | string, params?: any[]): void;
1885
+ /**
1886
+ * Log an LLM API error
1887
+ */
1888
+ logLlmError(provider: string, model: string, method: string, error: Error | string, requestData?: any): void;
1889
+ /**
1890
+ * Log tool execution error
1891
+ */
1892
+ logToolError(toolName: string, toolInput: any, error: Error | string): void;
1893
+ /**
1894
+ * Write final summary if there were errors
1895
+ */
1896
+ writeSummary(): void;
1897
+ /**
1898
+ * Check if any errors were logged
1899
+ */
1900
+ hadErrors(): boolean;
1901
+ private write;
1902
+ }
1903
+ declare const userPromptErrorLogger: UserPromptErrorLogger;
1904
+
1905
+ /**
1906
+ * BM25L Reranker for hybrid semantic search
1907
+ *
1908
+ * BM25L is an improved variant of BM25 that provides better handling of
1909
+ * long documents and term frequency saturation. This implementation is
1910
+ * designed to rerank semantic search results from ChromaDB.
1911
+ *
1912
+ * The hybrid approach combines:
1913
+ * 1. Semantic similarity from ChromaDB embeddings (dense vectors)
1914
+ * 2. Lexical matching from BM25L (sparse, keyword-based)
1915
+ *
1916
+ * This addresses the weakness of pure semantic search which may miss
1917
+ * exact keyword matches that are important for user intent.
1918
+ */
1919
+ interface BM25LOptions {
1920
+ /** Term frequency saturation parameter (default: 1.5) */
1921
+ k1?: number;
1922
+ /** Length normalization parameter (default: 0.75) */
1923
+ b?: number;
1924
+ /** Lower-bound adjustment from BM25L paper (default: 0.5) */
1925
+ delta?: number;
1926
+ }
1927
+ interface RerankedResult<T> {
1928
+ item: T;
1929
+ originalIndex: number;
1930
+ semanticScore: number;
1931
+ bm25Score: number;
1932
+ hybridScore: number;
1933
+ }
1934
+ interface HybridSearchOptions extends BM25LOptions {
1935
+ /** Weight for semantic score (0-1, default: 0.7) */
1936
+ semanticWeight?: number;
1937
+ /** Weight for BM25 score (0-1, default: 0.3) */
1938
+ bm25Weight?: number;
1939
+ /** Minimum hybrid score threshold (0-1, default: 0) */
1940
+ minScore?: number;
1941
+ }
1942
+ /**
1943
+ * BM25L implementation for lexical scoring
1944
+ */
1945
+ declare class BM25L {
1946
+ private k1;
1947
+ private b;
1948
+ private delta;
1949
+ private documents;
1950
+ private docLengths;
1951
+ private avgDocLength;
1952
+ private termDocFreq;
1953
+ /**
1954
+ * @param documents - Array of raw documents (strings)
1955
+ * @param opts - Optional BM25L parameters
1956
+ */
1957
+ constructor(documents?: string[], opts?: BM25LOptions);
1958
+ /**
1959
+ * Tokenize text into lowercase alphanumeric tokens
1960
+ */
1961
+ tokenize(text: string): string[];
1962
+ /**
1963
+ * Compute IDF (Inverse Document Frequency) with smoothing
1964
+ */
1965
+ private idf;
1966
+ /**
1967
+ * Compute BM25L score for a single document
1968
+ */
1969
+ score(query: string, docIndex: number): number;
1970
+ /**
1971
+ * Search and rank all documents
1972
+ */
1973
+ search(query: string): Array<{
1974
+ index: number;
1975
+ score: number;
1976
+ }>;
1977
+ }
1978
+ /**
1979
+ * Hybrid reranker that combines semantic and BM25L scores
1980
+ *
1981
+ * @param query - The search query
1982
+ * @param items - Array of items to rerank
1983
+ * @param getDocument - Function to extract document text from an item
1984
+ * @param getSemanticScore - Function to extract semantic similarity score from an item
1985
+ * @param options - Hybrid search options
1986
+ * @returns Reranked items with hybrid scores
1987
+ */
1988
+ declare function hybridRerank<T>(query: string, items: T[], getDocument: (item: T) => string, getSemanticScore: (item: T) => number, options?: HybridSearchOptions): RerankedResult<T>[];
1989
+ /**
1990
+ * Simple reranking function for ChromaDB results
1991
+ *
1992
+ * This is a convenience wrapper for reranking ChromaDB query results
1993
+ * that follow the standard { ids, documents, metadatas, distances } format.
1994
+ *
1995
+ * @param query - The search query
1996
+ * @param chromaResults - ChromaDB query results
1997
+ * @param options - Hybrid search options
1998
+ * @returns Reranked results with hybrid scores
1999
+ */
2000
+ declare function rerankChromaResults(query: string, chromaResults: {
2001
+ ids: string[][];
2002
+ documents: (string | null)[][];
2003
+ metadatas: Record<string, any>[][];
2004
+ distances: number[][];
2005
+ }, options?: HybridSearchOptions): Array<{
2006
+ id: string;
2007
+ document: string | null;
2008
+ metadata: Record<string, any>;
2009
+ distance: number;
2010
+ semanticScore: number;
2011
+ bm25Score: number;
2012
+ hybridScore: number;
2013
+ }>;
2014
+ /**
2015
+ * Rerank conversation search results specifically
2016
+ *
2017
+ * This function is designed to work with the conversation-history.search collection
2018
+ * where we need to fetch more results initially and then rerank them.
2019
+ *
2020
+ * @param query - The user's search query
2021
+ * @param results - Array of conversation search results from ChromaDB
2022
+ * @param options - Hybrid search options
2023
+ * @returns Reranked results sorted by hybrid score
2024
+ */
2025
+ declare function rerankConversationResults<T extends {
2026
+ userPrompt?: string;
2027
+ similarity?: number;
2028
+ }>(query: string, results: T[], options?: HybridSearchOptions): Array<T & {
2029
+ hybridScore: number;
2030
+ bm25Score: number;
2031
+ }>;
2032
+
2033
+ /**
2034
+ * QueryExecutionService - Handles all query execution, validation, and retry logic
2035
+ * Extracted from BaseLLM for better separation of concerns
2036
+ */
2037
+
2038
+ /**
2039
+ * Context for component when requesting query fix
2040
+ */
2041
+ interface ComponentContext {
2042
+ name: string;
2043
+ type: string;
2044
+ title?: string;
2045
+ }
2046
+ /**
2047
+ * Result of query validation
2048
+ */
2049
+ interface QueryValidationResult {
2050
+ component: Component | null;
2051
+ queryKey: string;
2052
+ result: any;
2053
+ validated: boolean;
2054
+ }
2055
+ /**
2056
+ * Result of batch query validation
2057
+ */
2058
+ interface BatchValidationResult {
2059
+ components: Component[];
2060
+ queryResults: Map<string, any>;
2061
+ }
2062
+ /**
2063
+ * Configuration for QueryExecutionService
2064
+ */
2065
+ interface QueryExecutionServiceConfig {
2066
+ defaultLimit: number;
2067
+ getModelForTask: (taskType: 'simple' | 'complex') => string;
2068
+ getApiKey: (apiKey?: string) => string | undefined;
2069
+ providerName: string;
2070
+ }
2071
+ /**
2072
+ * QueryExecutionService handles all query-related operations
2073
+ */
2074
+ declare class QueryExecutionService {
2075
+ private config;
2076
+ constructor(config: QueryExecutionServiceConfig);
2077
+ /**
2078
+ * Get the cache key for a query
2079
+ * This ensures the cache key matches what the frontend will send
2080
+ */
2081
+ getQueryCacheKey(query: any): string;
2082
+ /**
2083
+ * Execute a query against the database
2084
+ * @param query - The SQL query to execute (string or object with sql/values)
2085
+ * @param collections - Collections object containing database execute function
2086
+ * @returns Object with result data and cache key
2087
+ */
2088
+ executeQuery(query: any, collections: any): Promise<{
2089
+ result: any;
2090
+ cacheKey: string;
2091
+ }>;
2092
+ /**
2093
+ * Request the LLM to fix a failed SQL query
2094
+ * @param failedQuery - The query that failed execution
2095
+ * @param errorMessage - The error message from the failed execution
2096
+ * @param componentContext - Context about the component
2097
+ * @param apiKey - Optional API key
2098
+ * @returns Fixed query string
2099
+ */
2100
+ requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
2101
+ /**
2102
+ * Validate a single component's query with retry logic
2103
+ * @param component - The component to validate
2104
+ * @param collections - Collections object containing database execute function
2105
+ * @param apiKey - Optional API key for LLM calls
2106
+ * @returns Validation result with component, query key, and result
2107
+ */
2108
+ validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
2109
+ /**
2110
+ * Validate multiple component queries in parallel
2111
+ * @param components - Array of components with potential queries
2112
+ * @param collections - Collections object containing database execute function
2113
+ * @param apiKey - Optional API key for LLM calls
2114
+ * @returns Object with validated components and query results map
2115
+ */
2116
+ validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
2117
+ }
2118
+
2119
+ /**
2120
+ * Task types for model selection
2121
+ * - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
2122
+ * - 'simple': Classification, action generation (uses fast model in balanced mode)
2123
+ */
2124
+ type TaskType = 'complex' | 'simple';
2125
+ interface BaseLLMConfig {
2126
+ model?: string;
2127
+ fastModel?: string;
2128
+ defaultLimit?: number;
2129
+ apiKey?: string;
2130
+ /**
2131
+ * Model selection strategy:
2132
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
2133
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
2134
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
2135
+ */
2136
+ modelStrategy?: ModelStrategy;
2137
+ conversationSimilarityThreshold?: number;
2138
+ }
2139
+ /**
2140
+ * BaseLLM abstract class for AI-powered component generation and matching
2141
+ * Provides common functionality for all LLM providers
2142
+ */
2143
+ declare abstract class BaseLLM {
2144
+ protected model: string;
2145
+ protected fastModel: string;
2146
+ protected defaultLimit: number;
2147
+ protected apiKey?: string;
2148
+ protected modelStrategy: ModelStrategy;
2149
+ protected conversationSimilarityThreshold: number;
2150
+ protected queryService: QueryExecutionService;
2151
+ constructor(config?: BaseLLMConfig);
2152
+ /**
2153
+ * Get the appropriate model based on task type and model strategy
2154
+ * @param taskType - 'complex' for text generation/matching, 'simple' for classification/actions
2155
+ * @returns The model string to use for this task
2156
+ */
2157
+ protected getModelForTask(taskType: TaskType): string;
2158
+ /**
2159
+ * Set the model strategy at runtime
2160
+ * @param strategy - 'best', 'fast', or 'balanced'
2161
+ */
2162
+ setModelStrategy(strategy: ModelStrategy): void;
2163
+ /**
2164
+ * Get the current model strategy
2165
+ * @returns The current model strategy
2166
+ */
2167
+ getModelStrategy(): ModelStrategy;
2168
+ /**
2169
+ * Set the conversation similarity threshold at runtime
2170
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2171
+ */
2172
+ setConversationSimilarityThreshold(threshold: number): void;
2173
+ /**
2174
+ * Get the current conversation similarity threshold
2175
+ * @returns The current threshold value
2176
+ */
2177
+ getConversationSimilarityThreshold(): number;
2178
+ /**
2179
+ * Get the default model for this provider (used for complex tasks like text generation)
2180
+ */
2181
+ protected abstract getDefaultModel(): string;
2182
+ /**
2183
+ * Get the default fast model for this provider (used for simple tasks: classification, matching, actions)
2184
+ * Should return a cheaper/faster model like Haiku for Anthropic
2185
+ */
2186
+ protected abstract getDefaultFastModel(): string;
2187
+ /**
2188
+ * Get the default API key from environment
2189
+ */
2190
+ protected abstract getDefaultApiKey(): string | undefined;
2191
+ /**
2192
+ * Get the provider name (for logging)
2193
+ */
2194
+ protected abstract getProviderName(): string;
2195
+ /**
2196
+ * Get the API key (from instance, parameter, or environment)
2197
+ */
2198
+ protected getApiKey(apiKey?: string): string | undefined;
2199
+ /**
2200
+ * Check if a component contains a Form (data_modification component)
2201
+ * Forms have hardcoded defaultValues that become stale when cached
2202
+ * This checks both single Form components and Forms inside MultiComponentContainer
2203
+ */
2204
+ protected containsFormComponent(component: any): boolean;
2205
+ /**
2206
+ * Match components from text response suggestions and generate follow-up questions
2207
+ * Takes a text response with component suggestions (c1:type format) and matches with available components
2208
+ * Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
2209
+ * All components are placed in a default MultiComponentContainer layout
2210
+ * @param analysisContent - The text response containing component suggestions
2211
+ * @param components - List of available components
2212
+ * @param apiKey - Optional API key
2213
+ * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
2214
+ * @returns Object containing matched components, layout title/description, and follow-up actions
2215
+ */
2216
+ matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
2217
+ components: Component[];
2218
+ layoutTitle: string;
2219
+ layoutDescription: string;
2220
+ actions: Action[];
2221
+ }>;
2222
+ /**
2223
+ * Classify user question into category and detect external tools needed
2224
+ * Determines if question is for data analysis, requires external tools, or needs text response
2225
+ */
2226
+ classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
2227
+ category: 'data_analysis' | 'data_modification' | 'general';
2228
+ externalTools: Array<{
2229
+ type: string;
2230
+ name: string;
2231
+ description: string;
2232
+ parameters: Record<string, any>;
2233
+ }>;
2234
+ dataAnalysisType?: 'visualization' | 'calculation' | 'comparison' | 'trend';
2235
+ reasoning: string;
2236
+ confidence: number;
2237
+ }>;
2238
+ /**
2239
+ * Adapt UI block parameters based on current user question
2240
+ * Takes a matched UI block from semantic search and modifies its props to answer the new question
2241
+ * Also adapts the cached text response to match the new question
2242
+ */
2243
+ adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
2244
+ success: boolean;
2245
+ adaptedComponent?: Component;
2246
+ adaptedTextResponse?: string;
2247
+ parametersChanged?: Array<{
2248
+ field: string;
2249
+ reason: string;
2250
+ }>;
2251
+ explanation: string;
2252
+ }>;
2253
+ /**
2254
+ * Generate text-based response for user question
2255
+ * This provides conversational text responses instead of component generation
2256
+ * Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
2257
+ * After generating text response, if components are provided, matches suggested components
2258
+ */
2259
+ 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>;
2260
+ /**
2261
+ * Main orchestration function with semantic search and multi-step classification
2262
+ * NEW FLOW (Recommended):
2263
+ * 1. Semantic search: Check previous conversations (>60% match)
2264
+ * - If match found → Adapt UI block parameters and return
2265
+ * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
2266
+ * 3. Route appropriately based on category and response mode
2267
+ */
2268
+ 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>;
2269
+ /**
2270
+ * Generate next questions that the user might ask based on the original prompt and generated component
2271
+ * This helps provide intelligent suggestions for follow-up queries
2272
+ * For general/conversational questions without components, pass textResponse instead
2273
+ */
2274
+ generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string): Promise<string[]>;
2275
+ }
2276
+
2277
+ interface AnthropicLLMConfig extends BaseLLMConfig {
2278
+ }
2279
+ /**
2280
+ * AnthropicLLM class for handling AI-powered component generation and matching using Anthropic Claude
2281
+ */
2282
+ declare class AnthropicLLM extends BaseLLM {
2283
+ constructor(config?: AnthropicLLMConfig);
2284
+ protected getDefaultModel(): string;
2285
+ protected getDefaultFastModel(): string;
2286
+ protected getDefaultApiKey(): string | undefined;
2287
+ protected getProviderName(): string;
2288
+ }
2289
+ declare const anthropicLLM: AnthropicLLM;
2290
+
2291
+ interface GroqLLMConfig extends BaseLLMConfig {
2292
+ }
2293
+ /**
2294
+ * GroqLLM class for handling AI-powered component generation and matching using Groq
2295
+ */
2296
+ declare class GroqLLM extends BaseLLM {
2297
+ constructor(config?: GroqLLMConfig);
2298
+ protected getDefaultModel(): string;
2299
+ protected getDefaultFastModel(): string;
2300
+ protected getDefaultApiKey(): string | undefined;
2301
+ protected getProviderName(): string;
2302
+ }
2303
+ declare const groqLLM: GroqLLM;
2304
+
2305
+ interface GeminiLLMConfig extends BaseLLMConfig {
2306
+ }
2307
+ /**
2308
+ * GeminiLLM class for handling AI-powered component generation and matching using Google Gemini
2309
+ */
2310
+ declare class GeminiLLM extends BaseLLM {
2311
+ constructor(config?: GeminiLLMConfig);
2312
+ protected getDefaultModel(): string;
2313
+ protected getDefaultFastModel(): string;
2314
+ protected getDefaultApiKey(): string | undefined;
2315
+ protected getProviderName(): string;
2316
+ }
2317
+ declare const geminiLLM: GeminiLLM;
2318
+
2319
+ interface OpenAILLMConfig extends BaseLLMConfig {
2320
+ }
2321
+ /**
2322
+ * OpenAILLM class for handling AI-powered component generation and matching using OpenAI GPT models
2323
+ */
2324
+ declare class OpenAILLM extends BaseLLM {
2325
+ constructor(config?: OpenAILLMConfig);
2326
+ protected getDefaultModel(): string;
2327
+ protected getDefaultFastModel(): string;
2328
+ protected getDefaultApiKey(): string | undefined;
2329
+ protected getProviderName(): string;
2330
+ }
2331
+ declare const openaiLLM: OpenAILLM;
2332
+
2333
+ /**
2334
+ * Query Cache - Stores query results with configurable TTL
2335
+ * Used to avoid re-executing queries that were already validated
2336
+ */
2337
+ declare class QueryCache {
2338
+ private cache;
2339
+ private queryIdCache;
2340
+ private ttlMs;
2341
+ private cleanupInterval;
2342
+ constructor();
2343
+ /**
2344
+ * Set the cache TTL (Time To Live)
2345
+ * @param minutes - TTL in minutes (default: 5)
2346
+ */
2347
+ setTTL(minutes: number): void;
2348
+ /**
2349
+ * Get the current TTL in minutes
2350
+ */
2351
+ getTTL(): number;
2352
+ /**
2353
+ * Store query result in cache
2354
+ * Key is the exact query string (or JSON for parameterized queries)
2355
+ */
2356
+ set(query: string, data: any): void;
2357
+ /**
2358
+ * Get cached result if exists and not expired
2359
+ */
2360
+ get(query: string): any | null;
2361
+ /**
2362
+ * Check if query exists in cache (not expired)
2363
+ */
2364
+ has(query: string): boolean;
2365
+ /**
2366
+ * Remove a specific query from cache
2367
+ */
2368
+ delete(query: string): void;
2369
+ /**
2370
+ * Clear all cached entries
2371
+ */
2372
+ clear(): void;
2373
+ /**
2374
+ * Get cache statistics
2375
+ */
2376
+ getStats(): {
2377
+ size: number;
2378
+ oldestEntryAge: number | null;
2379
+ };
2380
+ /**
2381
+ * Start periodic cleanup of expired entries
2382
+ */
2383
+ private startCleanup;
2384
+ /**
2385
+ * Generate a unique query ID
2386
+ */
2387
+ private generateQueryId;
2388
+ /**
2389
+ * Store a query by ID. Returns the generated queryId.
2390
+ * The query is stored server-side; only the queryId is sent to the frontend.
2391
+ */
2392
+ storeQuery(query: any, data?: any): string;
2393
+ /**
2394
+ * Get a stored query by its ID (not expired)
2395
+ */
2396
+ getQuery(queryId: string): {
2397
+ query: any;
2398
+ data: any;
2399
+ } | null;
2400
+ /**
2401
+ * Update cached data for a queryId
2402
+ */
2403
+ setQueryData(queryId: string, data: any): void;
2404
+ /**
2405
+ * Stop cleanup interval (for graceful shutdown)
2406
+ */
2407
+ destroy(): void;
2408
+ }
2409
+ declare const queryCache: QueryCache;
2410
+
1292
2411
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
1293
2412
  declare class SuperatomSDK {
1294
2413
  private ws;
1295
2414
  private url;
1296
- private apiKey;
2415
+ private apiKey?;
1297
2416
  private projectId;
1298
- private userId;
1299
2417
  private type;
1300
2418
  private bundleDir;
1301
2419
  private messageHandlers;
@@ -1305,15 +2423,26 @@ declare class SuperatomSDK {
1305
2423
  private maxReconnectAttempts;
1306
2424
  private collections;
1307
2425
  private components;
2426
+ private tools;
1308
2427
  private anthropicApiKey;
1309
2428
  private groqApiKey;
2429
+ private geminiApiKey;
2430
+ private openaiApiKey;
1310
2431
  private llmProviders;
2432
+ private databaseType;
2433
+ private modelStrategy;
2434
+ private conversationSimilarityThreshold;
1311
2435
  private userManager;
1312
2436
  private dashboardManager;
1313
2437
  private reportManager;
2438
+ private pingInterval;
2439
+ private lastPong;
2440
+ private readonly PING_INTERVAL_MS;
2441
+ private readonly PONG_TIMEOUT_MS;
1314
2442
  constructor(config: SuperatomSDKConfig);
1315
2443
  /**
1316
2444
  * Initialize PromptLoader and load prompts into memory
2445
+ * Tries to load from file system first, then falls back to hardcoded prompts
1317
2446
  */
1318
2447
  private initializePromptLoader;
1319
2448
  /**
@@ -1377,7 +2506,56 @@ declare class SuperatomSDK {
1377
2506
  */
1378
2507
  addCollection<TParams = any, TResult = any>(collectionName: string, operation: CollectionOperation | string, handler: CollectionHandler<TParams, TResult>): void;
1379
2508
  private handleReconnect;
2509
+ /**
2510
+ * Start heartbeat to keep WebSocket connection alive
2511
+ * Sends PING every 3 minutes to prevent idle timeout from cloud infrastructure
2512
+ */
2513
+ private startHeartbeat;
2514
+ /**
2515
+ * Stop the heartbeat interval
2516
+ */
2517
+ private stopHeartbeat;
2518
+ /**
2519
+ * Handle PONG response from server
2520
+ */
2521
+ private handlePong;
1380
2522
  private storeComponents;
2523
+ /**
2524
+ * Set tools for the SDK instance
2525
+ */
2526
+ setTools(tools: Tool$1[]): void;
2527
+ /**
2528
+ * Get the stored tools
2529
+ */
2530
+ getTools(): Tool$1[];
2531
+ /**
2532
+ * Apply model strategy to all LLM provider singletons
2533
+ * @param strategy - 'best', 'fast', or 'balanced'
2534
+ */
2535
+ private applyModelStrategy;
2536
+ /**
2537
+ * Set model strategy at runtime
2538
+ * @param strategy - 'best', 'fast', or 'balanced'
2539
+ */
2540
+ setModelStrategy(strategy: ModelStrategy): void;
2541
+ /**
2542
+ * Get current model strategy
2543
+ */
2544
+ getModelStrategy(): ModelStrategy;
2545
+ /**
2546
+ * Apply conversation similarity threshold to all LLM provider singletons
2547
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2548
+ */
2549
+ private applyConversationSimilarityThreshold;
2550
+ /**
2551
+ * Set conversation similarity threshold at runtime
2552
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2553
+ */
2554
+ setConversationSimilarityThreshold(threshold: number): void;
2555
+ /**
2556
+ * Get current conversation similarity threshold
2557
+ */
2558
+ getConversationSimilarityThreshold(): number;
1381
2559
  }
1382
2560
 
1383
- 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 };
2561
+ 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 };