@superatomai/sdk-node 0.0.25 → 0.0.26-dsp

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
@@ -3,13 +3,20 @@ import Anthropic from '@anthropic-ai/sdk';
3
3
 
4
4
  /**
5
5
  * Unified UIBlock structure for database storage
6
- * Used in both bookmarks and user-conversations tables
6
+ * Used in both bookmarks and user-conversations tables.
7
+ *
8
+ * `analysis` always holds whatever real narration exists — the full answer on
9
+ * success, or whatever was actually streamed before a failure (may be empty).
10
+ * `error` is a dedicated field, null on success — it can be a plain string OR
11
+ * a structured object/array (e.g. the agent's raw `errors` list), whatever
12
+ * shape the failure naturally has; it's never coerced into `analysis`.
7
13
  */
8
14
  interface DBUIBlock {
9
15
  id: string;
10
16
  component: Record<string, any> | null;
11
17
  analysis: string | null;
12
18
  user_prompt: string;
19
+ error?: unknown | null;
13
20
  }
14
21
 
15
22
  /**
@@ -59,7 +66,18 @@ declare class Logger {
59
66
  * Log debug message (only shown for verbose level)
60
67
  */
61
68
  debug(...args: any[]): void;
69
+ /**
70
+ * Write to log file
71
+ */
62
72
  file(...args: any[]): void;
73
+ /**
74
+ * Clear the log file (call at start of new user request)
75
+ */
76
+ clearFile(): void;
77
+ /**
78
+ * Log LLM method prompts with clear labeling
79
+ */
80
+ logLLMPrompt(methodName: string, promptType: 'system' | 'user', content: string | object | any[]): void;
63
81
  }
64
82
  declare const logger: Logger;
65
83
 
@@ -90,7 +108,27 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
90
108
  deps?: string[] | undefined;
91
109
  }>, "many">>;
92
110
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
93
- render: z.ZodType<any, z.ZodTypeDef, any>;
111
+ render: z.ZodOptional<z.ZodType<any, z.ZodTypeDef, any>>;
112
+ pages: z.ZodOptional<z.ZodArray<z.ZodObject<{
113
+ id: z.ZodString;
114
+ name: z.ZodString;
115
+ order: z.ZodNumber;
116
+ icon: z.ZodOptional<z.ZodString>;
117
+ render: z.ZodType<any, z.ZodTypeDef, any>;
118
+ }, "strip", z.ZodTypeAny, {
119
+ id: string;
120
+ name: string;
121
+ order: number;
122
+ icon?: string | undefined;
123
+ render?: any;
124
+ }, {
125
+ id: string;
126
+ name: string;
127
+ order: number;
128
+ icon?: string | undefined;
129
+ render?: any;
130
+ }>, "many">>;
131
+ defaultPageId: z.ZodOptional<z.ZodString>;
94
132
  query: z.ZodOptional<z.ZodObject<{
95
133
  graphql: z.ZodOptional<z.ZodString>;
96
134
  sql: z.ZodOptional<z.ZodString>;
@@ -129,6 +167,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
129
167
  dependencies?: string[] | undefined;
130
168
  } | undefined;
131
169
  props?: Record<string, any> | undefined;
170
+ render?: any;
132
171
  states?: Record<string, any> | undefined;
133
172
  methods?: Record<string, {
134
173
  fn: string;
@@ -139,7 +178,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
139
178
  deps?: string[] | undefined;
140
179
  }[] | undefined;
141
180
  data?: Record<string, any> | undefined;
142
- render?: any;
181
+ pages?: {
182
+ id: string;
183
+ name: string;
184
+ order: number;
185
+ icon?: string | undefined;
186
+ render?: any;
187
+ }[] | undefined;
188
+ defaultPageId?: string | undefined;
143
189
  }, {
144
190
  id: string;
145
191
  name?: string | undefined;
@@ -153,6 +199,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
153
199
  dependencies?: string[] | undefined;
154
200
  } | undefined;
155
201
  props?: Record<string, any> | undefined;
202
+ render?: any;
156
203
  states?: Record<string, any> | undefined;
157
204
  methods?: Record<string, {
158
205
  fn: string;
@@ -163,7 +210,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
163
210
  deps?: string[] | undefined;
164
211
  }[] | undefined;
165
212
  data?: Record<string, any> | undefined;
166
- render?: any;
213
+ pages?: {
214
+ id: string;
215
+ name: string;
216
+ order: number;
217
+ icon?: string | undefined;
218
+ render?: any;
219
+ }[] | undefined;
220
+ defaultPageId?: string | undefined;
167
221
  }>;
168
222
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
169
223
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -181,6 +235,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
181
235
  dependencies?: string[] | undefined;
182
236
  } | undefined;
183
237
  props?: Record<string, any> | undefined;
238
+ render?: any;
184
239
  states?: Record<string, any> | undefined;
185
240
  methods?: Record<string, {
186
241
  fn: string;
@@ -191,7 +246,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
191
246
  deps?: string[] | undefined;
192
247
  }[] | undefined;
193
248
  data?: Record<string, any> | undefined;
194
- render?: any;
249
+ pages?: {
250
+ id: string;
251
+ name: string;
252
+ order: number;
253
+ icon?: string | undefined;
254
+ render?: any;
255
+ }[] | undefined;
256
+ defaultPageId?: string | undefined;
195
257
  };
196
258
  data?: Record<string, any> | undefined;
197
259
  context?: Record<string, any> | undefined;
@@ -209,6 +271,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
209
271
  dependencies?: string[] | undefined;
210
272
  } | undefined;
211
273
  props?: Record<string, any> | undefined;
274
+ render?: any;
212
275
  states?: Record<string, any> | undefined;
213
276
  methods?: Record<string, {
214
277
  fn: string;
@@ -219,7 +282,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
219
282
  deps?: string[] | undefined;
220
283
  }[] | undefined;
221
284
  data?: Record<string, any> | undefined;
222
- render?: any;
285
+ pages?: {
286
+ id: string;
287
+ name: string;
288
+ order: number;
289
+ icon?: string | undefined;
290
+ render?: any;
291
+ }[] | undefined;
292
+ defaultPageId?: string | undefined;
223
293
  };
224
294
  data?: Record<string, any> | undefined;
225
295
  context?: Record<string, any> | undefined;
@@ -292,6 +362,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
292
362
  dependencies?: string[] | undefined;
293
363
  } | undefined;
294
364
  props?: Record<string, any> | undefined;
365
+ render?: any;
295
366
  states?: Record<string, any> | undefined;
296
367
  methods?: Record<string, {
297
368
  fn: string;
@@ -302,7 +373,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
302
373
  deps?: string[] | undefined;
303
374
  }[] | undefined;
304
375
  data?: Record<string, any> | undefined;
305
- render?: any;
306
376
  }, {
307
377
  id: string;
308
378
  name?: string | undefined;
@@ -316,6 +386,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
316
386
  dependencies?: string[] | undefined;
317
387
  } | undefined;
318
388
  props?: Record<string, any> | undefined;
389
+ render?: any;
319
390
  states?: Record<string, any> | undefined;
320
391
  methods?: Record<string, {
321
392
  fn: string;
@@ -326,7 +397,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
326
397
  deps?: string[] | undefined;
327
398
  }[] | undefined;
328
399
  data?: Record<string, any> | undefined;
329
- render?: any;
330
400
  }>;
331
401
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
332
402
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -344,6 +414,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
344
414
  dependencies?: string[] | undefined;
345
415
  } | undefined;
346
416
  props?: Record<string, any> | undefined;
417
+ render?: any;
347
418
  states?: Record<string, any> | undefined;
348
419
  methods?: Record<string, {
349
420
  fn: string;
@@ -354,7 +425,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
354
425
  deps?: string[] | undefined;
355
426
  }[] | undefined;
356
427
  data?: Record<string, any> | undefined;
357
- render?: any;
358
428
  };
359
429
  data?: Record<string, any> | undefined;
360
430
  context?: Record<string, any> | undefined;
@@ -372,6 +442,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
372
442
  dependencies?: string[] | undefined;
373
443
  } | undefined;
374
444
  props?: Record<string, any> | undefined;
445
+ render?: any;
375
446
  states?: Record<string, any> | undefined;
376
447
  methods?: Record<string, {
377
448
  fn: string;
@@ -382,7 +453,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
382
453
  deps?: string[] | undefined;
383
454
  }[] | undefined;
384
455
  data?: Record<string, any> | undefined;
385
- render?: any;
386
456
  };
387
457
  data?: Record<string, any> | undefined;
388
458
  context?: Record<string, any> | undefined;
@@ -395,6 +465,7 @@ declare const UserSchema: z.ZodObject<{
395
465
  password: z.ZodString;
396
466
  fullname: z.ZodOptional<z.ZodString>;
397
467
  role: z.ZodOptional<z.ZodString>;
468
+ userInfo: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
398
469
  wsIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
399
470
  }, "strip", z.ZodTypeAny, {
400
471
  username: string;
@@ -402,6 +473,7 @@ declare const UserSchema: z.ZodObject<{
402
473
  email?: string | undefined;
403
474
  fullname?: string | undefined;
404
475
  role?: string | undefined;
476
+ userInfo?: Record<string, unknown> | undefined;
405
477
  wsIds?: string[] | undefined;
406
478
  }, {
407
479
  username: string;
@@ -409,6 +481,7 @@ declare const UserSchema: z.ZodObject<{
409
481
  email?: string | undefined;
410
482
  fullname?: string | undefined;
411
483
  role?: string | undefined;
484
+ userInfo?: Record<string, unknown> | undefined;
412
485
  wsIds?: string[] | undefined;
413
486
  }>;
414
487
  type User = z.infer<typeof UserSchema>;
@@ -419,6 +492,7 @@ declare const UsersDataSchema: z.ZodObject<{
419
492
  password: z.ZodString;
420
493
  fullname: z.ZodOptional<z.ZodString>;
421
494
  role: z.ZodOptional<z.ZodString>;
495
+ userInfo: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
422
496
  wsIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
423
497
  }, "strip", z.ZodTypeAny, {
424
498
  username: string;
@@ -426,6 +500,7 @@ declare const UsersDataSchema: z.ZodObject<{
426
500
  email?: string | undefined;
427
501
  fullname?: string | undefined;
428
502
  role?: string | undefined;
503
+ userInfo?: Record<string, unknown> | undefined;
429
504
  wsIds?: string[] | undefined;
430
505
  }, {
431
506
  username: string;
@@ -433,6 +508,7 @@ declare const UsersDataSchema: z.ZodObject<{
433
508
  email?: string | undefined;
434
509
  fullname?: string | undefined;
435
510
  role?: string | undefined;
511
+ userInfo?: Record<string, unknown> | undefined;
436
512
  wsIds?: string[] | undefined;
437
513
  }>, "many">;
438
514
  }, "strip", z.ZodTypeAny, {
@@ -442,6 +518,7 @@ declare const UsersDataSchema: z.ZodObject<{
442
518
  email?: string | undefined;
443
519
  fullname?: string | undefined;
444
520
  role?: string | undefined;
521
+ userInfo?: Record<string, unknown> | undefined;
445
522
  wsIds?: string[] | undefined;
446
523
  }[];
447
524
  }, {
@@ -451,6 +528,7 @@ declare const UsersDataSchema: z.ZodObject<{
451
528
  email?: string | undefined;
452
529
  fullname?: string | undefined;
453
530
  role?: string | undefined;
531
+ userInfo?: Record<string, unknown> | undefined;
454
532
  wsIds?: string[] | undefined;
455
533
  }[];
456
534
  }>;
@@ -555,60 +633,309 @@ declare const IncomingMessageSchema: z.ZodObject<{
555
633
  payload?: unknown;
556
634
  }>;
557
635
  type IncomingMessage = z.infer<typeof IncomingMessageSchema>;
636
+ declare const ComponentSchema: z.ZodObject<{
637
+ id: z.ZodString;
638
+ name: z.ZodString;
639
+ displayName: z.ZodOptional<z.ZodString>;
640
+ isDisplayComp: z.ZodOptional<z.ZodBoolean>;
641
+ type: z.ZodString;
642
+ description: z.ZodString;
643
+ props: z.ZodObject<{
644
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
645
+ title: z.ZodOptional<z.ZodString>;
646
+ description: z.ZodOptional<z.ZodString>;
647
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
648
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
649
+ }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
650
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
651
+ title: z.ZodOptional<z.ZodString>;
652
+ description: z.ZodOptional<z.ZodString>;
653
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
654
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
655
+ }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
656
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
657
+ title: z.ZodOptional<z.ZodString>;
658
+ description: z.ZodOptional<z.ZodString>;
659
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
660
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
661
+ }, z.ZodTypeAny, "passthrough">>;
662
+ category: z.ZodOptional<z.ZodString>;
663
+ keywords: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
664
+ }, "strip", z.ZodTypeAny, {
665
+ id: string;
666
+ type: string;
667
+ name: string;
668
+ description: string;
669
+ props: {
670
+ description?: string | undefined;
671
+ query?: string | {} | null | undefined;
672
+ title?: string | undefined;
673
+ config?: Record<string, unknown> | undefined;
674
+ actions?: any[] | undefined;
675
+ } & {
676
+ [k: string]: unknown;
677
+ };
678
+ displayName?: string | undefined;
679
+ isDisplayComp?: boolean | undefined;
680
+ category?: string | undefined;
681
+ keywords?: string[] | undefined;
682
+ }, {
683
+ id: string;
684
+ type: string;
685
+ name: string;
686
+ description: string;
687
+ props: {
688
+ description?: string | undefined;
689
+ query?: string | {} | null | undefined;
690
+ title?: string | undefined;
691
+ config?: Record<string, unknown> | undefined;
692
+ actions?: any[] | undefined;
693
+ } & {
694
+ [k: string]: unknown;
695
+ };
696
+ displayName?: string | undefined;
697
+ isDisplayComp?: boolean | undefined;
698
+ category?: string | undefined;
699
+ keywords?: string[] | undefined;
700
+ }>;
701
+ type Component = z.infer<typeof ComponentSchema>;
702
+ declare const OutputFieldSchema: z.ZodObject<{
703
+ name: z.ZodString;
704
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
705
+ description: z.ZodString;
706
+ }, "strip", z.ZodTypeAny, {
707
+ type: "string" | "number" | "boolean" | "date";
708
+ name: string;
709
+ description: string;
710
+ }, {
711
+ type: "string" | "number" | "boolean" | "date";
712
+ name: string;
713
+ description: string;
714
+ }>;
715
+ type OutputField = z.infer<typeof OutputFieldSchema>;
716
+ declare const OutputSchema: z.ZodObject<{
717
+ description: z.ZodString;
718
+ fields: z.ZodArray<z.ZodObject<{
719
+ name: z.ZodString;
720
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
721
+ description: z.ZodString;
722
+ }, "strip", z.ZodTypeAny, {
723
+ type: "string" | "number" | "boolean" | "date";
724
+ name: string;
725
+ description: string;
726
+ }, {
727
+ type: "string" | "number" | "boolean" | "date";
728
+ name: string;
729
+ description: string;
730
+ }>, "many">;
731
+ }, "strip", z.ZodTypeAny, {
732
+ description: string;
733
+ fields: {
734
+ type: "string" | "number" | "boolean" | "date";
735
+ name: string;
736
+ description: string;
737
+ }[];
738
+ }, {
739
+ description: string;
740
+ fields: {
741
+ type: "string" | "number" | "boolean" | "date";
742
+ name: string;
743
+ description: string;
744
+ }[];
745
+ }>;
746
+ type ToolOutputSchema = z.infer<typeof OutputSchema>;
558
747
  declare const ToolSchema: z.ZodObject<{
559
748
  id: z.ZodString;
560
749
  name: z.ZodString;
561
750
  description: z.ZodString;
751
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
752
+ toolType: z.ZodOptional<z.ZodEnum<["source", "direct"]>>;
753
+ /** Full untruncated schema for source agent (all columns visible) */
754
+ fullSchema: z.ZodOptional<z.ZodString>;
562
755
  params: z.ZodRecord<z.ZodString, z.ZodString>;
563
756
  fn: z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodAny>;
757
+ outputSchema: z.ZodOptional<z.ZodObject<{
758
+ description: z.ZodString;
759
+ fields: z.ZodArray<z.ZodObject<{
760
+ name: z.ZodString;
761
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
762
+ description: z.ZodString;
763
+ }, "strip", z.ZodTypeAny, {
764
+ type: "string" | "number" | "boolean" | "date";
765
+ name: string;
766
+ description: string;
767
+ }, {
768
+ type: "string" | "number" | "boolean" | "date";
769
+ name: string;
770
+ description: string;
771
+ }>, "many">;
772
+ }, "strip", z.ZodTypeAny, {
773
+ description: string;
774
+ fields: {
775
+ type: "string" | "number" | "boolean" | "date";
776
+ name: string;
777
+ description: string;
778
+ }[];
779
+ }, {
780
+ description: string;
781
+ fields: {
782
+ type: "string" | "number" | "boolean" | "date";
783
+ name: string;
784
+ description: string;
785
+ }[];
786
+ }>>;
787
+ /** Cache policy. `false` = never cache (live data, write ops). Mirrors HTTP `Cache-Control: no-store`. */
788
+ cache: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<false>, z.ZodObject<{
789
+ ttlMs: z.ZodOptional<z.ZodNumber>;
790
+ }, "strip", z.ZodTypeAny, {
791
+ ttlMs?: number | undefined;
792
+ }, {
793
+ ttlMs?: number | undefined;
794
+ }>]>>;
564
795
  }, "strip", z.ZodTypeAny, {
565
796
  id: string;
566
797
  params: Record<string, string>;
567
798
  name: string;
568
799
  description: string;
569
800
  fn: (args_0: any, ...args: unknown[]) => any;
801
+ toolType?: "source" | "direct" | undefined;
802
+ fullSchema?: string | undefined;
803
+ outputSchema?: {
804
+ description: string;
805
+ fields: {
806
+ type: "string" | "number" | "boolean" | "date";
807
+ name: string;
808
+ description: string;
809
+ }[];
810
+ } | undefined;
811
+ cache?: false | {
812
+ ttlMs?: number | undefined;
813
+ } | undefined;
570
814
  }, {
571
815
  id: string;
572
816
  params: Record<string, string>;
573
817
  name: string;
574
818
  description: string;
575
819
  fn: (args_0: any, ...args: unknown[]) => any;
820
+ toolType?: "source" | "direct" | undefined;
821
+ fullSchema?: string | undefined;
822
+ outputSchema?: {
823
+ description: string;
824
+ fields: {
825
+ type: "string" | "number" | "boolean" | "date";
826
+ name: string;
827
+ description: string;
828
+ }[];
829
+ } | undefined;
830
+ cache?: false | {
831
+ ttlMs?: number | undefined;
832
+ } | undefined;
576
833
  }>;
