@superatomai/sdk-node 0.0.4 → 0.0.5-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.ts CHANGED
@@ -1,4 +1,78 @@
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
+ }
14
+
15
+ /**
16
+ * Log levels in hierarchical order
17
+ * - errors: only error logs
18
+ * - warnings: warning + error logs
19
+ * - info: info + warning + error logs
20
+ * - verbose: all logs including debug
21
+ */
22
+ type LogLevel = 'errors' | 'warnings' | 'info' | 'verbose';
23
+ /**
24
+ * Logger class with environment-based log level support
25
+ */
26
+ declare class Logger {
27
+ private currentLevel;
28
+ private currentLevelPriority;
29
+ constructor();
30
+ /**
31
+ * Check if a string is a valid log level
32
+ */
33
+ private isValidLogLevel;
34
+ /**
35
+ * Check if a message should be logged based on current log level
36
+ */
37
+ private shouldLog;
38
+ /**
39
+ * Get current log level
40
+ */
41
+ getLogLevel(): LogLevel;
42
+ /**
43
+ * Set log level programmatically
44
+ */
45
+ setLogLevel(level: LogLevel): void;
46
+ /**
47
+ * Log info message (shown for info and verbose levels)
48
+ */
49
+ info(...args: any[]): void;
50
+ /**
51
+ * Log error message (shown for all levels)
52
+ */
53
+ error(...args: any[]): void;
54
+ /**
55
+ * Log warning message (shown for warnings, info, and verbose levels)
56
+ */
57
+ warn(...args: any[]): void;
58
+ /**
59
+ * Log debug message (only shown for verbose level)
60
+ */
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;
74
+ }
75
+ declare const logger: Logger;
2
76
 
3
77
  declare const DSLRendererPropsSchema$1: z.ZodObject<{
4
78
  dsl: z.ZodObject<{
@@ -27,7 +101,27 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
27
101
  deps?: string[] | undefined;
28
102
  }>, "many">>;
29
103
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
30
- 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>;
31
125
  query: z.ZodOptional<z.ZodObject<{
32
126
  graphql: z.ZodOptional<z.ZodString>;
33
127
  sql: z.ZodOptional<z.ZodString>;
@@ -66,6 +160,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
66
160
  dependencies?: string[] | undefined;
67
161
  } | undefined;
68
162
  props?: Record<string, any> | undefined;
163
+ render?: any;
69
164
  states?: Record<string, any> | undefined;
70
165
  methods?: Record<string, {
71
166
  fn: string;
@@ -76,7 +171,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
76
171
  deps?: string[] | undefined;
77
172
  }[] | undefined;
78
173
  data?: Record<string, any> | undefined;
79
- 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;
80
182
  }, {
81
183
  id: string;
82
184
  name?: string | undefined;
@@ -90,6 +192,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
90
192
  dependencies?: string[] | undefined;
91
193
  } | undefined;
92
194
  props?: Record<string, any> | undefined;
195
+ render?: any;
93
196
  states?: Record<string, any> | undefined;
94
197
  methods?: Record<string, {
95
198
  fn: string;
@@ -100,7 +203,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
100
203
  deps?: string[] | undefined;
101
204
  }[] | undefined;
102
205
  data?: Record<string, any> | undefined;
103
- 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;
104
214
  }>;
105
215
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
106
216
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -118,6 +228,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
118
228
  dependencies?: string[] | undefined;
119
229
  } | undefined;
120
230
  props?: Record<string, any> | undefined;
231
+ render?: any;
121
232
  states?: Record<string, any> | undefined;
122
233
  methods?: Record<string, {
123
234
  fn: string;
@@ -128,7 +239,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
128
239
  deps?: string[] | undefined;
129
240
  }[] | undefined;
130
241
  data?: Record<string, any> | undefined;
131
- 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;
132
250
  };
133
251
  data?: Record<string, any> | undefined;
134
252
  context?: Record<string, any> | undefined;
@@ -146,6 +264,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
146
264
  dependencies?: string[] | undefined;
147
265
  } | undefined;
148
266
  props?: Record<string, any> | undefined;
267
+ render?: any;
149
268
  states?: Record<string, any> | undefined;
150
269
  methods?: Record<string, {
151
270
  fn: string;
@@ -156,7 +275,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
156
275
  deps?: string[] | undefined;
157
276
  }[] | undefined;
