@superatomai/sdk-node 0.0.3 → 0.0.4-s

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,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,441 @@ 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
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
745
+ toolType: z.ZodOptional<z.ZodEnum<["source", "direct"]>>;
746
+ /** Full untruncated schema for source agent (all columns visible) */
747
+ fullSchema: z.ZodOptional<z.ZodString>;
748
+ params: z.ZodRecord<z.ZodString, z.ZodString>;
749
+ fn: z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodAny>;
750
+ outputSchema: z.ZodOptional<z.ZodObject<{
751
+ description: z.ZodString;
752
+ fields: z.ZodArray<z.ZodObject<{
753
+ name: z.ZodString;
754
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
755
+ description: z.ZodString;
756
+ }, "strip", z.ZodTypeAny, {
757
+ type: "string" | "number" | "boolean" | "date";
758
+ name: string;
759
+ description: string;
760
+ }, {
761
+ type: "string" | "number" | "boolean" | "date";
762
+ name: string;
763
+ description: string;
764
+ }>, "many">;
765
+ }, "strip", z.ZodTypeAny, {
766
+ description: string;
767
+ fields: {
768
+ type: "string" | "number" | "boolean" | "date";
769
+ name: string;
770
+ description: string;
771
+ }[];
772
+ }, {
773
+ description: string;
774
+ fields: {
775
+ type: "string" | "number" | "boolean" | "date";
776
+ name: string;
777
+ description: string;
778
+ }[];
779
+ }>>;
780
+ /** Cache policy. `false` = never cache (live data, write ops). Mirrors HTTP `Cache-Control: no-store`. */
781
+ cache: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<false>, z.ZodObject<{
782
+ ttlMs: z.ZodOptional<z.ZodNumber>;
783
+ }, "strip", z.ZodTypeAny, {
784
+ ttlMs?: number | undefined;
785
+ }, {
786
+ ttlMs?: number | undefined;
787
+ }>]>>;
788
+ }, "strip", z.ZodTypeAny, {
789
+ id: string;
790
+ params: Record<string, string>;
791
+ name: string;
792
+ description: string;
793
+ fn: (args_0: any, ...args: unknown[]) => any;
794
+ toolType?: "source" | "direct" | undefined;
795
+ fullSchema?: string | undefined;
796
+ outputSchema?: {
797
+ description: string;
798
+ fields: {
799
+ type: "string" | "number" | "boolean" | "date";
800
+ name: string;
801
+ description: string;
802
+ }[];
803
+ } | undefined;
804
+ cache?: false | {
805
+ ttlMs?: number | undefined;
806
+ } | undefined;
807
+ }, {
808
+ id: string;
809
+ params: Record<string, string>;
810
+ name: string;
811
+ description: string;
812
+ fn: (args_0: any, ...args: unknown[]) => any;
813
+ toolType?: "source" | "direct" | undefined;
814
+ fullSchema?: string | undefined;
815
+ outputSchema?: {
816
+ description: string;
817
+ fields: {
818
+ type: "string" | "number" | "boolean" | "date";
819
+ name: string;
820
+ description: string;
821
+ }[];
822
+ } | undefined;
823
+ cache?: false | {
824
+ ttlMs?: number | undefined;
825
+ } | undefined;
826
+ }>;
827
+ type Tool$1 = z.infer<typeof ToolSchema>;
429
828
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
430
829
  type CollectionHandler<TParams = any, TResult = any> = (params: TParams) => Promise<TResult> | TResult;
431
- type LLMProvider = 'anthropic' | 'groq';
830
+ type LLMProvider = 'anthropic' | 'groq' | 'gemini' | 'openai';
831
+
832
+ type DatabaseType = 'postgresql' | 'mssql' | 'snowflake' | 'mysql';
833
+ /**
834
+ * Model strategy for controlling which models are used for different tasks
835
+ * - 'best': Use the best model (e.g., Sonnet) for all tasks - highest quality, higher cost
836
+ * - 'fast': Use the fast model (e.g., Haiku) for all tasks - lower quality, lower cost
837
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
838
+ */
839
+ type ModelStrategy = 'best' | 'fast' | 'balanced';
840
+ /**
841
+ * Model configuration for DASH_COMP flow (dashboard component picking)
842
+ * Allows separate control of models used for component selection
843
+ */
844
+ interface DashCompModelConfig {
845
+ /**
846
+ * Primary model for DASH_COMP requests
847
+ * Format: "provider/model-name" (e.g., "anthropic/claude-sonnet-4-5-20250929")
848
+ */
849
+ model?: string;
850
+ /**
851
+ * Fast model for simpler DASH_COMP tasks (optional)
852
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
853
+ */
854
+ fastModel?: string;
855
+ }
432
856
  interface SuperatomSDKConfig {
433
857
  url?: string;
434
- apiKey: string;
858
+ apiKey?: string;
435
859
  projectId: string;
436
- userId?: string;
437
860
  type?: string;
438
861
  bundleDir?: string;
439
862
  promptsDir?: string;
863
+ databaseType?: DatabaseType;
440
864
  ANTHROPIC_API_KEY?: string;
441
865
  GROQ_API_KEY?: string;
866
+ GEMINI_API_KEY?: string;
867
+ OPENAI_API_KEY?: string;
442
868
  LLM_PROVIDERS?: LLMProvider[];
869
+ logLevel?: LogLevel;
870
+ /**
871
+ * Model selection strategy for LLM API calls:
872
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
873
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
874
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
875
+ */
876
+ modelStrategy?: ModelStrategy;
877
+ /**
878
+ * Model for the main agent (routing + analysis).
879
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
880
+ * If not set, uses the provider's default model.
881
+ */
882
+ mainAgentModel?: string;
883
+ /**
884
+ * Model for source agents (per-source query generation).
885
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
886
+ * If not set, uses the provider's default model.
887
+ */
888
+ sourceAgentModel?: string;
889
+ /**
890
+ * Separate model configuration for DASH_COMP flow (dashboard component picking)
891
+ * If not provided, falls back to provider-based model selection
892
+ */
893
+ dashCompModels?: DashCompModelConfig;
894
+ /**
895
+ * Similarity threshold for conversation search (semantic matching)
896
+ * Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
897
+ * Higher values require closer matches, lower values allow more distant matches
898
+ * Default: 0.8
899
+ */
900
+ conversationSimilarityThreshold?: number;
901
+ /**
902
+ * Query cache TTL (Time To Live) in minutes
903
+ * Cached query results expire after this duration
904
+ * Default: 5 minutes
905
+ */
906
+ queryCacheTTL?: number;
907
+ /**
908
+ * Dashboard conversation history TTL (Time To Live) in minutes
909
+ * Per-dashboard conversation histories expire after this duration
910
+ * Default: 30 minutes
911
+ */
912
+ dashboardHistoryTTL?: number;
443
913
  }
444
914
 
445
- interface User {
446
- username: string;
447
- password: string;
448
- wsIds: string[];
449
- }
450
- interface UsersData {
451
- users: User[];
915
+ declare const KbNodesQueryFiltersSchema: z.ZodObject<{
916
+ query: z.ZodOptional<z.ZodString>;
917
+ category: z.ZodOptional<z.ZodString>;
918
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
919
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
920
+ createdBy: z.ZodOptional<z.ZodString>;
921
+ }, "strip", z.ZodTypeAny, {
922
+ type?: "query" | "user" | "global" | undefined;
923
+ query?: string | undefined;
924
+ category?: string | undefined;
925
+ createdBy?: string | undefined;
926
+ tags?: string[] | undefined;
927
+ }, {
928
+ type?: "query" | "user" | "global" | undefined;
929
+ query?: string | undefined;
930
+ category?: string | undefined;
931
+ createdBy?: string | undefined;
932
+ tags?: string[] | undefined;
933
+ }>;
934
+ type KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
935
+ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
936
+ operation: z.ZodEnum<["create", "update", "delete", "getAll", "getOne", "search", "getByCategory", "getByUser", "getCategories", "getTags"]>;
937
+ data: z.ZodOptional<z.ZodObject<{
938
+ id: z.ZodOptional<z.ZodNumber>;
939
+ title: z.ZodOptional<z.ZodString>;
940
+ content: z.ZodOptional<z.ZodString>;
941
+ category: z.ZodOptional<z.ZodString>;
942
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
943
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
944
+ createdBy: z.ZodOptional<z.ZodString>;
945
+ updatedBy: z.ZodOptional<z.ZodString>;
946
+ userId: z.ZodOptional<z.ZodString>;
947
+ query: z.ZodOptional<z.ZodString>;
948
+ filters: z.ZodOptional<z.ZodObject<{
949
+ query: z.ZodOptional<z.ZodString>;
950
+ category: z.ZodOptional<z.ZodString>;
951
+ tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
952
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
953
+ createdBy: z.ZodOptional<z.ZodString>;
954
+ }, "strip", z.ZodTypeAny, {
955
+ type?: "query" | "user" | "global" | undefined;
956
+ query?: string | undefined;
957
+ category?: string | undefined;
958
+ createdBy?: string | undefined;
959
+ tags?: string[] | undefined;
960
+ }, {
961
+ type?: "query" | "user" | "global" | undefined;
962
+ query?: string | undefined;
963
+ category?: string | undefined;
964
+ createdBy?: string | undefined;
965
+ tags?: string[] | undefined;
966
+ }>>;
967
+ limit: z.ZodOptional<z.ZodNumber>;
968
+ offset: z.ZodOptional<z.ZodNumber>;
969
+ }, "strip", z.ZodTypeAny, {
970
+ id?: number | undefined;
971
+ type?: "query" | "user" | "global" | undefined;
972
+ query?: string | undefined;
973
+ title?: string | undefined;
974
+ category?: string | undefined;
975
+ userId?: string | undefined;
976
+ limit?: number | undefined;
977
+ filters?: {
978
+ type?: "query" | "user" | "global" | undefined;
979
+ query?: string | undefined;
980
+ category?: string | undefined;
981
+ createdBy?: string | undefined;
982
+ tags?: string[] | undefined;
983
+ } | undefined;
984
+ createdBy?: string | undefined;
985
+ updatedBy?: string | undefined;
986
+ offset?: number | undefined;
987
+ tags?: string[] | undefined;
988
+ content?: string | undefined;
989
+ }, {
990
+ id?: number | undefined;
991
+ type?: "query" | "user" | "global" | undefined;
992
+ query?: string | undefined;
993
+ title?: string | undefined;
994
+ category?: string | undefined;
995
+ userId?: string | undefined;
996
+ limit?: number | undefined;
997
+ filters?: {
998
+ type?: "query" | "user" | "global" | undefined;
999
+ query?: string | undefined;
1000
+ category?: string | undefined;
1001
+ createdBy?: string | undefined;
1002
+ tags?: string[] | undefined;
1003
+ } | undefined;
1004
+ createdBy?: string | undefined;
1005
+ updatedBy?: string | undefined;
1006
+ offset?: number | undefined;
1007
+ tags?: string[] | undefined;
1008
+ content?: string | undefined;
1009
+ }>>;
1010
+ }, "strip", z.ZodTypeAny, {
1011
+ operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
1012
+ data?: {
1013
+ id?: number | undefined;
1014
+ type?: "query" | "user" | "global" | undefined;
1015
+ query?: string | undefined;
1016
+ title?: string | undefined;
1017
+ category?: string | undefined;
1018
+ userId?: string | undefined;
1019
+ limit?: number | undefined;
1020
+ filters?: {
1021
+ type?: "query" | "user" | "global" | undefined;
1022
+ query?: string | undefined;
1023
+ category?: string | undefined;
1024
+ createdBy?: string | undefined;
1025
+ tags?: string[] | undefined;
1026
+ } | undefined;
1027
+ createdBy?: string | undefined;
1028
+ updatedBy?: string | undefined;
1029
+ offset?: number | undefined;
1030
+ tags?: string[] | undefined;
1031
+ content?: string | undefined;
1032
+ } | undefined;
1033
+ }, {
1034
+ operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
1035
+ data?: {
1036
+ id?: number | undefined;
1037
+ type?: "query" | "user" | "global" | undefined;
1038
+ query?: string | undefined;
1039
+ title?: string | undefined;
1040
+ category?: string | undefined;
1041
+ userId?: string | undefined;
1042
+ limit?: number | undefined;
1043
+ filters?: {
1044
+ type?: "query" | "user" | "global" | undefined;
1045
+ query?: string | undefined;
1046
+ category?: string | undefined;
1047
+ createdBy?: string | undefined;
1048
+ tags?: string[] | undefined;
1049
+ } | undefined;
1050
+ createdBy?: string | undefined;
1051
+ updatedBy?: string | undefined;
1052
+ offset?: number | undefined;
1053
+ tags?: string[] | undefined;
1054
+ content?: string | undefined;
1055
+ } | undefined;
1056
+ }>;
1057
+ type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
1058
+ interface T_RESPONSE {
1059
+ success: boolean;
1060
+ data?: any;
1061
+ errors: string[];
452
1062
  }