577
834
  type Tool$1 = z.infer<typeof ToolSchema>;
578
835
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
579
836
  type CollectionHandler<TParams = any, TResult = any> = (params: TParams) => Promise<TResult> | TResult;
580
837
  type LLMProvider = 'anthropic' | 'groq' | 'gemini' | 'openai';
581
838
 
839
+ type DatabaseType = 'postgresql' | 'mssql' | 'snowflake' | 'mysql';
840
+ /**
841
+ * Model strategy for controlling which models are used for different tasks
842
+ * - 'best': Use the best model (e.g., Sonnet) for all tasks - highest quality, higher cost
843
+ * - 'fast': Use the fast model (e.g., Haiku) for all tasks - lower quality, lower cost
844
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
845
+ */
846
+ type ModelStrategy = 'best' | 'fast' | 'balanced';
847
+ /**
848
+ * Model configuration for DASH_COMP flow (dashboard component picking)
849
+ * Allows separate control of models used for component selection
850
+ */
851
+ interface DashCompModelConfig {
852
+ /**
853
+ * Primary model for DASH_COMP requests
854
+ * Format: "provider/model-name" (e.g., "anthropic/claude-sonnet-4-5-20250929")
855
+ */
856
+ model?: string;
857
+ /**
858
+ * Fast model for simpler DASH_COMP tasks (optional)
859
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
860
+ */
861
+ fastModel?: string;
862
+ }
582
863
  interface SuperatomSDKConfig {
583
864
  url?: string;
584
865
  apiKey?: string;
585
866
  projectId: string;
586
- userId?: string;
587
867
  type?: string;
588
868
  bundleDir?: string;
589
869
  promptsDir?: string;
870
+ databaseType?: DatabaseType;
590
871
  ANTHROPIC_API_KEY?: string;
591
872
  GROQ_API_KEY?: string;
592
873
  GEMINI_API_KEY?: string;
593
874
  OPENAI_API_KEY?: string;
594
875
  LLM_PROVIDERS?: LLMProvider[];
595
876
  logLevel?: LogLevel;
877
+ /**
878
+ * Model selection strategy for LLM API calls:
879
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
880
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
881
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
882
+ */
883
+ modelStrategy?: ModelStrategy;
884
+ /**
885
+ * Model for the main agent (routing + analysis).
886
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
887
+ * If not set, uses the provider's default model.
888
+ */
889
+ mainAgentModel?: string;
890
+ /**
891
+ * Model for source agents (per-source query generation).
892
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
893
+ * If not set, uses the provider's default model.
894
+ */
895
+ sourceAgentModel?: string;
896
+ /**
897
+ * Separate model configuration for DASH_COMP flow (dashboard component picking)
898
+ * If not provided, falls back to provider-based model selection
899
+ */
900
+ dashCompModels?: DashCompModelConfig;
901
+ /**
902
+ * Similarity threshold for conversation search (semantic matching)
903
+ * Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
904
+ * Higher values require closer matches, lower values allow more distant matches
905
+ * Default: 0.8
906
+ */
907
+ conversationSimilarityThreshold?: number;
908
+ /**
909
+ * Query cache TTL (Time To Live) in minutes
910
+ * Cached query results expire after this duration
911
+ * Default: 5 minutes
912
+ */
913
+ queryCacheTTL?: number;
914
+ /**
915
+ * Dashboard conversation history TTL (Time To Live) in minutes
916
+ * Per-dashboard conversation histories expire after this duration
917
+ * Default: 30 minutes
918
+ */
919
+ dashboardHistoryTTL?: number;
596
920
  }
597
921
 
598
922
  declare const KbNodesQueryFiltersSchema: z.ZodObject<{
599
923
  query: z.ZodOptional<z.ZodString>;
600
924
  category: z.ZodOptional<z.ZodString>;
601
925
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
602
- createdBy: z.ZodOptional<z.ZodNumber>;
926
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
927
+ createdBy: z.ZodOptional<z.ZodString>;
603
928
  }, "strip", z.ZodTypeAny, {
929
+ type?: "query" | "user" | "global" | undefined;
604
930
  query?: string | undefined;
605
931
  category?: string | undefined;
606
- createdBy?: number | undefined;
932
+ createdBy?: string | undefined;
607
933
  tags?: string[] | undefined;
608
934
  }, {
935
+ type?: "query" | "user" | "global" | undefined;
609
936
  query?: string | undefined;
610
937
  category?: string | undefined;
611
- createdBy?: number | undefined;
938
+ createdBy?: string | undefined;
612
939
  tags?: string[] | undefined;
613
940
  }>;
614
941
  type KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
@@ -620,109 +947,126 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
620
947
  content: z.ZodOptional<z.ZodString>;
621
948
  category: z.ZodOptional<z.ZodString>;
622
949
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
623
- createdBy: z.ZodOptional<z.ZodNumber>;
624
- updatedBy: z.ZodOptional<z.ZodNumber>;
625
- userId: z.ZodOptional<z.ZodNumber>;
950
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
951
+ createdBy: z.ZodOptional<z.ZodString>;
952
+ updatedBy: z.ZodOptional<z.ZodString>;
953
+ userId: z.ZodOptional<z.ZodString>;
626
954
  query: z.ZodOptional<z.ZodString>;
627
955
  filters: z.ZodOptional<z.ZodObject<{
628
956
  query: z.ZodOptional<z.ZodString>;
629
957
  category: z.ZodOptional<z.ZodString>;
630
958
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
631
- createdBy: z.ZodOptional<z.ZodNumber>;
959
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
960
+ createdBy: z.ZodOptional<z.ZodString>;
632
961
  }, "strip", z.ZodTypeAny, {
962
+ type?: "query" | "user" | "global" | undefined;
633
963
  query?: string | undefined;
634
964
  category?: string | undefined;
635
- createdBy?: number | undefined;
965
+ createdBy?: string | undefined;
636
966
  tags?: string[] | undefined;
637
967
  }, {
968
+ type?: "query" | "user" | "global" | undefined;
638
969
  query?: string | undefined;
639
970
  category?: string | undefined;
640
- createdBy?: number | undefined;
971
+ createdBy?: string | undefined;
641
972
  tags?: string[] | undefined;
642
973
  }>>;
643
974
  limit: z.ZodOptional<z.ZodNumber>;
644
975
  offset: z.ZodOptional<z.ZodNumber>;
645
976
  }, "strip", z.ZodTypeAny, {
646
977
  id?: number | undefined;
978
+ type?: "query" | "user" | "global" | undefined;
647
979
  query?: string | undefined;
648
980
  title?: string | undefined;
649
981
  category?: string | undefined;
650
- userId?: number | undefined;
982
+ userId?: string | undefined;
651
983
  limit?: number | undefined;
652
984
  filters?: {
985
+ type?: "query" | "user" | "global" | undefined;
653
986
  query?: string | undefined;
654
987
  category?: string | undefined;
655
- createdBy?: number | undefined;
988
+ createdBy?: string | undefined;
656
989
  tags?: string[] | undefined;
657
990
  } | undefined;
658
- createdBy?: number | undefined;
659
- updatedBy?: number | undefined;
991
+ createdBy?: string | undefined;
992
+ updatedBy?: string | undefined;
993
+ offset?: number | undefined;
660
994
  tags?: string[] | undefined;
661
995
  content?: string | undefined;
662
- offset?: number | undefined;
663
996
  }, {
664
997
  id?: number | undefined;
998
+ type?: "query" | "user" | "global" | undefined;
665
999
  query?: string | undefined;
666
1000
  title?: string | undefined;
667
1001
  category?: string | undefined;
668
- userId?: number | undefined;
1002
+ userId?: string | undefined;
669
1003
  limit?: number | undefined;
670
1004
  filters?: {
1005
+ type?: "query" | "user" | "global" | undefined;
671
1006
  query?: string | undefined;
672
1007
  category?: string | undefined;
673
- createdBy?: number | undefined;
1008
+ createdBy?: string | undefined;
674
1009
  tags?: string[] | undefined;
675
1010
  } | undefined;
676
- createdBy?: number | undefined;
677
- updatedBy?: number | undefined;
1011
+ createdBy?: string | undefined;
1012
+ updatedBy?: string | undefined;
1013
+ offset?: number | undefined;
678
1014
  tags?: string[] | undefined;
679
1015
  content?: string | undefined;
680
- offset?: number | undefined;
681
1016
  }>>;
682
1017
  }, "strip", z.ZodTypeAny, {
683
1018
  operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
684
1019
  data?: {
685
1020
  id?: number | undefined;
1021
+ type?: "query" | "user" | "global" | undefined;
686
1022
  query?: string | undefined;
687
1023
  title?: string | undefined;
688
1024
  category?: string | undefined;
689
- userId?: number | undefined;
1025
+ userId?: string | undefined;
690
1026
  limit?: number | undefined;
691
1027
  filters?: {
1028
+ type?: "query" | "user" | "global" | undefined;
692
1029
  query?: string | undefined;
693
1030
  category?: string | undefined;
694
- createdBy?: number | undefined;
1031
+ createdBy?: string | undefined;
695
1032
  tags?: string[] | undefined;
696
1033
  } | undefined;
697
- createdBy?: number | undefined;
698
- updatedBy?: number | undefined;
1034
+ createdBy?: string | undefined;
1035
+ updatedBy?: string | undefined;
1036
+ offset?: number | undefined;
699
1037
  tags?: string[] | undefined;
700
1038
  content?: string | undefined;
701
- offset?: number | undefined;
702
1039
  } | undefined;
703
1040
  }, {
704
1041
  operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
705
1042
  data?: {
706
1043
  id?: number | undefined;
1044
+ type?: "query" | "user" | "global" | undefined;
707
1045
  query?: string | undefined;
708
1046
  title?: string | undefined;
709
1047
  category?: string | undefined;
710
- userId?: number | undefined;
1048
+ userId?: string | undefined;
711
1049
  limit?: number | undefined;
712
1050
  filters?: {
1051
+ type?: "query" | "user" | "global" | undefined;
713
1052
  query?: string | undefined;
714
1053
  category?: string | undefined;
715
- createdBy?: number | undefined;
1054
+ createdBy?: string | undefined;
716
1055
  tags?: string[] | undefined;
717
1056
  } | undefined;
718
- createdBy?: number | undefined;
719
- updatedBy?: number | undefined;
1057
+ createdBy?: string | undefined;
1058
+ updatedBy?: string | undefined;
1059
+ offset?: number | undefined;
720
1060
  tags?: string[] | undefined;
721
1061
  content?: string | undefined;
722
- offset?: number | undefined;
723
1062
  } | undefined;
724
1063
  }>;
725
1064
  type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
1065
+ interface T_RESPONSE {
1066
+ success: boolean;
1067
+ data?: any;
1068
+ errors: string[];
1069
+ }
726
1070
 