158
277
  data?: Record<string, any> | undefined;
159
- 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;
160
286
  };
161
287
  data?: Record<string, any> | undefined;
162
288
  context?: Record<string, any> | undefined;
@@ -229,6 +355,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
229
355
  dependencies?: string[] | undefined;
230
356
  } | undefined;
231
357
  props?: Record<string, any> | undefined;
358
+ render?: any;
232
359
  states?: Record<string, any> | undefined;
233
360
  methods?: Record<string, {
234
361
  fn: string;
@@ -239,7 +366,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
239
366
  deps?: string[] | undefined;
240
367
  }[] | undefined;
241
368
  data?: Record<string, any> | undefined;
242
- render?: any;
243
369
  }, {
244
370
  id: string;
245
371
  name?: string | undefined;
@@ -253,6 +379,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
253
379
  dependencies?: string[] | undefined;
254
380
  } | undefined;
255
381
  props?: Record<string, any> | undefined;
382
+ render?: any;
256
383
  states?: Record<string, any> | undefined;
257
384
  methods?: Record<string, {
258
385
  fn: string;
@@ -263,7 +390,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
263
390
  deps?: string[] | undefined;
264
391
  }[] | undefined;
265
392
  data?: Record<string, any> | undefined;
266
- render?: any;
267
393
  }>;
268
394
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
269
395
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -281,6 +407,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
281
407
  dependencies?: string[] | undefined;
282
408
  } | undefined;
283
409
  props?: Record<string, any> | undefined;
410
+ render?: any;
284
411
  states?: Record<string, any> | undefined;
285
412
  methods?: Record<string, {
286
413
  fn: string;
@@ -291,7 +418,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
291
418
  deps?: string[] | undefined;
292
419
  }[] | undefined;
293
420
  data?: Record<string, any> | undefined;
294
- render?: any;
295
421
  };
296
422
  data?: Record<string, any> | undefined;
297
423
  context?: Record<string, any> | undefined;
@@ -309,6 +435,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
309
435
  dependencies?: string[] | undefined;
310
436
  } | undefined;
311
437
  props?: Record<string, any> | undefined;
438
+ render?: any;
312
439
  states?: Record<string, any> | undefined;
313
440
  methods?: Record<string, {
314
441
  fn: string;
@@ -319,13 +446,86 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
319
446
  deps?: string[] | undefined;
320
447
  }[] | undefined;
321
448
  data?: Record<string, any> | undefined;
322
- render?: any;
323
449
  };
324
450
  data?: Record<string, any> | undefined;
325
451
  context?: Record<string, any> | undefined;
326
452
  }>;
327
453
  type DSLRendererProps = z.infer<typeof DSLRendererPropsSchema>;
328
454
 