1063
+
453
1064
  /**
454
1065
  * UserManager class to handle CRUD operations on users with file persistence
455
1066
  * and in-memory caching. Changes are synced to file periodically.
@@ -503,6 +1114,18 @@ declare class UserManager {
503
1114
  * @returns The user if found, undefined otherwise
504
1115
  */
505
1116
  getUser(username: string): User | undefined;
1117
+ /**
1118
+ * Read a user by email
1119
+ * @param email - Email to retrieve
1120
+ * @returns The user if found, undefined otherwise
1121
+ */
1122
+ getUserByEmail(email: string): User | undefined;
1123
+ /**
1124
+ * Find user by username or email
1125
+ * @param identifier - Username or email to search for
1126
+ * @returns The user if found, undefined otherwise
1127
+ */
1128
+ getUserByUsernameOrEmail(identifier: string): User | undefined;
506
1129
  /**
507
1130
  * Read all users
508
1131
  * @returns Array of all users
@@ -697,115 +1320,703 @@ declare class ReportManager {
697
1320
  getReportCount(): number;
698
1321
  }
699
1322
 
700
- interface LLMMessages {
701
- sys: string;
702
- user: string;
703
- }
704
- interface LLMOptions {
705
- model?: string;
706
- maxTokens?: number;
707
- temperature?: number;
708
- topP?: number;
709
- apiKey?: string;
710
- partial?: (chunk: string) => void;
711
- }
712
- declare class LLM {
713
- static text(messages: LLMMessages, options?: LLMOptions): Promise<string>;
714
- static stream<T = string>(messages: LLMMessages, options?: LLMOptions, json?: boolean): Promise<T extends string ? string : any>;
715
- /**
716
- * Parse model string to extract provider and model name
717
- * @param modelString - Format: "provider/model-name" or just "model-name"
718
- * @returns [provider, modelName]
719
- *
720
- * @example
721
- * "anthropic/claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"]
722
- * "groq/openai/gpt-oss-120b" → ["groq", "openai/gpt-oss-120b"]
723
- * "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
724
- */
725
- private static _parseModel;
726
- private static _anthropicText;
727
- private static _anthropicStream;
728
- private static _groqText;
729
- private static _groqStream;
730
- /**
731
- * Parse JSON string, handling markdown code blocks and surrounding text
732
- * Enhanced version from anthropic.ts implementation
733
- * @param text - Text that may contain JSON wrapped in ```json...``` or with surrounding text
734
- * @returns Parsed JSON object
735
- */
736
- private static _parseJSON;
737
- }
738
-
739
- interface CapturedLog {
740
- timestamp: number;
741
- level: 'info' | 'error' | 'warn' | 'debug';
742
- message: string;
743
- type?: 'explanation' | 'query' | 'general';
744
- data?: Record<string, any>;
745
- }
746
1323
  /**
747
- * UILogCollector captures logs during user prompt processing
748
- * and sends them to runtime via ui_logs message with uiBlockId as the message id
749
- * Logs are sent in real-time for streaming effect in the UI
1324
+ * StreamBuffer - Buffered streaming utility for smoother text delivery
1325
+ * Batches small chunks together and flushes at regular intervals
750
1326
  */