727
1071
  /**
728
1072
  * UserManager class to handle CRUD operations on users with file persistence
@@ -983,108 +1327,1128 @@ declare class ReportManager {
983
1327
  getReportCount(): number;
984
1328
  }
985
1329
 
986
- type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
987
- interface LLMMessages {
988
- sys: SystemPrompt;
989
- user: string;
990
- }
991
- interface LLMOptions {
992
- model?: string;
993
- maxTokens?: number;
994
- temperature?: number;
995
- topP?: number;
996
- apiKey?: string;
997
- partial?: (chunk: string) => void;
998
- }
999
- interface Tool {
1000
- name: string;
1001
- description: string;
1002
- input_schema: {
1003
- type: string;
1004
- properties: Record<string, any>;
1005
- required?: string[];
1006
- };
1007
- }
1008
- declare class LLM {
1009
- static text(messages: LLMMessages, options?: LLMOptions): Promise<string>;
1010
- static stream<T = string>(messages: LLMMessages, options?: LLMOptions, json?: boolean): Promise<T extends string ? string : any>;
1011
- static streamWithTools(messages: LLMMessages, tools: Tool[], toolHandler: (toolName: string, toolInput: any) => Promise<any>, options?: LLMOptions, maxIterations?: number): Promise<string>;
1330
+ /**
1331
+ * StreamBuffer - Buffered streaming utility for smoother text delivery
1332
+ * Batches small chunks together and flushes at regular intervals
1333
+ */
1334
+ type StreamCallback = (chunk: string) => void;
1335
+ /**
1336
+ * StreamBuffer class for managing buffered streaming output
1337
+ * Provides smooth text delivery by batching small chunks
1338
+ */
1339
+ declare class StreamBuffer {
1340
+ private buffer;
1341
+ private flushTimer;
1342
+ private callback;
1343
+ private fullText;
1344
+ constructor(callback?: StreamCallback);
1012
1345
  /**
1013
- * Normalize system prompt to Anthropic format
1014
- * Converts string to array format if needed
1015
- * @param sys - System prompt (string or array of blocks)
1016
- * @returns Normalized system prompt for Anthropic API
1346
+ * Check if the buffer has a callback configured
1017
1347
  */
1018
- private static _normalizeSystemPrompt;
1348
+ hasCallback(): boolean;
1019
1349
  /**
1020
- * Log cache usage metrics from Anthropic API response
1021
- * Shows cache hits, costs, and savings
1350
+ * Get all text that has been written (including already flushed)
1022
1351
  */
1023
- private static _logCacheUsage;
1352
+ getFullText(): string;
1024
1353
  /**
1025
- * Parse model string to extract provider and model name
1026
- * @param modelString - Format: "provider/model-name" or just "model-name"
1027
- * @returns [provider, modelName]
1354
+ * Write a chunk to the buffer
1355
+ * Large chunks or chunks with newlines are flushed immediately
1356
+ * Small chunks are batched and flushed after a short interval
1028
1357
  *
1029
- * @example
1030
- * "anthropic/claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"]
1031
- * "groq/openai/gpt-oss-120b" → ["groq", "openai/gpt-oss-120b"]
1032
- * "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
1358
+ * @param chunk - Text chunk to write
1033
1359
  */
1034
- private static _parseModel;
1035
- private static _anthropicText;
1036
- private static _anthropicStream;
1037
- private static _anthropicStreamWithTools;
1038
- private static _groqText;
1039
- private static _groqStream;
1040
- private static _geminiText;
1041
- private static _geminiStream;
1042
- private static _geminiStreamWithTools;
1043
- private static _openaiText;
1044
- private static _openaiStream;
1045
- private static _openaiStreamWithTools;
1360
+ write(chunk: string): void;
1046
1361
  /**
1047
- * Parse JSON string, handling markdown code blocks and surrounding text
1048
- * Enhanced version with jsonrepair to handle malformed JSON from LLMs
1049
- * @param text - Text that may contain JSON wrapped in ```json...``` or with surrounding text
1050
- * @returns Parsed JSON object or array
1362
+ * Flush the buffer immediately
1363
+ * Call this before tool execution or other operations that need clean output
1051
1364
  */
1052
- private static _parseJSON;
1365
+ flush(): void;
1366
+ /**
1367
+ * Internal flush implementation
1368
+ */
1369
+ private flushNow;
1370
+ /**
1371
+ * Clean up resources
1372
+ * Call this when done with the buffer
1373
+ */
1374
+ dispose(): void;
1053
1375
  }
1054
1376
 