455
+ declare const UserSchema: z.ZodObject<{
456
+ username: z.ZodString;
457
+ email: z.ZodOptional<z.ZodString>;
458
+ password: z.ZodString;
459
+ fullname: z.ZodOptional<z.ZodString>;
460
+ role: z.ZodOptional<z.ZodString>;
461
+ userInfo: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
462
+ wsIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
463
+ }, "strip", z.ZodTypeAny, {
464
+ username: string;
465
+ password: string;
466
+ email?: string | undefined;
467
+ fullname?: string | undefined;
468
+ role?: string | undefined;
469
+ userInfo?: Record<string, unknown> | undefined;
470
+ wsIds?: string[] | undefined;
471
+ }, {
472
+ username: string;
473
+ password: string;
474
+ email?: string | undefined;
475
+ fullname?: string | undefined;
476
+ role?: string | undefined;
477
+ userInfo?: Record<string, unknown> | undefined;
478
+ wsIds?: string[] | undefined;
479
+ }>;
480
+ type User = z.infer<typeof UserSchema>;
481
+ declare const UsersDataSchema: z.ZodObject<{
482
+ users: z.ZodArray<z.ZodObject<{
483
+ username: z.ZodString;
484
+ email: z.ZodOptional<z.ZodString>;
485
+ password: z.ZodString;
486
+ fullname: z.ZodOptional<z.ZodString>;
487
+ role: z.ZodOptional<z.ZodString>;
488
+ userInfo: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
489
+ wsIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
490
+ }, "strip", z.ZodTypeAny, {
491
+ username: string;
492
+ password: string;
493
+ email?: string | undefined;
494
+ fullname?: string | undefined;
495
+ role?: string | undefined;
496
+ userInfo?: Record<string, unknown> | undefined;
497
+ wsIds?: string[] | undefined;
498
+ }, {
499
+ username: string;
500
+ password: string;
501
+ email?: string | undefined;
502
+ fullname?: string | undefined;
503
+ role?: string | undefined;
504
+ userInfo?: Record<string, unknown> | undefined;
505
+ wsIds?: string[] | undefined;
506
+ }>, "many">;
507
+ }, "strip", z.ZodTypeAny, {
508
+ users: {
509
+ username: string;
510
+ password: string;
511
+ email?: string | undefined;
512
+ fullname?: string | undefined;
513
+ role?: string | undefined;
514
+ userInfo?: Record<string, unknown> | undefined;
515
+ wsIds?: string[] | undefined;
516
+ }[];
517
+ }, {
518
+ users: {
519
+ username: string;
520
+ password: string;
521
+ email?: string | undefined;
522
+ fullname?: string | undefined;
523
+ role?: string | undefined;
524
+ userInfo?: Record<string, unknown> | undefined;
525
+ wsIds?: string[] | undefined;
526
+ }[];
527
+ }>;
528
+ type UsersData = z.infer<typeof UsersDataSchema>;
329
529
  declare const MessageSchema: z.ZodObject<{
330
530
  id: z.ZodOptional<z.ZodString>;
331
531
  type: z.ZodString;
@@ -426,30 +626,401 @@ declare const IncomingMessageSchema: z.ZodObject<{
426
626
  payload?: unknown;
427
627
  }>;
428
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>;
429
806
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
430
807
  type CollectionHandler<TParams = any, TResult = any> = (params: TParams) => Promise<TResult> | TResult;
431
- type LLMProvider = 'anthropic' | 'groq';
808
+ type LLMProvider = 'anthropic' | 'groq' | 'gemini' | 'openai';
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
+ }
432
834
  interface SuperatomSDKConfig {
433
835
  url?: string;
434
- apiKey: string;
836
+ apiKey?: string;
435
837
  projectId: string;
436
- userId?: string;
437
838
  type?: string;
438
839
  bundleDir?: string;
439
840
  promptsDir?: string;
841
+ databaseType?: DatabaseType;
440
842
  ANTHROPIC_API_KEY?: string;
441
843
  GROQ_API_KEY?: string;
844
+ GEMINI_API_KEY?: string;
845
+ OPENAI_API_KEY?: string;
442
846
  LLM_PROVIDERS?: LLMProvider[];
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;
443
873
  }
444
874
 
445
- interface User {
446
- username: string;
447
- password: string;
448
- wsIds: string[];
449
- }
450
- interface UsersData {
451
- users: User[];
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[];
452
1022
  }
1023
+
453
1024
  /**
454
1025
  * UserManager class to handle CRUD operations on users with file persistence
455
1026
  * and in-memory caching. Changes are synced to file periodically.
@@ -503,6 +1074,18 @@ declare class UserManager {
503
1074
  * @returns The user if found, undefined otherwise
504
1075
  */
505
1076
  getUser(username: string): User | undefined;