751
- declare class UILogCollector {
752
- private logs;
753
- private uiBlockId;
754
- private clientId;
755
- private sendMessage;
756
- constructor(clientId: string, sendMessage: (message: Message) => void, uiBlockId?: string);
757
- /**
758
- * Check if logging is enabled (uiBlockId is provided)
759
- */
760
- isEnabled(): boolean;
761
- /**
762
- * Add a log entry with timestamp and immediately send to runtime
763
- */
764
- private addLog;
765
- /**
766
- * Send a single log to runtime immediately
767
- */
768
- private sendLogImmediately;
769
- /**
770
- * Log info message
771
- */
772
- info(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
773
- /**
774
- * Log error message
775
- */
776
- error(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
777
- /**
778
- * Log warning message
779
- */
780
- warn(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
1327
+ type StreamCallback = (chunk: string) => void;
1328
+ /**
1329
+ * StreamBuffer class for managing buffered streaming output
1330
+ * Provides smooth text delivery by batching small chunks
1331
+ */
1332
+ declare class StreamBuffer {
1333
+ private buffer;
1334
+ private flushTimer;
1335
+ private callback;
1336
+ private fullText;
1337
+ constructor(callback?: StreamCallback);
781
1338
  /**
782
- * Log debug message
1339
+ * Check if the buffer has a callback configured
783
1340
  */
784
- debug(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
1341
+ hasCallback(): boolean;
785
1342
  /**
786
- * Log LLM explanation with typed metadata
1343
+ * Get all text that has been written (including already flushed)
787
1344
  */
788
- logExplanation(message: string, explanation: string, data?: Record<string, any>): void;
1345
+ getFullText(): string;
789
1346
  /**
790
- * Log generated query with typed metadata
1347
+ * Write a chunk to the buffer
1348
+ * Large chunks or chunks with newlines are flushed immediately
1349
+ * Small chunks are batched and flushed after a short interval
1350
+ *
1351
+ * @param chunk - Text chunk to write
791
1352
  */
792
- logQuery(message: string, query: string, data?: Record<string, any>): void;
1353
+ write(chunk: string): void;
793
1354
  /**
794
- * Send all collected logs at once (optional, for final summary)
1355
+ * Flush the buffer immediately
1356
+ * Call this before tool execution or other operations that need clean output
795
1357
  */
796
- sendAllLogs(): void;
1358
+ flush(): void;
797
1359
  /**
798
- * Get all collected logs
1360
+ * Internal flush implementation
799
1361
  */
800
- getLogs(): CapturedLog[];
1362
+ private flushNow;
801
1363
  /**
802
- * Clear all logs
1364
+ * Clean up resources
1365
+ * Call this when done with the buffer
803
1366
  */
804
- clearLogs(): void;
805
- /**
806
- * Set uiBlockId (in case it's provided later)
1367
+ dispose(): void;
1368
+ }
1369
+
1370
+ /**
1371
+ * ToolExecutorService - Handles execution of SQL queries and external tools
1372
+ * Extracted from BaseLLM.generateTextResponse for better separation of concerns
1373
+ */
1374
+
1375
+ /**
1376
+ * External tool definition
1377
+ */
1378
+ interface ExternalTool {
1379
+ id: string;
1380
+ name: string;
1381
+ description?: string;
1382
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
1383
+ toolType?: 'source' | 'direct';
1384
+ /** Full untruncated schema for source agent (all columns visible) */
1385
+ fullSchema?: string;
1386
+ /** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
1387
+ schemaTier?: string;
1388
+ /** Schema search function for very_large tier — keyword search over entities */
1389
+ schemaSearchFn?: (keywords: string[]) => string;
1390
+ fn: (input: any) => Promise<any>;
1391
+ limit?: number;
1392
+ outputSchema?: any;
1393
+ executionType?: 'immediate' | 'deferred';
1394
+ userProvidedData?: any;
1395
+ params?: Record<string, any>;
1396
+ }
1397
+ /**
1398
+ * Executed tool tracking info
1399
+ */
1400
+ interface ExecutedToolInfo {
1401
+ id: string;
1402
+ name: string;
1403
+ params: any;
1404
+ result: {
1405
+ _totalRecords: number;
1406
+ _recordsShown: number;
1407
+ _metadata?: any;
1408
+ _sampleData: any[];
1409
+ };
1410
+ outputSchema?: any;
1411
+ sourceSchema?: string;
1412
+ sourceType?: string;
1413
+ }
1414
+
1415
+ /**
1416
+ * Multi-Agent Architecture Types
1417
+ *
1418
+ * Defines interfaces for the hierarchical agent system:
1419
+ * - Main Agent: ONE LLM.streamWithTools() call with source agent tools
1420
+ * - Source Agents: independent agents that query individual data sources
1421
+ *
1422
+ * The main agent sees only source summaries. When it calls a source tool,
1423
+ * the SourceAgent runs independently (own LLM, own retries) and returns clean data.
1424
+ */
1425
+
1426
+ /**
1427
+ * Per-entity detail: name, row count, and column names.
1428
+ * Gives the main agent enough context to route to the right source.
1429
+ */
1430
+ interface EntityDetail {
1431
+ /** Entity name (table, sheet, endpoint) */
1432
+ name: string;
1433
+ /** Approximate row count */
1434
+ rowCount?: number;
1435
+ /** Column/field names */
1436
+ columns: string[];
1437
+ }
1438
+ /**
1439
+ * Representation of a data source for the main agent.
1440
+ * Contains entity names WITH column names so the LLM can route accurately.
1441
+ */
1442
+ interface SourceSummary {
1443
+ /** Source ID (matches tool ID prefix) */
1444
+ id: string;
1445
+ /** Human-readable source name */
1446
+ name: string;
1447
+ /** Source type: postgres, excel, rest_api, etc. */
1448
+ type: string;
1449
+ /** Brief description of what data this source contains */
1450
+ description: string;
1451
+ /** Detailed entity info with column names for routing */
1452
+ entityDetails: EntityDetail[];
1453
+ /** The tool ID associated with this source */
1454
+ toolId: string;
1455
+ }
1456
+ /**
1457
+ * What a source agent returns after querying its data source.
1458
+ * The main agent uses this to analyze and compose the final response.
1459
+ */
1460
+ interface SourceAgentResult {
1461
+ /** Source ID */
1462
+ sourceId: string;
1463
+ /** Source name */
1464
+ sourceName: string;
1465
+ /** Whether the query succeeded */
1466
+ success: boolean;
1467
+ /** Result data rows */
1468
+ data: any[];
1469
+ /** Metadata about the query execution */
1470
+ metadata: SourceAgentMetadata;
1471
+ /** Tool execution info for the last successful query (backward compat) */
1472
+ executedTool: ExecutedToolInfo;
1473
+ /** All successful tool executions (primary + follow-up queries) */
1474
+ allExecutedTools?: ExecutedToolInfo[];
1475
+ /** Error message if failed */
1476
+ error?: string;
1477
+ }
1478
+ interface SourceAgentMetadata {
1479
+ /** Total rows that matched the query (before limit) */
1480
+ totalRowsMatched: number;
1481
+ /** Rows actually returned (after limit) */
1482
+ rowsReturned: number;
1483
+ /** Whether the result was truncated by the row limit */
1484
+ isLimited: boolean;
1485
+ /** The query/params that were executed */
1486
+ queryExecuted?: string;
1487
+ /** Execution time in milliseconds */
1488
+ executionTimeMs: number;
1489
+ }
1490
+ /**
1491
+ * A pre-built, multi-step UI flow registered with the SDK.
1492
+ *
1493
+ * When the main agent decides a user's question matches a workflow's whenToUse
1494
+ * trigger, it picks the workflow instead of running source agents / generating
1495
+ * dashboard components. The LLM extracts the workflow's required props from the
1496
+ * prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
1497
+ * workflow component directly — no analysis text, no chart generation. The
1498
+ * frontend renders the registered workflow component with the LLM-extracted
1499
+ * props.
1500
+ */
1501
+ interface WorkflowDescriptor {
1502
+ /** Unique workflow id (used as the LLM tool name) */
1503
+ id: string;
1504
+ /** Component name on the frontend (matches the registered React component) */
1505
+ name: string;
1506
+ /** Short human-readable description of what this workflow does */
1507
+ description: string;
1508
+ /**
1509
+ * 1–2 sentence trigger condition. The LLM uses this to decide if the
1510
+ * user's prompt matches this workflow. Be specific — e.g.
1511
+ * "User wants to *initiate* an inventory transfer (review + submit POs),
1512
+ * not just see analysis or charts."
807
1513
  */
808
- setUIBlockId(uiBlockId: string): void;
1514
+ whenToUse: string;
1515
+ /**
1516
+ * JSON-schema-style description of the props the workflow needs. Becomes
1517
+ * the LLM tool's input_schema, so the model fills these from the prompt.
1518
+ * Use the same shape as `params` on direct tools — string descriptors with
1519
+ * an optional "(optional)" suffix.
1520
+ *
1521
+ * Example:
1522
+ * ```
1523
+ * {
1524
+ * selectedStore: 'object — { id, name } of the source branch',
1525
+ * minROI: 'number (optional) — only show transfers with ROI ≥ this',
1526
+ * }
1527
+ * ```
1528
+ */
1529
+ propsSchema: Record<string, string>;
1530
+ /**
1531
+ * Optional: static prop defaults merged with LLM-extracted props before
1532
+ * the component is returned. Useful for things like the embedded
1533
+ * `externalTool` config that the workflow uses to fetch its own data.
1534
+ */
1535
+ defaultProps?: Record<string, any>;
1536
+ }
1537
+ /**
1538
+ * The workflow selection captured during a routing call.
1539
+ * Set on AgentResponse when the LLM picks a workflow tool.
1540
+ */
1541
+ interface SelectedWorkflow {
1542
+ /** Component name (matches WorkflowDescriptor.name) */
1543
+ name: string;
1544
+ /** Props extracted from the prompt + merged with workflow.defaultProps */
1545
+ props: Record<string, any>;
1546
+ }
1547
+ /**
1548
+ * The complete response from the multi-agent system.
1549
+ * Contains everything needed for text display + component generation.
1550
+ */
1551
+ interface AgentResponse {
1552
+ /** Generated text response (analysis of the data) */
1553
+ text: string;
1554
+ /** All executed tools across all source agents (for component generation) */
1555
+ executedTools: ExecutedToolInfo[];
1556
+ /** Individual results from each source agent */
1557
+ sourceResults: SourceAgentResult[];
1558
+ /**
1559
+ * Populated when MainAgent wrote AND successfully executed a script during its turn.
1560
+ * Caller (agent-user-response.ts) persists it via ScriptStore.save().
1561
+ * Absent when MainAgent didn't write one (trivial question / all attempts failed).
1562
+ */
1563
+ savedScript?: AgentWrittenScript;
1564
+ /**
1565
+ * Set when the LLM routed the question to a registered workflow component.
1566
+ * When present, the upstream caller should skip component generation and
1567
+ * return this workflow as the response.
1568
+ */
1569
+ workflow?: SelectedWorkflow;
1570
+ }
1571
+ /**
1572
+ * A script MainAgent authored + verified during its turn. Shape aligns with
1573
+ * what ScriptStore.save() needs — minus store-assigned fields (id, timestamps, counts).
1574
+ */
1575
+ interface AgentWrittenScript {
1576
+ /**
1577
+ * `ScriptRecipe.id` of the draft that was authored + verified during this turn.
1578
+ * The caller passes this to `ScriptStore.promoteToVerified(recipeId, …)` to
1579
+ * flip the draft to verified status and (when possible) drop the turn-suffix
1580
+ * from its filename.
1581
+ */
1582
+ recipeId: string;
1583
+ name: string;
1584
+ intentDescription: string;
1585
+ tags: string[];
1586
+ parameters: Array<{
1587
+ name: string;
1588
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
1589
+ required: boolean;
1590
+ default?: any;
1591
+ enumValues?: Record<string, string>;
1592
+ description: string;
1593
+ }>;
1594
+ scriptBody: string;
1595
+ /** Source IDs referenced by the script (extracted from ctx.query calls) */
1596
+ sourceIds: string[];
1597
+ /** Tables referenced in the script's SQL (regex-extracted) */
1598
+ tables: string[];
1599
+ /** Executed queries from the verified run — fed to component generation */
1600
+ executedQueries: Array<{
1601
+ sourceId: string;
1602
+ sourceName: string;
1603
+ sql: string;
1604
+ data: any[];
1605
+ count: number;
1606
+ totalCount?: number;
1607
+ executionTimeMs: number;
1608
+ /**
1609
+ * True for synthetic entries (ctx.emit datasets, the computed:_final
1610
+ * post-JS data). The component generator routes virtual sources through
1611
+ * the script_dataset sentinel toolId so the frontend resolves them via
1612
+ * queryCache instead of attempting to re-execute SQL.
1613
+ */
1614
+ virtual?: boolean;
1615
+ }>;
1616
+ }
1617
+ /**
1618
+ * Configuration for the multi-agent system.
1619
+ * Controls limits, models, and behavior.
1620
+ */
1621
+ interface AgentConfig {
1622
+ /** Max rows a source agent can return (default: 50) */
1623
+ maxRowsPerSource: number;
1624
+ /** Model for the main agent (routing + analysis in one LLM call) */
1625
+ mainAgentModel: string;
1626
+ /** Model for source agent query generation */
1627
+ sourceAgentModel: string;
1628
+ /** API key for LLM calls */
1629
+ apiKey?: string;
1630
+ /** Max retry attempts per source agent */
1631
+ maxRetries: number;
1632
+ /** Max tool calling iterations for the main agent loop */
1633
+ maxIterations: number;
1634
+ /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
1635
+ globalKnowledgeBase?: string;
1636
+ /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
1637
+ knowledgeBaseContext?: string;
1638
+ /** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
1639
+ collections?: any;
1640
+ /** Optional project ID for scoping embedding searches */
1641
+ projectId?: string;
1642
+ }
1643
+ /**
1644
+ * Default agent configuration
1645
+ */
1646
+ declare const DEFAULT_AGENT_CONFIG: AgentConfig;
1647
+
1648
+ /**
1649
+ * Script Flow Types
1650
+ *
1651
+ * Defines interfaces for the script-based query architecture:
1652
+ * - ScriptRecipe: metadata for matching, validation, and quality tracking
1653
+ * - ScriptResult: output from executing a script
1654
+ * - ScriptMatch: result from the LLM-based script matcher
1655
+ */
1656
+ /**
1657
+ * Recipe metadata stored alongside each script.
1658
+ * Used for matching, validation, and quality tracking.
1659
+ */
1660
+ interface ScriptRecipe {
1661
+ /** Unique script identifier */
1662
+ id: string;
1663
+ /** Version number (incremented on regeneration) */
1664
+ version: number;
1665
+ /** Human-readable name (e.g., "Revenue by Dimension") */
1666
+ name: string;
1667
+ /** Natural language description of what this script does */
1668
+ intentDescription: string;
1669
+ /** Keyword tags for quick filtering */
1670
+ tags: string[];
1671
+ /** Source tool IDs this script queries (e.g., ["mssql-abc123_query"]) */
1672
+ sourceIds: string[];
1673
+ /** Table names used (for future schema drift detection) */
1674
+ tables: string[];
1675
+ /** Parameter definitions — what can vary */
1676
+ parameters: ScriptParameter[];
1677
+ /** The script function body as a string */
1678
+ scriptBody: string;
1679
+ /** Times this script was used successfully */
1680
+ successCount: number;
1681
+ /** Times this script failed */
1682
+ failureCount: number;
1683
+ /** ISO timestamp of last usage */
1684
+ lastUsed: string;
1685
+ /** Original user question that created this script */
1686
+ createdFrom: string;
1687
+ /** ISO timestamp */
1688
+ createdAt: string;
1689
+ /** ISO timestamp */
1690
+ updatedAt: string;
1691
+ /**
1692
+ * `recipe.id` of the parent this script was forked from.
1693
+ * Undefined for root scripts (those written from scratch by MainAgent).
1694
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md.
1695
+ */
1696
+ parentId?: string;
1697
+ /** 0 for root scripts; `parent.forkDepth + 1` for forks. Capped at 3. */
1698
+ forkDepth?: number;
1699
+ /**
1700
+ * Brief description of what this fork changed vs its parent
1701
+ * (sourced from the matcher's `modificationHint`).
1702
+ */
1703
+ forkReason?: string;
1704
+ /**
1705
+ * Lifecycle stage of this recipe on disk.
1706
+ * - 'draft': written by MainAgent's write_script during a turn; filtered out
1707
+ * of `ScriptStore.getAll()` so the matcher never picks it.
1708
+ * Filename is suffixed with `turnId` to keep concurrent turns
1709
+ * from clobbering each other's drafts.
1710
+ * - 'verified': promoted after `execute_script` succeeded; the matcher sees it.
1711
+ * Filename drops the turn suffix unless a verified file with
1712
+ * the same slug already exists (collision case keeps the suffix).
1713
+ *
1714
+ * Recipes loaded from disk without this field default to 'verified' so
1715
+ * existing scripts keep working unchanged.
1716
+ */
1717
+ status?: 'draft' | 'verified';
1718
+ /**
1719
+ * Per-turn unique suffix used for draft filenames (e.g. `1714745623-x9k2`).
1720
+ * Set when the draft is saved; carried until the recipe is promoted.
1721
+ */
1722
+ turnId?: string;
1723
+ /**
1724
+ * Last execution error captured by `recordDraftError` while the recipe was
1725
+ * still a draft. Lets users open the draft .json file and see why it failed
1726
+ * without grepping logs. Cleared on promotion to 'verified'.
1727
+ */
1728
+ lastError?: {
1729
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
1730
+ message: string;
1731
+ at: string;
1732
+ attempt: number;
1733
+ };
1734
+ }
1735
+ interface ScriptParameter {
1736
+ /** Parameter name (used in script body as params.name) */
1737
+ name: string;
1738
+ /** Parameter type */
1739
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
1740
+ /** Whether this parameter is required */
1741
+ required: boolean;
1742
+ /** Default value if not provided */
1743
+ default?: any;
1744
+ /** For enum type — maps user-facing values to internal values */
1745
+ enumValues?: Record<string, string>;
1746
+ /** Human-readable description (used in the matcher LLM prompt) */
1747
+ description: string;
1748
+ }
1749
+
1750
+ /**
1751
+ * ScriptStore — Persistent Storage for Script Recipes
1752
+ *
1753
+ * Layout:
1754
+ * scripts-store/
1755
+ * metadata/<name>.json ← recipe metadata (params, tables, counts, ...)
1756
+ * <name>.ts ← the getData() function body, editable in your IDE
1757
+ *
1758
+ * Each VM deployment is a single project, so no project ID prefix needed.
1759
+ * Legacy single-file format (JSON with embedded scriptBody) is still loadable
1760
+ * for backwards compatibility and auto-migrated to the split format on next save.
1761
+ */
1762
+
1763
+ /**
1764
+ * Input for `ScriptStore.saveDraft()`. Identifies the draft by `recipeId` so
1765
+ * retries within the same turn overwrite the same files (or omit `recipeId`
1766
+ * on the first call to mint a fresh draft).
1767
+ */
1768
+ interface SaveDraftInput {
1769
+ /** Reuse an existing draft (retry); omit to mint a new one. */
1770
+ recipeId?: string;
1771
+ /** Per-turn unique suffix, stable across retries within the turn. */
1772
+ turnId: string;
1773
+ name: string;
1774
+ intentDescription: string;
1775
+ tags: string[];
1776
+ parameters: ScriptParameter[];
1777
+ scriptBody: string;
1778
+ createdFrom: string;
1779
+ }
1780
+ /**
1781
+ * Lineage + provenance fields applied when a draft is promoted to verified.
1782
+ * MainAgent gathers `sourceIds` and `tables` from the verified execution; the
1783
+ * caller (agent-user-response.ts) supplies the optional fork lineage.
1784
+ */
1785
+ interface PromoteToVerifiedInput {
1786
+ sourceIds: string[];
1787
+ tables: string[];
1788
+ parentId?: string;
1789
+ forkDepth?: number;
1790
+ forkReason?: string;
1791
+ }
1792
+ declare class ScriptStore {
1793
+ private recipes;
1794
+ private storeDir;
1795
+ private loaded;
1796
+ constructor(baseDir?: string);
1797
+ private metadataDir;
1798
+ /**
1799
+ * Filename base for a recipe. Drafts include the per-turn suffix so two
1800
+ * concurrent turns can never clobber each other's draft files; verified
1801
+ * recipes use the bare slug.
1802
+ */
1803
+ private fileBaseName;
1804
+ /**
1805
+ * Absolute path to the .ts file for a recipe. Callers (e.g. ScriptRunner,
1806
+ * MainAgent's execute_script) use this to hand off the path to the tsx child.
1807
+ */
1808
+ getScriptPath(recipe: ScriptRecipe): string;
1809
+ /**
1810
+ * Absolute path to the metadata JSON for a recipe.
1811
+ */
1812
+ private getMetadataPath;
1813
+ /**
1814
+ * Get all VERIFIED recipes — drafts are filtered out so the matcher never
1815
+ * considers an unverified script. Loads from disk on first access.
1816
+ */
1817
+ getAll(): ScriptRecipe[];
1818
+ /**
1819
+ * Get a recipe by ID — returns drafts as well as verified scripts.
1820
+ * Used by MainAgent and the promotion path.
1821
+ */
1822
+ get(id: string): ScriptRecipe | null;
1823
+ /**
1824
+ * Number of verified recipes (matches `getAll().length`).
1825
+ */
1826
+ count(): number;
1827
+ /**
1828
+ * Save a recipe (create or update).
1829
+ * File is named after the script: "order-status-distribution.json"
1830
+ */
1831
+ save(recipe: ScriptRecipe): void;
1832
+ /**
1833
+ * Persist (or update) a draft recipe to disk. Always writes immediately so
1834
+ * the `.ts` body is visible in the IDE the moment MainAgent calls
1835
+ * `write_script`. Within one turn, retries that pass the same `recipeId`
1836
+ * overwrite the same files (the LLM rewriting itself); a fresh `recipeId`
1837
+ * is minted only on the first call of the turn.
1838
+ *
1839
+ * Filename includes the `turnId` suffix so concurrent turns never collide.
1840
+ */
1841
+ saveDraft(input: SaveDraftInput): ScriptRecipe;
1842
+ /**
1843
+ * Stamp the draft with the most recent execution failure so it is visible
1844
+ * in the metadata JSON without grepping logs. No-op if the recipe doesn't
1845
+ * exist or has already been promoted.
1846
+ */
1847
+ recordDraftError(recipeId: string, err: {
1848
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
1849
+ message: string;
1850
+ attempt: number;
1851
+ }): void;
1852
+ /**
1853
+ * Promote a successfully-executed draft into a verified script.
1854
+ *
1855
+ * - Renames the on-disk files from `<slug>-<turnId>.{ts,json}` to the bare
1856
+ * `<slug>.{ts,json}`. If a verified file with the same slug already exists
1857
+ * (concurrent turn won the race, or a prior session has it), the recipe
1858
+ * keeps its turn-suffixed filename so we never overwrite verified work —
1859
+ * the matcher keys on `recipe.id`, so two siblings with similar slugs is fine.
1860
+ * - Flips `status: 'verified'`, clears `lastError`, applies provenance
1861
+ * (`sourceIds`, `tables`) and optional fork lineage.
1862
+ */
1863
+ promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): ScriptRecipe | null;
1864
+ /**
1865
+ * Drop a draft from disk + memory (e.g. when an outer error path wants to
1866
+ * clean up). Per the agreed policy, MainAgent's normal failure path does
1867
+ * NOT call this — failed drafts are kept on disk for the user to inspect.
1868
+ */
1869
+ discardDraft(recipeId: string): void;
1870
+ /**
1871
+ * Delete a recipe by ID.
1872
+ */
1873
+ delete(id: string): void;
1874
+ /**
1875
+ * Record a successful execution for a recipe.
1876
+ */
1877
+ recordSuccess(id: string): void;
1878
+ /**
1879
+ * Record a failed execution for a recipe.
1880
+ */
1881
+ recordFailure(id: string): void;
1882
+ /**
1883
+ * Get the failure rate for a recipe (0 to 1).
1884
+ * Returns 0 if the recipe has fewer than 5 total uses.
1885
+ */
1886
+ getFailureRate(id: string): number;
1887
+ private ensureLoaded;
1888
+ /**
1889
+ * Convert a script name to a safe filename.
1890
+ * "Order Status Distribution" → "order-status-distribution"
1891
+ */
1892
+ private toFileName;
1893
+ /**
1894
+ * Load all script files from disk.
1895
+ *
1896
+ * Supports two layouts:
1897
+ * - New (preferred): metadata/<name>.json + <name>.ts
1898
+ * - Legacy: <name>.json with embedded scriptBody (auto-migrated on next save)
1899
+ */
1900
+ private loadAllFromDisk;
1901
+ /**
1902
+ * Save a recipe to disk in split format:
1903
+ * metadata/<name>.json (metadata, no scriptBody)
1904
+ * <name>.ts (just the function body)
1905
+ *
1906
+ * If a legacy top-level <name>.json exists for the same recipe, remove it
1907
+ * so we don't end up with duplicate sources of truth.
1908
+ */
1909
+ private saveRecipeToDisk;
1910
+ /**
1911
+ * Delete a recipe's files from disk (both metadata + body, plus any legacy file).
1912
+ */
1913
+ private deleteRecipeFromDisk;
1914
+ }
1915
+
1916
+ /**
1917
+ * Main Agent (Orchestrator)
1918
+ *
1919
+ * A single LLM.streamWithTools() call that handles everything:
1920
+ * - Routing: decides which source(s) to query based on summaries
1921
+ * - Querying: calls source tools (each wraps an independent SourceAgent)
1922
+ * - Direct tools: calls pre-built function tools directly with LLM-provided params
1923
+ * - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
1924
+ * - Analysis: generates final text response from the data
1925
+ *
1926
+ * Two tool types:
1927
+ * - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
1928
+ * - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
1929
+ */
1930
+
1931
+ declare class MainAgent {
1932
+ private externalTools;
1933
+ private workflows;
1934
+ private config;
1935
+ private streamBuffer;
1936
+ /**
1937
+ * Optional: when provided, MainAgent exposes the `write_script` /
1938
+ * `execute_script` tools to the LLM and persists drafts to disk via the
1939
+ * store. Headless callers (alert analyzer, metric resolver) omit these to
1940
+ * suppress script authoring entirely — drafts would otherwise leak onto
1941
+ * disk with no caller to promote or clean them up.
1942
+ */
1943
+ private scriptStore;
1944
+ private turnId;
1945
+ private createdFromPrompt;
1946
+ private scriptState;
1947
+ constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[]);
1948
+ private get scriptingEnabled();
1949
+ /**
1950
+ * Handle a user question using the multi-agent system.
1951
+ *
1952
+ * This is ONE LLM.streamWithTools() call. The LLM:
1953
+ * 1. Sees source summaries + direct tool descriptions in system prompt
1954
+ * 2. Decides which tool(s) to call (routing)
1955
+ * 3. Source tools → SourceAgent runs independently → returns data
1956
+ * 4. Direct tools → fn() called directly with LLM params → returns data
1957
+ * 5. Generates final analysis text
1958
+ */
1959
+ handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void): Promise<AgentResponse>;
1960
+ private handleWriteScript;
1961
+ private handleExecuteScript;
1962
+ /**
1963
+ * Build the AgentWrittenScript payload the caller will hand to
1964
+ * `ScriptStore.promoteToVerified()`. Only returned when a verified
1965
+ * successful execution is on record.
1966
+ */
1967
+ private buildSavedScript;
1968
+ private normalizeParameterList;
1969
+ /**
1970
+ * Use the schema embedding collection to pre-select relevant tables for
1971
+ * this source + intent. Returns a formatted schema block if confidence is
1972
+ * high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
1973
+ *
1974
+ * When this returns a block, we can skip the SourceAgent's `search_schema`
1975
+ * loop and reduce iteration budget. When it returns null, the SourceAgent
1976
+ * falls back to the existing LLM-driven keyword search (same as today).
1977
+ */
1978
+ private preResolveSchema;
1979
+ /**
1980
+ * Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
1981
+ */
1982
+ private handleDirectTool;
1983
+ /**
1984
+ * Build the main agent's system prompt with source summaries, direct tool descriptions,
1985
+ * and workflow component descriptions.
1986
+ */
1987
+ private buildSystemPrompt;
1988
+ /**
1989
+ * Build tool definitions for source tools — summary-only descriptions.
1990
+ * The full schema is inside the SourceAgent which runs independently.
1991
+ */
1992
+ private buildSourceToolDefinitions;
1993
+ /**
1994
+ * Build tool definitions for direct tools — expose their actual params.
1995
+ * These are called directly by the main agent LLM, no SourceAgent.
1996
+ */
1997
+ private buildDirectToolDefinitions;
1998
+ /**
1999
+ * Capture a workflow selection. We do NOT execute anything — the LLM has
2000
+ * already extracted the props it wants the workflow rendered with. We
2001
+ * record the selection (via the capture callback) and return a short
2002
+ * acknowledgement so the LLM ends its turn cleanly without writing
2003
+ * analysis text or calling more tools.
2004
+ */
2005
+ private handleWorkflow;
2006
+ /**
2007
+ * Build LLM tool definitions for workflow components. The workflow's
2008
+ * propsSchema becomes the tool's input_schema so the LLM extracts props
2009
+ * directly from the prompt — same mechanic as direct tools.
2010
+ */
2011
+ private buildWorkflowToolDefinitions;
2012
+ /**
2013
+ * Format a source agent's result as a clean string for the main agent LLM.
2014
+ */
2015
+ private formatResultForMainAgent;
2016
+ /**
2017
+ * Get source summaries (for external inspection/debugging).
2018
+ */
2019
+ getSourceSummaries(): SourceSummary[];
809
2020
  }
810
2021
 
811
2022
  /**
@@ -818,15 +2029,170 @@ interface Action {
818
2029
  [key: string]: any;
819
2030
  }
820
2031
 
2032
+ type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
2033
+ interface LLMMessages {
2034
+ sys: SystemPrompt;
2035
+ user: string;
2036
+ prefill?: string;
2037
+ }
2038
+ interface LLMOptions {
2039
+ model?: string;
2040
+ maxTokens?: number;
2041
+ temperature?: number;
2042
+ topP?: number;
2043
+ apiKey?: string;
2044
+ partial?: (chunk: string) => void;
2045
+ }
2046
+ interface Tool {
2047
+ name: string;
2048
+ description: string;
2049
+ input_schema: {
2050
+ type: string;
2051
+ properties: Record<string, any>;
2052
+ required?: string[];
2053
+ };
2054
+ }
2055
+ declare class LLM {
2056
+ static text(messages: LLMMessages, options?: LLMOptions): Promise<string>;
2057
+ static stream<T = string>(messages: LLMMessages, options?: LLMOptions, json?: boolean): Promise<T extends string ? string : any>;
2058
+ static streamWithTools(messages: LLMMessages, tools: Tool[], toolHandler: (toolName: string, toolInput: any) => Promise<any>, options?: LLMOptions, maxIterations?: number): Promise<string>;
2059
+ /**
2060
+ * Normalize system prompt to Anthropic format
2061
+ * Converts string to array format if needed
2062
+ * @param sys - System prompt (string or array of blocks)
2063
+ * @returns Normalized system prompt for Anthropic API
2064
+ */
2065
+ private static _normalizeSystemPrompt;
2066
+ /**
2067
+ * Log cache usage metrics from Anthropic API response
2068
+ * Shows cache hits, costs, and savings
2069
+ */
2070
+ private static _logCacheUsage;
2071
+ /**
2072
+ * Parse model string to extract provider and model name
2073
+ * @param modelString - Format: "provider/model-name" or just "model-name"
2074
+ * @returns [provider, modelName]
2075
+ *
2076
+ * @example
2077
+ * "anthropic/claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"]
2078
+ * "groq/openai/gpt-oss-120b" → ["groq", "openai/gpt-oss-120b"]
2079
+ * "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
2080
+ */
2081
+ private static _parseModel;
2082
+ private static _anthropicText;
2083
+ private static _anthropicStream;
2084
+ private static _anthropicStreamWithTools;
2085
+ private static _groqText;
2086
+ private static _groqStream;
2087
+ private static _geminiText;
2088
+ private static _geminiStream;
2089
+ /**
2090
+ * Recursively strip unsupported JSON Schema properties for Gemini
2091
+ * Gemini doesn't support: additionalProperties, $schema, etc.
2092
+ */
2093
+ private static _cleanSchemaForGemini;
2094
+ private static _geminiStreamWithTools;
2095
+ private static _openaiText;
2096
+ private static _openaiStream;
2097
+ private static _openaiStreamWithTools;
2098
+ /**
2099
+ * Parse JSON string, handling markdown code blocks and surrounding text
2100
+ * Enhanced version with jsonrepair to handle malformed JSON from LLMs
2101
+ * @param text - Text that may contain JSON wrapped in ```json...``` or with surrounding text
2102
+ * @returns Parsed JSON object or array
2103
+ */
2104
+ private static _parseJSON;
2105
+ }
2106
+
2107
+ interface CapturedLog {
2108
+ timestamp: number;
2109
+ level: 'info' | 'error' | 'warn' | 'debug';
2110
+ message: string;
2111
+ type?: 'explanation' | 'query' | 'general';
2112
+ data?: Record<string, any>;
2113
+ }
2114
+ /**
2115
+ * UILogCollector captures logs during user prompt processing
2116
+ * and sends them to runtime via ui_logs message with uiBlockId as the message id
2117
+ * Logs are sent in real-time for streaming effect in the UI
2118
+ * Respects the global log level configuration
2119
+ */
2120
+ declare class UILogCollector {
2121
+ private logs;
2122
+ private uiBlockId;
2123
+ private clientId;
2124
+ private sendMessage;
2125
+ private currentLogLevel;
2126
+ constructor(clientId: string, sendMessage: (message: Message) => void, uiBlockId?: string);
2127
+ /**
2128
+ * Check if logging is enabled (uiBlockId is provided)
2129
+ */
2130
+ isEnabled(): boolean;
2131
+ /**
2132
+ * Check if a message should be logged based on current log level
2133
+ */
2134
+ private shouldLog;
2135
+ /**
2136
+ * Add a log entry with timestamp and immediately send to runtime
2137
+ * Only logs that pass the log level filter are captured and sent
2138
+ */
2139
+ private addLog;
2140
+ /**
2141
+ * Send a single log to runtime immediately
2142
+ */
2143
+ private sendLogImmediately;
2144
+ /**
2145
+ * Log info message
2146
+ */
2147
+ info(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
2148
+ /**
2149
+ * Log error message
2150
+ */
2151
+ error(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
2152
+ /**
2153
+ * Log warning message
2154
+ */
2155
+ warn(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
2156
+ /**
2157
+ * Log debug message
2158
+ */
2159
+ debug(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
2160
+ /**
2161
+ * Log LLM explanation with typed metadata
2162
+ */
2163
+ logExplanation(message: string, explanation: string, data?: Record<string, any>): void;
2164
+ /**
2165
+ * Log generated query with typed metadata
2166
+ */
2167
+ logQuery(message: string, query: string, data?: Record<string, any>): void;
2168
+ /**
2169
+ * Send all collected logs at once (optional, for final summary)
2170
+ */
2171
+ sendAllLogs(): void;
2172
+ /**
2173
+ * Get all collected logs
2174
+ */
2175
+ getLogs(): CapturedLog[];
2176
+ /**
2177
+ * Clear all logs
2178
+ */
2179
+ clearLogs(): void;
2180
+ /**
2181
+ * Set uiBlockId (in case it's provided later)
2182
+ */
2183
+ setUIBlockId(uiBlockId: string): void;
2184
+ }
2185
+
821
2186
  /**
822
2187
  * UIBlock represents a single user and assistant message block in a thread
823
- * Contains user question, component metadata, component data, and available actions
2188
+ * Contains user question, component metadata, component data, text response, and available actions
824
2189
  */
825
2190
  declare class UIBlock {
826
2191
  private id;
827
2192
  private userQuestion;
828
2193
  private generatedComponentMetadata;
829
2194
  private componentData;
2195
+ private textResponse;
830
2196
  private actions;
831
2197
  private createdAt;
832
2198
  /**
@@ -836,8 +2202,9 @@ declare class UIBlock {
836
2202
  * @param generatedComponentMetadata - Optional metadata about the generated component
837
2203
  * @param actions - Optional array of available actions
838
2204
  * @param id - Optional custom ID, generates UUID if not provided
2205
+ * @param textResponse - Optional text response from LLM
839
2206
  */
840
- constructor(userQuestion: string, componentData?: Record<string, any>, generatedComponentMetadata?: Record<string, any>, actions?: Action[], id?: string);
2207
+ constructor(userQuestion: string, componentData?: Record<string, any>, generatedComponentMetadata?: Record<string, any>, actions?: Action[], id?: string, textResponse?: string | null);
841
2208
  /**
842
2209
  * Get the UIBlock ID
843
2210
  */
@@ -854,6 +2221,7 @@ declare class UIBlock {
854
2221
  * Get component metadata
855
2222
  */
856
2223
  getComponentMetadata(): Record<string, any>;
2224
+ getTextResponse(): string;
857
2225
  /**
858
2226
  * Set or update component metadata
859
2227
  */
@@ -882,6 +2250,10 @@ declare class UIBlock {
882
2250
  * Set or update component data with size and row limits
883
2251
  */
884
2252
  setComponentData(data: Record<string, any>): void;
2253
+ /**
2254
+ * Set or update text response
2255
+ */
2256
+ setTextResponse(textResponse: string | null): void;
885
2257
  /**
886
2258
  * Get all actions (only if they are resolved, not if fetching)
887
2259
  */
@@ -894,6 +2266,10 @@ declare class UIBlock {
894
2266
  * @returns Promise resolving to Action[]
895
2267
  */
896
2268
  getOrFetchActions(generateFn: () => Promise<Action[]>): Promise<Action[]>;
2269
+ /**
2270
+ * Set or replace all actions
2271
+ */
2272
+ setActions(actions: Action[]): void;
897
2273
  /**
898
2274
  * Add a single action (only if actions are resolved)
899
2275
  */
@@ -989,12 +2365,20 @@ declare class Thread {
989
2365
 
990
2366
  /**
991
2367
  * ThreadManager manages all threads globally
992
- * Provides methods to create, retrieve, and delete threads
2368
+ * Provides methods to create, retrieve, and delete threads.
2369
+ * Includes automatic cleanup to prevent unbounded memory growth.
993
2370
  */
994
2371
  declare class ThreadManager {
995
2372
  private static instance;
996
2373
  private threads;
2374
+ private cleanupInterval;
2375
+ private readonly threadTtlMs;
997
2376
  private constructor();
2377
+ /**
2378
+ * Periodically remove threads older than 7 days.
2379
+ * Runs every hour to avoid frequent iteration over the map.
2380
+ */
2381
+ private startCleanup;
998
2382
  /**
999
2383
  * Get singleton instance of ThreadManager
1000
2384
  */
@@ -1124,15 +2508,17 @@ declare const STORAGE_CONFIG: {
1124
2508
  */
1125
2509
  MAX_ROWS_PER_BLOCK: number;
1126
2510
  /**
1127
- * Maximum size in bytes per UIBlock (1MB)
2511
+ * Maximum size in bytes per UIBlock (500KB - reduced to save memory)
1128
2512
  */
1129
2513
  MAX_SIZE_PER_BLOCK_BYTES: number;
1130
2514
  /**
1131
2515
  * Number of days to keep threads before cleanup
2516
+ * Note: This is for in-memory storage. Conversations are also persisted to database.
1132
2517
  */
1133
2518
  THREAD_RETENTION_DAYS: number;
1134
2519
  /**
1135
2520
  * Number of days to keep UIBlocks before cleanup
2521
+ * Note: This is for in-memory storage. Data is also persisted to database.
1136
2522
  */
1137
2523
  UIBLOCK_RETENTION_DAYS: number;
1138
2524
  };
@@ -1149,14 +2535,701 @@ declare const CONTEXT_CONFIG: {
1149
2535
  MAX_CONVERSATION_CONTEXT_BLOCKS: number;
1150
2536
  };
1151
2537
 
1152
- declare const SDK_VERSION = "0.0.8";
2538
+ /**
2539
+ * LLM Usage Logger - Tracks token usage, costs, and timing for all LLM API calls
2540
+ */
2541
+ interface LLMUsageEntry {
2542
+ timestamp: string;
2543
+ requestId: string;
2544
+ provider: string;
2545
+ model: string;
2546
+ method: string;
2547
+ inputTokens: number;
2548
+ outputTokens: number;
2549
+ cacheReadTokens?: number;
2550
+ cacheWriteTokens?: number;
2551
+ totalTokens: number;
2552
+ costUSD: number;
2553
+ durationMs: number;
2554
+ toolCalls?: number;
2555
+ success: boolean;
2556
+ error?: string;
2557
+ }
2558
+ declare class LLMUsageLogger {
2559
+ private logStream;
2560
+ private logPath;
2561
+ private enabled;
2562
+ private sessionStats;
2563
+ constructor();
2564
+ private initLogStream;
2565
+ private writeHeader;
2566
+ /**
2567
+ * Calculate cost based on token usage and model
2568
+ */
2569
+ calculateCost(model: string, inputTokens: number, outputTokens: number, cacheReadTokens?: number, cacheWriteTokens?: number): number;
2570
+ /**
2571
+ * Log an LLM API call
2572
+ */
2573
+ log(entry: LLMUsageEntry): void;
2574
+ /**
2575
+ * Log session summary (call at end of request)
2576
+ */
2577
+ logSessionSummary(requestContext?: string): void;
2578
+ /**
2579
+ * Reset session stats (call at start of new user request)
2580
+ */
2581
+ resetSession(): void;
2582
+ /**
2583
+ * Reset the log file for a new request (clears previous logs)
2584
+ * Call this at the start of each USER_PROMPT_REQ
2585
+ */
2586
+ resetLogFile(requestContext?: string): void;
2587
+ /**
2588
+ * Get current session stats
2589
+ */
2590
+ getSessionStats(): {
2591
+ totalCalls: number;
2592
+ totalInputTokens: number;
2593
+ totalOutputTokens: number;
2594
+ totalCacheReadTokens: number;
2595
+ totalCacheWriteTokens: number;
2596
+ totalCostUSD: number;
2597
+ totalDurationMs: number;
2598
+ };
2599
+ /**
2600
+ * Generate a unique request ID
2601
+ */
2602
+ generateRequestId(): string;
2603
+ }
2604
+ declare const llmUsageLogger: LLMUsageLogger;
2605
+
2606
+ /**
2607
+ * User Prompt Error Logger - Captures detailed errors for USER_PROMPT_REQ
2608
+ * Logs full error details including raw strings for parse failures
2609
+ */
2610
+ declare class UserPromptErrorLogger {
2611
+ private logStream;
2612
+ private logPath;
2613
+ private enabled;
2614
+ private hasErrors;
2615
+ constructor();
2616
+ /**
2617
+ * Reset the error log file for a new request
2618
+ */
2619
+ resetLogFile(requestContext?: string): void;
2620
+ /**
2621
+ * Log a JSON parse error with the raw string that failed
2622
+ */
2623
+ logJsonParseError(context: string, rawString: string, error: Error): void;
2624
+ /**
2625
+ * Log a general error with full details
2626
+ */
2627
+ logError(context: string, error: Error | string, additionalData?: Record<string, any>): void;
2628
+ /**
2629
+ * Log a SQL query error with the full query
2630
+ */
2631
+ logSqlError(query: string, error: Error | string, params?: any[]): void;
2632
+ /**
2633
+ * Log an LLM API error
2634
+ */
2635
+ logLlmError(provider: string, model: string, method: string, error: Error | string, requestData?: any): void;
2636
+ /**
2637
+ * Log tool execution error
2638
+ */
2639
+ logToolError(toolName: string, toolInput: any, error: Error | string): void;
2640
+ /**
2641
+ * Write final summary if there were errors
2642
+ */
2643
+ writeSummary(): void;
2644
+ /**
2645
+ * Check if any errors were logged
2646
+ */
2647
+ hadErrors(): boolean;
2648
+ private write;
2649
+ }
2650
+ declare const userPromptErrorLogger: UserPromptErrorLogger;
2651
+
2652
+ /**
2653
+ * BM25L Reranker for hybrid semantic search
2654
+ *
2655
+ * BM25L is an improved variant of BM25 that provides better handling of
2656
+ * long documents and term frequency saturation. This implementation is
2657
+ * designed to rerank semantic search results from ChromaDB.
2658
+ *
2659
+ * The hybrid approach combines:
2660
+ * 1. Semantic similarity from ChromaDB embeddings (dense vectors)
2661
+ * 2. Lexical matching from BM25L (sparse, keyword-based)
2662
+ *
2663
+ * This addresses the weakness of pure semantic search which may miss
2664
+ * exact keyword matches that are important for user intent.
2665
+ */
2666
+ interface BM25LOptions {
2667
+ /** Term frequency saturation parameter (default: 1.5) */
2668
+ k1?: number;
2669
+ /** Length normalization parameter (default: 0.75) */
2670
+ b?: number;
2671
+ /** Lower-bound adjustment from BM25L paper (default: 0.5) */
2672
+ delta?: number;
2673
+ }
2674
+ interface RerankedResult<T> {
2675
+ item: T;
2676
+ originalIndex: number;
2677
+ semanticScore: number;
2678
+ bm25Score: number;
2679
+ hybridScore: number;
2680
+ }
2681
+ interface HybridSearchOptions extends BM25LOptions {
2682
+ /** Weight for semantic score (0-1, default: 0.7) */
2683
+ semanticWeight?: number;
2684
+ /** Weight for BM25 score (0-1, default: 0.3) */
2685
+ bm25Weight?: number;
2686
+ /** Minimum hybrid score threshold (0-1, default: 0) */
2687
+ minScore?: number;
2688
+ }
2689
+ /**
2690
+ * BM25L implementation for lexical scoring
2691
+ */
2692
+ declare class BM25L {
2693
+ private k1;
2694
+ private b;
2695
+ private delta;
2696
+ private documents;
2697
+ private docLengths;
2698
+ private avgDocLength;
2699
+ private termDocFreq;
2700
+ /**
2701
+ * @param documents - Array of raw documents (strings)
2702
+ * @param opts - Optional BM25L parameters
2703
+ */
2704
+ constructor(documents?: string[], opts?: BM25LOptions);
2705
+ /**
2706
+ * Tokenize text into lowercase alphanumeric tokens
2707
+ */
2708
+ tokenize(text: string): string[];
2709
+ /**
2710
+ * Compute IDF (Inverse Document Frequency) with smoothing
2711
+ */
2712
+ private idf;
2713
+ /**
2714
+ * Compute BM25L score for a single document
2715
+ */
2716
+ score(query: string, docIndex: number): number;
2717
+ /**
2718
+ * Search and rank all documents
2719
+ */
2720
+ search(query: string): Array<{
2721
+ index: number;
2722
+ score: number;
2723
+ }>;
2724
+ }
2725
+ /**
2726
+ * Hybrid reranker that combines semantic and BM25L scores
2727
+ *
2728
+ * @param query - The search query
2729
+ * @param items - Array of items to rerank
2730
+ * @param getDocument - Function to extract document text from an item
2731
+ * @param getSemanticScore - Function to extract semantic similarity score from an item
2732
+ * @param options - Hybrid search options
2733
+ * @returns Reranked items with hybrid scores
2734
+ */
2735
+ declare function hybridRerank<T>(query: string, items: T[], getDocument: (item: T) => string, getSemanticScore: (item: T) => number, options?: HybridSearchOptions): RerankedResult<T>[];
2736
+ /**
2737
+ * Simple reranking function for ChromaDB results
2738
+ *
2739
+ * This is a convenience wrapper for reranking ChromaDB query results
2740
+ * that follow the standard { ids, documents, metadatas, distances } format.
2741
+ *
2742
+ * @param query - The search query
2743
+ * @param chromaResults - ChromaDB query results
2744
+ * @param options - Hybrid search options
2745
+ * @returns Reranked results with hybrid scores
2746
+ */
2747
+ declare function rerankChromaResults(query: string, chromaResults: {
2748
+ ids: string[][];
2749
+ documents: (string | null)[][];
2750
+ metadatas: Record<string, any>[][];
2751
+ distances: number[][];
2752
+ }, options?: HybridSearchOptions): Array<{
2753
+ id: string;
2754
+ document: string | null;
2755
+ metadata: Record<string, any>;
2756
+ distance: number;
2757
+ semanticScore: number;
2758
+ bm25Score: number;
2759
+ hybridScore: number;
2760
+ }>;
2761
+ /**
2762
+ * Rerank conversation search results specifically
2763
+ *
2764
+ * This function is designed to work with the conversation-history.search collection
2765
+ * where we need to fetch more results initially and then rerank them.
2766
+ *
2767
+ * @param query - The user's search query
2768
+ * @param results - Array of conversation search results from ChromaDB
2769
+ * @param options - Hybrid search options
2770
+ * @returns Reranked results sorted by hybrid score
2771
+ */
2772
+ declare function rerankConversationResults<T extends {
2773
+ userPrompt?: string;
2774
+ similarity?: number;
2775
+ }>(query: string, results: T[], options?: HybridSearchOptions): Array<T & {
2776
+ hybridScore: number;
2777
+ bm25Score: number;
2778
+ }>;
2779
+
2780
+ /**
2781
+ * QueryExecutionService - Handles all query execution, validation, and retry logic
2782
+ * Extracted from BaseLLM for better separation of concerns
2783
+ */
2784
+
2785
+ /**
2786
+ * Context for component when requesting query fix
2787
+ */
2788
+ interface ComponentContext {
2789
+ name: string;
2790
+ type: string;
2791
+ title?: string;
2792
+ }
2793
+ /**
2794
+ * Result of query validation
2795
+ */
2796
+ interface QueryValidationResult {
2797
+ component: Component | null;
2798
+ queryKey: string;
2799
+ result: any;
2800
+ validated: boolean;
2801
+ }
2802
+ /**
2803
+ * Result of batch query validation
2804
+ */
2805
+ interface BatchValidationResult {
2806
+ components: Component[];
2807
+ queryResults: Map<string, any>;
2808
+ }
2809
+ /**
2810
+ * Configuration for QueryExecutionService
2811
+ */
2812
+ interface QueryExecutionServiceConfig {
2813
+ defaultLimit: number;
2814
+ getModelForTask: (taskType: 'simple' | 'complex') => string;
2815
+ getApiKey: (apiKey?: string) => string | undefined;
2816
+ providerName: string;
2817
+ }
2818
+ /**
2819
+ * QueryExecutionService handles all query-related operations
2820
+ */
2821
+ declare class QueryExecutionService {
2822
+ private config;
2823
+ constructor(config: QueryExecutionServiceConfig);
2824
+ /**
2825
+ * Get the cache key for a query
2826
+ * This ensures the cache key matches what the frontend will send
2827
+ */
2828
+ getQueryCacheKey(query: any): string;
2829
+ /**
2830
+ * Execute a query against the database
2831
+ * @param query - The SQL query to execute (string or object with sql/values)
2832
+ * @param collections - Collections object containing database execute function
2833
+ * @returns Object with result data and cache key
2834
+ */
2835
+ executeQuery(query: any, collections: any): Promise<{
2836
+ result: any;
2837
+ cacheKey: string;
2838
+ }>;
2839
+ /**
2840
+ * Request the LLM to fix a failed SQL query
2841
+ * @param failedQuery - The query that failed execution
2842
+ * @param errorMessage - The error message from the failed execution
2843
+ * @param componentContext - Context about the component
2844
+ * @param apiKey - Optional API key
2845
+ * @returns Fixed query string
2846
+ */
2847
+ requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
2848
+ /**
2849
+ * Validate a single component's query with retry logic
2850
+ * @param component - The component to validate
2851
+ * @param collections - Collections object containing database execute function
2852
+ * @param apiKey - Optional API key for LLM calls
2853
+ * @returns Validation result with component, query key, and result
2854
+ */
2855
+ validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
2856
+ /**
2857
+ * Validate multiple component queries in parallel
2858
+ * @param components - Array of components with potential queries
2859
+ * @param collections - Collections object containing database execute function
2860
+ * @param apiKey - Optional API key for LLM calls
2861
+ * @returns Object with validated components and query results map
2862
+ */
2863
+ validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
2864
+ }
2865
+
2866
+ /**
2867
+ * Task types for model selection
2868
+ * - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
2869
+ * - 'simple': Classification, action generation (uses fast model in balanced mode)
2870
+ */
2871
+ type TaskType = 'complex' | 'simple';
2872
+ interface BaseLLMConfig {
2873
+ model?: string;
2874
+ fastModel?: string;
2875
+ defaultLimit?: number;
2876
+ apiKey?: string;
2877
+ /**
2878
+ * Model selection strategy:
2879
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
2880
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
2881
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
2882
+ */
2883
+ modelStrategy?: ModelStrategy;
2884
+ conversationSimilarityThreshold?: number;
2885
+ }
2886
+ /**
2887
+ * BaseLLM abstract class for AI-powered component generation and matching
2888
+ * Provides common functionality for all LLM providers
2889
+ */
2890
+ declare abstract class BaseLLM {
2891
+ protected model: string;
2892
+ protected fastModel: string;
2893
+ protected defaultLimit: number;
2894
+ protected apiKey?: string;
2895
+ protected modelStrategy: ModelStrategy;
2896
+ protected conversationSimilarityThreshold: number;
2897
+ protected queryService: QueryExecutionService;
2898
+ constructor(config?: BaseLLMConfig);
2899
+ /**
2900
+ * Get the appropriate model based on task type and model strategy
2901
+ * @param taskType - 'complex' for text generation/matching, 'simple' for classification/actions
2902
+ * @returns The model string to use for this task
2903
+ */
2904
+ protected getModelForTask(taskType: TaskType): string;
2905
+ /**
2906
+ * Set the model strategy at runtime
2907
+ * @param strategy - 'best', 'fast', or 'balanced'
2908
+ */
2909
+ setModelStrategy(strategy: ModelStrategy): void;
2910
+ /**
2911
+ * Get the current model strategy
2912
+ * @returns The current model strategy
2913
+ */
2914
+ getModelStrategy(): ModelStrategy;
2915
+ /**
2916
+ * Set the conversation similarity threshold at runtime
2917
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2918
+ */
2919
+ setConversationSimilarityThreshold(threshold: number): void;
2920
+ /**
2921
+ * Get the current conversation similarity threshold
2922
+ * @returns The current threshold value
2923
+ */
2924
+ getConversationSimilarityThreshold(): number;
2925
+ /**
2926
+ * Get the default model for this provider (used for complex tasks like text generation)
2927
+ */
2928
+ protected abstract getDefaultModel(): string;
2929
+ /**
2930
+ * Get the default fast model for this provider (used for simple tasks: classification, matching, actions)
2931
+ * Should return a cheaper/faster model like Haiku for Anthropic
2932
+ */
2933
+ protected abstract getDefaultFastModel(): string;
2934
+ /**
2935
+ * Get the default API key from environment
2936
+ */
2937
+ protected abstract getDefaultApiKey(): string | undefined;
2938
+ /**
2939
+ * Get the provider name (for logging)
2940
+ */
2941
+ protected abstract getProviderName(): string;
2942
+ /**
2943
+ * Get the API key (from instance, parameter, or environment)
2944
+ */
2945
+ protected getApiKey(apiKey?: string): string | undefined;
2946
+ /**
2947
+ * Check if a component contains a Form (data_modification component)
2948
+ * Forms have hardcoded defaultValues that become stale when cached
2949
+ * This checks both single Form components and Forms inside MultiComponentContainer
2950
+ */
2951
+ protected containsFormComponent(component: any): boolean;
2952
+ /**
2953
+ * Match components from text response suggestions and generate follow-up questions
2954
+ * Takes a text response with component suggestions (c1:type format) and matches with available components
2955
+ * Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
2956
+ * All components are placed in a default MultiComponentContainer layout
2957
+ * @param analysisContent - The text response containing component suggestions
2958
+ * @param components - List of available components
2959
+ * @param apiKey - Optional API key
2960
+ * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
2961
+ * @returns Object containing matched components, layout title/description, and follow-up actions
2962
+ */
2963
+ matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
2964
+ components: Component[];
2965
+ layoutTitle: string;
2966
+ layoutDescription: string;
2967
+ actions: Action[];
2968
+ }>;
2969
+ /**
2970
+ * Classify user question into category and detect external tools needed
2971
+ * Determines if question is for data analysis, requires external tools, or needs text response
2972
+ */
2973
+ classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
2974
+ category: 'data_analysis' | 'data_modification' | 'general';
2975
+ externalTools: Array<{
2976
+ type: string;
2977
+ name: string;
2978
+ description: string;
2979
+ parameters: Record<string, any>;
2980
+ }>;
2981
+ dataAnalysisType?: 'visualization' | 'calculation' | 'comparison' | 'trend';
2982
+ reasoning: string;
2983
+ confidence: number;
2984
+ }>;
2985
+ /**
2986
+ * Adapt UI block parameters based on current user question
2987
+ * Takes a matched UI block from semantic search and modifies its props to answer the new question
2988
+ * Also adapts the cached text response to match the new question
2989
+ */
2990
+ adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
2991
+ success: boolean;
2992
+ adaptedComponent?: Component;
2993
+ adaptedTextResponse?: string;
2994
+ parametersChanged?: Array<{
2995
+ field: string;
2996
+ reason: string;
2997
+ }>;
2998
+ explanation: string;
2999
+ }>;
3000
+ /**
3001
+ * Generate text-based response for user question
3002
+ * This provides conversational text responses instead of component generation
3003
+ * Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
3004
+ * After generating text response, if components are provided, matches suggested components
3005
+ */
3006
+ 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>;
3007
+ /**
3008
+ * Main orchestration function with semantic search and multi-step classification
3009
+ * NEW FLOW (Recommended):
3010
+ * 1. Semantic search: Check previous conversations (>60% match)
3011
+ * - If match found → Adapt UI block parameters and return
3012
+ * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
3013
+ * 3. Route appropriately based on category and response mode
3014
+ */
3015
+ 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>;
3016
+ /**
3017
+ * Generate next questions that the user might ask based on the original prompt and generated component
3018
+ * This helps provide intelligent suggestions for follow-up queries
3019
+ * For general/conversational questions without components, pass textResponse instead
3020
+ */
3021
+ generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string): Promise<string[]>;
3022
+ }
3023
+
3024
+ interface AnthropicLLMConfig extends BaseLLMConfig {
3025
+ }
3026
+ /**
3027
+ * AnthropicLLM class for handling AI-powered component generation and matching using Anthropic Claude
3028
+ */
3029
+ declare class AnthropicLLM extends BaseLLM {
3030
+ constructor(config?: AnthropicLLMConfig);
3031
+ protected getDefaultModel(): string;
3032
+ protected getDefaultFastModel(): string;
3033
+ protected getDefaultApiKey(): string | undefined;
3034
+ protected getProviderName(): string;
3035
+ }
3036
+ declare const anthropicLLM: AnthropicLLM;
3037
+
3038
+ interface GroqLLMConfig extends BaseLLMConfig {
3039
+ }
3040
+ /**
3041
+ * GroqLLM class for handling AI-powered component generation and matching using Groq
3042
+ */
3043
+ declare class GroqLLM extends BaseLLM {
3044
+ constructor(config?: GroqLLMConfig);
3045
+ protected getDefaultModel(): string;
3046
+ protected getDefaultFastModel(): string;
3047
+ protected getDefaultApiKey(): string | undefined;
3048
+ protected getProviderName(): string;
3049
+ }
3050
+ declare const groqLLM: GroqLLM;
3051
+
3052
+ interface GeminiLLMConfig extends BaseLLMConfig {
3053
+ }
3054
+ /**
3055
+ * GeminiLLM class for handling AI-powered component generation and matching using Google Gemini
3056
+ */
3057
+ declare class GeminiLLM extends BaseLLM {
3058
+ constructor(config?: GeminiLLMConfig);
3059
+ protected getDefaultModel(): string;
3060
+ protected getDefaultFastModel(): string;
3061
+ protected getDefaultApiKey(): string | undefined;
3062
+ protected getProviderName(): string;
3063
+ }
3064
+ declare const geminiLLM: GeminiLLM;
3065
+
3066
+ interface OpenAILLMConfig extends BaseLLMConfig {
3067
+ }
3068
+ /**
3069
+ * OpenAILLM class for handling AI-powered component generation and matching using OpenAI GPT models
3070
+ */
3071
+ declare class OpenAILLM extends BaseLLM {
3072
+ constructor(config?: OpenAILLMConfig);
3073
+ protected getDefaultModel(): string;
3074
+ protected getDefaultFastModel(): string;
3075
+ protected getDefaultApiKey(): string | undefined;
3076
+ protected getProviderName(): string;
3077
+ }
3078
+ declare const openaiLLM: OpenAILLM;
3079
+
3080
+ /**
3081
+ * Query Cache — Two mechanisms:
3082
+ *
3083
+ * 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
3084
+ * of recently validated queries. True LRU eviction: reads bubble entries to the back via
3085
+ * delete+re-set so the oldest *unused* entry is evicted, not the oldest *inserted*.
3086
+ *
3087
+ * 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
3088
+ * No server-side storage needed for SQL mappings. The token is decrypted on each request.
3089
+ * This eliminates the unbounded queryIdCache that previously grew forever and caused
3090
+ * memory bloat (hundreds of MBs after thousands of queries).
3091
+ *
3092
+ * Result data can still be cached temporarily via the data cache (mechanism 1).
3093
+ */
3094
+ declare class QueryCache {
3095
+ private cache;
3096
+ private ttlMs;
3097
+ private maxCacheSize;
3098
+ private cleanupInterval;
3099
+ private readonly algorithm;
3100
+ private encryptionKey;
3101
+ constructor();
3102
+ /**
3103
+ * Set the cache TTL (Time To Live)
3104
+ * @param minutes - TTL in minutes (default: 10)
3105
+ */
3106
+ setTTL(minutes: number): void;
3107
+ /**
3108
+ * Get the current TTL in minutes
3109
+ */
3110
+ getTTL(): number;
3111
+ /**
3112
+ * Store query result in data cache.
3113
+ * If the key already exists, it's removed first so the re-insert places it
3114
+ * at the back of the iteration order (LRU). Eviction only fires when adding
3115
+ * a genuinely new key past the size limit.
3116
+ */
3117
+ set(query: string, data: any): void;
3118
+ /**
3119
+ * Get cached result if exists and not expired.
3120
+ * On hit, re-inserts the entry so it moves to the back of the Map's
3121
+ * iteration order — turning FIFO eviction into true LRU.
3122
+ */
3123
+ get(query: string): any | null;
3124
+ /**
3125
+ * Check if query exists in cache (not expired)
3126
+ */
3127
+ has(query: string): boolean;
3128
+ /**
3129
+ * Remove a specific query from cache
3130
+ */
3131
+ delete(query: string): void;
3132
+ /**
3133
+ * Clear all cached entries
3134
+ */
3135
+ clear(): void;
3136
+ /**
3137
+ * Get cache statistics
3138
+ */
3139
+ getStats(): {
3140
+ size: number;
3141
+ queryIdCount: number;
3142
+ oldestEntryAge: number | null;
3143
+ };
3144
+ /**
3145
+ * Start periodic cleanup of expired data cache entries.
3146
+ */
3147
+ private startCleanup;
3148
+ /**
3149
+ * Encrypt a payload into a self-contained token.
3150
+ */
3151
+ private encrypt;
3152
+ /**
3153
+ * Decrypt a token back to the original payload.
3154
+ */
3155
+ private decrypt;
3156
+ /**
3157
+ * Store a query by generating an encrypted token as queryId.
3158
+ * The SQL is encrypted INTO the token — nothing stored in memory.
3159
+ * If data is provided, it's cached temporarily in the data cache.
3160
+ */
3161
+ storeQuery(query: any, data?: any): string;
3162
+ /**
3163
+ * Get a stored query by decrypting its token.
3164
+ * Returns the SQL + any cached result data.
3165
+ */
3166
+ getQuery(queryId: string): {
3167
+ query: any;
3168
+ data: any;
3169
+ } | null;
3170
+ /**
3171
+ * Update cached data for a queryId token
3172
+ */
3173
+ setQueryData(queryId: string, data: any): void;
3174
+ /**
3175
+ * Stop cleanup interval (for graceful shutdown)
3176
+ */
3177
+ destroy(): void;
3178
+ }
3179
+ declare const queryCache: QueryCache;
3180
+
3181
+ /**
3182
+ * Manages conversation history scoped per user + dashboard.
3183
+ * Each user-dashboard pair has its own isolated history that expires after a configurable TTL.
3184
+ */
3185
+ declare class DashboardConversationHistory {
3186
+ private histories;
3187
+ private ttlMs;
3188
+ private maxEntries;
3189
+ private cleanupInterval;
3190
+ constructor();
3191
+ /**
3192
+ * Set the TTL for dashboard histories
3193
+ * @param minutes - TTL in minutes
3194
+ */
3195
+ setTTL(minutes: number): void;
3196
+ /**
3197
+ * Set max entries per dashboard
3198
+ */
3199
+ setMaxEntries(max: number): void;
3200
+ /**
3201
+ * Add a conversation entry for a user's dashboard
3202
+ */
3203
+ addEntry(dashboardId: string, userPrompt: string, componentSummary: string, userId?: string): void;
3204
+ /**
3205
+ * Get formatted conversation history for a user's dashboard
3206
+ */
3207
+ getHistory(dashboardId: string, userId?: string): string;
3208
+ /**
3209
+ * Clear history for a specific user's dashboard
3210
+ */
3211
+ clearDashboard(dashboardId: string, userId?: string): void;
3212
+ /**
3213
+ * Clear all dashboard histories
3214
+ */
3215
+ clearAll(): void;
3216
+ /**
3217
+ * Start periodic cleanup of expired histories
3218
+ */
3219
+ private startCleanup;
3220
+ /**
3221
+ * Stop cleanup interval (for graceful shutdown)
3222
+ */
3223
+ destroy(): void;
3224
+ }
3225
+ declare const dashboardConversationHistory: DashboardConversationHistory;
3226
+
1153
3227
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
1154
3228
  declare class SuperatomSDK {
1155
3229
  private ws;
1156
3230
  private url;
1157
- private apiKey;
3231
+ private apiKey?;
1158
3232
  private projectId;
1159
- private userId;
1160
3233
  private type;
1161
3234
  private bundleDir;
1162
3235
  private messageHandlers;
@@ -1166,15 +3239,30 @@ declare class SuperatomSDK {
1166
3239
  private maxReconnectAttempts;
1167
3240
  private collections;
1168
3241
  private components;
3242
+ private tools;
3243
+ private workflows;
1169
3244
  private anthropicApiKey;
1170
3245
  private groqApiKey;
3246
+ private geminiApiKey;
3247
+ private openaiApiKey;
1171
3248
  private llmProviders;
3249
+ private databaseType;
3250
+ private modelStrategy;
3251
+ private mainAgentModel;
3252
+ private sourceAgentModel;
3253
+ private dashCompModels?;
3254
+ private conversationSimilarityThreshold;
1172
3255
  private userManager;
1173
3256
  private dashboardManager;
1174
3257
  private reportManager;
3258
+ private pingInterval;
3259
+ private lastPong;
3260
+ private readonly PING_INTERVAL_MS;
3261
+ private readonly PONG_TIMEOUT_MS;
1175
3262
  constructor(config: SuperatomSDKConfig);
1176
3263
  /**
1177
3264
  * Initialize PromptLoader and load prompts into memory
3265
+ * Tries to load from file system first, then falls back to hardcoded prompts
1178
3266
  */
1179
3267
  private initializePromptLoader;
1180
3268
  /**
@@ -1210,9 +3298,11 @@ declare class SuperatomSDK {
1210
3298
  */
1211
3299
  private handleMessage;
1212
3300
  /**
1213
- * Send a message to the Superatom service
3301
+ * Send a message to the Superatom service.
3302
+ * Returns true if the message was sent, false if the WebSocket is not connected.
3303
+ * Does NOT throw on closed connections — callers can check the return value if needed.
1214
3304
  */
1215
- send(message: Message): void;
3305
+ send(message: Message): boolean;
1216
3306
  /**
1217
3307
  * Register a message handler to receive all messages
1218
3308
  */
@@ -1238,7 +3328,69 @@ declare class SuperatomSDK {
1238
3328
  */
1239
3329
  addCollection<TParams = any, TResult = any>(collectionName: string, operation: CollectionOperation | string, handler: CollectionHandler<TParams, TResult>): void;
1240
3330
  private handleReconnect;
3331
+ /**
3332
+ * Start heartbeat to keep WebSocket connection alive
3333
+ * Sends PING every 3 minutes to prevent idle timeout from cloud infrastructure
3334
+ */
3335
+ private startHeartbeat;
3336
+ /**
3337
+ * Stop the heartbeat interval
3338
+ */
3339
+ private stopHeartbeat;
3340
+ /**
3341
+ * Handle PONG response from server
3342
+ */
3343
+ private handlePong;
1241
3344
  private storeComponents;
3345
+ /**
3346
+ * Set tools for the SDK instance
3347
+ */
3348
+ setTools(tools: Tool$1[]): void;
3349
+ /**
3350
+ * Get the stored tools
3351
+ */
3352
+ getTools(): Tool$1[];
3353
+ /**
3354
+ * Register workflow components for the SDK instance.
3355
+ *
3356
+ * Workflows are pre-built multi-step UI flows the main agent can pick when
3357
+ * the user's prompt matches a workflow's `whenToUse` trigger. Picking a
3358
+ * workflow short-circuits analysis text + dashboard component generation —
3359
+ * the workflow component is returned directly, with the LLM-extracted props.
3360
+ */
3361
+ setWorkflows(workflows: WorkflowDescriptor[]): void;
3362
+ /**
3363
+ * Get the registered workflow components.
3364
+ */
3365
+ getWorkflows(): WorkflowDescriptor[];
3366
+ /**
3367
+ * Apply model strategy to all LLM provider singletons
3368
+ * @param strategy - 'best', 'fast', or 'balanced'
3369
+ */
3370
+ private applyModelStrategy;
3371
+ /**
3372
+ * Set model strategy at runtime
3373
+ * @param strategy - 'best', 'fast', or 'balanced'
3374
+ */
3375
+ setModelStrategy(strategy: ModelStrategy): void;
3376
+ /**
3377
+ * Get current model strategy
3378
+ */
3379
+ getModelStrategy(): ModelStrategy;
3380
+ /**
3381
+ * Apply conversation similarity threshold to all LLM provider singletons
3382
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
3383
+ */
3384
+ private applyConversationSimilarityThreshold;
3385
+ /**
3386
+ * Set conversation similarity threshold at runtime
3387
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
3388
+ */
3389
+ setConversationSimilarityThreshold(threshold: number): void;
3390
+ /**
3391
+ * Get current conversation similarity threshold
3392
+ */
3393
+ getConversationSimilarityThreshold(): number;
1242
3394
  }
1243
3395
 
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 };
3396
+ export { type Action, type AgentConfig, type AgentResponse, BM25L, type BM25LOptions, type BaseLLMConfig, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, DEFAULT_AGENT_CONFIG, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, MainAgent, type Message, type ModelStrategy, type OutputField, type RerankedResult, STORAGE_CONFIG, type SelectedWorkflow, SuperatomSDK, type SuperatomSDKConfig, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, type ToolOutputSchema, UIBlock, UILogCollector, type User, UserManager, type UsersData, type WorkflowDescriptor, anthropicLLM, dashboardConversationHistory, geminiLLM, groqLLM, hybridRerank, llmUsageLogger, logger, openaiLLM, queryCache, rerankChromaResults, rerankConversationResults, userPromptErrorLogger };