1055
- interface CapturedLog {
1056
- timestamp: number;
1057
- level: 'info' | 'error' | 'warn' | 'debug';
1058
- message: string;
1059
- type?: 'explanation' | 'query' | 'general';
1060
- data?: Record<string, any>;
1377
+ /**
1378
+ * ToolExecutorService - Handles execution of SQL queries and external tools
1379
+ * Extracted from BaseLLM.generateTextResponse for better separation of concerns
1380
+ */
1381
+
1382
+ /**
1383
+ * External tool definition
1384
+ */
1385
+ interface ExternalTool {
1386
+ id: string;
1387
+ name: string;
1388
+ description?: string;
1389
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
1390
+ toolType?: 'source' | 'direct';
1391
+ /** Full untruncated schema for source agent (all columns visible) */
1392
+ fullSchema?: string;
1393
+ /** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
1394
+ schemaTier?: string;
1395
+ /** Schema search function for very_large tier — keyword search over entities */
1396
+ schemaSearchFn?: (keywords: string[]) => string;
1397
+ fn: (input: any) => Promise<any>;
1398
+ limit?: number;
1399
+ outputSchema?: any;
1400
+ executionType?: 'immediate' | 'deferred';
1401
+ userProvidedData?: any;
1402
+ params?: Record<string, any>;
1061
1403
  }
1062
1404
  /**
1063
- * UILogCollector captures logs during user prompt processing
1064
- * and sends them to runtime via ui_logs message with uiBlockId as the message id
1065
- * Logs are sent in real-time for streaming effect in the UI
1066
- * Respects the global log level configuration
1405
+ * Executed tool tracking info
1067
1406
  */
1068
- declare class UILogCollector {
1069
- private logs;
1070
- private uiBlockId;
1071
- private clientId;
1072
- private sendMessage;
1073
- private currentLogLevel;
1074
- constructor(clientId: string, sendMessage: (message: Message) => void, uiBlockId?: string);
1407
+ interface ExecutedToolInfo {
1408
+ id: string;
1409
+ name: string;
1410
+ params: any;
1411
+ result: {
1412
+ _totalRecords: number;
1413
+ _recordsShown: number;
1414
+ _metadata?: any;
1415
+ _sampleData: any[];
1416
+ /** Bounded summary over the FULL fetched result (complete structure). */
1417
+ _summary?: any;
1418
+ /** Up to MAIN_AGENT_COMPLETE_ROWS rows — the complete result when small. */
1419
+ _mainAgentRows?: any[];
1420
+ };
1421
+ outputSchema?: any;
1422
+ sourceSchema?: string;
1423
+ sourceType?: string;
1424
+ }
1425
+
1426
+ /**
1427
+ * Multi-Agent Architecture Types
1428
+ *
1429
+ * Defines interfaces for the hierarchical agent system:
1430
+ * - Main Agent: ONE LLM.streamWithTools() call with source agent tools
1431
+ * - Source Agents: independent agents that query individual data sources
1432
+ *
1433
+ * The main agent sees only source summaries. When it calls a source tool,
1434
+ * the SourceAgent runs independently (own LLM, own retries) and returns clean data.
1435
+ */
1436
+
1437
+ /**
1438
+ * Per-entity detail: name, row count, and column names.
1439
+ * Gives the main agent enough context to route to the right source.
1440
+ */
1441
+ interface EntityDetail {
1442
+ /** Entity name (table, sheet, endpoint) */
1443
+ name: string;
1444
+ /** Approximate row count */
1445
+ rowCount?: number;
1446
+ /** Column/field names */
1447
+ columns: string[];
1448
+ /** Entity-level semantic summary (what the table means) — for main-agent routing. */
1449
+ summary?: string;
1450
+ }
1451
+ /**
1452
+ * Representation of a data source for the main agent.
1453
+ * Contains entity names WITH column names so the LLM can route accurately.
1454
+ */
1455
+ interface SourceSummary {
1456
+ /** Source ID (matches tool ID prefix) */
1457
+ id: string;
1458
+ /** Human-readable source name */
1459
+ name: string;
1460
+ /** Source type: postgres, excel, rest_api, etc. */
1461
+ type: string;
1462
+ /** Brief description of what data this source contains */
1463
+ description: string;
1464
+ /** Detailed entity info with column names for routing */
1465
+ entityDetails: EntityDetail[];
1466
+ /** The tool ID associated with this source */
1467
+ toolId: string;
1468
+ }
1469
+ /**
1470
+ * What a source agent returns after querying its data source.
1471
+ * The main agent uses this to analyze and compose the final response.
1472
+ */
1473
+ interface SourceAgentResult {
1474
+ /** Source ID */
1475
+ sourceId: string;
1476
+ /** Source name */
1477
+ sourceName: string;
1478
+ /** Whether the query succeeded */
1479
+ success: boolean;
1480
+ /** Result data rows */
1481
+ data: any[];
1482
+ /** Metadata about the query execution */
1483
+ metadata: SourceAgentMetadata;
1484
+ /** Tool execution info for the last successful query (backward compat) */
1485
+ executedTool: ExecutedToolInfo;
1486
+ /** All successful tool executions (primary + follow-up queries) */
1487
+ allExecutedTools?: ExecutedToolInfo[];
1488
+ /** Error message if failed */
1489
+ error?: string;
1490
+ }
1491
+ interface SourceAgentMetadata {
1492
+ /** Total rows that matched the query (before limit) */
1493
+ totalRowsMatched: number;
1494
+ /** Rows actually returned (after limit) */
1495
+ rowsReturned: number;
1496
+ /** Whether the result was truncated by the row limit */
1497
+ isLimited: boolean;
1498
+ /** The query/params that were executed */
1499
+ queryExecuted?: string;
1500
+ /** Execution time in milliseconds */
1501
+ executionTimeMs: number;
1502
+ }
1503
+ /**
1504
+ * A pre-built, multi-step UI flow registered with the SDK.
1505
+ *
1506
+ * When the main agent decides a user's question matches a workflow's whenToUse
1507
+ * trigger, it picks the workflow instead of running source agents / generating
1508
+ * dashboard components. The LLM extracts the workflow's required props from the
1509
+ * prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
1510
+ * workflow component directly — no analysis text, no chart generation. The
1511
+ * frontend renders the registered workflow component with the LLM-extracted
1512
+ * props.
1513
+ */
1514
+ interface WorkflowDescriptor {
1515
+ /** Unique workflow id (used as the LLM tool name) */
1516
+ id: string;
1517
+ /** Component name on the frontend (matches the registered React component) */
1518
+ name: string;
1519
+ /** Short human-readable description of what this workflow does */
1520
+ description: string;
1075
1521
  /**
1076
- * Check if logging is enabled (uiBlockId is provided)
1522
+ * 1–2 sentence trigger condition. The LLM uses this to decide if the
1523
+ * user's prompt matches this workflow. Be specific — e.g.
1524
+ * "User wants to *initiate* an inventory transfer (review + submit POs),
1525
+ * not just see analysis or charts."
1077
1526
  */
1078
- isEnabled(): boolean;
1527
+ whenToUse: string;
1079
1528
  /**
1080
- * Check if a message should be logged based on current log level
1529
+ * JSON-schema-style description of the props the workflow needs. Becomes
1530
+ * the LLM tool's input_schema, so the model fills these from the prompt.
1531
+ * Use the same shape as `params` on direct tools — string descriptors with
1532
+ * an optional "(optional)" suffix.
1533
+ *
1534
+ * Example:
1535
+ * ```
1536
+ * {
1537
+ * selectedStore: 'object — { id, name } of the source branch',
1538
+ * minROI: 'number (optional) — only show transfers with ROI ≥ this',
1539
+ * }
1540
+ * ```
1081
1541
  */
1082
- private shouldLog;
1542
+ propsSchema: Record<string, string>;
1083
1543
  /**
1084
- * Add a log entry with timestamp and immediately send to runtime
1085
- * Only logs that pass the log level filter are captured and sent
1544
+ * Optional: static prop defaults merged with LLM-extracted props before
1545
+ * the component is returned. Useful for things like the embedded
1546
+ * `externalTool` config that the workflow uses to fetch its own data.
1086
1547
  */
1087
- private addLog;
1548
+ defaultProps?: Record<string, any>;
1549
+ }
1550
+ /**
1551
+ * The workflow selection captured during a routing call.
1552
+ * Set on AgentResponse when the LLM picks a workflow tool.
1553
+ */
1554
+ interface SelectedWorkflow {
1555
+ /** Component name (matches WorkflowDescriptor.name) */
1556
+ name: string;
1557
+ /** Props extracted from the prompt + merged with workflow.defaultProps */
1558
+ props: Record<string, any>;
1559
+ }
1560
+ /**
1561
+ * The complete response from the multi-agent system.
1562
+ * Contains everything needed for text display + component generation.
1563
+ */
1564
+ interface AgentResponse {
1565
+ /** Generated text response (analysis of the data) */
1566
+ text: string;
1567
+ /** All executed tools across all source agents (for component generation) */
1568
+ executedTools: ExecutedToolInfo[];
1569
+ /** Individual results from each source agent */
1570
+ sourceResults: SourceAgentResult[];
1571
+ /**
1572
+ * Populated when MainAgent wrote AND successfully executed a script during its turn.
1573
+ * Caller (agent-user-response.ts) persists it via ScriptStore.save().
1574
+ * Absent when MainAgent didn't write one (trivial question / all attempts failed).
1575
+ */
1576
+ savedScript?: AgentWrittenScript;
1577
+ /**
1578
+ * Set when the LLM routed the question to a registered workflow component.
1579
+ * When present, the upstream caller should skip component generation and
1580
+ * return this workflow as the response.
1581
+ */
1582
+ workflow?: SelectedWorkflow;
1583
+ }
1584
+ /**
1585
+ * A script MainAgent authored + verified during its turn. Shape aligns with
1586
+ * what ScriptStore.save() needs — minus store-assigned fields (id, timestamps, counts).
1587
+ */
1588
+ interface AgentWrittenScript {
1589
+ /**
1590
+ * `ScriptRecipe.id` of the draft that was authored + verified during this turn.
1591
+ * The caller passes this to `ScriptStore.promoteToVerified(recipeId, …)` to
1592
+ * flip the draft to verified status and (when possible) drop the turn-suffix
1593
+ * from its filename.
1594
+ */
1595
+ recipeId: string;
1596
+ name: string;
1597
+ intentDescription: string;
1598
+ tags: string[];
1599
+ parameters: Array<{
1600
+ name: string;
1601
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
1602
+ required: boolean;
1603
+ default?: any;
1604
+ enumValues?: Record<string, string>;
1605
+ description: string;
1606
+ }>;
1607
+ scriptBody: string;
1608
+ /** Source IDs referenced by the script (extracted from ctx.query calls) */
1609
+ sourceIds: string[];
1610
+ /** Tables referenced in the script's SQL (regex-extracted) */
1611
+ tables: string[];
1612
+ /** Executed queries from the verified run — fed to component generation */
1613
+ executedQueries: Array<{
1614
+ sourceId: string;
1615
+ sourceName: string;
1616
+ sql: string;
1617
+ data: any[];
1618
+ count: number;
1619
+ totalCount?: number;
1620
+ executionTimeMs: number;
1621
+ /**
1622
+ * True for synthetic entries (ctx.emit datasets, the computed:_final
1623
+ * post-JS data). The component generator routes virtual sources through
1624
+ * the script_dataset sentinel toolId so the frontend resolves them via
1625
+ * queryCache instead of attempting to re-execute SQL.
1626
+ */
1627
+ virtual?: boolean;
1628
+ }>;
1629
+ }
1630
+ /**
1631
+ * Configuration for the multi-agent system.
1632
+ * Controls limits, models, and behavior.
1633
+ */
1634
+ interface AgentConfig {
1635
+ /** Max rows shown to the UI preview / inlined per source (default: 10) */
1636
+ maxRowsPerSource: number;
1637
+ /**
1638
+ * Max rows a source query may FETCH from the DB server-side (default: 2000).
1639
+ * Decoupled from what the main agent is shown: the full result is fetched and
1640
+ * summarized (bounded), but only a small/complete slice enters LLM context.
1641
+ * This lets small lookups (benchmark maps) arrive COMPLETE without letting
1642
+ * large results blow up context.
1643
+ */
1644
+ maxRowsFetched: number;
1645
+ /** Model for the main agent (routing + analysis in one LLM call) */
1646
+ mainAgentModel: string;
1647
+ /** Model for source agent query generation */
1648
+ sourceAgentModel: string;
1649
+ /** API key for LLM calls */
1650
+ apiKey?: string;
1651
+ /** Max retry attempts per source agent */
1652
+ maxRetries: number;
1653
+ /** Max tool calling iterations for the main agent loop */
1654
+ maxIterations: number;
1655
+ /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
1656
+ globalKnowledgeBase?: string;
1657
+ /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
1658
+ knowledgeBaseContext?: string;
1659
+ /** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
1660
+ collections?: any;
1661
+ /** Optional project ID for scoping embedding searches */
1662
+ projectId?: string;
1663
+ }
1664
+ /**
1665
+ * Default agent configuration
1666
+ */
1667
+ declare const DEFAULT_AGENT_CONFIG: AgentConfig;
1668
+
1669
+ /**
1670
+ * Script Flow Types
1671
+ *
1672
+ * Defines interfaces for the script-based query architecture:
1673
+ * - ScriptRecipe: metadata for matching, validation, and quality tracking
1674
+ * - ScriptResult: output from executing a script
1675
+ * - ScriptMatch: result from the LLM-based script matcher
1676
+ */
1677
+ /**
1678
+ * Recipe metadata stored alongside each script.
1679
+ * Used for matching, validation, and quality tracking.
1680
+ */
1681
+ interface ScriptRecipe {
1682
+ /** Unique script identifier */
1683
+ id: string;
1684
+ /** Version number (incremented on regeneration) */
1685
+ version: number;
1686
+ /** Human-readable name (e.g., "Revenue by Dimension") */
1687
+ name: string;
1688
+ /** Natural language description of what this script does */
1689
+ intentDescription: string;
1690
+ /** Keyword tags for quick filtering */
1691
+ tags: string[];
1692
+ /** Source tool IDs this script queries (e.g., ["mssql-abc123_query"]) */
1693
+ sourceIds: string[];
1694
+ /** Table names used (for future schema drift detection) */
1695
+ tables: string[];
1696
+ /** Parameter definitions — what can vary */
1697
+ parameters: ScriptParameter[];
1698
+ /** The script function body as a string. Loaded from disk (scripts-store/<fileBase>.ts). */
1699
+ scriptBody: string;
1700
+ /**
1701
+ * On-disk filename stem for the body: scripts-store/<fileBase>.ts.
1702
+ * Editable in the IDE. Decided at authoring time (slug of `name`, with a
1703
+ * short id suffix on collision) and stable across promotion.
1704
+ */
1705
+ fileBase?: string;
1706
+ /** sha256 of the on-disk body — lets the runtime detect manual edits. */
1707
+ bodyHash?: string;
1708
+ /** Project scope (single-VM deployments may leave this undefined). */
1709
+ projectId?: string;
1710
+ /** Times this script was used successfully */
1711
+ successCount: number;
1712
+ /** Times this script failed */
1713
+ failureCount: number;
1714
+ /** ISO timestamp of last usage */
1715
+ lastUsed: string;
1716
+ /** Original user question that created this script */
1717
+ createdFrom: string;
1718
+ /** ISO timestamp */
1719
+ createdAt: string;
1720
+ /** ISO timestamp */
1721
+ updatedAt: string;
1722
+ /**
1723
+ * `recipe.id` of the parent this script was forked from.
1724
+ * Undefined for root scripts (those written from scratch by MainAgent).
1725
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md.
1726
+ */
1727
+ parentId?: string;
1728
+ /** 0 for root scripts; `parent.forkDepth + 1` for forks. Capped at 3. */
1729
+ forkDepth?: number;
1730
+ /**
1731
+ * Brief description of what this fork changed vs its parent
1732
+ * (sourced from the matcher's `modificationHint`).
1733
+ */
1734
+ forkReason?: string;
1735
+ /**
1736
+ * Validated component specs captured at authoring time. On a tier-high
1737
+ * replay these are rebound to fresh queryIds deterministically — no
1738
+ * component-generation LLM call, and the rendered columns can't drift from
1739
+ * what was validated when the script was authored. Absent on recipes
1740
+ * authored before this landed; those fall back to LLM component generation.
1741
+ * See backend/docs/SCRIPT-COMPONENT-CONSISTENCY.md.
1742
+ */
1743
+ components?: ScriptComponentSpec[];
1744
+ /**
1745
+ * Lifecycle stage of this recipe on disk.
1746
+ * - 'draft': written by MainAgent's write_script during a turn; filtered out
1747
+ * of FTS results (status='verified' only) so the matcher never picks it.
1748
+ * Filename is suffixed with `turnId` to keep concurrent turns
1749
+ * from clobbering each other's drafts.
1750
+ * - 'verified': promoted after `execute_script` succeeded; the matcher sees it.
1751
+ * Filename drops the turn suffix unless a verified file with
1752
+ * the same slug already exists (collision case keeps the suffix).
1753
+ *
1754
+ * Recipes loaded from disk without this field default to 'verified' so
1755
+ * existing scripts keep working unchanged.
1756
+ */
1757
+ status?: 'draft' | 'verified';
1758
+ /**
1759
+ * Per-turn unique suffix used for draft filenames (e.g. `1714745623-x9k2`).
1760
+ * Set when the draft is saved; carried until the recipe is promoted.
1761
+ */
1762
+ turnId?: string;
1763
+ /**
1764
+ * Last execution error captured by `recordDraftError` while the recipe was
1765
+ * still a draft. Lets users open the draft .json file and see why it failed
1766
+ * without grepping logs. Cleared on promotion to 'verified'.
1767
+ */
1768
+ lastError?: {
1769
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
1770
+ message: string;
1771
+ at: string;
1772
+ attempt: number;
1773
+ };
1774
+ }
1775
+ interface ScriptParameter {
1776
+ /** Parameter name (used in script body as params.name) */
1777
+ name: string;
1778
+ /** Parameter type */
1779
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
1780
+ /** Whether this parameter is required */
1781
+ required: boolean;
1782
+ /** Default value if not provided */
1783
+ default?: any;
1784
+ /** For enum type — maps user-facing values to internal values */
1785
+ enumValues?: Record<string, string>;
1786
+ /** Human-readable description (used in the matcher LLM prompt) */
1787
+ description: string;
1788
+ }
1789
+ /**
1790
+ * A reusable component binding captured when a script is authored. Stored on
1791
+ * the recipe so tier-high replays rebuild components deterministically (rebind
1792
+ * to fresh queryIds) instead of re-running the component-picker LLM.
1793
+ */
1794
+ interface ScriptComponentSpec {
1795
+ /** Registered component name (e.g. "DynamicBarChart") — matched against the available component library. */
1796
+ componentType: string;
1797
+ /** `executedQuery.sourceId` to bind to (e.g. a tool id or 'computed:_final'), 'federation' for a cross-source component, or 'markdown' for a content-only narrative block (no data source). */
1798
+ sourceRef: string;
1799
+ /** Present only when sourceRef === 'federation' — the DuckDB SQL to re-execute on replay. */
1800
+ federationSql?: string;
1801
+ /** Present only when sourceRef === 'markdown' — the narrative text to render on replay (markdown has no data source, so its content must be persisted). */
1802
+ content?: string;
1803
+ title?: string;
1804
+ description?: string;
1805
+ /** Validated axis/value keys + aggregation — all referencing real columns of the bound source. */
1806
+ config: Record<string, any>;
1807
+ }
1808
+ /**
1809
+ * Result from executing a script via ScriptRunner.
1810
+ */
1811
+ interface ScriptResult {
1812
+ /** Whether the script executed successfully */
1813
+ success: boolean;
1814
+ /** Combined data from all queries */
1815
+ data: any[];
1816
+ /** Individual query results tracked during execution */
1817
+ executedQueries: ScriptQueryResult[];
1818
+ /** Error message if failed */
1819
+ error?: string;
1820
+ /**
1821
+ * Where in the lifecycle the error occurred. Lets MainAgent's fix-loop
1822
+ * decide between "rewrite the whole draft" (compile) and "patch the
1823
+ * specific line" (runtime).
1824
+ */
1825
+ errorPhase?: 'compile' | 'runtime' | 'timeout' | 'ipc';
1826
+ /** Total execution time in milliseconds */
1827
+ executionTimeMs: number;
1828
+ }
1829
+ /**
1830
+ * A single query executed during script runtime.
1831
+ * Tracked by ScriptContext for component generation and debugging.
1832
+ */
1833
+ interface ScriptQueryResult {
1834
+ /** Source tool ID */
1835
+ sourceId: string;
1836
+ /** Human-readable source name */
1837
+ sourceName: string;
1838
+ /** The SQL that was executed */
1839
+ sql: string;
1840
+ /** Result data rows */
1841
+ data: any[];
1842
+ /** Number of rows returned */
1843
+ count: number;
1844
+ /** Total rows that matched before limit (if available) */
1845
+ totalCount?: number;
1846
+ /** Query execution time in milliseconds */
1847
+ executionTimeMs: number;
1848
+ /**
1849
+ * True for rows that did NOT come from a real SQL execution — either a
1850
+ * ctx.emit() dataset or the synthesized "computed:_final" entry that
1851
+ * carries the script's post-JS returned data. The component generator
1852
+ * uses this to route the resulting component through the script_dataset
1853
+ * sentinel toolId so the frontend resolves it via the queryCache short-circuit.
1854
+ */
1855
+ virtual?: boolean;
1856
+ }
1857
+ /**
1858
+ * Match tier returned by the LLM script matcher.
1859
+ *
1860
+ * - 'high': the script answers the question directly; only parameter values
1861
+ * may differ. The runtime replays it with extracted params (cheapest path).
1862
+ * - 'near': the script answers a STRUCTURALLY similar question but needs
1863
+ * body modification (different metric, dimension, table, filter shape).
1864
+ * The runtime forks the parent and adapts the body via MainAgent's normal
1865
+ * write_script + execute_script loop — no SourceAgent dispatch needed.
1866
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md for the full design.
1867
+ * - 'none': no script is relevant; full agent flow runs.
1868
+ */
1869
+ type MatchTier = 'high' | 'near' | 'none';
1870
+ /**
1871
+ * Result from the LLM-based script matcher.
1872
+ *
1873
+ * For `tier: 'high'`, `extractedParams` carries the values to pass to the
1874
+ * existing script. For `tier: 'near'`, `gaps` and `modificationHint` describe
1875
+ * what the fork-author needs to change in the parent body.
1876
+ */
1877
+ interface ScriptMatch {
1878
+ /** The matched script recipe */
1879
+ recipe: ScriptRecipe;
1880
+ /** Match tier — see MatchTier docs */
1881
+ tier: MatchTier;
1882
+ /** Similarity score (0-1, derived from LLM tier) */
1883
+ similarity: number;
1884
+ /**
1885
+ * Legacy confidence level. Mirrors `tier === 'high'`/`'near'` for now;
1886
+ * kept so existing callers compile while we migrate to tier-based logic.
1887
+ */
1888
+ confidence: 'high' | 'medium';
1889
+ /** Parameters extracted from the user question by the LLM (tier='high') */
1890
+ extractedParams?: Record<string, any>;
1891
+ /** What the user question needs that the parent doesn't cover (tier='near') */
1892
+ gaps?: string[];
1893
+ /** One-sentence description of the change the fork-author should make (tier='near') */
1894
+ modificationHint?: string;
1895
+ /** Why the matcher made this choice (for logs and telemetry) */
1896
+ reasoning?: string;
1897
+ }
1898
+
1899
+ /**
1900
+ * ScriptRecipeStore — injected metadata backend for the script flow.
1901
+ *
1902
+ * The SDK is standalone (no DB dependency). The backend implements this
1903
+ * interface over Postgres (full-text search + atomic counters) and injects it
1904
+ * via `collections['script-recipes']`, exactly like `collections['source-embeddings']`.
1905
+ * `ScriptStore` consumes it for all METADATA operations while keeping the
1906
+ * executable body on disk as scripts-store/<fileBase>.ts.
1907
+ *
1908
+ * All metadata rows are plain JSON (no scriptBody — that lives on disk).
1909
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md (#1, #3, #7).
1910
+ */
1911
+
1912
+ /** One recipe's metadata as stored in Postgres (mirrors the script_recipes table). */
1913
+ interface ScriptRecipeMetaRow {
1914
+ id: string;
1915
+ projectId?: string | null;
1916
+ version: number;
1917
+ name: string;
1918
+ intentDescription: string;
1919
+ tags: string[] | null;
1920
+ createdFrom: string | null;
1921
+ sourceIds: string[] | null;
1922
+ tables: string[] | null;
1923
+ parameters: ScriptParameter[] | null;
1924
+ components?: ScriptComponentSpec[] | null;
1925
+ fileBase: string;
1926
+ bodyHash?: string | null;
1927
+ successCount: number;
1928
+ failureCount: number;
1929
+ lastUsed: string | null;
1930
+ parentId?: string | null;
1931
+ forkDepth?: number | null;
1932
+ forkReason?: string | null;
1933
+ status: 'draft' | 'verified' | string;
1934
+ turnId?: string | null;
1935
+ lastError?: {
1936
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
1937
+ message: string;
1938
+ at: string;
1939
+ attempt: number;
1940
+ } | null;
1941
+ createdAt?: string | null;
1942
+ updatedAt?: string | null;
1943
+ }
1944
+ interface ScriptRecipeStore {
1945
+ /** FTS shortlist of healthy verified recipes for the matcher (metadata only). */
1946
+ search(params: {
1947
+ prompt: string;
1948
+ projectId?: string;
1949
+ limit?: number;
1950
+ }): Promise<ScriptRecipeMetaRow[]>;
1951
+ /** Fetch one recipe by id (any status). */
1952
+ getById(id: string): Promise<ScriptRecipeMetaRow | null>;
1953
+ /** Count healthy verified recipes (drives the "any scripts?" gate). */
1954
+ count(params?: {
1955
+ projectId?: string;
1956
+ }): Promise<number>;
1957
+ /** Insert or update a recipe row (keyed by id). */
1958
+ upsert(row: ScriptRecipeMetaRow): Promise<void>;
1959
+ /** Atomically bump counters / last-used. */
1960
+ updateStats(id: string, patch: {
1961
+ successDelta?: number;
1962
+ failureDelta?: number;
1963
+ lastUsed?: string;
1964
+ }): Promise<void>;
1965
+ /** Flip a draft to verified, applying provenance + optional fork lineage. */
1966
+ promote(id: string, patch: {
1967
+ sourceIds: string[];
1968
+ tables: string[];
1969
+ fileBase?: string;
1970
+ parentId?: string;
1971
+ forkDepth?: number;
1972
+ forkReason?: string;
1973
+ components?: ScriptComponentSpec[];
1974
+ }): Promise<ScriptRecipeMetaRow | null>;
1975
+ /** Stamp a draft's last execution error. */
1976
+ recordDraftError(id: string, err: {
1977
+ phase: string;
1978
+ message: string;
1979
+ attempt: number;
1980
+ at: string;
1981
+ }): Promise<void>;
1982
+ /** Delete a recipe row (body file removed separately). */
1983
+ remove(id: string): Promise<void>;
1984
+ /** True if `fileBase` is taken by a different recipe in this project. */
1985
+ fileBaseTaken(fileBase: string, excludeId: string, projectId?: string): Promise<boolean>;
1986
+ }
1987
+ /** Pull the injected store off the collections bag (or null if not wired). */
1988
+ declare function resolveScriptRecipeStore(collections: any): ScriptRecipeStore | null;
1989
+
1990
+ /**
1991
+ * ScriptStore — Postgres metadata + on-disk body for script recipes.
1992
+ *
1993
+ * Split of responsibilities:
1994
+ * - METADATA → injected `ScriptRecipeStore` (Postgres FTS + atomic counters),
1995
+ * resolved from `collections['script-recipes']`.
1996
+ * - BODY → scripts-store/<fileBase>.ts, editable in your IDE. Written
1997
+ * atomically (temp + rename); `bodyHash` (sha256) detects edits.
1998
+ *
1999
+ * The old "read every file every turn + send the whole catalog to the LLM"
2000
+ * matcher is gone — matching is `store.search(prompt)` (FTS shortlist). The
2001
+ * draft/verified filename dance is gone too: `status` is a DB column and the
2002
+ * file keeps a stable `<fileBase>.ts` name across promotion.
2003
+ *
2004
+ * When no metadata store is injected, the store degrades to a safe no-op
2005
+ * (count 0 → script flow disabled) instead of crashing.
2006
+ *
2007
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md.
2008
+ */
2009
+
2010
+ interface SaveDraftInput {
2011
+ /** Reuse an existing draft (retry); omit to mint a new one. */
2012
+ recipeId?: string;
2013
+ /** Per-turn unique suffix, stable across retries within the turn. */
2014
+ turnId: string;
2015
+ name: string;
2016
+ intentDescription: string;
2017
+ tags: string[];
2018
+ parameters: ScriptParameter[];
2019
+ scriptBody: string;
2020
+ createdFrom: string;
2021
+ }
2022
+ interface PromoteToVerifiedInput {
2023
+ sourceIds: string[];
2024
+ tables: string[];
2025
+ parentId?: string;
2026
+ forkDepth?: number;
2027
+ forkReason?: string;
2028
+ components?: ScriptComponentSpec[];
2029
+ }
2030
+ interface ScriptStoreOptions {
2031
+ /** Explicit metadata store, or resolved from `collections['script-recipes']`. */
2032
+ store?: ScriptRecipeStore | null;
2033
+ collections?: any;
2034
+ /** Body directory (defaults to <cwd>/scripts-store). */
2035
+ baseDir?: string;
2036
+ /** Project scope stamped on every row. */
2037
+ projectId?: string;
2038
+ }
2039
+ /**
2040
+ * Normalize a scriptBody into the on-disk form (strip a leading comment block,
2041
+ * ensure `export async function getData`). Exported for MainAgent.
2042
+ */
2043
+ declare function normalizeScriptBody(scriptBody: string): string;
2044
+ declare class ScriptStore {
2045
+ private store;
2046
+ private storeDir;
2047
+ private projectId?;
2048
+ constructor(opts?: ScriptStoreOptions);
2049
+ /** Whether a metadata store is wired (matcher / authoring are gated on this). */
2050
+ hasStore(): boolean;
2051
+ /** Number of healthy verified recipes (gates the script-matching path). */
2052
+ count(): Promise<number>;
2053
+ /**
2054
+ * FTS shortlist for the matcher (metadata only — bodies are loaded lazily by
2055
+ * `get()` once the LLM picks one). Returns verified, healthy recipes ranked
2056
+ * by relevance.
2057
+ */
2058
+ search(prompt: string, limit?: number): Promise<ScriptRecipe[]>;
2059
+ /** Fetch one recipe by id with its body loaded from disk. */
2060
+ get(id: string): Promise<ScriptRecipe | null>;
2061
+ /** Create or update a recipe (metadata upsert + body write when changed). */
2062
+ save(recipe: ScriptRecipe): Promise<void>;
2063
+ /**
2064
+ * Persist (or update) a draft. Within a turn, retries that pass the same
2065
+ * `recipeId` overwrite the same row + file; a fresh `recipeId` mints a new
2066
+ * draft. The body is visible at scripts-store/<fileBase>.ts immediately.
2067
+ */
2068
+ saveDraft(input: SaveDraftInput): Promise<ScriptRecipe>;
2069
+ /** Stamp a draft's last execution error (metadata only). */
2070
+ recordDraftError(recipeId: string, err: {
2071
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2072
+ message: string;
2073
+ attempt: number;
2074
+ }): Promise<void>;
2075
+ /**
2076
+ * Promote a successfully-executed draft into a verified script.
2077
+ * The on-disk body already exists at <fileBase>.ts (written at write_script
2078
+ * time) and keeps its name — only the DB row flips status + provenance.
2079
+ */
2080
+ promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): Promise<ScriptRecipe | null>;
2081
+ /**
2082
+ * Drop a draft (row + body file). MainAgent calls this at end-of-turn when a
2083
+ * draft was authored but never verified — failed drafts are never matched, so
2084
+ * deleting them immediately avoids unbounded accumulation (#5). No-op if the
2085
+ * recipe isn't a draft (so a promoted/verified script is never removed here).
2086
+ */
2087
+ discardDraft(recipeId: string): Promise<void>;
2088
+ /** Delete a recipe (row + body file). */
2089
+ delete(id: string): Promise<void>;
2090
+ /** Record a successful execution (atomic counter bump). */
2091
+ recordSuccess(id: string): Promise<void>;
2092
+ /** Record a failed execution (atomic counter bump). */
2093
+ recordFailure(id: string): Promise<void>;
2094
+ /** Absolute path to the .ts body for a recipe (used by the runner/MainAgent). */
2095
+ getScriptPath(recipe: ScriptRecipe): string;
2096
+ private removeById;
2097
+ private rowToRecipe;
2098
+ private recipeToRow;
2099
+ /** slug of name, with a short id suffix when the bare slug is already taken. */
2100
+ private computeFileBase;
2101
+ private toSlug;
2102
+ private hash;
2103
+ private bodyPath;
2104
+ private readBody;
2105
+ /** Atomic body write (temp + rename) so concurrent reads never see a partial file. */
2106
+ private writeBody;
2107
+ private unlinkBody;
2108
+ }
2109
+
2110
+ /**
2111
+ * Main Agent (Orchestrator)
2112
+ *
2113
+ * A single LLM.streamWithTools() call that handles everything:
2114
+ * - Routing: decides which source(s) to query based on summaries
2115
+ * - Querying: calls source tools (each wraps an independent SourceAgent)
2116
+ * - Direct tools: calls pre-built function tools directly with LLM-provided params
2117
+ * - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
2118
+ * - Analysis: generates final text response from the data
2119
+ *
2120
+ * Two tool types:
2121
+ * - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
2122
+ * - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
2123
+ */
2124
+
2125
+ declare class MainAgent {
2126
+ private externalTools;
2127
+ private workflows;
2128
+ private config;
2129
+ private streamBuffer;
2130
+ /**
2131
+ * Optional: when provided, MainAgent exposes the `write_script` /
2132
+ * `execute_script` tools to the LLM and persists drafts to disk via the
2133
+ * store. Headless callers (alert analyzer, metric resolver) omit these to
2134
+ * suppress script authoring entirely — drafts would otherwise leak onto
2135
+ * disk with no caller to promote or clean them up.
2136
+ */
2137
+ private scriptStore;
2138
+ private turnId;
2139
+ private createdFromPrompt;
2140
+ private scriptState;
2141
+ /**
2142
+ * Fork mode — set when this turn is adapting a near-matching parent script.
2143
+ * In fork mode there is no legitimate "answer with bare text" outcome: the
2144
+ * only correct first move is a tool call (write_script, or a source tool for
2145
+ * schema discovery). We therefore force tool use on the first LLM iteration
2146
+ * so the model can't end its turn with a bare "I'll adapt…" preamble and zero
2147
+ * tool calls. Never set on the fresh-authoring / general-question path.
2148
+ */
2149
+ private forkMode;
2150
+ /**
2151
+ * Per-turn cancellation signal (user hit "Stop"). Set at the top of
2152
+ * handleQuestion and read by the tool handler, the SourceAgent dispatch, and
2153
+ * the script subprocess so an abort tears down every layer of the turn.
2154
+ */
2155
+ private abortSignal?;
2156
+ constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[], forkMode?: boolean);
2157
+ private get scriptingEnabled();
2158
+ /**
2159
+ * Handle a user question using the multi-agent system.
2160
+ *
2161
+ * This is ONE LLM.streamWithTools() call. The LLM:
2162
+ * 1. Sees source summaries + direct tool descriptions in system prompt
2163
+ * 2. Decides which tool(s) to call (routing)
2164
+ * 3. Source tools → SourceAgent runs independently → returns data
2165
+ * 4. Direct tools → fn() called directly with LLM params → returns data
2166
+ * 5. Generates final analysis text
2167
+ */
2168
+ handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, signal?: AbortSignal): Promise<AgentResponse>;
2169
+ private handleWriteScript;
2170
+ private handleExecuteScript;
2171
+ /**
2172
+ * Build the AgentWrittenScript payload the caller will hand to
2173
+ * `ScriptStore.promoteToVerified()`. Only returned when a verified
2174
+ * successful execution is on record.
2175
+ */
2176
+ private buildSavedScript;
2177
+ private normalizeParameterList;
2178
+ /**
2179
+ * Use the schema embedding collection to pre-select relevant tables for
2180
+ * this source + intent. Returns a formatted schema block if confidence is
2181
+ * high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
2182
+ *
2183
+ * When this returns a block, we can skip the SourceAgent's `search_schema`
2184
+ * loop and reduce iteration budget. When it returns null, the SourceAgent
2185
+ * falls back to the existing LLM-driven keyword search (same as today).
2186
+ */
2187
+ private preResolveSchema;
2188
+ /**
2189
+ * Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
2190
+ */
2191
+ private handleDirectTool;
2192
+ /**
2193
+ * Build the main agent's system prompt with source summaries, direct tool descriptions,
2194
+ * and workflow component descriptions.
2195
+ */
2196
+ private buildSystemPrompt;
2197
+ /**
2198
+ * Build tool definitions for source tools — summary-only descriptions.
2199
+ * The full schema is inside the SourceAgent which runs independently.
2200
+ */
2201
+ private buildSourceToolDefinitions;
2202
+ /**
2203
+ * Build tool definitions for direct tools — expose their actual params.
2204
+ * These are called directly by the main agent LLM, no SourceAgent.
2205
+ */
2206
+ private buildDirectToolDefinitions;
2207
+ /**
2208
+ * Capture a workflow selection. We do NOT execute anything — the LLM has
2209
+ * already extracted the props it wants the workflow rendered with. We
2210
+ * record the selection (via the capture callback) and return a short
2211
+ * acknowledgement so the LLM ends its turn cleanly without writing
2212
+ * analysis text or calling more tools.
2213
+ */
2214
+ private handleWorkflow;
2215
+ /**
2216
+ * Build LLM tool definitions for workflow components. The workflow's
2217
+ * propsSchema becomes the tool's input_schema so the LLM extracts props
2218
+ * directly from the prompt — same mechanic as direct tools.
2219
+ */
2220
+ private buildWorkflowToolDefinitions;
2221
+ /**
2222
+ * Format a source agent's result as a clean string for the main agent LLM.
2223
+ */
2224
+ private formatResultForMainAgent;
2225
+ /**
2226
+ * Get source summaries (for external inspection/debugging).
2227
+ */
2228
+ getSourceSummaries(): SourceSummary[];
2229
+ }
2230
+
2231
+ /**
2232
+ * Represents an action that can be performed on a UIBlock
2233
+ */
2234
+ interface Action {
2235
+ id: string;
2236
+ name: string;
2237
+ type: string;
2238
+ [key: string]: any;
2239
+ }
2240
+
2241
+ type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
2242
+ interface LLMMessages {
2243
+ sys: SystemPrompt;
2244
+ user: string;
2245
+ prefill?: string;
2246
+ }
2247
+ interface LLMOptions {
2248
+ model?: string;
2249
+ maxTokens?: number;
2250
+ temperature?: number;
2251
+ topP?: number;
2252
+ apiKey?: string;
2253
+ baseURL?: string;
2254
+ partial?: (chunk: string) => void;
2255
+ /**
2256
+ * Per-request cancellation. When the caller aborts this signal (user hit
2257
+ * "Stop"), the underlying provider request is cancelled and the call throws
2258
+ * a RequestAbortedError. Threaded into the provider `messages.create` request
2259
+ * options and checked between tool-loop iterations. Currently honored on the
2260
+ * Anthropic path (the agent flow's default provider).
2261
+ */
2262
+ signal?: AbortSignal;
2263
+ /**
2264
+ * Forces a tool call on the FIRST iteration of streamWithTools only
2265
+ * (subsequent iterations revert to auto). Used by fork mode to stop the
2266
+ * model from ending its turn with a bare "I'll adapt the script…" preamble
2267
+ * and zero tool calls. `{ type: 'any' }` lets the model pick which tool
2268
+ * (write_script in the common case, a source tool for schema discovery);
2269
+ * `{ type: 'tool', name }` pins a specific tool. Honored on both the
2270
+ * Anthropic path and the OpenAI/OpenRouter path (mapped to OpenAI's
2271
+ * tool_choice: 'required' / a named function).
2272
+ */
2273
+ firstIterationToolChoice?: {
2274
+ type: 'any';
2275
+ } | {
2276
+ type: 'tool';
2277
+ name: string;
2278
+ };
2279
+ /**
2280
+ * Internal — set only by the OpenRouter wrappers when the target is a Claude
2281
+ * model. Tells the OpenAI-wire path to emit Anthropic `cache_control`
2282
+ * breakpoints (OpenRouter forwards them to Anthropic for prompt caching).
2283
+ * Never set for direct OpenAI/Groq calls, so their requests are unchanged.
2284
+ */
2285
+ _openrouterClaudeCaching?: boolean;
2286
+ /**
2287
+ * Internal — OpenRouter provider-routing preferences (forwarded as the
2288
+ * `provider` body field). Set by the OpenRouter wrappers to steer routing to
2289
+ * a fast backend (e.g. {sort:'throughput'}). Never set for direct OpenAI/Groq.
2290
+ */
2291
+ _openrouterProvider?: Record<string, unknown>;
2292
+ }
2293
+ interface Tool {
2294
+ name: string;
2295
+ description: string;
2296
+ input_schema: {
2297
+ type: string;
2298
+ properties: Record<string, any>;
2299
+ required?: string[];
2300
+ };
2301
+ }
2302
+ declare class LLM {
2303
+ static text(messages: LLMMessages, options?: LLMOptions): Promise<string>;
2304
+ static stream<T = string>(messages: LLMMessages, options?: LLMOptions, json?: boolean): Promise<T extends string ? string : any>;
2305
+ static streamWithTools(messages: LLMMessages, tools: Tool[], toolHandler: (toolName: string, toolInput: any) => Promise<any>, options?: LLMOptions, maxIterations?: number): Promise<string>;
2306
+ /**
2307
+ * Normalize system prompt to Anthropic format
2308
+ * Converts string to array format if needed
2309
+ * @param sys - System prompt (string or array of blocks)
2310
+ * @returns Normalized system prompt for Anthropic API
2311
+ */
2312
+ private static _normalizeSystemPrompt;
2313
+ /**
2314
+ * Strip unpaired UTF-16 surrogates from every text field of a message set.
2315
+ *
2316
+ * A lone surrogate (from mid-pair string slicing or corrupt source data)
2317
+ * serializes to a bare `\udXXX` escape that strict JSON parsers — including
2318
+ * the one on Anthropic's API — reject with "no low surrogate in string",
2319
+ * failing the whole request. Sanitizing here, at the single boundary every
2320
+ * provider call flows through, guarantees no request can carry one.
2321
+ */
2322
+ private static _sanitizeMessages;
2323
+ /**
2324
+ * Log cache usage metrics from Anthropic API response
2325
+ * Shows cache hits, costs, and savings
2326
+ */
2327
+ private static _logCacheUsage;
2328
+ /**
2329
+ * Parse model string to extract provider and model name
2330
+ * @param modelString - Format: "provider/model-name" or just "model-name"
2331
+ * @returns [provider, modelName]
2332
+ *
2333
+ * @example
2334
+ * "anthropic/claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"]
2335
+ * "groq/openai/gpt-oss-120b" → ["groq", "openai/gpt-oss-120b"]
2336
+ * "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
2337
+ */
2338
+ private static _parseModel;
2339
+ /**
2340
+ * Map an Anthropic model id (e.g. "claude-sonnet-4-5-20250929") to the OpenRouter slug
2341
+ * (e.g. "claude-sonnet-4.5"). OpenRouter slugs drop the date suffix and use dotted versions.
2342
+ */
2343
+ private static _toOpenRouterSlug;
2344
+ /**
2345
+ * Per-provider proxy base URL. Returns `${SUPERATOM_LLM_PROXY_URL}/<provider>`
2346
+ * when our Cloudflare LLM proxy is configured, else undefined (→ talk to the
2347
+ * provider directly, legacy behaviour). An explicit options.baseURL (e.g.
2348
+ * OpenRouter) always wins and is never overridden. See backend/docs/llm-proxy.md.
2349
+ */
2350
+ private static _proxyBaseURL;
2351
+ private static _openrouterOptions;
2352
+ private static _isRetryableProviderError;
2353
+ private static _withOpenrouterRetry;
2354
+ private static _openrouterText;
2355
+ private static _openrouterStream;
2356
+ private static _openrouterStreamWithTools;
2357
+ /**
2358
+ * Build an Anthropic client. Routes through our Cloudflare LLM proxy when
2359
+ * SUPERATOM_LLM_PROXY_URL is set (each client ships a per-client proxy key as
2360
+ * ANTHROPIC_API_KEY and never holds the real key); otherwise talks to
2361
+ * api.anthropic.com directly. See backend/docs/llm-proxy.md.
2362
+ */
2363
+ private static _anthropicClient;
2364
+ /** True when OpenRouter is configured as a fail-open fallback for Claude. */
2365
+ private static _openrouterAvailable;
2366
+ /** Remap an Anthropic model id to the OpenRouter model path for fail-open. */
2367
+ private static _anthropicFallbackModel;
2368
+ private static _anthropicText;
2369
+ private static _anthropicStream;
2370
+ private static _anthropicStreamWithTools;
2371
+ private static _groqText;
2372
+ private static _groqStream;
2373
+ /**
2374
+ * Gemini request options carrying the proxy base URL, or undefined → talk to
2375
+ * generativelanguage.googleapis.com directly. The Google SDK takes baseUrl as a
2376
+ * per-model request option, not a constructor arg. See backend/docs/llm-proxy.md.
2377
+ */
2378
+ private static _geminiRequestOptions;
2379
+ private static _geminiText;
2380
+ private static _geminiStream;
2381
+ /**
2382
+ * Recursively strip unsupported JSON Schema properties for Gemini
2383
+ * Gemini doesn't support: additionalProperties, $schema, etc.
2384
+ */
2385
+ private static _cleanSchemaForGemini;
2386
+ private static _geminiStreamWithTools;
2387
+ /** True for Anthropic/Claude model ids — gates OpenRouter prompt caching. */
2388
+ private static _isClaudeModel;
2389
+ /**
2390
+ * Build the OpenAI-wire system message. For OpenRouter + Claude
2391
+ * (cacheClaude=true) it emits content parts carrying Anthropic
2392
+ * `cache_control` breakpoints (preserving any the caller set, else marking
2393
+ * the last block), so OpenRouter forwards them to Anthropic for prompt
2394
+ * caching. Otherwise it returns a plain flattened string — unchanged for
2395
+ * direct OpenAI/Groq.
2396
+ */
2397
+ private static _openaiSystemMessage;
2398
+ /**
2399
+ * Split an OpenAI-wire usage object. `prompt_tokens` INCLUDES cached tokens,
2400
+ * so we subtract them out (Anthropic-style: input excludes cache reads) and
2401
+ * report cached separately — this makes calculateCost price cache reads at
2402
+ * the discounted rate and reflects OpenRouter prompt-cache savings in logs.
2403
+ */
2404
+ private static _openaiUsage;
2405
+ private static _openaiText;
2406
+ private static _openaiStream;
2407
+ /** Map the Anthropic-style firstIterationToolChoice to OpenAI's tool_choice. */
2408
+ private static _openaiToolChoice;
2409
+ private static _openaiStreamWithTools;
2410
+ /**
2411
+ * Parse JSON string, handling markdown code blocks and surrounding text
2412
+ * Enhanced version with jsonrepair to handle malformed JSON from LLMs
2413
+ * @param text - Text that may contain JSON wrapped in ```json...``` or with surrounding text
2414
+ * @returns Parsed JSON object or array
2415
+ */
2416
+ private static _parseJSON;
2417
+ }
2418
+
2419
+ interface CapturedLog {
2420
+ timestamp: number;
2421
+ level: 'info' | 'error' | 'warn' | 'debug';
2422
+ message: string;
2423
+ type?: 'explanation' | 'query' | 'general';
2424
+ data?: Record<string, any>;
2425
+ }
2426
+ /**
2427
+ * UILogCollector captures logs during user prompt processing
2428
+ * and sends them to runtime via ui_logs message with uiBlockId as the message id
2429
+ * Logs are sent in real-time for streaming effect in the UI
2430
+ * Respects the global log level configuration
2431
+ */
2432
+ declare class UILogCollector {
2433
+ private logs;
2434
+ private uiBlockId;
2435
+ private clientId;
2436
+ private sendMessage;
2437
+ private currentLogLevel;
2438
+ constructor(clientId: string, sendMessage: (message: Message) => void, uiBlockId?: string);
2439
+ /**
2440
+ * Check if logging is enabled (uiBlockId is provided)
2441
+ */
2442
+ isEnabled(): boolean;
2443
+ /**
2444
+ * Check if a message should be logged based on current log level
2445
+ */
2446
+ private shouldLog;
2447
+ /**
2448
+ * Add a log entry with timestamp and immediately send to runtime
2449
+ * Only logs that pass the log level filter are captured and sent
2450
+ */
2451
+ private addLog;
1088
2452
  /**
1089
2453
  * Send a single log to runtime immediately
1090
2454
  */
@@ -1131,16 +2495,6 @@ declare class UILogCollector {
1131
2495
  setUIBlockId(uiBlockId: string): void;
1132
2496
  }
1133
2497
 
1134
- /**
1135
- * Represents an action that can be performed on a UIBlock
1136
- */
1137
- interface Action {
1138
- id: string;
1139
- name: string;
1140
- type: string;
1141
- [key: string]: any;
1142
- }
1143
-
1144
2498
  /**
1145
2499
  * UIBlock represents a single user and assistant message block in a thread
1146
2500
  * Contains user question, component metadata, component data, text response, and available actions
@@ -1323,12 +2677,20 @@ declare class Thread {
1323
2677
 
1324
2678
  /**
1325
2679
  * ThreadManager manages all threads globally
1326
- * Provides methods to create, retrieve, and delete threads
2680
+ * Provides methods to create, retrieve, and delete threads.
2681
+ * Includes automatic cleanup to prevent unbounded memory growth.
1327
2682
  */
1328
2683
  declare class ThreadManager {
1329
2684
  private static instance;
1330
2685
  private threads;
2686
+ private cleanupInterval;
2687
+ private readonly threadTtlMs;
1331
2688
  private constructor();
2689
+ /**
2690
+ * Periodically remove threads older than 7 days.
2691
+ * Runs every hour to avoid frequent iteration over the map.
2692
+ */
2693
+ private startCleanup;
1332
2694
  /**
1333
2695
  * Get singleton instance of ThreadManager
1334
2696
  */
@@ -1458,15 +2820,17 @@ declare const STORAGE_CONFIG: {
1458
2820
  */
1459
2821
  MAX_ROWS_PER_BLOCK: number;
1460
2822
  /**
1461
- * Maximum size in bytes per UIBlock (1MB)
2823
+ * Maximum size in bytes per UIBlock (500KB - reduced to save memory)
1462
2824
  */
1463
2825
  MAX_SIZE_PER_BLOCK_BYTES: number;
1464
2826
  /**
1465
2827
  * Number of days to keep threads before cleanup
2828
+ * Note: This is for in-memory storage. Conversations are also persisted to database.
1466
2829
  */
1467
2830
  THREAD_RETENTION_DAYS: number;
1468
2831
  /**
1469
2832
  * Number of days to keep UIBlocks before cleanup
2833
+ * Note: This is for in-memory storage. Data is also persisted to database.
1470
2834
  */
1471
2835
  UIBLOCK_RETENTION_DAYS: number;
1472
2836
  };
@@ -1484,13 +2848,127 @@ declare const CONTEXT_CONFIG: {
1484
2848
  };
1485
2849
 
1486
2850
  /**
1487
- * BM25L Reranker for hybrid semantic search
1488
- *
1489
- * BM25L is an improved variant of BM25 that provides better handling of
1490
- * long documents and term frequency saturation. This implementation is
1491
- * designed to rerank semantic search results from ChromaDB.
1492
- *
1493
- * The hybrid approach combines:
2851
+ * LLM Usage Logger - Tracks token usage, costs, and timing for all LLM API calls
2852
+ */
2853
+ interface LLMUsageEntry {
2854
+ timestamp: string;
2855
+ requestId: string;
2856
+ provider: string;
2857
+ model: string;
2858
+ method: string;
2859
+ inputTokens: number;
2860
+ outputTokens: number;
2861
+ cacheReadTokens?: number;
2862
+ cacheWriteTokens?: number;
2863
+ totalTokens: number;
2864
+ costUSD: number;
2865
+ durationMs: number;
2866
+ toolCalls?: number;
2867
+ success: boolean;
2868
+ error?: string;
2869
+ }
2870
+ declare class LLMUsageLogger {
2871
+ private logStream;
2872
+ private logPath;
2873
+ private enabled;
2874
+ private sessionStats;
2875
+ constructor();
2876
+ private initLogStream;
2877
+ private writeHeader;
2878
+ /**
2879
+ * Calculate cost based on token usage and model
2880
+ */
2881
+ calculateCost(model: string, inputTokens: number, outputTokens: number, cacheReadTokens?: number, cacheWriteTokens?: number): number;
2882
+ /**
2883
+ * Log an LLM API call
2884
+ */
2885
+ log(entry: LLMUsageEntry): void;
2886
+ /**
2887
+ * Log session summary (call at end of request)
2888
+ */
2889
+ logSessionSummary(requestContext?: string): void;
2890
+ /**
2891
+ * Reset session stats (call at start of new user request)
2892
+ */
2893
+ resetSession(): void;
2894
+ /**
2895
+ * Reset the log file for a new request (clears previous logs)
2896
+ * Call this at the start of each USER_PROMPT_REQ
2897
+ */
2898
+ resetLogFile(requestContext?: string): void;
2899
+ /**
2900
+ * Get current session stats
2901
+ */
2902
+ getSessionStats(): {
2903
+ totalCalls: number;
2904
+ totalInputTokens: number;
2905
+ totalOutputTokens: number;
2906
+ totalCacheReadTokens: number;
2907
+ totalCacheWriteTokens: number;
2908
+ totalCostUSD: number;
2909
+ totalDurationMs: number;
2910
+ };
2911
+ /**
2912
+ * Generate a unique request ID
2913
+ */
2914
+ generateRequestId(): string;
2915
+ }
2916
+ declare const llmUsageLogger: LLMUsageLogger;
2917
+
2918
+ /**
2919
+ * User Prompt Error Logger - Captures detailed errors for USER_PROMPT_REQ
2920
+ * Logs full error details including raw strings for parse failures
2921
+ */
2922
+ declare class UserPromptErrorLogger {
2923
+ private logStream;
2924
+ private logPath;
2925
+ private enabled;
2926
+ private hasErrors;
2927
+ constructor();
2928
+ /**
2929
+ * Reset the error log file for a new request
2930
+ */
2931
+ resetLogFile(requestContext?: string): void;
2932
+ /**
2933
+ * Log a JSON parse error with the raw string that failed
2934
+ */
2935
+ logJsonParseError(context: string, rawString: string, error: Error): void;
2936
+ /**
2937
+ * Log a general error with full details
2938
+ */
2939
+ logError(context: string, error: Error | string, additionalData?: Record<string, any>): void;
2940
+ /**
2941
+ * Log a SQL query error with the full query
2942
+ */
2943
+ logSqlError(query: string, error: Error | string, params?: any[]): void;
2944
+ /**
2945
+ * Log an LLM API error
2946
+ */
2947
+ logLlmError(provider: string, model: string, method: string, error: Error | string, requestData?: any): void;
2948
+ /**
2949
+ * Log tool execution error
2950
+ */
2951
+ logToolError(toolName: string, toolInput: any, error: Error | string): void;
2952
+ /**
2953
+ * Write final summary if there were errors
2954
+ */
2955
+ writeSummary(): void;
2956
+ /**
2957
+ * Check if any errors were logged
2958
+ */
2959
+ hadErrors(): boolean;
2960
+ private write;
2961
+ }
2962
+ declare const userPromptErrorLogger: UserPromptErrorLogger;
2963
+
2964
+ /**
2965
+ * BM25L Reranker for hybrid semantic search
2966
+ *
2967
+ * BM25L is an improved variant of BM25 that provides better handling of
2968
+ * long documents and term frequency saturation. This implementation is
2969
+ * designed to rerank semantic search results from ChromaDB.
2970
+ *
2971
+ * The hybrid approach combines:
1494
2972
  * 1. Semantic similarity from ChromaDB embeddings (dense vectors)
1495
2973
  * 2. Lexical matching from BM25L (sparse, keyword-based)
1496
2974
  *
@@ -1611,14 +3089,608 @@ declare function rerankConversationResults<T extends {
1611
3089
  bm25Score: number;
1612
3090
  }>;
1613
3091
 
1614
- declare const SDK_VERSION = "0.0.8";
3092
+ /**
3093
+ * QueryExecutionService - Handles all query execution, validation, and retry logic
3094
+ * Extracted from BaseLLM for better separation of concerns
3095
+ */
3096
+
3097
+ /**
3098
+ * Context for component when requesting query fix
3099
+ */
3100
+ interface ComponentContext {
3101
+ name: string;
3102
+ type: string;
3103
+ title?: string;
3104
+ }
3105
+ /**
3106
+ * Result of query validation
3107
+ */
3108
+ interface QueryValidationResult {
3109
+ component: Component | null;
3110
+ queryKey: string;
3111
+ result: any;
3112
+ validated: boolean;
3113
+ }
3114
+ /**
3115
+ * Result of batch query validation
3116
+ */
3117
+ interface BatchValidationResult {
3118
+ components: Component[];
3119
+ queryResults: Map<string, any>;
3120
+ }
3121
+ /**
3122
+ * Configuration for QueryExecutionService
3123
+ */
3124
+ interface QueryExecutionServiceConfig {
3125
+ defaultLimit: number;
3126
+ getModelForTask: (taskType: 'simple' | 'complex') => string;
3127
+ getApiKey: (apiKey?: string) => string | undefined;
3128
+ providerName: string;
3129
+ }
3130
+ /**
3131
+ * QueryExecutionService handles all query-related operations
3132
+ */
3133
+ declare class QueryExecutionService {
3134
+ private config;
3135
+ constructor(config: QueryExecutionServiceConfig);
3136
+ /**
3137
+ * Get the cache key for a query
3138
+ * This ensures the cache key matches what the frontend will send
3139
+ */
3140
+ getQueryCacheKey(query: any): string;
3141
+ /**
3142
+ * Execute a query against the database
3143
+ * @param query - The SQL query to execute (string or object with sql/values)
3144
+ * @param collections - Collections object containing database execute function
3145
+ * @returns Object with result data and cache key
3146
+ */
3147
+ executeQuery(query: any, collections: any): Promise<{
3148
+ result: any;
3149
+ cacheKey: string;
3150
+ }>;
3151
+ /**
3152
+ * Request the LLM to fix a failed SQL query
3153
+ * @param failedQuery - The query that failed execution
3154
+ * @param errorMessage - The error message from the failed execution
3155
+ * @param componentContext - Context about the component
3156
+ * @param apiKey - Optional API key
3157
+ * @returns Fixed query string
3158
+ */
3159
+ requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
3160
+ /**
3161
+ * Validate a single component's query with retry logic
3162
+ * @param component - The component to validate
3163
+ * @param collections - Collections object containing database execute function
3164
+ * @param apiKey - Optional API key for LLM calls
3165
+ * @returns Validation result with component, query key, and result
3166
+ */
3167
+ validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
3168
+ /**
3169
+ * Validate multiple component queries in parallel
3170
+ * @param components - Array of components with potential queries
3171
+ * @param collections - Collections object containing database execute function
3172
+ * @param apiKey - Optional API key for LLM calls
3173
+ * @returns Object with validated components and query results map
3174
+ */
3175
+ validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
3176
+ }
3177
+
3178
+ /**
3179
+ * Task types for model selection
3180
+ * - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
3181
+ * - 'simple': Classification, action generation (uses fast model in balanced mode)
3182
+ */
3183
+ type TaskType = 'complex' | 'simple';
3184
+ interface BaseLLMConfig {
3185
+ model?: string;
3186
+ fastModel?: string;
3187
+ defaultLimit?: number;
3188
+ apiKey?: string;
3189
+ /**
3190
+ * Model selection strategy:
3191
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
3192
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
3193
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
3194
+ */
3195
+ modelStrategy?: ModelStrategy;
3196
+ conversationSimilarityThreshold?: number;
3197
+ }
3198
+ /**
3199
+ * BaseLLM abstract class for AI-powered component generation and matching
3200
+ * Provides common functionality for all LLM providers
3201
+ */
3202
+ declare abstract class BaseLLM {
3203
+ protected model: string;
3204
+ protected fastModel: string;
3205
+ protected defaultLimit: number;
3206
+ protected apiKey?: string;
3207
+ protected modelStrategy: ModelStrategy;
3208
+ protected conversationSimilarityThreshold: number;
3209
+ protected queryService: QueryExecutionService;
3210
+ constructor(config?: BaseLLMConfig);
3211
+ /**
3212
+ * Get the appropriate model based on task type and model strategy
3213
+ * @param taskType - 'complex' for text generation/matching, 'simple' for classification/actions
3214
+ * @returns The model string to use for this task
3215
+ */
3216
+ protected getModelForTask(taskType: TaskType): string;
3217
+ /**
3218
+ * Set the model strategy at runtime
3219
+ * @param strategy - 'best', 'fast', or 'balanced'
3220
+ */
3221
+ setModelStrategy(strategy: ModelStrategy): void;
3222
+ /**
3223
+ * Get the current model strategy
3224
+ * @returns The current model strategy
3225
+ */
3226
+ getModelStrategy(): ModelStrategy;
3227
+ /**
3228
+ * Set the conversation similarity threshold at runtime
3229
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
3230
+ */
3231
+ setConversationSimilarityThreshold(threshold: number): void;
3232
+ /**
3233
+ * Get the current conversation similarity threshold
3234
+ * @returns The current threshold value
3235
+ */
3236
+ getConversationSimilarityThreshold(): number;
3237
+ /**
3238
+ * Get the default model for this provider (used for complex tasks like text generation)
3239
+ */
3240
+ protected abstract getDefaultModel(): string;
3241
+ /**
3242
+ * Get the default fast model for this provider (used for simple tasks: classification, matching, actions)
3243
+ * Should return a cheaper/faster model like Haiku for Anthropic
3244
+ */
3245
+ protected abstract getDefaultFastModel(): string;
3246
+ /**
3247
+ * Get the default API key from environment
3248
+ */
3249
+ protected abstract getDefaultApiKey(): string | undefined;
3250
+ /**
3251
+ * Get the provider name (for logging)
3252
+ */
3253
+ protected abstract getProviderName(): string;
3254
+ /**
3255
+ * Get the API key (from instance, parameter, or environment)
3256
+ */
3257
+ protected getApiKey(apiKey?: string): string | undefined;
3258
+ /**
3259
+ * Check if a component contains a Form (data_modification component)
3260
+ * Forms have hardcoded defaultValues that become stale when cached
3261
+ * This checks both single Form components and Forms inside MultiComponentContainer
3262
+ */
3263
+ protected containsFormComponent(component: any): boolean;
3264
+ /**
3265
+ * Match components from text response suggestions and generate follow-up questions
3266
+ * Takes a text response with component suggestions (c1:type format) and matches with available components
3267
+ * Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
3268
+ * All components are placed in a default MultiComponentContainer layout
3269
+ * @param analysisContent - The text response containing component suggestions
3270
+ * @param components - List of available components
3271
+ * @param apiKey - Optional API key
3272
+ * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
3273
+ * @returns Object containing matched components, layout title/description, and follow-up actions
3274
+ */
3275
+ matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
3276
+ components: Component[];
3277
+ layoutTitle: string;
3278
+ layoutDescription: string;
3279
+ actions: Action[];
3280
+ }>;
3281
+ /**
3282
+ * Classify user question into category and detect external tools needed
3283
+ * Determines if question is for data analysis, requires external tools, or needs text response
3284
+ */
3285
+ classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
3286
+ category: 'data_analysis' | 'data_modification' | 'general';
3287
+ externalTools: Array<{
3288
+ type: string;
3289
+ name: string;
3290
+ description: string;
3291
+ parameters: Record<string, any>;
3292
+ }>;
3293
+ dataAnalysisType?: 'visualization' | 'calculation' | 'comparison' | 'trend';
3294
+ reasoning: string;
3295
+ confidence: number;
3296
+ }>;
3297
+ /**
3298
+ * Adapt UI block parameters based on current user question
3299
+ * Takes a matched UI block from semantic search and modifies its props to answer the new question
3300
+ * Also adapts the cached text response to match the new question
3301
+ */
3302
+ adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
3303
+ success: boolean;
3304
+ adaptedComponent?: Component;
3305
+ adaptedTextResponse?: string;
3306
+ parametersChanged?: Array<{
3307
+ field: string;
3308
+ reason: string;
3309
+ }>;
3310
+ explanation: string;
3311
+ }>;
3312
+ /**
3313
+ * Generate text-based response for user question
3314
+ * This provides conversational text responses instead of component generation
3315
+ * Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
3316
+ * After generating text response, if components are provided, matches suggested components
3317
+ */
3318
+ 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>;
3319
+ /**
3320
+ * Main orchestration function with semantic search and multi-step classification
3321
+ * NEW FLOW (Recommended):
3322
+ * 1. Semantic search: Check previous conversations (>60% match)
3323
+ * - If match found → Adapt UI block parameters and return
3324
+ * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
3325
+ * 3. Route appropriately based on category and response mode
3326
+ */
3327
+ 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>;
3328
+ /**
3329
+ * Generate next questions that the user might ask based on the original prompt and generated component
3330
+ * This helps provide intelligent suggestions for follow-up queries
3331
+ * For general/conversational questions without components, pass textResponse instead
3332
+ */
3333
+ generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string, signal?: AbortSignal): Promise<string[]>;
3334
+ }
3335
+
3336
+ interface AnthropicLLMConfig extends BaseLLMConfig {
3337
+ }
3338
+ /**
3339
+ * AnthropicLLM class for handling AI-powered component generation and matching using Anthropic Claude
3340
+ */
3341
+ declare class AnthropicLLM extends BaseLLM {
3342
+ constructor(config?: AnthropicLLMConfig);
3343
+ protected getDefaultModel(): string;
3344
+ protected getDefaultFastModel(): string;
3345
+ protected getDefaultApiKey(): string | undefined;
3346
+ protected getProviderName(): string;
3347
+ }
3348
+ declare const anthropicLLM: AnthropicLLM;
3349
+
3350
+ interface GroqLLMConfig extends BaseLLMConfig {
3351
+ }
3352
+ /**
3353
+ * GroqLLM class for handling AI-powered component generation and matching using Groq
3354
+ */
3355
+ declare class GroqLLM extends BaseLLM {
3356
+ constructor(config?: GroqLLMConfig);
3357
+ protected getDefaultModel(): string;
3358
+ protected getDefaultFastModel(): string;
3359
+ protected getDefaultApiKey(): string | undefined;
3360
+ protected getProviderName(): string;
3361
+ }
3362
+ declare const groqLLM: GroqLLM;
3363
+
3364
+ interface GeminiLLMConfig extends BaseLLMConfig {
3365
+ }
3366
+ /**
3367
+ * GeminiLLM class for handling AI-powered component generation and matching using Google Gemini
3368
+ */
3369
+ declare class GeminiLLM extends BaseLLM {
3370
+ constructor(config?: GeminiLLMConfig);
3371
+ protected getDefaultModel(): string;
3372
+ protected getDefaultFastModel(): string;
3373
+ protected getDefaultApiKey(): string | undefined;
3374
+ protected getProviderName(): string;
3375
+ }
3376
+ declare const geminiLLM: GeminiLLM;
3377
+
3378
+ interface OpenAILLMConfig extends BaseLLMConfig {
3379
+ }
3380
+ /**
3381
+ * OpenAILLM class for handling AI-powered component generation and matching using OpenAI GPT models
3382
+ */
3383
+ declare class OpenAILLM extends BaseLLM {
3384
+ constructor(config?: OpenAILLMConfig);
3385
+ protected getDefaultModel(): string;
3386
+ protected getDefaultFastModel(): string;
3387
+ protected getDefaultApiKey(): string | undefined;
3388
+ protected getProviderName(): string;
3389
+ }
3390
+ declare const openaiLLM: OpenAILLM;
3391
+
3392
+ /**
3393
+ * Query Cache — Two mechanisms:
3394
+ *
3395
+ * 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
3396
+ * of recently validated queries. True LRU eviction: reads bubble entries to the back via
3397
+ * delete+re-set so the oldest *unused* entry is evicted, not the oldest *inserted*.
3398
+ *
3399
+ * 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
3400
+ * No server-side storage needed for SQL mappings. The token is decrypted on each request.
3401
+ * This eliminates the unbounded queryIdCache that previously grew forever and caused
3402
+ * memory bloat (hundreds of MBs after thousands of queries).
3403
+ *
3404
+ * Result data can still be cached temporarily via the data cache (mechanism 1).
3405
+ */
3406
+ declare class QueryCache {
3407
+ private cache;
3408
+ private ttlMs;
3409
+ private maxCacheSize;
3410
+ private cleanupInterval;
3411
+ private readonly algorithm;
3412
+ private encryptionKey;
3413
+ constructor();
3414
+ /**
3415
+ * Set the cache TTL (Time To Live)
3416
+ * @param minutes - TTL in minutes (default: 10)
3417
+ */
3418
+ setTTL(minutes: number): void;
3419
+ /**
3420
+ * Get the current TTL in minutes
3421
+ */
3422
+ getTTL(): number;
3423
+ /**
3424
+ * Store query result in data cache.
3425
+ * If the key already exists, it's removed first so the re-insert places it
3426
+ * at the back of the iteration order (LRU). Eviction only fires when adding
3427
+ * a genuinely new key past the size limit.
3428
+ */
3429
+ set(query: string, data: any): void;
3430
+ /**
3431
+ * Get cached result if exists and not expired.
3432
+ * On hit, re-inserts the entry so it moves to the back of the Map's
3433
+ * iteration order — turning FIFO eviction into true LRU.
3434
+ */
3435
+ get(query: string): any | null;
3436
+ /**
3437
+ * Check if query exists in cache (not expired)
3438
+ */
3439
+ has(query: string): boolean;
3440
+ /**
3441
+ * Remove a specific query from cache
3442
+ */
3443
+ delete(query: string): void;
3444
+ /**
3445
+ * Clear all cached entries
3446
+ */
3447
+ clear(): void;
3448
+ /**
3449
+ * Get cache statistics
3450
+ */
3451
+ getStats(): {
3452
+ size: number;
3453
+ queryIdCount: number;
3454
+ oldestEntryAge: number | null;
3455
+ };
3456
+ /**
3457
+ * Start periodic cleanup of expired data cache entries.
3458
+ */
3459
+ private startCleanup;
3460
+ /**
3461
+ * Encrypt a payload into a self-contained token.
3462
+ */
3463
+ private encrypt;
3464
+ /**
3465
+ * Decrypt a token back to the original payload.
3466
+ */
3467
+ private decrypt;
3468
+ /**
3469
+ * Store a query by generating an encrypted token as queryId.
3470
+ * The SQL is encrypted INTO the token — nothing stored in memory.
3471
+ * If data is provided, it's cached temporarily in the data cache.
3472
+ */
3473
+ storeQuery(query: any, data?: any): string;
3474
+ /**
3475
+ * Get a stored query by decrypting its token.
3476
+ * Returns the SQL + any cached result data.
3477
+ */
3478
+ getQuery(queryId: string): {
3479
+ query: any;
3480
+ data: any;
3481
+ } | null;
3482
+ /**
3483
+ * Update cached data for a queryId token
3484
+ */
3485
+ setQueryData(queryId: string, data: any): void;
3486
+ /**
3487
+ * Stop cleanup interval (for graceful shutdown)
3488
+ */
3489
+ destroy(): void;
3490
+ }
3491
+ declare const queryCache: QueryCache;
3492
+
3493
+ /**
3494
+ * Manages conversation history scoped per user + dashboard.
3495
+ * Each user-dashboard pair has its own isolated history that expires after a configurable TTL.
3496
+ */
3497
+ declare class DashboardConversationHistory {
3498
+ private histories;
3499
+ private ttlMs;
3500
+ private maxEntries;
3501
+ private cleanupInterval;
3502
+ constructor();
3503
+ /**
3504
+ * Set the TTL for dashboard histories
3505
+ * @param minutes - TTL in minutes
3506
+ */
3507
+ setTTL(minutes: number): void;
3508
+ /**
3509
+ * Set max entries per dashboard
3510
+ */
3511
+ setMaxEntries(max: number): void;
3512
+ /**
3513
+ * Add a conversation entry for a user's dashboard
3514
+ */
3515
+ addEntry(dashboardId: string, userPrompt: string, componentSummary: string, userId?: string): void;
3516
+ /**
3517
+ * Get formatted conversation history for a user's dashboard
3518
+ */
3519
+ getHistory(dashboardId: string, userId?: string): string;
3520
+ /**
3521
+ * Clear history for a specific user's dashboard
3522
+ */
3523
+ clearDashboard(dashboardId: string, userId?: string): void;
3524
+ /**
3525
+ * Clear all dashboard histories
3526
+ */
3527
+ clearAll(): void;
3528
+ /**
3529
+ * Start periodic cleanup of expired histories
3530
+ */
3531
+ private startCleanup;
3532
+ /**
3533
+ * Stop cleanup interval (for graceful shutdown)
3534
+ */
3535
+ destroy(): void;
3536
+ }
3537
+ declare const dashboardConversationHistory: DashboardConversationHistory;
3538
+
3539
+ /**
3540
+ * Whole-dashboard generation via Pi, a terminal coding agent — as opposed to
3541
+ * DASH_COMP_REQ's single-widget-at-a-time flow. Runs Pi in-process via its
3542
+ * SDK (createAgentSession), not as a subprocess: no shell, no argument
3543
+ * quoting, no stdin/stdout piping, none of the Windows-specific subprocess
3544
+ * issues that came with spawning the `pi` CLI directly.
3545
+ *
3546
+ * Called from sdk-nodejs/src/dashboardAgent/index.ts (DASHBOARD_AGENT_REQ),
3547
+ * which owns the generic streaming/abort machinery (mirrors USER_PROMPT_REQ)
3548
+ * and passes `signal`/`onProgress` alongside the normal params — this stays
3549
+ * within CollectionHandler's loose (params) => Promise<result> typing, no
3550
+ * change needed to that shared type.
3551
+ *
3552
+ * This mechanism is generic and reusable across any deployment. What's
3553
+ * genuinely project-specific — where AGENTS.md lives, which model to use —
3554
+ * is supplied via `DashboardAgentCollectionConfig`, with defaults sensible
3555
+ * enough that most callers don't need to override them (see below). The
3556
+ * data-source tool list and the dashboard's current state both come from
3557
+ * things sdk-nodejs already exposes generically: `sdk.getTools()` (whatever
3558
+ * this deployment registered via `sdk.setTools()`) and `sdk.callCollection
3559
+ * ('dashboards', 'query', ...)` (whatever this deployment already registered
3560
+ * under that name/shape) — no per-deployment callback needed for either.
3561
+ * Same convention on the way out: after a successful run, the prompt and the
3562
+ * full response text are handed to `sdk.callCollection('dashboard-agent-
3563
+ * conversations', 'create', ...)` if this deployment has registered one —
3564
+ * skipped silently otherwise, since conversation history is optional.
3565
+ *
3566
+ * Pi verifies every query against the live database itself (via whatever
3567
+ * local tool-execution bridge the deployment exposes, e.g. an HTTP bridge
3568
+ * on localhost), but does NOT persist the result itself — it writes the
3569
+ * finished DSL to an absolute path inside `runtimeDir`, told to it explicitly
3570
+ * in the prompt, and stops there. This handler reads that file after the run
3571
+ * finishes and returns its content as `dashboard` in the result. The caller
3572
+ * (frontend) is the one that actually saves it, via whatever authenticated
3573
+ * create/update path any other dashboard edit goes through — Pi has no user
3574
+ * session/auth context of its own, so persistence shouldn't happen from
3575
+ * inside it.
3576
+ *
3577
+ * Session persistence: the FIRST call for a dashboardId pays the full cost
3578
+ * (explore KB, discover schema, plan, verify, build). Every call after that
3579
+ * resumes the same session file (SessionManager.open) so Pi has everything
3580
+ * it already learned — it only needs to reason about the new, smaller ask,
3581
+ * not rediscover the whole dashboard from scratch. The session's file path
3582
+ * (AgentSession.sessionFile) is captured right after creation and persisted
3583
+ * in a small local file, keyed by dashboardId, inside `runtimeDir`.
3584
+ */
3585
+ interface DashboardAgentCollectionConfig {
3586
+ /**
3587
+ * Working directory Pi runs from — must contain AGENTS.md. This is a
3588
+ * version-controlled prompt file, so `cwd` is expected to live somewhere
3589
+ * like a `.prompts/` folder alongside the deployment's other prompts.
3590
+ * Default: `<process.cwd()>/.prompts/dashboard-agent` — the same
3591
+ * process.cwd()-based convention PromptLoader already uses for the main
3592
+ * agent's prompts, which needs no explicit override in the common case
3593
+ * (the backend process's own cwd already is its project root).
3594
+ */
3595
+ cwd?: string;
3596
+ /**
3597
+ * Where drafts/, the session-id map, and dashboard.log get written —
3598
+ * separate from `cwd` deliberately, so this deployment's runtime state
3599
+ * (regenerated per session, safe to gitignore) doesn't sit inside the
3600
+ * same folder as the version-controlled AGENTS.md prompt.
3601
+ * Default: `<process.cwd()>/.pi-dashboard-agent-runtime`.
3602
+ */
3603
+ runtimeDir?: string;
3604
+ /** Model provider (default: process.env.PI_AGENT_PROVIDER || 'openrouter'). */
3605
+ provider?: string;
3606
+ /** Model id (default: process.env.PI_AGENT_MODEL || 'anthropic/claude-sonnet-4.5'). */
3607
+ model?: string;
3608
+ /**
3609
+ * true (default): every request starts a brand-new pi session, with the 2
3610
+ * most recent prior responses (if any) injected into the prompt as
3611
+ * context — bounded cost per request, but pi re-explores schema/KB facts
3612
+ * it already verified in an earlier turn on this same dashboard.
3613
+ * false: resumes the same session file across requests on a given
3614
+ * dashboard — pi keeps everything it already learned, but context (and
3615
+ * cost) grows unbounded across turns (one observed turn: 2M+ cache-read
3616
+ * tokens after a handful of edits on the same dashboard).
3617
+ * Default: process.env.PI_AGENT_FRESH_SESSION !== 'false'.
3618
+ */
3619
+ freshSession?: boolean;
3620
+ }
3621
+ declare function registerDashboardAgentCollection(sdk: SuperatomSDK, config?: DashboardAgentCollectionConfig): void;
3622
+
3623
+ /**
3624
+ * ScriptMatcher — LLM-Based Script Matching + Parameter Extraction
3625
+ *
3626
+ * Uses ONE LLM call to:
3627
+ * 1. Pick the best matching script from the library (or "none")
3628
+ * 2. Extract parameter values from the user question
3629
+ *
3630
+ * Why LLM over embeddings:
3631
+ * - Embeddings capture topic similarity ("overstock" ≈ "inventory" ≈ "revenue")
3632
+ * but can't distinguish structurally different questions about the same domain
3633
+ * - LLM understands that "overstock by warehouse" needs a different script than
3634
+ * "revenue by warehouse" even though they're semantically close
3635
+ * - One call does both matching AND parameter extraction
3636
+ *
3637
+ * When script library grows past ~50, add an embedding pre-filter
3638
+ * (ChromaDB narrows to top 10 → LLM picks from those 10).
3639
+ */
3640
+
3641
+ declare class ScriptMatcher {
3642
+ private store;
3643
+ constructor(store: ScriptStore);
3644
+ /**
3645
+ * Find the best matching script for a user question.
3646
+ * Uses ONE LLM call that picks the script AND extracts parameters.
3647
+ * Returns null if no script matches.
3648
+ */
3649
+ match(userPrompt: string, apiKey?: string, model?: string, signal?: AbortSignal): Promise<ScriptMatch | null>;
3650
+ /**
3651
+ * Build the script catalog string for the LLM prompt.
3652
+ * Each script gets: index, ID, name, description, and parameter definitions.
3653
+ */
3654
+ private buildScriptCatalog;
3655
+ }
3656
+
3657
+ /**
3658
+ * ScriptRunner — Execute scripts in an isolated tsx subprocess.
3659
+ *
3660
+ * The subprocess approach replaces the earlier `new Function()` eval and gives us:
3661
+ * - Real sandbox (separate process, SIGKILL on timeout).
3662
+ * - Real TypeScript (tsx transpiles on the fly).
3663
+ * - npm imports available to scripts (clustering, stats, geo, etc.).
3664
+ *
3665
+ * Protocol: NDJSON over the child's stdin/stdout. See script-ipc.ts + backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md.
3666
+ */
3667
+
3668
+ interface RunScriptOptions {
3669
+ /** Data sources the script is allowed to query via ctx.query */
3670
+ externalTools: ExternalTool[];
3671
+ /** Optional — for propagating per-query UI progress to the user */
3672
+ streamBuffer?: StreamBuffer;
3673
+ /** Override the wall-clock timeout (default `SCRIPT_TIMEOUT_MS`, 60s). */
3674
+ timeoutMs?: number;
3675
+ /**
3676
+ * Per-turn cancellation signal. When the user hits "Stop" mid-run, the child
3677
+ * process group is SIGKILLed and the run resolves as an aborted failure (the
3678
+ * caller is already unwinding, so the result is discarded).
3679
+ */
3680
+ signal?: AbortSignal;
3681
+ }
3682
+ /**
3683
+ * Execute a recipe by spawning a tsx child on the script's .ts file.
3684
+ * `scriptPath` is the absolute path to the saved `.ts` body.
3685
+ */
3686
+ declare function runScript(recipe: ScriptRecipe, scriptPath: string, params: Record<string, any>, options: RunScriptOptions): Promise<ScriptResult>;
3687
+
1615
3688
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
1616
3689
  declare class SuperatomSDK {
1617
3690
  private ws;
1618
3691
  private url;
1619
3692
  private apiKey?;
1620
3693
  private projectId;
1621
- private userId;
1622
3694
  private type;
1623
3695
  private bundleDir;
1624
3696
  private messageHandlers;
@@ -1629,14 +3701,27 @@ declare class SuperatomSDK {
1629
3701
  private collections;
1630
3702
  private components;
1631
3703
  private tools;
3704
+ private workflows;
1632
3705
  private anthropicApiKey;
1633
3706
  private groqApiKey;
1634
3707
  private geminiApiKey;
1635
3708
  private openaiApiKey;
1636
3709
  private llmProviders;
3710
+ private databaseType;
3711
+ private modelStrategy;
3712
+ private mainAgentModel;
3713
+ private sourceAgentModel;
3714
+ private dashCompModels?;
3715
+ private conversationSimilarityThreshold;
1637
3716
  private userManager;
1638
3717
  private dashboardManager;
1639
3718
  private reportManager;
3719
+ private pingInterval;
3720
+ private lastPong;
3721
+ private readonly PING_INTERVAL_MS;
3722
+ private readonly PONG_TIMEOUT_MS;
3723
+ private pendingOutbox;
3724
+ private readonly MAX_OUTBOX_SIZE;
1640
3725
  constructor(config: SuperatomSDKConfig);
1641
3726
  /**
1642
3727
  * Initialize PromptLoader and load prompts into memory
@@ -1676,9 +3761,25 @@ declare class SuperatomSDK {
1676
3761
  */
1677
3762
  private handleMessage;
1678
3763
  /**
1679
- * Send a message to the Superatom service
3764
+ * Send a message to the Superatom service.
3765
+ * Returns true if the message was sent, false if the WebSocket is not connected.
3766
+ * Does NOT throw on closed connections — callers can check the return value if needed.
3767
+ */
3768
+ send(message: Message): boolean;
3769
+ /**
3770
+ * Queue a message that couldn't be delivered because the socket was down,
3771
+ * to be resent once it reconnects. Drops the oldest entry once the bound is
3772
+ * hit — an outage long enough to fill this queue means the oldest queued
3773
+ * responses are for requests the caller has likely already given up on.
1680
3774
  */
1681
- send(message: Message): void;
3775
+ private queuePendingMessage;
3776
+ /**
3777
+ * Resend everything queued while the socket was down, now that it's back
3778
+ * up. Uses this.ws.send() directly (not send()) so a message that fails
3779
+ * again goes back through queuePendingMessage() rather than being silently
3780
+ * dropped a second time.
3781
+ */
3782
+ private flushPendingOutbox;
1682
3783
  /**
1683
3784
  * Register a message handler to receive all messages
1684
3785
  */
@@ -1704,7 +3805,28 @@ declare class SuperatomSDK {
1704
3805
  */
1705
3806
  addCollection<TParams = any, TResult = any>(collectionName: string, operation: CollectionOperation | string, handler: CollectionHandler<TParams, TResult>): void;
1706
3807
  private handleReconnect;
3808
+ /**
3809
+ * Start heartbeat to keep WebSocket connection alive
3810
+ * Sends PING every 3 minutes to prevent idle timeout from cloud infrastructure
3811
+ */
3812
+ private startHeartbeat;
3813
+ /**
3814
+ * Stop the heartbeat interval
3815
+ */
3816
+ private stopHeartbeat;
3817
+ /**
3818
+ * Handle PONG response from server
3819
+ */
3820
+ private handlePong;
1707
3821
  private storeComponents;
3822
+ /**
3823
+ * The live, frontend-registered component catalog (name, type, description,
3824
+ * and full prop schema per component) — the same authoritative source
3825
+ * DASH_COMP_REQ's LLM prompt is built from. Exposed so other integrations
3826
+ * (e.g. the dashboard-agent script bridge) can read real component
3827
+ * contracts instead of maintaining a separate, driftable hand-written copy.
3828
+ */
3829
+ getComponents(): Component[];
1708
3830
  /**
1709
3831
  * Set tools for the SDK instance
1710
3832
  */
@@ -1713,6 +3835,57 @@ declare class SuperatomSDK {
1713
3835
  * Get the stored tools
1714
3836
  */
1715
3837
  getTools(): Tool$1[];
3838
+ /**
3839
+ * Call a registered collection operation in-process — no WebSocket
3840
+ * round-trip, since the caller is already running inside this same SDK
3841
+ * instance. Lets SDK-internal features (e.g. the dashboard agent) reuse
3842
+ * whatever collection a deployment has already registered (e.g.
3843
+ * 'dashboards'.'query') by name/convention, instead of requiring a
3844
+ * separate callback purely to re-expose data a collection already serves.
3845
+ * Throws if the collection or operation isn't registered.
3846
+ */
3847
+ callCollection<TResult = any>(collectionName: string, operation: string, params?: any): Promise<TResult>;
3848
+ /**
3849
+ * Register workflow components for the SDK instance.
3850
+ *
3851
+ * Workflows are pre-built multi-step UI flows the main agent can pick when
3852
+ * the user's prompt matches a workflow's `whenToUse` trigger. Picking a
3853
+ * workflow short-circuits analysis text + dashboard component generation —
3854
+ * the workflow component is returned directly, with the LLM-extracted props.
3855
+ */
3856
+ setWorkflows(workflows: WorkflowDescriptor[]): void;
3857
+ /**
3858
+ * Get the registered workflow components.
3859
+ */
3860
+ getWorkflows(): WorkflowDescriptor[];
3861
+ /**
3862
+ * Apply model strategy to all LLM provider singletons
3863
+ * @param strategy - 'best', 'fast', or 'balanced'
3864
+ */
3865
+ private applyModelStrategy;
3866
+ /**
3867
+ * Set model strategy at runtime
3868
+ * @param strategy - 'best', 'fast', or 'balanced'
3869
+ */
3870
+ setModelStrategy(strategy: ModelStrategy): void;
3871
+ /**
3872
+ * Get current model strategy
3873
+ */
3874
+ getModelStrategy(): ModelStrategy;
3875
+ /**
3876
+ * Apply conversation similarity threshold to all LLM provider singletons
3877
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
3878
+ */
3879
+ private applyConversationSimilarityThreshold;
3880
+ /**
3881
+ * Set conversation similarity threshold at runtime
3882
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
3883
+ */
3884
+ setConversationSimilarityThreshold(threshold: number): void;
3885
+ /**
3886
+ * Get current conversation similarity threshold
3887
+ */
3888
+ getConversationSimilarityThreshold(): number;
1716
3889
  }
1717
3890
 
1718
- export { type Action, BM25L, type BM25LOptions, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LogLevel, type Message, type RerankedResult, SDK_VERSION, STORAGE_CONFIG, SuperatomSDK, type SuperatomSDKConfig, Thread, ThreadManager, type Tool$1 as Tool, UIBlock, UILogCollector, type User, UserManager, type UsersData, hybridRerank, logger, rerankChromaResults, rerankConversationResults };
3891
+ 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 DashboardAgentCollectionConfig, 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 ScriptComponentSpec, ScriptMatcher, type ScriptParameter, type ScriptRecipe, type ScriptRecipeMetaRow, type ScriptRecipeStore, type ScriptResult, ScriptStore, type ScriptStoreOptions, 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, normalizeScriptBody, openaiLLM, queryCache, registerDashboardAgentCollection, rerankChromaResults, rerankConversationResults, resolveScriptRecipeStore, runScript, userPromptErrorLogger };