1077
+ /**
1078
+ * Read a user by email
1079
+ * @param email - Email to retrieve
1080
+ * @returns The user if found, undefined otherwise
1081
+ */
1082
+ getUserByEmail(email: string): User | undefined;
1083
+ /**
1084
+ * Find user by username or email
1085
+ * @param identifier - Username or email to search for
1086
+ * @returns The user if found, undefined otherwise
1087
+ */
1088
+ getUserByUsernameOrEmail(identifier: string): User | undefined;
506
1089
  /**
507
1090
  * Read all users
508
1091
  * @returns Array of all users
@@ -697,9 +1280,11 @@ declare class ReportManager {
697
1280
  getReportCount(): number;
698
1281
  }
699
1282
 
1283
+ type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
700
1284
  interface LLMMessages {
701
- sys: string;
1285
+ sys: SystemPrompt;
702
1286
  user: string;
1287
+ prefill?: string;
703
1288
  }
704
1289
  interface LLMOptions {
705
1290
  model?: string;
@@ -709,9 +1294,31 @@ interface LLMOptions {
709
1294
  apiKey?: string;
710
1295
  partial?: (chunk: string) => void;
711
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
+ }
712
1306
  declare class LLM {
713
1307
  static text(messages: LLMMessages, options?: LLMOptions): Promise<string>;
714
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;
715
1322
  /**
716
1323
  * Parse model string to extract provider and model name
717
1324
  * @param modelString - Format: "provider/model-name" or just "model-name"
@@ -725,13 +1332,25 @@ declare class LLM {
725
1332
  private static _parseModel;
726
1333
  private static _anthropicText;
727
1334
  private static _anthropicStream;
1335
+ private static _anthropicStreamWithTools;
728
1336
  private static _groqText;
729
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;
730
1349
  /**
731
1350
  * Parse JSON string, handling markdown code blocks and surrounding text
732
- * Enhanced version from anthropic.ts implementation
1351
+ * Enhanced version with jsonrepair to handle malformed JSON from LLMs
733
1352
  * @param text - Text that may contain JSON wrapped in ```json...``` or with surrounding text
734
- * @returns Parsed JSON object
1353
+ * @returns Parsed JSON object or array
735
1354
  */
736
1355
  private static _parseJSON;
737
1356
  }
@@ -747,19 +1366,26 @@ interface CapturedLog {
747
1366
  * UILogCollector captures logs during user prompt processing
748
1367
  * and sends them to runtime via ui_logs message with uiBlockId as the message id
749
1368
  * Logs are sent in real-time for streaming effect in the UI
1369
+ * Respects the global log level configuration
750
1370
  */
751
1371
  declare class UILogCollector {
752
1372
  private logs;
753
1373
  private uiBlockId;
754
1374
  private clientId;
755
1375
  private sendMessage;
1376
+ private currentLogLevel;
756
1377
  constructor(clientId: string, sendMessage: (message: Message) => void, uiBlockId?: string);
757
1378
  /**
758
1379
  * Check if logging is enabled (uiBlockId is provided)
759
1380
  */
760
1381
  isEnabled(): boolean;
1382
+ /**
1383
+ * Check if a message should be logged based on current log level
1384
+ */
1385
+ private shouldLog;
761
1386
  /**
762
1387
  * Add a log entry with timestamp and immediately send to runtime
1388
+ * Only logs that pass the log level filter are captured and sent
763
1389
  */
764
1390
  private addLog;
765
1391
  /**
@@ -820,13 +1446,14 @@ interface Action {
820
1446
 
821
1447
  /**
822
1448
  * UIBlock represents a single user and assistant message block in a thread
823
- * Contains user question, component metadata, component data, and available actions
1449
+ * Contains user question, component metadata, component data, text response, and available actions
824
1450
  */
825
1451
  declare class UIBlock {
826
1452
  private id;
827
1453
  private userQuestion;
828
1454
  private generatedComponentMetadata;
829
1455
  private componentData;
1456
+ private textResponse;
830
1457
  private actions;
831
1458
  private createdAt;
832
1459
  /**
@@ -836,8 +1463,9 @@ declare class UIBlock {
836
1463
  * @param generatedComponentMetadata - Optional metadata about the generated component
837
1464
  * @param actions - Optional array of available actions
838
1465
  * @param id - Optional custom ID, generates UUID if not provided
1466
+ * @param textResponse - Optional text response from LLM
839
1467
  */
840
- constructor(userQuestion: string, componentData?: Record<string, any>, generatedComponentMetadata?: Record<string, any>, actions?: Action[], id?: string);
1468
+ constructor(userQuestion: string, componentData?: Record<string, any>, generatedComponentMetadata?: Record<string, any>, actions?: Action[], id?: string, textResponse?: string | null);
841
1469
  /**
842
1470
  * Get the UIBlock ID
843
1471
  */
@@ -854,6 +1482,7 @@ declare class UIBlock {
854
1482
  * Get component metadata
855
1483
  */
856
1484
  getComponentMetadata(): Record<string, any>;
1485
+ getTextResponse(): string;
857
1486
  /**
858
1487
  * Set or update component metadata
859
1488
  */
@@ -882,6 +1511,10 @@ declare class UIBlock {
882
1511
  * Set or update component data with size and row limits
883
1512
  */
884
1513
  setComponentData(data: Record<string, any>): void;
1514
+ /**
1515
+ * Set or update text response
1516
+ */
1517
+ setTextResponse(textResponse: string | null): void;
885
1518
  /**
886
1519
  * Get all actions (only if they are resolved, not if fetching)
887
1520
  */
@@ -894,6 +1527,10 @@ declare class UIBlock {
894
1527
  * @returns Promise resolving to Action[]
895
1528
  */
896
1529
  getOrFetchActions(generateFn: () => Promise<Action[]>): Promise<Action[]>;
1530
+ /**
1531
+ * Set or replace all actions
1532
+ */
1533
+ setActions(actions: Action[]): void;
897
1534
  /**
898
1535
  * Add a single action (only if actions are resolved)
899
1536
  */
@@ -1124,15 +1761,17 @@ declare const STORAGE_CONFIG: {
1124
1761
  */
1125
1762
  MAX_ROWS_PER_BLOCK: number;
1126
1763
  /**
1127
- * Maximum size in bytes per UIBlock (1MB)
1764
+ * Maximum size in bytes per UIBlock (500KB - reduced to save memory)
1128
1765
  */
1129
1766
  MAX_SIZE_PER_BLOCK_BYTES: number;
1130
1767
  /**
1131
1768
  * Number of days to keep threads before cleanup
1769
+ * Note: This is for in-memory storage. Conversations are also persisted to database.
1132
1770
  */
1133
1771
  THREAD_RETENTION_DAYS: number;
1134
1772
  /**
1135
1773
  * Number of days to keep UIBlocks before cleanup
1774
+ * Note: This is for in-memory storage. Data is also persisted to database.
1136
1775
  */
1137
1776
  UIBLOCK_RETENTION_DAYS: number;
1138
1777
  };
@@ -1149,14 +1788,632 @@ declare const CONTEXT_CONFIG: {
1149
1788
  MAX_CONVERSATION_CONTEXT_BLOCKS: number;
1150
1789
  };
1151
1790
 
1152
- 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
+
1153
2411
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
1154
2412
  declare class SuperatomSDK {
1155
2413
  private ws;
1156
2414
  private url;
1157
- private apiKey;
2415
+ private apiKey?;
1158
2416
  private projectId;
1159
- private userId;
1160
2417
  private type;
1161
2418
  private bundleDir;
1162
2419
  private messageHandlers;
@@ -1166,15 +2423,26 @@ declare class SuperatomSDK {
1166
2423
  private maxReconnectAttempts;
1167
2424
  private collections;
1168
2425
  private components;
2426
+ private tools;
1169
2427
  private anthropicApiKey;
1170
2428
  private groqApiKey;
2429
+ private geminiApiKey;
2430
+ private openaiApiKey;
1171
2431
  private llmProviders;
2432
+ private databaseType;
2433
+ private modelStrategy;
2434
+ private conversationSimilarityThreshold;
1172
2435
  private userManager;
1173
2436
  private dashboardManager;
1174
2437
  private reportManager;
2438
+ private pingInterval;
2439
+ private lastPong;
2440
+ private readonly PING_INTERVAL_MS;
2441
+ private readonly PONG_TIMEOUT_MS;
1175
2442
  constructor(config: SuperatomSDKConfig);
1176
2443
  /**
1177
2444
  * Initialize PromptLoader and load prompts into memory
2445
+ * Tries to load from file system first, then falls back to hardcoded prompts
1178
2446
  */
1179
2447
  private initializePromptLoader;
1180
2448
  /**
@@ -1238,7 +2506,56 @@ declare class SuperatomSDK {
1238
2506
  */
1239
2507
  addCollection<TParams = any, TResult = any>(collectionName: string, operation: CollectionOperation | string, handler: CollectionHandler<TParams, TResult>): void;
1240
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;
1241
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;
1242
2559
  }
1243
2560
 
1244
- export { type Action, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type IncomingMessage, LLM, type Message, SDK_VERSION, STORAGE_CONFIG, SuperatomSDK, type SuperatomSDKConfig, Thread, ThreadManager, UIBlock, UILogCollector, type User, UserManager, type UsersData };
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 };