@superatomai/sdk-node 0.0.32 → 0.0.33-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,32 @@ 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;
20
+ /**
21
+ * The script recipe that produced this answer, when one did. Read back via
22
+ * `conversation-history.exactMatch` so an edit follow-up still has a target
23
+ * after a reload (the in-memory thread is gone by then), and indexed so
24
+ * committing an edit can purge every cached answer bound to the recipe.
25
+ */
26
+ scriptBinding?: {
27
+ recipeId: string;
28
+ params?: Record<string, any>;
29
+ name?: string;
30
+ columns?: string[];
31
+ };
13
32
  }
14
33
 
15
34
  /**
@@ -59,7 +78,18 @@ declare class Logger {
59
78
  * Log debug message (only shown for verbose level)
60
79
  */
61
80
  debug(...args: any[]): void;
81
+ /**
82
+ * Write to log file
83
+ */
62
84
  file(...args: any[]): void;
85
+ /**
86
+ * Clear the log file (call at start of new user request)
87
+ */
88
+ clearFile(): void;
89
+ /**
90
+ * Log LLM method prompts with clear labeling
91
+ */
92
+ logLLMPrompt(methodName: string, promptType: 'system' | 'user', content: string | object | any[]): void;
63
93
  }
64
94
  declare const logger: Logger;
65
95
 
@@ -90,7 +120,27 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
90
120
  deps?: string[] | undefined;
91
121
  }>, "many">>;
92
122
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
93
- render: z.ZodType<any, z.ZodTypeDef, any>;
123
+ render: z.ZodOptional<z.ZodType<any, z.ZodTypeDef, any>>;
124
+ pages: z.ZodOptional<z.ZodArray<z.ZodObject<{
125
+ id: z.ZodString;
126
+ name: z.ZodString;
127
+ order: z.ZodNumber;
128
+ icon: z.ZodOptional<z.ZodString>;
129
+ render: z.ZodType<any, z.ZodTypeDef, any>;
130
+ }, "strip", z.ZodTypeAny, {
131
+ id: string;
132
+ name: string;
133
+ order: number;
134
+ icon?: string | undefined;
135
+ render?: any;
136
+ }, {
137
+ id: string;
138
+ name: string;
139
+ order: number;
140
+ icon?: string | undefined;
141
+ render?: any;
142
+ }>, "many">>;
143
+ defaultPageId: z.ZodOptional<z.ZodString>;
94
144
  query: z.ZodOptional<z.ZodObject<{
95
145
  graphql: z.ZodOptional<z.ZodString>;
96
146
  sql: z.ZodOptional<z.ZodString>;
@@ -129,6 +179,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
129
179
  dependencies?: string[] | undefined;
130
180
  } | undefined;
131
181
  props?: Record<string, any> | undefined;
182
+ render?: any;
132
183
  states?: Record<string, any> | undefined;
133
184
  methods?: Record<string, {
134
185
  fn: string;
@@ -139,7 +190,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
139
190
  deps?: string[] | undefined;
140
191
  }[] | undefined;
141
192
  data?: Record<string, any> | undefined;
142
- render?: any;
193
+ pages?: {
194
+ id: string;
195
+ name: string;
196
+ order: number;
197
+ icon?: string | undefined;
198
+ render?: any;
199
+ }[] | undefined;
200
+ defaultPageId?: string | undefined;
143
201
  }, {
144
202
  id: string;
145
203
  name?: string | undefined;
@@ -153,6 +211,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
153
211
  dependencies?: string[] | undefined;
154
212
  } | undefined;
155
213
  props?: Record<string, any> | undefined;
214
+ render?: any;
156
215
  states?: Record<string, any> | undefined;
157
216
  methods?: Record<string, {
158
217
  fn: string;
@@ -163,7 +222,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
163
222
  deps?: string[] | undefined;
164
223
  }[] | undefined;
165
224
  data?: Record<string, any> | undefined;
166
- render?: any;
225
+ pages?: {
226
+ id: string;
227
+ name: string;
228
+ order: number;
229
+ icon?: string | undefined;
230
+ render?: any;
231
+ }[] | undefined;
232
+ defaultPageId?: string | undefined;
167
233
  }>;
168
234
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
169
235
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -181,6 +247,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
181
247
  dependencies?: string[] | undefined;
182
248
  } | undefined;
183
249
  props?: Record<string, any> | undefined;
250
+ render?: any;
184
251
  states?: Record<string, any> | undefined;
185
252
  methods?: Record<string, {
186
253
  fn: string;
@@ -191,7 +258,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
191
258
  deps?: string[] | undefined;
192
259
  }[] | undefined;
193
260
  data?: Record<string, any> | undefined;
194
- render?: any;
261
+ pages?: {
262
+ id: string;
263
+ name: string;
264
+ order: number;
265
+ icon?: string | undefined;
266
+ render?: any;
267
+ }[] | undefined;
268
+ defaultPageId?: string | undefined;
195
269
  };
196
270
  data?: Record<string, any> | undefined;
197
271
  context?: Record<string, any> | undefined;
@@ -209,6 +283,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
209
283
  dependencies?: string[] | undefined;
210
284
  } | undefined;
211
285
  props?: Record<string, any> | undefined;
286
+ render?: any;
212
287
  states?: Record<string, any> | undefined;
213
288
  methods?: Record<string, {
214
289
  fn: string;
@@ -219,7 +294,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
219
294
  deps?: string[] | undefined;
220
295
  }[] | undefined;
221
296
  data?: Record<string, any> | undefined;
222
- render?: any;
297
+ pages?: {
298
+ id: string;
299
+ name: string;
300
+ order: number;
301
+ icon?: string | undefined;
302
+ render?: any;
303
+ }[] | undefined;
304
+ defaultPageId?: string | undefined;
223
305
  };
224
306
  data?: Record<string, any> | undefined;
225
307
  context?: Record<string, any> | undefined;
@@ -292,6 +374,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
292
374
  dependencies?: string[] | undefined;
293
375
  } | undefined;
294
376
  props?: Record<string, any> | undefined;
377
+ render?: any;
295
378
  states?: Record<string, any> | undefined;
296
379
  methods?: Record<string, {
297
380
  fn: string;
@@ -302,7 +385,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
302
385
  deps?: string[] | undefined;
303
386
  }[] | undefined;
304
387
  data?: Record<string, any> | undefined;
305
- render?: any;
306
388
  }, {
307
389
  id: string;
308
390
  name?: string | undefined;
@@ -316,6 +398,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
316
398
  dependencies?: string[] | undefined;
317
399
  } | undefined;
318
400
  props?: Record<string, any> | undefined;
401
+ render?: any;
319
402
  states?: Record<string, any> | undefined;
320
403
  methods?: Record<string, {
321
404
  fn: string;
@@ -326,7 +409,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
326
409
  deps?: string[] | undefined;
327
410
  }[] | undefined;
328
411
  data?: Record<string, any> | undefined;
329
- render?: any;
330
412
  }>;
331
413
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
332
414
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -344,6 +426,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
344
426
  dependencies?: string[] | undefined;
345
427
  } | undefined;
346
428
  props?: Record<string, any> | undefined;
429
+ render?: any;
347
430
  states?: Record<string, any> | undefined;
348
431
  methods?: Record<string, {
349
432
  fn: string;
@@ -354,7 +437,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
354
437
  deps?: string[] | undefined;
355
438
  }[] | undefined;
356
439
  data?: Record<string, any> | undefined;
357
- render?: any;
358
440
  };
359
441
  data?: Record<string, any> | undefined;
360
442
  context?: Record<string, any> | undefined;
@@ -372,6 +454,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
372
454
  dependencies?: string[] | undefined;
373
455
  } | undefined;
374
456
  props?: Record<string, any> | undefined;
457
+ render?: any;
375
458
  states?: Record<string, any> | undefined;
376
459
  methods?: Record<string, {
377
460
  fn: string;
@@ -382,7 +465,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
382
465
  deps?: string[] | undefined;
383
466
  }[] | undefined;
384
467
  data?: Record<string, any> | undefined;
385
- render?: any;
386
468
  };
387
469
  data?: Record<string, any> | undefined;
388
470
  context?: Record<string, any> | undefined;
@@ -563,24 +645,203 @@ declare const IncomingMessageSchema: z.ZodObject<{
563
645
  payload?: unknown;
564
646
  }>;
565
647
  type IncomingMessage = z.infer<typeof IncomingMessageSchema>;
648
+ declare const ComponentSchema: z.ZodObject<{
649
+ id: z.ZodString;
650
+ name: z.ZodString;
651
+ displayName: z.ZodOptional<z.ZodString>;
652
+ isDisplayComp: z.ZodOptional<z.ZodBoolean>;
653
+ type: z.ZodString;
654
+ description: z.ZodString;
655
+ props: z.ZodObject<{
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
+ }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
662
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
663
+ title: z.ZodOptional<z.ZodString>;
664
+ description: z.ZodOptional<z.ZodString>;
665
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
666
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
667
+ }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
668
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
669
+ title: z.ZodOptional<z.ZodString>;
670
+ description: z.ZodOptional<z.ZodString>;
671
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
672
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
673
+ }, z.ZodTypeAny, "passthrough">>;
674
+ category: z.ZodOptional<z.ZodString>;
675
+ keywords: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
676
+ }, "strip", z.ZodTypeAny, {
677
+ id: string;
678
+ type: string;
679
+ name: string;
680
+ description: string;
681
+ props: {
682
+ description?: string | undefined;
683
+ query?: string | {} | null | undefined;
684
+ title?: string | undefined;
685
+ config?: Record<string, unknown> | undefined;
686
+ actions?: any[] | undefined;
687
+ } & {
688
+ [k: string]: unknown;
689
+ };
690
+ displayName?: string | undefined;
691
+ isDisplayComp?: boolean | undefined;
692
+ category?: string | undefined;
693
+ keywords?: string[] | undefined;
694
+ }, {
695
+ id: string;
696
+ type: string;
697
+ name: string;
698
+ description: string;
699
+ props: {
700
+ description?: string | undefined;
701
+ query?: string | {} | null | undefined;
702
+ title?: string | undefined;
703
+ config?: Record<string, unknown> | undefined;
704
+ actions?: any[] | undefined;
705
+ } & {
706
+ [k: string]: unknown;
707
+ };
708
+ displayName?: string | undefined;
709
+ isDisplayComp?: boolean | undefined;
710
+ category?: string | undefined;
711
+ keywords?: string[] | undefined;
712
+ }>;
713
+ type Component = z.infer<typeof ComponentSchema>;
714
+ declare const OutputFieldSchema: z.ZodObject<{
715
+ name: z.ZodString;
716
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
717
+ description: z.ZodString;
718
+ }, "strip", z.ZodTypeAny, {
719
+ type: "string" | "number" | "boolean" | "date";
720
+ name: string;
721
+ description: string;
722
+ }, {
723
+ type: "string" | "number" | "boolean" | "date";
724
+ name: string;
725
+ description: string;
726
+ }>;
727
+ type OutputField = z.infer<typeof OutputFieldSchema>;
728
+ declare const OutputSchema: z.ZodObject<{
729
+ description: z.ZodString;
730
+ fields: z.ZodArray<z.ZodObject<{
731
+ name: z.ZodString;
732
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
733
+ description: z.ZodString;
734
+ }, "strip", z.ZodTypeAny, {
735
+ type: "string" | "number" | "boolean" | "date";
736
+ name: string;
737
+ description: string;
738
+ }, {
739
+ type: "string" | "number" | "boolean" | "date";
740
+ name: string;
741
+ description: string;
742
+ }>, "many">;
743
+ }, "strip", z.ZodTypeAny, {
744
+ description: string;
745
+ fields: {
746
+ type: "string" | "number" | "boolean" | "date";
747
+ name: string;
748
+ description: string;
749
+ }[];
750
+ }, {
751
+ description: string;
752
+ fields: {
753
+ type: "string" | "number" | "boolean" | "date";
754
+ name: string;
755
+ description: string;
756
+ }[];
757
+ }>;
758
+ type ToolOutputSchema = z.infer<typeof OutputSchema>;
566
759
  declare const ToolSchema: z.ZodObject<{
567
760
  id: z.ZodString;
568
761
  name: z.ZodString;
569
762
  description: z.ZodString;
763
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
764
+ toolType: z.ZodOptional<z.ZodEnum<["source", "direct"]>>;
765
+ /** Full untruncated schema for source agent (all columns visible) */
766
+ fullSchema: z.ZodOptional<z.ZodString>;
570
767
  params: z.ZodRecord<z.ZodString, z.ZodString>;
571
768
  fn: z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodAny>;
769
+ outputSchema: z.ZodOptional<z.ZodObject<{
770
+ description: z.ZodString;
771
+ fields: z.ZodArray<z.ZodObject<{
772
+ name: z.ZodString;
773
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
774
+ description: z.ZodString;
775
+ }, "strip", z.ZodTypeAny, {
776
+ type: "string" | "number" | "boolean" | "date";
777
+ name: string;
778
+ description: string;
779
+ }, {
780
+ type: "string" | "number" | "boolean" | "date";
781
+ name: string;
782
+ description: string;
783
+ }>, "many">;
784
+ }, "strip", z.ZodTypeAny, {
785
+ description: string;
786
+ fields: {
787
+ type: "string" | "number" | "boolean" | "date";
788
+ name: string;
789
+ description: string;
790
+ }[];
791
+ }, {
792
+ description: string;
793
+ fields: {
794
+ type: "string" | "number" | "boolean" | "date";
795
+ name: string;
796
+ description: string;
797
+ }[];
798
+ }>>;
799
+ /** Cache policy. `false` = never cache (live data, write ops). Mirrors HTTP `Cache-Control: no-store`. */
800
+ cache: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<false>, z.ZodObject<{
801
+ ttlMs: z.ZodOptional<z.ZodNumber>;
802
+ }, "strip", z.ZodTypeAny, {
803
+ ttlMs?: number | undefined;
804
+ }, {
805
+ ttlMs?: number | undefined;
806
+ }>]>>;
572
807
  }, "strip", z.ZodTypeAny, {
573
808
  id: string;
574
809
  params: Record<string, string>;
575
810
  name: string;
576
811
  description: string;
577
812
  fn: (args_0: any, ...args: unknown[]) => any;
813
+ toolType?: "source" | "direct" | undefined;
814
+ fullSchema?: string | undefined;
815
+ outputSchema?: {
816
+ description: string;
817
+ fields: {
818
+ type: "string" | "number" | "boolean" | "date";
819
+ name: string;
820
+ description: string;
821
+ }[];
822
+ } | undefined;
823
+ cache?: false | {
824
+ ttlMs?: number | undefined;
825
+ } | undefined;
578
826
  }, {
579
827
  id: string;
580
828
  params: Record<string, string>;
581
829
  name: string;
582
830
  description: string;
583
831
  fn: (args_0: any, ...args: unknown[]) => any;
832
+ toolType?: "source" | "direct" | undefined;
833
+ fullSchema?: string | undefined;
834
+ outputSchema?: {
835
+ description: string;
836
+ fields: {
837
+ type: "string" | "number" | "boolean" | "date";
838
+ name: string;
839
+ description: string;
840
+ }[];
841
+ } | undefined;
842
+ cache?: false | {
843
+ ttlMs?: number | undefined;
844
+ } | undefined;
584
845
  }>;
585
846
  type Tool$1 = z.infer<typeof ToolSchema>;
586
847
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
@@ -588,11 +849,33 @@ type CollectionHandler<TParams = any, TResult = any> = (params: TParams) => Prom
588
849
  type LLMProvider = 'anthropic' | 'groq' | 'gemini' | 'openai';
589
850
 
590
851
  type DatabaseType = 'postgresql' | 'mssql' | 'snowflake' | 'mysql';
852
+ /**
853
+ * Model strategy for controlling which models are used for different tasks
854
+ * - 'best': Use the best model (e.g., Sonnet) for all tasks - highest quality, higher cost
855
+ * - 'fast': Use the fast model (e.g., Haiku) for all tasks - lower quality, lower cost
856
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
857
+ */
858
+ type ModelStrategy = 'best' | 'fast' | 'balanced';
859
+ /**
860
+ * Model configuration for DASH_COMP flow (dashboard component picking)
861
+ * Allows separate control of models used for component selection
862
+ */
863
+ interface DashCompModelConfig {
864
+ /**
865
+ * Primary model for DASH_COMP requests
866
+ * Format: "provider/model-name" (e.g., "anthropic/claude-sonnet-4-5-20250929")
867
+ */
868
+ model?: string;
869
+ /**
870
+ * Fast model for simpler DASH_COMP tasks (optional)
871
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
872
+ */
873
+ fastModel?: string;
874
+ }
591
875
  interface SuperatomSDKConfig {
592
876
  url?: string;
593
877
  apiKey?: string;
594
878
  projectId: string;
595
- userId?: string;
596
879
  type?: string;
597
880
  bundleDir?: string;
598
881
  promptsDir?: string;
@@ -603,22 +886,68 @@ interface SuperatomSDKConfig {
603
886
  OPENAI_API_KEY?: string;
604
887
  LLM_PROVIDERS?: LLMProvider[];
605
888
  logLevel?: LogLevel;
889
+ /**
890
+ * Model selection strategy for LLM API calls:
891
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
892
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
893
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
894
+ */
895
+ modelStrategy?: ModelStrategy;
896
+ /**
897
+ * Model for the main agent (routing + analysis).
898
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
899
+ * If not set, uses the provider's default model.
900
+ */
901
+ mainAgentModel?: string;
902
+ /**
903
+ * Model for source agents (per-source query generation).
904
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
905
+ * If not set, uses the provider's default model.
906
+ */
907
+ sourceAgentModel?: string;
908
+ /**
909
+ * Separate model configuration for DASH_COMP flow (dashboard component picking)
910
+ * If not provided, falls back to provider-based model selection
911
+ */
912
+ dashCompModels?: DashCompModelConfig;
913
+ /**
914
+ * Similarity threshold for conversation search (semantic matching)
915
+ * Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
916
+ * Higher values require closer matches, lower values allow more distant matches
917
+ * Default: 0.8
918
+ */
919
+ conversationSimilarityThreshold?: number;
920
+ /**
921
+ * Query cache TTL (Time To Live) in minutes
922
+ * Cached query results expire after this duration
923
+ * Default: 5 minutes
924
+ */
925
+ queryCacheTTL?: number;
926
+ /**
927
+ * Dashboard conversation history TTL (Time To Live) in minutes
928
+ * Per-dashboard conversation histories expire after this duration
929
+ * Default: 30 minutes
930
+ */
931
+ dashboardHistoryTTL?: number;
606
932
  }
607
933
 
608
934
  declare const KbNodesQueryFiltersSchema: z.ZodObject<{
609
935
  query: z.ZodOptional<z.ZodString>;
610
936
  category: z.ZodOptional<z.ZodString>;
611
937
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
612
- createdBy: z.ZodOptional<z.ZodNumber>;
938
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
939
+ createdBy: z.ZodOptional<z.ZodString>;
613
940
  }, "strip", z.ZodTypeAny, {
941
+ type?: "query" | "user" | "global" | undefined;
614
942
  query?: string | undefined;
615
943
  category?: string | undefined;
616
- createdBy?: number | undefined;
944
+ createdBy?: string | undefined;
617
945
  tags?: string[] | undefined;
618
946
  }, {
947
+ type?: "query" | "user" | "global" | undefined;
619
948
  query?: string | undefined;
620
949
  category?: string | undefined;
621
- createdBy?: number | undefined;
950
+ createdBy?: string | undefined;
622
951
  tags?: string[] | undefined;
623
952
  }>;
624
953
  type KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
@@ -630,109 +959,126 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
630
959
  content: z.ZodOptional<z.ZodString>;
631
960
  category: z.ZodOptional<z.ZodString>;
632
961
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
633
- createdBy: z.ZodOptional<z.ZodNumber>;
634
- updatedBy: z.ZodOptional<z.ZodNumber>;
635
- userId: z.ZodOptional<z.ZodNumber>;
962
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
963
+ createdBy: z.ZodOptional<z.ZodString>;
964
+ updatedBy: z.ZodOptional<z.ZodString>;
965
+ userId: z.ZodOptional<z.ZodString>;
636
966
  query: z.ZodOptional<z.ZodString>;
637
967
  filters: z.ZodOptional<z.ZodObject<{
638
968
  query: z.ZodOptional<z.ZodString>;
639
969
  category: z.ZodOptional<z.ZodString>;
640
970
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
641
- createdBy: z.ZodOptional<z.ZodNumber>;
971
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
972
+ createdBy: z.ZodOptional<z.ZodString>;
642
973
  }, "strip", z.ZodTypeAny, {
974
+ type?: "query" | "user" | "global" | undefined;
643
975
  query?: string | undefined;
644
976
  category?: string | undefined;
645
- createdBy?: number | undefined;
977
+ createdBy?: string | undefined;
646
978
  tags?: string[] | undefined;
647
979
  }, {
980
+ type?: "query" | "user" | "global" | undefined;
648
981
  query?: string | undefined;
649
982
  category?: string | undefined;
650
- createdBy?: number | undefined;
983
+ createdBy?: string | undefined;
651
984
  tags?: string[] | undefined;
652
985
  }>>;
653
986
  limit: z.ZodOptional<z.ZodNumber>;
654
987
  offset: z.ZodOptional<z.ZodNumber>;
655
988
  }, "strip", z.ZodTypeAny, {
656
989
  id?: number | undefined;
990
+ type?: "query" | "user" | "global" | undefined;
657
991
  query?: string | undefined;
658
992
  title?: string | undefined;
659
993
  category?: string | undefined;
660
- userId?: number | undefined;
994
+ userId?: string | undefined;
661
995
  limit?: number | undefined;
662
996
  filters?: {
997
+ type?: "query" | "user" | "global" | undefined;
663
998
  query?: string | undefined;
664
999
  category?: string | undefined;
665
- createdBy?: number | undefined;
1000
+ createdBy?: string | undefined;
666
1001
  tags?: string[] | undefined;
667
1002
  } | undefined;
668
- createdBy?: number | undefined;
669
- updatedBy?: number | undefined;
1003
+ createdBy?: string | undefined;
1004
+ updatedBy?: string | undefined;
1005
+ offset?: number | undefined;
670
1006
  tags?: string[] | undefined;
671
1007
  content?: string | undefined;
672
- offset?: number | undefined;
673
1008
  }, {
674
1009
  id?: number | undefined;
1010
+ type?: "query" | "user" | "global" | undefined;
675
1011
  query?: string | undefined;
676
1012
  title?: string | undefined;
677
1013
  category?: string | undefined;
678
- userId?: number | undefined;
1014
+ userId?: string | undefined;
679
1015
  limit?: number | undefined;
680
1016
  filters?: {
1017
+ type?: "query" | "user" | "global" | undefined;
681
1018
  query?: string | undefined;
682
1019
  category?: string | undefined;
683
- createdBy?: number | undefined;
1020
+ createdBy?: string | undefined;
684
1021
  tags?: string[] | undefined;
685
1022
  } | undefined;
686
- createdBy?: number | undefined;
687
- updatedBy?: number | undefined;
1023
+ createdBy?: string | undefined;
1024
+ updatedBy?: string | undefined;
1025
+ offset?: number | undefined;
688
1026
  tags?: string[] | undefined;
689
1027
  content?: string | undefined;
690
- offset?: number | undefined;
691
1028
  }>>;
692
1029
  }, "strip", z.ZodTypeAny, {
693
1030
  operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
694
1031
  data?: {
695
1032
  id?: number | undefined;
1033
+ type?: "query" | "user" | "global" | undefined;
696
1034
  query?: string | undefined;
697
1035
  title?: string | undefined;
698
1036
  category?: string | undefined;
699
- userId?: number | undefined;
1037
+ userId?: string | undefined;
700
1038
  limit?: number | undefined;
701
1039
  filters?: {
1040
+ type?: "query" | "user" | "global" | undefined;
702
1041
  query?: string | undefined;
703
1042
  category?: string | undefined;
704
- createdBy?: number | undefined;
1043
+ createdBy?: string | undefined;
705
1044
  tags?: string[] | undefined;
706
1045
  } | undefined;
707
- createdBy?: number | undefined;
708
- updatedBy?: number | undefined;
1046
+ createdBy?: string | undefined;
1047
+ updatedBy?: string | undefined;
1048
+ offset?: number | undefined;
709
1049
  tags?: string[] | undefined;
710
1050
  content?: string | undefined;
711
- offset?: number | undefined;
712
1051
  } | undefined;
713
1052
  }, {
714
1053
  operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
715
1054
  data?: {
716
1055
  id?: number | undefined;
1056
+ type?: "query" | "user" | "global" | undefined;
717
1057
  query?: string | undefined;
718
1058
  title?: string | undefined;
719
1059
  category?: string | undefined;
720
- userId?: number | undefined;
1060
+ userId?: string | undefined;
721
1061
  limit?: number | undefined;
722
1062
  filters?: {
1063
+ type?: "query" | "user" | "global" | undefined;
723
1064
  query?: string | undefined;
724
1065
  category?: string | undefined;
725
- createdBy?: number | undefined;
1066
+ createdBy?: string | undefined;
726
1067
  tags?: string[] | undefined;
727
1068
  } | undefined;
728
- createdBy?: number | undefined;
729
- updatedBy?: number | undefined;
1069
+ createdBy?: string | undefined;
1070
+ updatedBy?: string | undefined;
1071
+ offset?: number | undefined;
730
1072
  tags?: string[] | undefined;
731
1073
  content?: string | undefined;
732
- offset?: number | undefined;
733
1074
  } | undefined;
734
1075
  }>;
735
1076
  type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
1077
+ interface T_RESPONSE {
1078
+ success: boolean;
1079
+ data?: any;
1080
+ errors: string[];
1081
+ }
736
1082
 
737
1083
  /**
738
1084
  * UserManager class to handle CRUD operations on users with file persistence
@@ -993,130 +1339,1406 @@ declare class ReportManager {
993
1339
  getReportCount(): number;
994
1340
  }
995
1341
 
996
- type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
997
- interface LLMMessages {
998
- sys: SystemPrompt;
999
- user: string;
1000
- }
1001
- interface LLMOptions {
1002
- model?: string;
1003
- maxTokens?: number;
1004
- temperature?: number;
1005
- topP?: number;
1006
- apiKey?: string;
1007
- partial?: (chunk: string) => void;
1008
- }
1009
- interface Tool {
1010
- name: string;
1011
- description: string;
1012
- input_schema: {
1013
- type: string;
1014
- properties: Record<string, any>;
1015
- required?: string[];
1016
- };
1017
- }
1018
- declare class LLM {
1019
- static text(messages: LLMMessages, options?: LLMOptions): Promise<string>;
1020
- static stream<T = string>(messages: LLMMessages, options?: LLMOptions, json?: boolean): Promise<T extends string ? string : any>;
1021
- static streamWithTools(messages: LLMMessages, tools: Tool[], toolHandler: (toolName: string, toolInput: any) => Promise<any>, options?: LLMOptions, maxIterations?: number): Promise<string>;
1342
+ /**
1343
+ * StreamBuffer - Buffered streaming utility for smoother text delivery
1344
+ * Batches small chunks together and flushes at regular intervals
1345
+ */
1346
+ type StreamCallback = (chunk: string) => void;
1347
+ /**
1348
+ * StreamBuffer class for managing buffered streaming output
1349
+ * Provides smooth text delivery by batching small chunks
1350
+ */
1351
+ declare class StreamBuffer {
1352
+ private buffer;
1353
+ private flushTimer;
1354
+ private callback;
1355
+ private fullText;
1356
+ constructor(callback?: StreamCallback);
1022
1357
  /**
1023
- * Normalize system prompt to Anthropic format
1024
- * Converts string to array format if needed
1025
- * @param sys - System prompt (string or array of blocks)
1026
- * @returns Normalized system prompt for Anthropic API
1358
+ * Check if the buffer has a callback configured
1027
1359
  */
1028
- private static _normalizeSystemPrompt;
1360
+ hasCallback(): boolean;
1029
1361
  /**
1030
- * Log cache usage metrics from Anthropic API response
1031
- * Shows cache hits, costs, and savings
1362
+ * Get all text that has been written (including already flushed)
1032
1363
  */
1033
- private static _logCacheUsage;
1364
+ getFullText(): string;
1034
1365
  /**
1035
- * Parse model string to extract provider and model name
1036
- * @param modelString - Format: "provider/model-name" or just "model-name"
1037
- * @returns [provider, modelName]
1366
+ * Write a chunk to the buffer
1367
+ * Large chunks or chunks with newlines are flushed immediately
1368
+ * Small chunks are batched and flushed after a short interval
1038
1369
  *
1039
- * @example
1040
- * "anthropic/claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"]
1041
- * "groq/openai/gpt-oss-120b" → ["groq", "openai/gpt-oss-120b"]
1042
- * "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
1370
+ * @param chunk - Text chunk to write
1043
1371
  */
1044
- private static _parseModel;
1045
- private static _anthropicText;
1046
- private static _anthropicStream;
1047
- private static _anthropicStreamWithTools;
1048
- private static _groqText;
1049
- private static _groqStream;
1050
- private static _geminiText;
1051
- private static _geminiStream;
1052
- private static _geminiStreamWithTools;
1053
- private static _openaiText;
1054
- private static _openaiStream;
1055
- private static _openaiStreamWithTools;
1372
+ write(chunk: string): void;
1056
1373
  /**
1057
- * Parse JSON string, handling markdown code blocks and surrounding text
1058
- * Enhanced version with jsonrepair to handle malformed JSON from LLMs
1059
- * @param text - Text that may contain JSON wrapped in ```json...``` or with surrounding text
1060
- * @returns Parsed JSON object or array
1374
+ * Flush the buffer immediately
1375
+ * Call this before tool execution or other operations that need clean output
1061
1376
  */
1062
- private static _parseJSON;
1377
+ flush(): void;
1378
+ /**
1379
+ * Internal flush implementation
1380
+ */
1381
+ private flushNow;
1382
+ /**
1383
+ * Clean up resources
1384
+ * Call this when done with the buffer
1385
+ */
1386
+ dispose(): void;
1063
1387
  }
1064
1388
 
1065
- interface CapturedLog {
1066
- timestamp: number;
1067
- level: 'info' | 'error' | 'warn' | 'debug';
1068
- message: string;
1069
- type?: 'explanation' | 'query' | 'general';
1070
- data?: Record<string, any>;
1389
+ /**
1390
+ * ToolExecutorService - Handles execution of SQL queries and external tools
1391
+ * Extracted from BaseLLM.generateTextResponse for better separation of concerns
1392
+ */
1393
+
1394
+ /**
1395
+ * External tool definition
1396
+ */
1397
+ interface ExternalTool {
1398
+ id: string;
1399
+ name: string;
1400
+ description?: string;
1401
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
1402
+ toolType?: 'source' | 'direct';
1403
+ /** Full untruncated schema for source agent (all columns visible) */
1404
+ fullSchema?: string;
1405
+ /** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
1406
+ schemaTier?: string;
1407
+ /** Schema search function for very_large tier — keyword search over entities */
1408
+ schemaSearchFn?: (keywords: string[]) => string;
1409
+ fn: (input: any) => Promise<any>;
1410
+ limit?: number;
1411
+ outputSchema?: any;
1412
+ executionType?: 'immediate' | 'deferred';
1413
+ userProvidedData?: any;
1414
+ params?: Record<string, any>;
1071
1415
  }
1072
1416
  /**
1073
- * UILogCollector captures logs during user prompt processing
1074
- * and sends them to runtime via ui_logs message with uiBlockId as the message id
1075
- * Logs are sent in real-time for streaming effect in the UI
1076
- * Respects the global log level configuration
1417
+ * Executed tool tracking info
1077
1418
  */
1078
- declare class UILogCollector {
1079
- private logs;
1080
- private uiBlockId;
1081
- private clientId;
1082
- private sendMessage;
1083
- private currentLogLevel;
1084
- constructor(clientId: string, sendMessage: (message: Message) => void, uiBlockId?: string);
1085
- /**
1086
- * Check if logging is enabled (uiBlockId is provided)
1087
- */
1088
- isEnabled(): boolean;
1089
- /**
1090
- * Check if a message should be logged based on current log level
1091
- */
1092
- private shouldLog;
1093
- /**
1094
- * Add a log entry with timestamp and immediately send to runtime
1095
- * Only logs that pass the log level filter are captured and sent
1096
- */
1097
- private addLog;
1098
- /**
1099
- * Send a single log to runtime immediately
1100
- */
1101
- private sendLogImmediately;
1102
- /**
1103
- * Log info message
1104
- */
1105
- info(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
1106
- /**
1107
- * Log error message
1419
+ interface ExecutedToolInfo {
1420
+ id: string;
1421
+ name: string;
1422
+ params: any;
1423
+ result: {
1424
+ _totalRecords: number;
1425
+ _recordsShown: number;
1426
+ _metadata?: any;
1427
+ _sampleData: any[];
1428
+ /** Bounded summary over the FULL fetched result (complete structure). */
1429
+ _summary?: any;
1430
+ /** Up to MAIN_AGENT_COMPLETE_ROWS rows — the complete result when small. */
1431
+ _mainAgentRows?: any[];
1432
+ };
1433
+ outputSchema?: any;
1434
+ sourceSchema?: string;
1435
+ sourceType?: string;
1436
+ }
1437
+
1438
+ /**
1439
+ * Script Flow Types
1440
+ *
1441
+ * Defines interfaces for the script-based query architecture:
1442
+ * - ScriptRecipe: metadata for matching, validation, and quality tracking
1443
+ * - ScriptResult: output from executing a script
1444
+ * - ScriptMatch: result from the LLM-based script matcher
1445
+ */
1446
+ /**
1447
+ * Recipe metadata stored alongside each script.
1448
+ * Used for matching, validation, and quality tracking.
1449
+ */
1450
+ interface ScriptRecipe {
1451
+ /** Unique script identifier */
1452
+ id: string;
1453
+ /** Version number (incremented on regeneration) */
1454
+ version: number;
1455
+ /** Human-readable name (e.g., "Revenue by Dimension") */
1456
+ name: string;
1457
+ /** Natural language description of what this script does */
1458
+ intentDescription: string;
1459
+ /** Keyword tags for quick filtering */
1460
+ tags: string[];
1461
+ /** Source tool IDs this script queries (e.g., ["mssql-abc123_query"]) */
1462
+ sourceIds: string[];
1463
+ /** Table names used (for future schema drift detection) */
1464
+ tables: string[];
1465
+ /** Parameter definitions — what can vary */
1466
+ parameters: ScriptParameter[];
1467
+ /** The script function body as a string. Loaded from disk (scripts-store/<fileBase>.ts). */
1468
+ scriptBody: string;
1469
+ /**
1470
+ * On-disk filename stem for the body: scripts-store/<fileBase>.ts.
1471
+ * Editable in the IDE. Decided at authoring time (slug of `name`, with a
1472
+ * short id suffix on collision) and stable across promotion.
1473
+ */
1474
+ fileBase?: string;
1475
+ /** sha256 of the on-disk body — lets the runtime detect manual edits. */
1476
+ bodyHash?: string;
1477
+ /** Project scope (single-VM deployments may leave this undefined). */
1478
+ projectId?: string;
1479
+ /** Times this script was used successfully */
1480
+ successCount: number;
1481
+ /** Times this script failed */
1482
+ failureCount: number;
1483
+ /** ISO timestamp of last usage */
1484
+ lastUsed: string;
1485
+ /** Original user question that created this script */
1486
+ createdFrom: string;
1487
+ /** ISO timestamp */
1488
+ createdAt: string;
1489
+ /** ISO timestamp */
1490
+ updatedAt: string;
1491
+ /**
1492
+ * `recipe.id` of the parent this script was forked from.
1493
+ * Undefined for root scripts (those written from scratch by MainAgent).
1494
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md.
1495
+ */
1496
+ parentId?: string;
1497
+ /** 0 for root scripts; `parent.forkDepth + 1` for forks. Capped at 3. */
1498
+ forkDepth?: number;
1499
+ /**
1500
+ * Brief description of what this fork changed vs its parent
1501
+ * (sourced from the matcher's `modificationHint`).
1502
+ */
1503
+ forkReason?: string;
1504
+ /**
1505
+ * Validated component specs captured at authoring time. On a tier-high
1506
+ * replay these are rebound to fresh queryIds deterministically — no
1507
+ * component-generation LLM call, and the rendered columns can't drift from
1508
+ * what was validated when the script was authored. Absent on recipes
1509
+ * authored before this landed; those fall back to LLM component generation.
1510
+ * See backend/docs/SCRIPT-COMPONENT-CONSISTENCY.md.
1511
+ */
1512
+ components?: ScriptComponentSpec[];
1513
+ /**
1514
+ * What the user explicitly asked the output to LOOK like, set by a display
1515
+ * edit ("show that as a bar chart", "make the bars horizontal").
1516
+ *
1517
+ * Deliberately SEPARATE from `components`. Those are validated bindings that
1518
+ * must be cleared on a data edit — after "break it down by brand" the axis
1519
+ * keys are wrong, and after "use the mode" the stored title still says
1520
+ * "Average…". A rendering CHOICE, by contrast, is still valid afterwards.
1521
+ * Keeping them in one field meant every data edit silently discarded the
1522
+ * user's chart type.
1523
+ *
1524
+ * Fed to the component generator as a hint whenever specs are (re)generated,
1525
+ * so the chosen rendering comes back even after the SQL changes.
1526
+ */
1527
+ displayPreference?: ScriptDisplayPreference;
1528
+ /**
1529
+ * Lifecycle stage of this recipe on disk.
1530
+ * - 'draft': written by MainAgent's write_script during a turn; filtered out
1531
+ * of FTS results (status='verified' only) so the matcher never picks it.
1532
+ * Filename is suffixed with `turnId` to keep concurrent turns
1533
+ * from clobbering each other's drafts.
1534
+ * - 'verified': promoted after `execute_script` succeeded; the matcher sees it.
1535
+ * Filename drops the turn suffix unless a verified file with
1536
+ * the same slug already exists (collision case keeps the suffix).
1537
+ *
1538
+ * Recipes loaded from disk without this field default to 'verified' so
1539
+ * existing scripts keep working unchanged.
1108
1540
  */
1109
- error(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
1541
+ status?: 'draft' | 'verified';
1110
1542
  /**
1111
- * Log warning message
1543
+ * Per-turn unique suffix used for draft filenames (e.g. `1714745623-x9k2`).
1544
+ * Set when the draft is saved; carried until the recipe is promoted.
1112
1545
  */
1113
- warn(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
1546
+ turnId?: string;
1114
1547
  /**
1115
- * Log debug message
1548
+ * Last execution error captured by `recordDraftError` while the recipe was
1549
+ * still a draft. Lets users open the draft .json file and see why it failed
1550
+ * without grepping logs. Cleared on promotion to 'verified'.
1116
1551
  */
1117
- debug(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
1552
+ lastError?: {
1553
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
1554
+ message: string;
1555
+ at: string;
1556
+ attempt: number;
1557
+ };
1558
+ /** userId who committed the most recent edit (audit trail — recipes are project-scoped). */
1559
+ editedBy?: string;
1560
+ /** The instruction that produced the current version. */
1561
+ editedFrom?: string;
1118
1562
  /**
1119
- * Log LLM explanation with typed metadata
1563
+ * Prior versions, newest last. The body itself is archived on disk as
1564
+ * `<fileBase>.v<version>.ts`; this records what changed and who did it.
1565
+ */
1566
+ history?: ScriptVersionRecord[];
1567
+ }
1568
+ /**
1569
+ * A durable, user-stated rendering choice for a recipe. Survives data edits.
1570
+ */
1571
+ interface ScriptDisplayPreference {
1572
+ /** Component types the user's chosen rendering resolved to, e.g. ["DynamicBarChart"]. */
1573
+ componentTypes: string[];
1574
+ /** The instruction itself — carries nuance the types can't ("horizontal", "sorted descending"). */
1575
+ instruction: string;
1576
+ /** ISO timestamp of the display edit that set this. */
1577
+ at: string;
1578
+ }
1579
+ /** One superseded version of a recipe body (see ScriptStore.commitEdit). */
1580
+ interface ScriptVersionRecord {
1581
+ /** Version number this record superseded (i.e. the OLD version). */
1582
+ version: number;
1583
+ /** ISO timestamp of the edit that superseded it. */
1584
+ at: string;
1585
+ /** userId who made the edit, when known. */
1586
+ by?: string;
1587
+ /** The edit instruction that caused the supersede. */
1588
+ instruction?: string;
1589
+ /** One-line summary of what changed, for the version picker. */
1590
+ changeSummary?: string;
1591
+ /** sha256 of the superseded body — pairs with `<fileBase>.v<version>.ts`. */
1592
+ bodyHash?: string;
1593
+ }
1594
+ interface ScriptParameter {
1595
+ /** Parameter name (used in script body as params.name) */
1596
+ name: string;
1597
+ /** Parameter type */
1598
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
1599
+ /** Whether this parameter is required */
1600
+ required: boolean;
1601
+ /** Default value if not provided */
1602
+ default?: any;
1603
+ /** For enum type — maps user-facing values to internal values */
1604
+ enumValues?: Record<string, string>;
1605
+ /** Human-readable description (used in the matcher LLM prompt) */
1606
+ description: string;
1607
+ }
1608
+ /**
1609
+ * A reusable component binding captured when a script is authored. Stored on
1610
+ * the recipe so tier-high replays rebuild components deterministically (rebind
1611
+ * to fresh queryIds) instead of re-running the component-picker LLM.
1612
+ */
1613
+ interface ScriptComponentSpec {
1614
+ /** Registered component name (e.g. "DynamicBarChart") — matched against the available component library. */
1615
+ componentType: string;
1616
+ /** `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). */
1617
+ sourceRef: string;
1618
+ /** Present only when sourceRef === 'federation' — the DuckDB SQL to re-execute on replay. */
1619
+ federationSql?: string;
1620
+ /** Present only when sourceRef === 'markdown' — the narrative text to render on replay (markdown has no data source, so its content must be persisted). */
1621
+ content?: string;
1622
+ title?: string;
1623
+ description?: string;
1624
+ /** Validated axis/value keys + aggregation — all referencing real columns of the bound source. */
1625
+ config: Record<string, any>;
1626
+ }
1627
+ /**
1628
+ * Result from executing a script via ScriptRunner.
1629
+ */
1630
+ interface ScriptResult {
1631
+ /** Whether the script executed successfully */
1632
+ success: boolean;
1633
+ /** Combined data from all queries */
1634
+ data: any[];
1635
+ /** Individual query results tracked during execution */
1636
+ executedQueries: ScriptQueryResult[];
1637
+ /** Error message if failed */
1638
+ error?: string;
1639
+ /**
1640
+ * Where in the lifecycle the error occurred. Lets MainAgent's fix-loop
1641
+ * decide between "rewrite the whole draft" (compile) and "patch the
1642
+ * specific line" (runtime).
1643
+ */
1644
+ errorPhase?: 'compile' | 'runtime' | 'timeout' | 'ipc';
1645
+ /** Total execution time in milliseconds */
1646
+ executionTimeMs: number;
1647
+ }
1648
+ /**
1649
+ * A single query executed during script runtime.
1650
+ * Tracked by ScriptContext for component generation and debugging.
1651
+ */
1652
+ interface ScriptQueryResult {
1653
+ /** Source tool ID */
1654
+ sourceId: string;
1655
+ /** Human-readable source name */
1656
+ sourceName: string;
1657
+ /** The SQL that was executed */
1658
+ sql: string;
1659
+ /** Result data rows */
1660
+ data: any[];
1661
+ /** Number of rows returned */
1662
+ count: number;
1663
+ /** Total rows that matched before limit (if available) */
1664
+ totalCount?: number;
1665
+ /** Query execution time in milliseconds */
1666
+ executionTimeMs: number;
1667
+ /**
1668
+ * True for rows that did NOT come from a real SQL execution — either a
1669
+ * ctx.emit() dataset or the synthesized "computed:_final" entry that
1670
+ * carries the script's post-JS returned data. The component generator
1671
+ * uses this to route the resulting component through the script_dataset
1672
+ * sentinel toolId so the frontend resolves it via the queryCache short-circuit.
1673
+ */
1674
+ virtual?: boolean;
1675
+ }
1676
+ /**
1677
+ * Match tier returned by the LLM script matcher.
1678
+ *
1679
+ * - 'high': the script answers the question directly; only parameter values
1680
+ * may differ. The runtime replays it with extracted params (cheapest path).
1681
+ * - 'near': the script answers a STRUCTURALLY similar question but needs
1682
+ * body modification (different metric, dimension, table, filter shape).
1683
+ * The runtime forks the parent and adapts the body via MainAgent's normal
1684
+ * write_script + execute_script loop — no SourceAgent dispatch needed.
1685
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md for the full design.
1686
+ * - 'edit': the user is INSTRUCTING a change to the script that produced the
1687
+ * previous answer (not asking a new question). Only reachable when the turn
1688
+ * carries a ScriptBinding — without one the matcher coerces it to 'none', so
1689
+ * a prompt regression can't turn this into a loose similarity path. The
1690
+ * runtime runs MainAgent in edit mode and commits the result in place.
1691
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md.
1692
+ * - 'none': no script is relevant; full agent flow runs.
1693
+ */
1694
+ type MatchTier = 'high' | 'near' | 'edit' | 'none';
1695
+ /**
1696
+ * Which recipe produced the answer the user is currently looking at.
1697
+ *
1698
+ * Set whenever a turn's answer came from a script (replay, fresh authoring, or
1699
+ * a committed edit) and carried on the UIBlock + saved conversation row. Two
1700
+ * consumers:
1701
+ * 1. The matcher — the 'edit' tier is ONLY reachable when a binding exists, so
1702
+ * "use mode instead of mean" resolves to a concrete script instead of being
1703
+ * matched on keywords it shares with no script name.
1704
+ * 2. Cache invalidation — after an edit commits, conversations bound to that
1705
+ * recipeId must be dropped, or the exact-match cache replays the pre-edit
1706
+ * answer and the edit looks like a no-op.
1707
+ *
1708
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
1709
+ */
1710
+ interface ScriptBinding {
1711
+ recipeId: string;
1712
+ /** Params the script ran with — the edit's starting point. */
1713
+ params: Record<string, any>;
1714
+ /** Recipe name at bind time (matcher catalog + user-facing confirmation). */
1715
+ name: string;
1716
+ /** Columns the last run returned — grounds the editor without a re-query. */
1717
+ columns?: string[];
1718
+ /**
1719
+ * The question that produced this answer. Required for disambiguation when a
1720
+ * thread ran several scripts — without it the candidates are just names and
1721
+ * the matcher cannot resolve "use the mode for the WSP one".
1722
+ */
1723
+ userPrompt?: string;
1724
+ }
1725
+ /**
1726
+ * Result from the LLM-based script matcher.
1727
+ *
1728
+ * For `tier: 'high'`, `extractedParams` carries the values to pass to the
1729
+ * existing script. For `tier: 'near'`, `gaps` and `modificationHint` describe
1730
+ * what the fork-author needs to change in the parent body.
1731
+ */
1732
+ interface ScriptMatch {
1733
+ /** The matched script recipe */
1734
+ recipe: ScriptRecipe;
1735
+ /** Match tier — see MatchTier docs */
1736
+ tier: MatchTier;
1737
+ /** Similarity score (0-1, derived from LLM tier) */
1738
+ similarity: number;
1739
+ /**
1740
+ * Legacy confidence level. Mirrors `tier === 'high'`/`'near'` for now;
1741
+ * kept so existing callers compile while we migrate to tier-based logic.
1742
+ */
1743
+ confidence: 'high' | 'medium';
1744
+ /** Parameters extracted from the user question by the LLM (tier='high') */
1745
+ extractedParams?: Record<string, any>;
1746
+ /** What the user question needs that the parent doesn't cover (tier='near') */
1747
+ gaps?: string[];
1748
+ /** One-sentence description of the change the fork-author should make (tier='near') */
1749
+ modificationHint?: string;
1750
+ /**
1751
+ * Which HALF of the recipe the edit targets (tier='edit'). A recipe has two
1752
+ * independently editable halves:
1753
+ * - 'data' — the scriptBody: how the rows are produced (aggregation,
1754
+ * filters, joins, grouping). Runs MainAgent in edit mode.
1755
+ * - 'display' — the component specs: how those SAME rows are shown (chart
1756
+ * type, orientation, columns, labels). Replays the proven SQL
1757
+ * and regenerates the specs — never authors a script.
1758
+ * Defaults to 'data' when the matcher omits it.
1759
+ */
1760
+ editTarget?: 'data' | 'display';
1761
+ /**
1762
+ * Self-contained restatement of the change the user asked for (tier='edit').
1763
+ * MUST have pronouns/deixis resolved ("this", "it", "that column") — the edit
1764
+ * prompt never sees the conversation history, so an unresolved instruction is
1765
+ * unusable downstream.
1766
+ */
1767
+ editInstruction?: string;
1768
+ /** Why the matcher made this choice (for logs and telemetry) */
1769
+ reasoning?: string;
1770
+ }
1771
+
1772
+ /**
1773
+ * Multi-Agent Architecture Types
1774
+ *
1775
+ * Defines interfaces for the hierarchical agent system:
1776
+ * - Main Agent: ONE LLM.streamWithTools() call with source agent tools
1777
+ * - Source Agents: independent agents that query individual data sources
1778
+ *
1779
+ * The main agent sees only source summaries. When it calls a source tool,
1780
+ * the SourceAgent runs independently (own LLM, own retries) and returns clean data.
1781
+ */
1782
+
1783
+ /**
1784
+ * Per-entity detail: name, row count, and column names.
1785
+ * Gives the main agent enough context to route to the right source.
1786
+ */
1787
+ interface EntityDetail {
1788
+ /** Entity name (table, sheet, endpoint) */
1789
+ name: string;
1790
+ /** Approximate row count */
1791
+ rowCount?: number;
1792
+ /** Column/field names */
1793
+ columns: string[];
1794
+ /** Entity-level semantic summary (what the table means) — for main-agent routing. */
1795
+ summary?: string;
1796
+ }
1797
+ /**
1798
+ * Representation of a data source for the main agent.
1799
+ * Contains entity names WITH column names so the LLM can route accurately.
1800
+ */
1801
+ interface SourceSummary {
1802
+ /** Source ID (matches tool ID prefix) */
1803
+ id: string;
1804
+ /** Human-readable source name */
1805
+ name: string;
1806
+ /** Source type: postgres, excel, rest_api, etc. */
1807
+ type: string;
1808
+ /** Brief description of what data this source contains */
1809
+ description: string;
1810
+ /** Detailed entity info with column names for routing */
1811
+ entityDetails: EntityDetail[];
1812
+ /** The tool ID associated with this source */
1813
+ toolId: string;
1814
+ }
1815
+ /**
1816
+ * What a source agent returns after querying its data source.
1817
+ * The main agent uses this to analyze and compose the final response.
1818
+ */
1819
+ interface SourceAgentResult {
1820
+ /** Source ID */
1821
+ sourceId: string;
1822
+ /** Source name */
1823
+ sourceName: string;
1824
+ /** Whether the query succeeded */
1825
+ success: boolean;
1826
+ /** Result data rows */
1827
+ data: any[];
1828
+ /** Metadata about the query execution */
1829
+ metadata: SourceAgentMetadata;
1830
+ /** Tool execution info for the last successful query (backward compat) */
1831
+ executedTool: ExecutedToolInfo;
1832
+ /** All successful tool executions (primary + follow-up queries) */
1833
+ allExecutedTools?: ExecutedToolInfo[];
1834
+ /** Error message if failed */
1835
+ error?: string;
1836
+ }
1837
+ interface SourceAgentMetadata {
1838
+ /** Total rows that matched the query (before limit) */
1839
+ totalRowsMatched: number;
1840
+ /** Rows actually returned (after limit) */
1841
+ rowsReturned: number;
1842
+ /** Whether the result was truncated by the row limit */
1843
+ isLimited: boolean;
1844
+ /** The query/params that were executed */
1845
+ queryExecuted?: string;
1846
+ /** Execution time in milliseconds */
1847
+ executionTimeMs: number;
1848
+ }
1849
+ /**
1850
+ * A pre-built, multi-step UI flow registered with the SDK.
1851
+ *
1852
+ * When the main agent decides a user's question matches a workflow's whenToUse
1853
+ * trigger, it picks the workflow instead of running source agents / generating
1854
+ * dashboard components. The LLM extracts the workflow's required props from the
1855
+ * prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
1856
+ * workflow component directly — no analysis text, no chart generation. The
1857
+ * frontend renders the registered workflow component with the LLM-extracted
1858
+ * props.
1859
+ */
1860
+ interface WorkflowDescriptor {
1861
+ /** Unique workflow id (used as the LLM tool name) */
1862
+ id: string;
1863
+ /** Component name on the frontend (matches the registered React component) */
1864
+ name: string;
1865
+ /** Short human-readable description of what this workflow does */
1866
+ description: string;
1867
+ /**
1868
+ * 1–2 sentence trigger condition. The LLM uses this to decide if the
1869
+ * user's prompt matches this workflow. Be specific — e.g.
1870
+ * "User wants to *initiate* an inventory transfer (review + submit POs),
1871
+ * not just see analysis or charts."
1872
+ */
1873
+ whenToUse: string;
1874
+ /**
1875
+ * JSON-schema-style description of the props the workflow needs. Becomes
1876
+ * the LLM tool's input_schema, so the model fills these from the prompt.
1877
+ * Use the same shape as `params` on direct tools — string descriptors with
1878
+ * an optional "(optional)" suffix.
1879
+ *
1880
+ * Example:
1881
+ * ```
1882
+ * {
1883
+ * selectedStore: 'object — { id, name } of the source branch',
1884
+ * minROI: 'number (optional) — only show transfers with ROI ≥ this',
1885
+ * }
1886
+ * ```
1887
+ */
1888
+ propsSchema: Record<string, string>;
1889
+ /**
1890
+ * Optional: static prop defaults merged with LLM-extracted props before
1891
+ * the component is returned. Useful for things like the embedded
1892
+ * `externalTool` config that the workflow uses to fetch its own data.
1893
+ */
1894
+ defaultProps?: Record<string, any>;
1895
+ }
1896
+ /**
1897
+ * The workflow selection captured during a routing call.
1898
+ * Set on AgentResponse when the LLM picks a workflow tool.
1899
+ */
1900
+ interface SelectedWorkflow {
1901
+ /** Component name (matches WorkflowDescriptor.name) */
1902
+ name: string;
1903
+ /** Props extracted from the prompt + merged with workflow.defaultProps */
1904
+ props: Record<string, any>;
1905
+ }
1906
+ /**
1907
+ * Set when this turn applies a user-directed edit to an existing script instead
1908
+ * of authoring a new one. MainAgent keeps the SAME harness (tools, loop,
1909
+ * write_script/execute_script verification) and swaps only the system prompt —
1910
+ * `agent-main-edit` instead of `agent-main`.
1911
+ *
1912
+ * The two framings contradict each other on whether to query a source first, so
1913
+ * they must never be resident in one rendered prompt.
1914
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § D3.
1915
+ */
1916
+ interface EditContext {
1917
+ /** Recipe being edited — the shadow draft records it as parentId. */
1918
+ recipeId: string;
1919
+ parentName: string;
1920
+ parentBody: string;
1921
+ /** Self-contained restatement of the change (from the matcher). */
1922
+ instruction: string;
1923
+ /** Columns the last run returned — grounds the edit without a re-query. */
1924
+ lastResultColumns?: string[];
1925
+ /** Rendered parameter list of the parent, for the prompt. */
1926
+ parentParams?: string;
1927
+ }
1928
+ /**
1929
+ * The complete response from the multi-agent system.
1930
+ * Contains everything needed for text display + component generation.
1931
+ */
1932
+ interface AgentResponse {
1933
+ /** Generated text response (analysis of the data) */
1934
+ text: string;
1935
+ /** All executed tools across all source agents (for component generation) */
1936
+ executedTools: ExecutedToolInfo[];
1937
+ /** Individual results from each source agent */
1938
+ sourceResults: SourceAgentResult[];
1939
+ /**
1940
+ * Populated when MainAgent wrote AND successfully executed a script during its turn.
1941
+ * Caller (agent-user-response.ts) persists it via ScriptStore.save().
1942
+ * Absent when MainAgent didn't write one (trivial question / all attempts failed).
1943
+ */
1944
+ savedScript?: AgentWrittenScript;
1945
+ /**
1946
+ * Set when the LLM routed the question to a registered workflow component.
1947
+ * When present, the upstream caller should skip component generation and
1948
+ * return this workflow as the response.
1949
+ */
1950
+ workflow?: SelectedWorkflow;
1951
+ /**
1952
+ * Validated component specs the agent authored via `render_components`.
1953
+ * When present the caller assembles the dashboard from these instead of
1954
+ * running the component-generation LLM. Absent when the agent didn't call
1955
+ * the tool — the caller then falls back to `generateScriptComponents`.
1956
+ * See backend/docs/COMPONENT-GENERATION-V2.md §2.2.
1957
+ */
1958
+ componentSpecs?: ScriptComponentSpec[];
1959
+ /** Layout title/description from the same `render_components` call. */
1960
+ componentLayout?: {
1961
+ title: string;
1962
+ description?: string;
1963
+ };
1964
+ }
1965
+ /**
1966
+ * A script MainAgent authored + verified during its turn. Shape aligns with
1967
+ * what ScriptStore.save() needs — minus store-assigned fields (id, timestamps, counts).
1968
+ */
1969
+ interface AgentWrittenScript {
1970
+ /**
1971
+ * `ScriptRecipe.id` of the draft that was authored + verified during this turn.
1972
+ * The caller passes this to `ScriptStore.promoteToVerified(recipeId, …)` to
1973
+ * flip the draft to verified status and (when possible) drop the turn-suffix
1974
+ * from its filename.
1975
+ */
1976
+ recipeId: string;
1977
+ name: string;
1978
+ intentDescription: string;
1979
+ tags: string[];
1980
+ parameters: Array<{
1981
+ name: string;
1982
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
1983
+ required: boolean;
1984
+ default?: any;
1985
+ enumValues?: Record<string, string>;
1986
+ description: string;
1987
+ }>;
1988
+ scriptBody: string;
1989
+ /** Source IDs referenced by the script (extracted from ctx.query calls) */
1990
+ sourceIds: string[];
1991
+ /** Tables referenced in the script's SQL (regex-extracted) */
1992
+ tables: string[];
1993
+ /** Executed queries from the verified run — fed to component generation */
1994
+ executedQueries: Array<{
1995
+ sourceId: string;
1996
+ sourceName: string;
1997
+ sql: string;
1998
+ data: any[];
1999
+ count: number;
2000
+ totalCount?: number;
2001
+ executionTimeMs: number;
2002
+ /**
2003
+ * True for synthetic entries (ctx.emit datasets, the computed:_final
2004
+ * post-JS data). The component generator routes virtual sources through
2005
+ * the script_dataset sentinel toolId so the frontend resolves them via
2006
+ * queryCache instead of attempting to re-execute SQL.
2007
+ */
2008
+ virtual?: boolean;
2009
+ }>;
2010
+ }
2011
+ /**
2012
+ * Configuration for the multi-agent system.
2013
+ * Controls limits, models, and behavior.
2014
+ */
2015
+ interface AgentConfig {
2016
+ /** Max rows shown to the UI preview / inlined per source (default: 10) */
2017
+ maxRowsPerSource: number;
2018
+ /**
2019
+ * Max rows a source query may FETCH from the DB server-side (default: 2000).
2020
+ * Decoupled from what the main agent is shown: the full result is fetched and
2021
+ * summarized (bounded), but only a small/complete slice enters LLM context.
2022
+ * This lets small lookups (benchmark maps) arrive COMPLETE without letting
2023
+ * large results blow up context.
2024
+ */
2025
+ maxRowsFetched: number;
2026
+ /** Model for the main agent (routing + analysis in one LLM call) */
2027
+ mainAgentModel: string;
2028
+ /** Model for source agent query generation */
2029
+ sourceAgentModel: string;
2030
+ /** API key for LLM calls */
2031
+ apiKey?: string;
2032
+ /** Max retry attempts per source agent */
2033
+ maxRetries: number;
2034
+ /** Max tool calling iterations for the main agent loop */
2035
+ maxIterations: number;
2036
+ /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
2037
+ globalKnowledgeBase?: string;
2038
+ /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
2039
+ knowledgeBaseContext?: string;
2040
+ /** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
2041
+ collections?: any;
2042
+ /** Optional project ID for scoping embedding searches */
2043
+ projectId?: string;
2044
+ }
2045
+ /**
2046
+ * Default agent configuration
2047
+ */
2048
+ declare const DEFAULT_AGENT_CONFIG: AgentConfig;
2049
+
2050
+ /**
2051
+ * ScriptRecipeStore — injected metadata backend for the script flow.
2052
+ *
2053
+ * The SDK is standalone (no DB dependency). The backend implements this
2054
+ * interface over Postgres (full-text search + atomic counters) and injects it
2055
+ * via `collections['script-recipes']`, exactly like `collections['source-embeddings']`.
2056
+ * `ScriptStore` consumes it for all METADATA operations while keeping the
2057
+ * executable body on disk as scripts-store/<fileBase>.ts.
2058
+ *
2059
+ * All metadata rows are plain JSON (no scriptBody — that lives on disk).
2060
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md (#1, #3, #7).
2061
+ */
2062
+
2063
+ /** One recipe's metadata as stored in Postgres (mirrors the script_recipes table). */
2064
+ interface ScriptRecipeMetaRow {
2065
+ id: string;
2066
+ projectId?: string | null;
2067
+ version: number;
2068
+ name: string;
2069
+ intentDescription: string;
2070
+ tags: string[] | null;
2071
+ createdFrom: string | null;
2072
+ sourceIds: string[] | null;
2073
+ tables: string[] | null;
2074
+ parameters: ScriptParameter[] | null;
2075
+ components?: ScriptComponentSpec[] | null;
2076
+ displayPreference?: ScriptDisplayPreference | null;
2077
+ fileBase: string;
2078
+ bodyHash?: string | null;
2079
+ successCount: number;
2080
+ failureCount: number;
2081
+ lastUsed: string | null;
2082
+ parentId?: string | null;
2083
+ forkDepth?: number | null;
2084
+ forkReason?: string | null;
2085
+ status: 'draft' | 'verified' | string;
2086
+ turnId?: string | null;
2087
+ editedBy?: string | null;
2088
+ editedFrom?: string | null;
2089
+ history?: ScriptVersionRecord[] | null;
2090
+ lastError?: {
2091
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2092
+ message: string;
2093
+ at: string;
2094
+ attempt: number;
2095
+ } | null;
2096
+ createdAt?: string | null;
2097
+ updatedAt?: string | null;
2098
+ }
2099
+ interface ScriptRecipeStore {
2100
+ /** FTS shortlist of healthy verified recipes for the matcher (metadata only). */
2101
+ search(params: {
2102
+ prompt: string;
2103
+ projectId?: string;
2104
+ limit?: number;
2105
+ }): Promise<ScriptRecipeMetaRow[]>;
2106
+ /** Fetch one recipe by id (any status). */
2107
+ getById(id: string): Promise<ScriptRecipeMetaRow | null>;
2108
+ /** Count healthy verified recipes (drives the "any scripts?" gate). */
2109
+ count(params?: {
2110
+ projectId?: string;
2111
+ }): Promise<number>;
2112
+ /** Insert or update a recipe row (keyed by id). */
2113
+ upsert(row: ScriptRecipeMetaRow): Promise<void>;
2114
+ /** Atomically bump counters / last-used. */
2115
+ updateStats(id: string, patch: {
2116
+ successDelta?: number;
2117
+ failureDelta?: number;
2118
+ lastUsed?: string;
2119
+ }): Promise<void>;
2120
+ /** Flip a draft to verified, applying provenance + optional fork lineage. */
2121
+ promote(id: string, patch: {
2122
+ sourceIds: string[];
2123
+ tables: string[];
2124
+ fileBase?: string;
2125
+ parentId?: string;
2126
+ forkDepth?: number;
2127
+ forkReason?: string;
2128
+ components?: ScriptComponentSpec[];
2129
+ }): Promise<ScriptRecipeMetaRow | null>;
2130
+ /**
2131
+ * Commit a verified edit onto an EXISTING recipe: bump `version`, replace the
2132
+ * body-bearing metadata, append a history record, reset health counters, and
2133
+ * clear the component specs (they were validated against the old shape).
2134
+ * Returns the updated row, or null when the target is gone.
2135
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5.
2136
+ */
2137
+ commitEdit?(id: string, patch: {
2138
+ name?: string;
2139
+ intentDescription?: string;
2140
+ tags?: string[];
2141
+ parameters?: ScriptParameter[];
2142
+ bodyHash: string;
2143
+ /** New on-disk stem when the edit renamed the script; omitted otherwise. */
2144
+ fileBase?: string;
2145
+ sourceIds?: string[];
2146
+ tables?: string[];
2147
+ editedBy?: string;
2148
+ editedFrom?: string;
2149
+ historyEntry: {
2150
+ version: number;
2151
+ at: string;
2152
+ by?: string;
2153
+ instruction?: string;
2154
+ changeSummary?: string;
2155
+ bodyHash?: string;
2156
+ };
2157
+ }): Promise<ScriptRecipeMetaRow | null>;
2158
+ /** Stamp a draft's last execution error. */
2159
+ recordDraftError(id: string, err: {
2160
+ phase: string;
2161
+ message: string;
2162
+ attempt: number;
2163
+ at: string;
2164
+ }): Promise<void>;
2165
+ /** Delete a recipe row (body file removed separately). */
2166
+ remove(id: string): Promise<void>;
2167
+ /** True if `fileBase` is taken by a different recipe in this project. */
2168
+ fileBaseTaken(fileBase: string, excludeId: string, projectId?: string): Promise<boolean>;
2169
+ }
2170
+ /** Pull the injected store off the collections bag (or null if not wired). */
2171
+ declare function resolveScriptRecipeStore(collections: any): ScriptRecipeStore | null;
2172
+
2173
+ /**
2174
+ * ScriptStore — Postgres metadata + on-disk body for script recipes.
2175
+ *
2176
+ * Split of responsibilities:
2177
+ * - METADATA → injected `ScriptRecipeStore` (Postgres FTS + atomic counters),
2178
+ * resolved from `collections['script-recipes']`.
2179
+ * - BODY → scripts-store/<fileBase>.ts, editable in your IDE. Written
2180
+ * atomically (temp + rename); `bodyHash` (sha256) detects edits.
2181
+ *
2182
+ * The old "read every file every turn + send the whole catalog to the LLM"
2183
+ * matcher is gone — matching is `store.search(prompt)` (FTS shortlist). The
2184
+ * draft/verified filename dance is gone too: `status` is a DB column and the
2185
+ * file keeps a stable `<fileBase>.ts` name across promotion.
2186
+ *
2187
+ * When no metadata store is injected, the store degrades to a safe no-op
2188
+ * (count 0 → script flow disabled) instead of crashing.
2189
+ *
2190
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md.
2191
+ */
2192
+
2193
+ interface SaveDraftInput {
2194
+ /** Reuse an existing draft (retry); omit to mint a new one. */
2195
+ recipeId?: string;
2196
+ /** Per-turn unique suffix, stable across retries within the turn. */
2197
+ turnId: string;
2198
+ name: string;
2199
+ intentDescription: string;
2200
+ tags: string[];
2201
+ parameters: ScriptParameter[];
2202
+ scriptBody: string;
2203
+ createdFrom: string;
2204
+ /**
2205
+ * Set when this draft is a SHADOW of an existing recipe being edited. The
2206
+ * draft is verified independently and merged back onto the parent via
2207
+ * `commitEdit`, so the working script is never clobbered by an edit that
2208
+ * turns out not to run. See backend/docs/SCRIPT-EDIT-DESIGN.md § D5.
2209
+ */
2210
+ parentId?: string;
2211
+ }
2212
+ interface PromoteToVerifiedInput {
2213
+ sourceIds: string[];
2214
+ tables: string[];
2215
+ parentId?: string;
2216
+ forkDepth?: number;
2217
+ forkReason?: string;
2218
+ components?: ScriptComponentSpec[];
2219
+ }
2220
+ interface ScriptStoreOptions {
2221
+ /** Explicit metadata store, or resolved from `collections['script-recipes']`. */
2222
+ store?: ScriptRecipeStore | null;
2223
+ collections?: any;
2224
+ /** Body directory (defaults to <cwd>/scripts-store). */
2225
+ baseDir?: string;
2226
+ /** Project scope stamped on every row. */
2227
+ projectId?: string;
2228
+ }
2229
+ /**
2230
+ * Normalize a scriptBody into the on-disk form (strip a leading comment block,
2231
+ * ensure `export async function getData`). Exported for MainAgent.
2232
+ */
2233
+ declare function normalizeScriptBody(scriptBody: string): string;
2234
+ declare class ScriptStore {
2235
+ private store;
2236
+ private storeDir;
2237
+ private projectId?;
2238
+ constructor(opts?: ScriptStoreOptions);
2239
+ /** Whether a metadata store is wired (matcher / authoring are gated on this). */
2240
+ hasStore(): boolean;
2241
+ /** Number of healthy verified recipes (gates the script-matching path). */
2242
+ count(): Promise<number>;
2243
+ /**
2244
+ * FTS shortlist for the matcher (metadata only — bodies are loaded lazily by
2245
+ * `get()` once the LLM picks one). Returns verified, healthy recipes ranked
2246
+ * by relevance.
2247
+ */
2248
+ search(prompt: string, limit?: number): Promise<ScriptRecipe[]>;
2249
+ /** Fetch one recipe by id with its body loaded from disk. */
2250
+ get(id: string): Promise<ScriptRecipe | null>;
2251
+ /** Create or update a recipe (metadata upsert + body write when changed). */
2252
+ save(recipe: ScriptRecipe): Promise<void>;
2253
+ /**
2254
+ * Persist (or update) a draft. Within a turn, retries that pass the same
2255
+ * `recipeId` overwrite the same row + file; a fresh `recipeId` mints a new
2256
+ * draft. The body is visible at scripts-store/<fileBase>.ts immediately.
2257
+ */
2258
+ saveDraft(input: SaveDraftInput): Promise<ScriptRecipe>;
2259
+ /** Stamp a draft's last execution error (metadata only). */
2260
+ recordDraftError(recipeId: string, err: {
2261
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2262
+ message: string;
2263
+ attempt: number;
2264
+ }): Promise<void>;
2265
+ /**
2266
+ * Promote a successfully-executed draft into a verified script.
2267
+ * The on-disk body already exists at <fileBase>.ts (written at write_script
2268
+ * time) and keeps its name — only the DB row flips status + provenance.
2269
+ */
2270
+ promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): Promise<ScriptRecipe | null>;
2271
+ /**
2272
+ * Commit a user-directed edit: merge a VERIFIED shadow draft back onto the
2273
+ * recipe it was editing, as version N+1 under the SAME recipe id.
2274
+ *
2275
+ * Keeping the id stable is the point of the whole feature — every cached
2276
+ * conversation, `script_dataset` regeneration descriptor and persisted
2277
+ * component spec already points at it, so the correction applies retroactively
2278
+ * to replays instead of stranding them on the old body.
2279
+ *
2280
+ * Steps (see backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5):
2281
+ * 1. archive the current body as `<fileBase>.v<version>.ts`
2282
+ * 2. write the edited body to the original fileBase (atomic)
2283
+ * 3. version++, copy name/description/params, append a history record
2284
+ * 4. reset health counters — the pre-edit failure history is stale
2285
+ * 5. clear component specs — they were validated against the OLD shape
2286
+ * 6. delete the shadow draft (row + file)
2287
+ *
2288
+ * Returns the updated recipe, or null when the commit could not be applied
2289
+ * (caller should then fall back to treating the draft as a new script).
2290
+ */
2291
+ commitEdit(targetId: string, draft: {
2292
+ recipeId: string;
2293
+ name?: string;
2294
+ intentDescription?: string;
2295
+ tags?: string[];
2296
+ parameters?: ScriptParameter[];
2297
+ scriptBody: string;
2298
+ sourceIds?: string[];
2299
+ tables?: string[];
2300
+ }, meta: {
2301
+ instruction?: string;
2302
+ changeSummary?: string;
2303
+ editedBy?: string;
2304
+ }): Promise<ScriptRecipe | null>;
2305
+ /**
2306
+ * Drop a draft (row + body file). MainAgent calls this at end-of-turn when a
2307
+ * draft was authored but never verified — failed drafts are never matched, so
2308
+ * deleting them immediately avoids unbounded accumulation (#5). No-op if the
2309
+ * recipe isn't a draft (so a promoted/verified script is never removed here).
2310
+ */
2311
+ discardDraft(recipeId: string): Promise<void>;
2312
+ /** Delete a recipe (row + body file). */
2313
+ delete(id: string): Promise<void>;
2314
+ /** Record a successful execution (atomic counter bump). */
2315
+ recordSuccess(id: string): Promise<void>;
2316
+ /** Record a failed execution (atomic counter bump). */
2317
+ recordFailure(id: string): Promise<void>;
2318
+ /** Absolute path to the .ts body for a recipe (used by the runner/MainAgent). */
2319
+ getScriptPath(recipe: ScriptRecipe): string;
2320
+ private removeById;
2321
+ private rowToRecipe;
2322
+ private recipeToRow;
2323
+ /** slug of name, with a short id suffix when the bare slug is already taken. */
2324
+ private computeFileBase;
2325
+ private toSlug;
2326
+ private hash;
2327
+ private bodyPath;
2328
+ private readBody;
2329
+ /** Directory holding superseded bodies. Dot-prefixed so IDEs/`ls` hide it. */
2330
+ private get archiveDir();
2331
+ /**
2332
+ * Archive a superseded body as `.versions/<fileBase>.v<n>.ts`.
2333
+ *
2334
+ * Kept out of the main store directory on purpose — see commitEdit step 1.
2335
+ * To roll back: copy the file back over `scripts-store/<fileBase>.ts`.
2336
+ */
2337
+ private writeArchive;
2338
+ /**
2339
+ * Move a recipe's archived versions to a new prefix when its fileBase changes,
2340
+ * so all versions of one recipe stay grouped. Without this, two renames would
2341
+ * scatter a single recipe's history across three prefixes in `.versions/` with
2342
+ * nothing linking them back to the live script.
2343
+ */
2344
+ private renameArchives;
2345
+ /** Atomic body write (temp + rename) so concurrent reads never see a partial file. */
2346
+ private writeBody;
2347
+ private unlinkBody;
2348
+ }
2349
+
2350
+ /**
2351
+ * Main Agent (Orchestrator)
2352
+ *
2353
+ * A single LLM.streamWithTools() call that handles everything:
2354
+ * - Routing: decides which source(s) to query based on summaries
2355
+ * - Querying: calls source tools (each wraps an independent SourceAgent)
2356
+ * - Direct tools: calls pre-built function tools directly with LLM-provided params
2357
+ * - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
2358
+ * - Analysis: generates final text response from the data
2359
+ *
2360
+ * Two tool types:
2361
+ * - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
2362
+ * - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
2363
+ */
2364
+
2365
+ declare class MainAgent {
2366
+ private externalTools;
2367
+ private workflows;
2368
+ private config;
2369
+ private streamBuffer;
2370
+ /**
2371
+ * Optional: when provided, MainAgent exposes the `write_script` /
2372
+ * `execute_script` tools to the LLM and persists drafts to disk via the
2373
+ * store. Headless callers (alert analyzer, metric resolver) omit these to
2374
+ * suppress script authoring entirely — drafts would otherwise leak onto
2375
+ * disk with no caller to promote or clean them up.
2376
+ */
2377
+ private scriptStore;
2378
+ private turnId;
2379
+ private createdFromPrompt;
2380
+ private scriptState;
2381
+ /** Answer-flow component catalog (filtered + projected by the caller). */
2382
+ private componentCatalog;
2383
+ /** Specs accepted by `render_components` this turn; empty until it succeeds. */
2384
+ private componentSpecs;
2385
+ private componentLayout;
2386
+ private renderComponentAttempts;
2387
+ /**
2388
+ * Fork mode — set when this turn is adapting a near-matching parent script.
2389
+ * In fork mode there is no legitimate "answer with bare text" outcome: the
2390
+ * only correct first move is a tool call (write_script, or a source tool for
2391
+ * schema discovery). We therefore force tool use on the first LLM iteration
2392
+ * so the model can't end its turn with a bare "I'll adapt…" preamble and zero
2393
+ * tool calls. Never set on the fresh-authoring / general-question path.
2394
+ */
2395
+ private forkMode;
2396
+ /**
2397
+ * Edit mode — set when this turn applies a user-directed change to an
2398
+ * existing script. Swaps the system prompt to `agent-main-edit` and stamps
2399
+ * the shadow draft's parentId. Like fork mode there is no legitimate
2400
+ * "answer with bare text" outcome, so tool use is forced on iteration 1.
2401
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 4.
2402
+ */
2403
+ private editContext;
2404
+ /**
2405
+ * Per-turn cancellation signal (user hit "Stop"). Set at the top of
2406
+ * handleQuestion and read by the tool handler, the SourceAgent dispatch, and
2407
+ * the script subprocess so an abort tears down every layer of the turn.
2408
+ */
2409
+ private abortSignal?;
2410
+ constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[], forkMode?: boolean, editContext?: EditContext, componentCatalog?: Component[]);
2411
+ /** True when the turn is applying a user-directed script edit. */
2412
+ private get editMode();
2413
+ private get scriptingEnabled();
2414
+ /**
2415
+ * Handle a user question using the multi-agent system.
2416
+ *
2417
+ * This is ONE LLM.streamWithTools() call. The LLM:
2418
+ * 1. Sees source summaries + direct tool descriptions in system prompt
2419
+ * 2. Decides which tool(s) to call (routing)
2420
+ * 3. Source tools → SourceAgent runs independently → returns data
2421
+ * 4. Direct tools → fn() called directly with LLM params → returns data
2422
+ * 5. Generates final analysis text
2423
+ */
2424
+ handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, signal?: AbortSignal): Promise<AgentResponse>;
2425
+ /**
2426
+ * Tool definition, with the catalog rendered from the registered `Metadata`
2427
+ * the caller passed in. Generated rather than hand-written so it cannot drift
2428
+ * from what the frontend actually ships.
2429
+ */
2430
+ private buildRenderComponentsToolDef;
2431
+ /**
2432
+ * Validate the agent's component picks against the REAL columns of each bound
2433
+ * dataset. All-or-nothing: any error rejects the whole call and returns the
2434
+ * findings, because a partially-accepted dashboard makes the retry ambiguous.
2435
+ */
2436
+ private handleRenderComponents;
2437
+ private handleWriteScript;
2438
+ private handleExecuteScript;
2439
+ /**
2440
+ * Build the AgentWrittenScript payload the caller will hand to
2441
+ * `ScriptStore.promoteToVerified()`. Only returned when a verified
2442
+ * successful execution is on record.
2443
+ */
2444
+ private buildSavedScript;
2445
+ private normalizeParameterList;
2446
+ /**
2447
+ * Use the schema embedding collection to pre-select relevant tables for
2448
+ * this source + intent. Returns a formatted schema block if confidence is
2449
+ * high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
2450
+ *
2451
+ * When this returns a block, we can skip the SourceAgent's `search_schema`
2452
+ * loop and reduce iteration budget. When it returns null, the SourceAgent
2453
+ * falls back to the existing LLM-driven keyword search (same as today).
2454
+ */
2455
+ private preResolveSchema;
2456
+ /**
2457
+ * Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
2458
+ */
2459
+ private handleDirectTool;
2460
+ /**
2461
+ * Build the main agent's system prompt with source summaries, direct tool descriptions,
2462
+ * and workflow component descriptions.
2463
+ */
2464
+ private buildSystemPrompt;
2465
+ /**
2466
+ * Build tool definitions for source tools — summary-only descriptions.
2467
+ * The full schema is inside the SourceAgent which runs independently.
2468
+ */
2469
+ private buildSourceToolDefinitions;
2470
+ /**
2471
+ * Build tool definitions for direct tools — expose their actual params.
2472
+ * These are called directly by the main agent LLM, no SourceAgent.
2473
+ */
2474
+ private buildDirectToolDefinitions;
2475
+ /**
2476
+ * Capture a workflow selection. We do NOT execute anything — the LLM has
2477
+ * already extracted the props it wants the workflow rendered with. We
2478
+ * record the selection (via the capture callback) and return a short
2479
+ * acknowledgement so the LLM ends its turn cleanly without writing
2480
+ * analysis text or calling more tools.
2481
+ */
2482
+ private handleWorkflow;
2483
+ /**
2484
+ * Build LLM tool definitions for workflow components. The workflow's
2485
+ * propsSchema becomes the tool's input_schema so the LLM extracts props
2486
+ * directly from the prompt — same mechanic as direct tools.
2487
+ */
2488
+ private buildWorkflowToolDefinitions;
2489
+ /**
2490
+ * Format a source agent's result as a clean string for the main agent LLM.
2491
+ */
2492
+ private formatResultForMainAgent;
2493
+ /**
2494
+ * Get source summaries (for external inspection/debugging).
2495
+ */
2496
+ getSourceSummaries(): SourceSummary[];
2497
+ }
2498
+
2499
+ /**
2500
+ * Represents an action that can be performed on a UIBlock
2501
+ */
2502
+ interface Action {
2503
+ id: string;
2504
+ name: string;
2505
+ type: string;
2506
+ [key: string]: any;
2507
+ }
2508
+
2509
+ type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
2510
+ interface LLMMessages {
2511
+ sys: SystemPrompt;
2512
+ user: string;
2513
+ prefill?: string;
2514
+ }
2515
+ interface LLMOptions {
2516
+ model?: string;
2517
+ maxTokens?: number;
2518
+ temperature?: number;
2519
+ topP?: number;
2520
+ apiKey?: string;
2521
+ baseURL?: string;
2522
+ partial?: (chunk: string) => void;
2523
+ /**
2524
+ * Per-request cancellation. When the caller aborts this signal (user hit
2525
+ * "Stop"), the underlying provider request is cancelled and the call throws
2526
+ * a RequestAbortedError. Threaded into the provider `messages.create` request
2527
+ * options and checked between tool-loop iterations. Currently honored on the
2528
+ * Anthropic path (the agent flow's default provider).
2529
+ */
2530
+ signal?: AbortSignal;
2531
+ /**
2532
+ * Forces a tool call on the FIRST iteration of streamWithTools only
2533
+ * (subsequent iterations revert to auto). Used by fork mode to stop the
2534
+ * model from ending its turn with a bare "I'll adapt the script…" preamble
2535
+ * and zero tool calls. `{ type: 'any' }` lets the model pick which tool
2536
+ * (write_script in the common case, a source tool for schema discovery);
2537
+ * `{ type: 'tool', name }` pins a specific tool. Honored on both the
2538
+ * Anthropic path and the OpenAI/OpenRouter path (mapped to OpenAI's
2539
+ * tool_choice: 'required' / a named function).
2540
+ */
2541
+ firstIterationToolChoice?: {
2542
+ type: 'any';
2543
+ } | {
2544
+ type: 'tool';
2545
+ name: string;
2546
+ };
2547
+ /**
2548
+ * Internal — set only by the OpenRouter wrappers when the target is a Claude
2549
+ * model. Tells the OpenAI-wire path to emit Anthropic `cache_control`
2550
+ * breakpoints (OpenRouter forwards them to Anthropic for prompt caching).
2551
+ * Never set for direct OpenAI/Groq calls, so their requests are unchanged.
2552
+ */
2553
+ _openrouterClaudeCaching?: boolean;
2554
+ /**
2555
+ * Internal — OpenRouter provider-routing preferences (forwarded as the
2556
+ * `provider` body field). Set by the OpenRouter wrappers to steer routing to
2557
+ * a fast backend (e.g. {sort:'throughput'}). Never set for direct OpenAI/Groq.
2558
+ */
2559
+ _openrouterProvider?: Record<string, unknown>;
2560
+ }
2561
+ interface Tool {
2562
+ name: string;
2563
+ description: string;
2564
+ input_schema: {
2565
+ type: string;
2566
+ properties: Record<string, any>;
2567
+ required?: string[];
2568
+ };
2569
+ }
2570
+ declare class LLM {
2571
+ static text(messages: LLMMessages, options?: LLMOptions): Promise<string>;
2572
+ static stream<T = string>(messages: LLMMessages, options?: LLMOptions, json?: boolean): Promise<T extends string ? string : any>;
2573
+ static streamWithTools(messages: LLMMessages, tools: Tool[], toolHandler: (toolName: string, toolInput: any) => Promise<any>, options?: LLMOptions, maxIterations?: number): Promise<string>;
2574
+ /**
2575
+ * Normalize system prompt to Anthropic format
2576
+ * Converts string to array format if needed
2577
+ * @param sys - System prompt (string or array of blocks)
2578
+ * @returns Normalized system prompt for Anthropic API
2579
+ */
2580
+ private static _normalizeSystemPrompt;
2581
+ /**
2582
+ * Strip unpaired UTF-16 surrogates from every text field of a message set.
2583
+ *
2584
+ * A lone surrogate (from mid-pair string slicing or corrupt source data)
2585
+ * serializes to a bare `\udXXX` escape that strict JSON parsers — including
2586
+ * the one on Anthropic's API — reject with "no low surrogate in string",
2587
+ * failing the whole request. Sanitizing here, at the single boundary every
2588
+ * provider call flows through, guarantees no request can carry one.
2589
+ */
2590
+ private static _sanitizeMessages;
2591
+ /**
2592
+ * Log cache usage metrics from Anthropic API response
2593
+ * Shows cache hits, costs, and savings
2594
+ */
2595
+ private static _logCacheUsage;
2596
+ /**
2597
+ * Parse model string to extract provider and model name
2598
+ * @param modelString - Format: "provider/model-name" or just "model-name"
2599
+ * @returns [provider, modelName]
2600
+ *
2601
+ * @example
2602
+ * "anthropic/claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"]
2603
+ * "groq/openai/gpt-oss-120b" → ["groq", "openai/gpt-oss-120b"]
2604
+ * "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
2605
+ */
2606
+ private static _parseModel;
2607
+ /**
2608
+ * Map an Anthropic model id (e.g. "claude-sonnet-4-5-20250929") to the OpenRouter slug
2609
+ * (e.g. "claude-sonnet-4.5"). OpenRouter slugs drop the date suffix and use dotted versions.
2610
+ */
2611
+ private static _toOpenRouterSlug;
2612
+ /**
2613
+ * Per-provider proxy base URL. Returns `${SUPERATOM_LLM_PROXY_URL}/<provider>`
2614
+ * when our Cloudflare LLM proxy is configured, else undefined (→ talk to the
2615
+ * provider directly, legacy behaviour). An explicit options.baseURL (e.g.
2616
+ * OpenRouter) always wins and is never overridden. See backend/docs/llm-proxy.md.
2617
+ */
2618
+ private static _proxyBaseURL;
2619
+ private static _openrouterOptions;
2620
+ private static _isRetryableProviderError;
2621
+ private static _withOpenrouterRetry;
2622
+ private static _openrouterText;
2623
+ private static _openrouterStream;
2624
+ private static _openrouterStreamWithTools;
2625
+ /**
2626
+ * Build an Anthropic client. Routes through our Cloudflare LLM proxy when
2627
+ * SUPERATOM_LLM_PROXY_URL is set (each client ships a per-client proxy key as
2628
+ * ANTHROPIC_API_KEY and never holds the real key); otherwise talks to
2629
+ * api.anthropic.com directly. See backend/docs/llm-proxy.md.
2630
+ */
2631
+ private static _anthropicClient;
2632
+ /** True when OpenRouter is configured as a fail-open fallback for Claude. */
2633
+ private static _openrouterAvailable;
2634
+ /** Remap an Anthropic model id to the OpenRouter model path for fail-open. */
2635
+ private static _anthropicFallbackModel;
2636
+ private static _anthropicText;
2637
+ private static _anthropicStream;
2638
+ private static _anthropicStreamWithTools;
2639
+ private static _groqText;
2640
+ private static _groqStream;
2641
+ /**
2642
+ * Gemini request options carrying the proxy base URL, or undefined → talk to
2643
+ * generativelanguage.googleapis.com directly. The Google SDK takes baseUrl as a
2644
+ * per-model request option, not a constructor arg. See backend/docs/llm-proxy.md.
2645
+ */
2646
+ private static _geminiRequestOptions;
2647
+ private static _geminiText;
2648
+ private static _geminiStream;
2649
+ /**
2650
+ * Recursively strip unsupported JSON Schema properties for Gemini
2651
+ * Gemini doesn't support: additionalProperties, $schema, etc.
2652
+ */
2653
+ private static _cleanSchemaForGemini;
2654
+ private static _geminiStreamWithTools;
2655
+ /** True for Anthropic/Claude model ids — gates OpenRouter prompt caching. */
2656
+ private static _isClaudeModel;
2657
+ /**
2658
+ * Build the OpenAI-wire system message. For OpenRouter + Claude
2659
+ * (cacheClaude=true) it emits content parts carrying Anthropic
2660
+ * `cache_control` breakpoints (preserving any the caller set, else marking
2661
+ * the last block), so OpenRouter forwards them to Anthropic for prompt
2662
+ * caching. Otherwise it returns a plain flattened string — unchanged for
2663
+ * direct OpenAI/Groq.
2664
+ */
2665
+ private static _openaiSystemMessage;
2666
+ /**
2667
+ * Split an OpenAI-wire usage object. `prompt_tokens` INCLUDES cached tokens,
2668
+ * so we subtract them out (Anthropic-style: input excludes cache reads) and
2669
+ * report cached separately — this makes calculateCost price cache reads at
2670
+ * the discounted rate and reflects OpenRouter prompt-cache savings in logs.
2671
+ */
2672
+ private static _openaiUsage;
2673
+ private static _openaiText;
2674
+ private static _openaiStream;
2675
+ /** Map the Anthropic-style firstIterationToolChoice to OpenAI's tool_choice. */
2676
+ private static _openaiToolChoice;
2677
+ private static _openaiStreamWithTools;
2678
+ /**
2679
+ * Parse JSON string, handling markdown code blocks and surrounding text
2680
+ * Enhanced version with jsonrepair to handle malformed JSON from LLMs
2681
+ * @param text - Text that may contain JSON wrapped in ```json...``` or with surrounding text
2682
+ * @returns Parsed JSON object or array
2683
+ */
2684
+ private static _parseJSON;
2685
+ }
2686
+
2687
+ interface CapturedLog {
2688
+ timestamp: number;
2689
+ level: 'info' | 'error' | 'warn' | 'debug';
2690
+ message: string;
2691
+ type?: 'explanation' | 'query' | 'general';
2692
+ data?: Record<string, any>;
2693
+ }
2694
+ /**
2695
+ * UILogCollector captures logs during user prompt processing
2696
+ * and sends them to runtime via ui_logs message with uiBlockId as the message id
2697
+ * Logs are sent in real-time for streaming effect in the UI
2698
+ * Respects the global log level configuration
2699
+ */
2700
+ declare class UILogCollector {
2701
+ private logs;
2702
+ private uiBlockId;
2703
+ private clientId;
2704
+ private sendMessage;
2705
+ private currentLogLevel;
2706
+ constructor(clientId: string, sendMessage: (message: Message) => void, uiBlockId?: string);
2707
+ /**
2708
+ * Check if logging is enabled (uiBlockId is provided)
2709
+ */
2710
+ isEnabled(): boolean;
2711
+ /**
2712
+ * Check if a message should be logged based on current log level
2713
+ */
2714
+ private shouldLog;
2715
+ /**
2716
+ * Add a log entry with timestamp and immediately send to runtime
2717
+ * Only logs that pass the log level filter are captured and sent
2718
+ */
2719
+ private addLog;
2720
+ /**
2721
+ * Send a single log to runtime immediately
2722
+ */
2723
+ private sendLogImmediately;
2724
+ /**
2725
+ * Log info message
2726
+ */
2727
+ info(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
2728
+ /**
2729
+ * Log error message
2730
+ */
2731
+ error(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
2732
+ /**
2733
+ * Log warning message
2734
+ */
2735
+ warn(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
2736
+ /**
2737
+ * Log debug message
2738
+ */
2739
+ debug(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
2740
+ /**
2741
+ * Log LLM explanation with typed metadata
1120
2742
  */
1121
2743
  logExplanation(message: string, explanation: string, data?: Record<string, any>): void;
1122
2744
  /**
@@ -1141,16 +2763,6 @@ declare class UILogCollector {
1141
2763
  setUIBlockId(uiBlockId: string): void;
1142
2764
  }
1143
2765
 
1144
- /**
1145
- * Represents an action that can be performed on a UIBlock
1146
- */
1147
- interface Action {
1148
- id: string;
1149
- name: string;
1150
- type: string;
1151
- [key: string]: any;
1152
- }
1153
-
1154
2766
  /**
1155
2767
  * UIBlock represents a single user and assistant message block in a thread
1156
2768
  * Contains user question, component metadata, component data, text response, and available actions
@@ -1163,6 +2775,13 @@ declare class UIBlock {
1163
2775
  private textResponse;
1164
2776
  private actions;
1165
2777
  private createdAt;
2778
+ /**
2779
+ * Which script recipe produced this answer, when a script did. Read on the
2780
+ * NEXT turn so the user can say "use mode instead" and have the matcher
2781
+ * resolve it to a concrete script (the `edit` tier is unreachable without it).
2782
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
2783
+ */
2784
+ private scriptBinding;
1166
2785
  /**
1167
2786
  * Creates a new UIBlock instance
1168
2787
  * @param userQuestion - The user's question or input
@@ -1257,6 +2876,14 @@ declare class UIBlock {
1257
2876
  /**
1258
2877
  * Get creation timestamp
1259
2878
  */
2879
+ /**
2880
+ * Bind this block to the script recipe that produced its answer.
2881
+ */
2882
+ setScriptBinding(binding: Record<string, any> | null): void;
2883
+ /**
2884
+ * The script recipe bound to this block, if any.
2885
+ */
2886
+ getScriptBinding(): Record<string, any> | null;
1260
2887
  getCreatedAt(): Date;
1261
2888
  /**
1262
2889
  * Convert UIBlock to JSON-serializable object
@@ -1324,6 +2951,32 @@ declare class Thread {
1324
2951
  * @param currentUIBlockId - ID of current UIBlock to exclude from context (optional)
1325
2952
  * @returns Formatted conversation history string
1326
2953
  */
2954
+ /**
2955
+ * The script recipe bound to the most recent completed UIBlock — i.e. the
2956
+ * script behind the answer the user is currently looking at. Drives the
2957
+ * matcher's `edit` tier: without it, "use mode instead" has no target and
2958
+ * falls through to regeneration.
2959
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
2960
+ */
2961
+ getActiveScriptBinding(currentUIBlockId?: string): Record<string, any> | null;
2962
+ /**
2963
+ * The recent script-backed answers in this thread, newest first — the
2964
+ * candidate set a user-directed edit can target.
2965
+ *
2966
+ * Returning several rather than only the newest is what lets an instruction
2967
+ * name its own target ("use the mode for the WSP one"). With a single
2968
+ * candidate every edit lands on the most recent script, which silently edits
2969
+ * the wrong recipe whenever the user meant an earlier one.
2970
+ *
2971
+ * Deduped by recipeId (newest occurrence wins) so a long editing session on
2972
+ * one script doesn't crowd out the others. Each entry carries the question
2973
+ * that produced it — without that the candidates are indistinguishable.
2974
+ *
2975
+ * In-memory only: dies with the process. The caller falls back to the
2976
+ * persisted bindings when this comes back empty.
2977
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
2978
+ */
2979
+ getScriptBindings(limit?: number, currentUIBlockId?: string): Record<string, any>[];
1327
2980
  getConversationContext(limit?: number, currentUIBlockId?: string): string;
1328
2981
  /**
1329
2982
  * Convert Thread to JSON-serializable object
@@ -1333,12 +2986,20 @@ declare class Thread {
1333
2986
 
1334
2987
  /**
1335
2988
  * ThreadManager manages all threads globally
1336
- * Provides methods to create, retrieve, and delete threads
2989
+ * Provides methods to create, retrieve, and delete threads.
2990
+ * Includes automatic cleanup to prevent unbounded memory growth.
1337
2991
  */
1338
2992
  declare class ThreadManager {
1339
2993
  private static instance;
1340
2994
  private threads;
2995
+ private cleanupInterval;
2996
+ private readonly threadTtlMs;
1341
2997
  private constructor();
2998
+ /**
2999
+ * Periodically remove threads older than 7 days.
3000
+ * Runs every hour to avoid frequent iteration over the map.
3001
+ */
3002
+ private startCleanup;
1342
3003
  /**
1343
3004
  * Get singleton instance of ThreadManager
1344
3005
  */
@@ -1446,54 +3107,168 @@ declare class CleanupService {
1446
3107
  */
1447
3108
  stopAutoCleanup(): void;
1448
3109
  /**
1449
- * Check if auto cleanup is running
3110
+ * Check if auto cleanup is running
3111
+ */
3112
+ isAutoCleanupRunning(): boolean;
3113
+ /**
3114
+ * Get current memory usage statistics
3115
+ */
3116
+ getMemoryStats(): {
3117
+ threadCount: number;
3118
+ totalUIBlocks: number;
3119
+ avgUIBlocksPerThread: number;
3120
+ };
3121
+ }
3122
+
3123
+ /**
3124
+ * Configuration for data storage limits in UIBlocks
3125
+ */
3126
+ declare const STORAGE_CONFIG: {
3127
+ /**
3128
+ * Maximum number of rows to store in UIBlock data
3129
+ */
3130
+ MAX_ROWS_PER_BLOCK: number;
3131
+ /**
3132
+ * Maximum size in bytes per UIBlock (500KB - reduced to save memory)
3133
+ */
3134
+ MAX_SIZE_PER_BLOCK_BYTES: number;
3135
+ /**
3136
+ * Number of days to keep threads before cleanup
3137
+ * Note: This is for in-memory storage. Conversations are also persisted to database.
3138
+ */
3139
+ THREAD_RETENTION_DAYS: number;
3140
+ /**
3141
+ * Number of days to keep UIBlocks before cleanup
3142
+ * Note: This is for in-memory storage. Data is also persisted to database.
3143
+ */
3144
+ UIBLOCK_RETENTION_DAYS: number;
3145
+ };
3146
+
3147
+ /**
3148
+ * Configuration for conversation context and history management
3149
+ */
3150
+ declare const CONTEXT_CONFIG: {
3151
+ /**
3152
+ * Maximum number of previous UIBlocks to include as conversation context
3153
+ * Set to 0 to disable conversation history
3154
+ * Higher values provide more context but may increase token usage
3155
+ */
3156
+ MAX_CONVERSATION_CONTEXT_BLOCKS: number;
3157
+ };
3158
+
3159
+ /**
3160
+ * LLM Usage Logger - Tracks token usage, costs, and timing for all LLM API calls
3161
+ */
3162
+ interface LLMUsageEntry {
3163
+ timestamp: string;
3164
+ requestId: string;
3165
+ provider: string;
3166
+ model: string;
3167
+ method: string;
3168
+ inputTokens: number;
3169
+ outputTokens: number;
3170
+ cacheReadTokens?: number;
3171
+ cacheWriteTokens?: number;
3172
+ totalTokens: number;
3173
+ costUSD: number;
3174
+ durationMs: number;
3175
+ toolCalls?: number;
3176
+ success: boolean;
3177
+ error?: string;
3178
+ }
3179
+ declare class LLMUsageLogger {
3180
+ private logStream;
3181
+ private logPath;
3182
+ private enabled;
3183
+ private sessionStats;
3184
+ constructor();
3185
+ private initLogStream;
3186
+ private writeHeader;
3187
+ /**
3188
+ * Calculate cost based on token usage and model
3189
+ */
3190
+ calculateCost(model: string, inputTokens: number, outputTokens: number, cacheReadTokens?: number, cacheWriteTokens?: number): number;
3191
+ /**
3192
+ * Log an LLM API call
3193
+ */
3194
+ log(entry: LLMUsageEntry): void;
3195
+ /**
3196
+ * Log session summary (call at end of request)
3197
+ */
3198
+ logSessionSummary(requestContext?: string): void;
3199
+ /**
3200
+ * Reset session stats (call at start of new user request)
3201
+ */
3202
+ resetSession(): void;
3203
+ /**
3204
+ * Reset the log file for a new request (clears previous logs)
3205
+ * Call this at the start of each USER_PROMPT_REQ
1450
3206
  */
1451
- isAutoCleanupRunning(): boolean;
3207
+ resetLogFile(requestContext?: string): void;
1452
3208
  /**
1453
- * Get current memory usage statistics
3209
+ * Get current session stats
1454
3210
  */
1455
- getMemoryStats(): {
1456
- threadCount: number;
1457
- totalUIBlocks: number;
1458
- avgUIBlocksPerThread: number;
3211
+ getSessionStats(): {
3212
+ totalCalls: number;
3213
+ totalInputTokens: number;
3214
+ totalOutputTokens: number;
3215
+ totalCacheReadTokens: number;
3216
+ totalCacheWriteTokens: number;
3217
+ totalCostUSD: number;
3218
+ totalDurationMs: number;
1459
3219
  };
3220
+ /**
3221
+ * Generate a unique request ID
3222
+ */
3223
+ generateRequestId(): string;
1460
3224
  }
3225
+ declare const llmUsageLogger: LLMUsageLogger;
1461
3226
 
1462
3227
  /**
1463
- * Configuration for data storage limits in UIBlocks
3228
+ * User Prompt Error Logger - Captures detailed errors for USER_PROMPT_REQ
3229
+ * Logs full error details including raw strings for parse failures
1464
3230
  */
1465
- declare const STORAGE_CONFIG: {
3231
+ declare class UserPromptErrorLogger {
3232
+ private logStream;
3233
+ private logPath;
3234
+ private enabled;
3235
+ private hasErrors;
3236
+ constructor();
1466
3237
  /**
1467
- * Maximum number of rows to store in UIBlock data
3238
+ * Reset the error log file for a new request
1468
3239
  */
1469
- MAX_ROWS_PER_BLOCK: number;
3240
+ resetLogFile(requestContext?: string): void;
1470
3241
  /**
1471
- * Maximum size in bytes per UIBlock (500KB - reduced to save memory)
3242
+ * Log a JSON parse error with the raw string that failed
1472
3243
  */
1473
- MAX_SIZE_PER_BLOCK_BYTES: number;
3244
+ logJsonParseError(context: string, rawString: string, error: Error): void;
1474
3245
  /**
1475
- * Number of days to keep threads before cleanup
1476
- * Note: This is for in-memory storage. Conversations are also persisted to database.
3246
+ * Log a general error with full details
1477
3247
  */
1478
- THREAD_RETENTION_DAYS: number;
3248
+ logError(context: string, error: Error | string, additionalData?: Record<string, any>): void;
1479
3249
  /**
1480
- * Number of days to keep UIBlocks before cleanup
1481
- * Note: This is for in-memory storage. Data is also persisted to database.
3250
+ * Log a SQL query error with the full query
1482
3251
  */
1483
- UIBLOCK_RETENTION_DAYS: number;
1484
- };
1485
-
1486
- /**
1487
- * Configuration for conversation context and history management
1488
- */
1489
- declare const CONTEXT_CONFIG: {
3252
+ logSqlError(query: string, error: Error | string, params?: any[]): void;
1490
3253
  /**
1491
- * Maximum number of previous UIBlocks to include as conversation context
1492
- * Set to 0 to disable conversation history
1493
- * Higher values provide more context but may increase token usage
3254
+ * Log an LLM API error
1494
3255
  */
1495
- MAX_CONVERSATION_CONTEXT_BLOCKS: number;
1496
- };
3256
+ logLlmError(provider: string, model: string, method: string, error: Error | string, requestData?: any): void;
3257
+ /**
3258
+ * Log tool execution error
3259
+ */
3260
+ logToolError(toolName: string, toolInput: any, error: Error | string): void;
3261
+ /**
3262
+ * Write final summary if there were errors
3263
+ */
3264
+ writeSummary(): void;
3265
+ /**
3266
+ * Check if any errors were logged
3267
+ */
3268
+ hadErrors(): boolean;
3269
+ private write;
3270
+ }
3271
+ declare const userPromptErrorLogger: UserPromptErrorLogger;
1497
3272
 
1498
3273
  /**
1499
3274
  * BM25L Reranker for hybrid semantic search
@@ -1623,14 +3398,640 @@ declare function rerankConversationResults<T extends {
1623
3398
  bm25Score: number;
1624
3399
  }>;
1625
3400
 
1626
- declare const SDK_VERSION = "0.0.8";
3401
+ /**
3402
+ * QueryExecutionService - Handles all query execution, validation, and retry logic
3403
+ * Extracted from BaseLLM for better separation of concerns
3404
+ */
3405
+
3406
+ /**
3407
+ * Context for component when requesting query fix
3408
+ */
3409
+ interface ComponentContext {
3410
+ name: string;
3411
+ type: string;
3412
+ title?: string;
3413
+ }
3414
+ /**
3415
+ * Result of query validation
3416
+ */
3417
+ interface QueryValidationResult {
3418
+ component: Component | null;
3419
+ queryKey: string;
3420
+ result: any;
3421
+ validated: boolean;
3422
+ }
3423
+ /**
3424
+ * Result of batch query validation
3425
+ */
3426
+ interface BatchValidationResult {
3427
+ components: Component[];
3428
+ queryResults: Map<string, any>;
3429
+ }
3430
+ /**
3431
+ * Configuration for QueryExecutionService
3432
+ */
3433
+ interface QueryExecutionServiceConfig {
3434
+ defaultLimit: number;
3435
+ getModelForTask: (taskType: 'simple' | 'complex') => string;
3436
+ getApiKey: (apiKey?: string) => string | undefined;
3437
+ providerName: string;
3438
+ }
3439
+ /**
3440
+ * QueryExecutionService handles all query-related operations
3441
+ */
3442
+ declare class QueryExecutionService {
3443
+ private config;
3444
+ constructor(config: QueryExecutionServiceConfig);
3445
+ /**
3446
+ * Get the cache key for a query
3447
+ * This ensures the cache key matches what the frontend will send
3448
+ */
3449
+ getQueryCacheKey(query: any): string;
3450
+ /**
3451
+ * Execute a query against the database
3452
+ * @param query - The SQL query to execute (string or object with sql/values)
3453
+ * @param collections - Collections object containing database execute function
3454
+ * @returns Object with result data and cache key
3455
+ */
3456
+ executeQuery(query: any, collections: any): Promise<{
3457
+ result: any;
3458
+ cacheKey: string;
3459
+ }>;
3460
+ /**
3461
+ * Request the LLM to fix a failed SQL query
3462
+ * @param failedQuery - The query that failed execution
3463
+ * @param errorMessage - The error message from the failed execution
3464
+ * @param componentContext - Context about the component
3465
+ * @param apiKey - Optional API key
3466
+ * @returns Fixed query string
3467
+ */
3468
+ requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
3469
+ /**
3470
+ * Validate a single component's query with retry logic
3471
+ * @param component - The component to validate
3472
+ * @param collections - Collections object containing database execute function
3473
+ * @param apiKey - Optional API key for LLM calls
3474
+ * @returns Validation result with component, query key, and result
3475
+ */
3476
+ validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
3477
+ /**
3478
+ * Validate multiple component queries in parallel
3479
+ * @param components - Array of components with potential queries
3480
+ * @param collections - Collections object containing database execute function
3481
+ * @param apiKey - Optional API key for LLM calls
3482
+ * @returns Object with validated components and query results map
3483
+ */
3484
+ validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
3485
+ }
3486
+
3487
+ /**
3488
+ * Task types for model selection
3489
+ * - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
3490
+ * - 'simple': Classification, action generation (uses fast model in balanced mode)
3491
+ */
3492
+ type TaskType = 'complex' | 'simple';
3493
+ interface BaseLLMConfig {
3494
+ model?: string;
3495
+ fastModel?: string;
3496
+ defaultLimit?: number;
3497
+ apiKey?: string;
3498
+ /**
3499
+ * Model selection strategy:
3500
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
3501
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
3502
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
3503
+ */
3504
+ modelStrategy?: ModelStrategy;
3505
+ conversationSimilarityThreshold?: number;
3506
+ }
3507
+ /**
3508
+ * BaseLLM abstract class for AI-powered component generation and matching
3509
+ * Provides common functionality for all LLM providers
3510
+ */
3511
+ declare abstract class BaseLLM {
3512
+ protected model: string;
3513
+ protected fastModel: string;
3514
+ protected defaultLimit: number;
3515
+ protected apiKey?: string;
3516
+ protected modelStrategy: ModelStrategy;
3517
+ protected conversationSimilarityThreshold: number;
3518
+ protected queryService: QueryExecutionService;
3519
+ constructor(config?: BaseLLMConfig);
3520
+ /**
3521
+ * Get the appropriate model based on task type and model strategy
3522
+ * @param taskType - 'complex' for text generation/matching, 'simple' for classification/actions
3523
+ * @returns The model string to use for this task
3524
+ */
3525
+ protected getModelForTask(taskType: TaskType): string;
3526
+ /**
3527
+ * Set the model strategy at runtime
3528
+ * @param strategy - 'best', 'fast', or 'balanced'
3529
+ */
3530
+ setModelStrategy(strategy: ModelStrategy): void;
3531
+ /**
3532
+ * Get the current model strategy
3533
+ * @returns The current model strategy
3534
+ */
3535
+ getModelStrategy(): ModelStrategy;
3536
+ /**
3537
+ * Set the conversation similarity threshold at runtime
3538
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
3539
+ */
3540
+ setConversationSimilarityThreshold(threshold: number): void;
3541
+ /**
3542
+ * Get the current conversation similarity threshold
3543
+ * @returns The current threshold value
3544
+ */
3545
+ getConversationSimilarityThreshold(): number;
3546
+ /**
3547
+ * Get the default model for this provider (used for complex tasks like text generation)
3548
+ */
3549
+ protected abstract getDefaultModel(): string;
3550
+ /**
3551
+ * Get the default fast model for this provider (used for simple tasks: classification, matching, actions)
3552
+ * Should return a cheaper/faster model like Haiku for Anthropic
3553
+ */
3554
+ protected abstract getDefaultFastModel(): string;
3555
+ /**
3556
+ * Get the default API key from environment
3557
+ */
3558
+ protected abstract getDefaultApiKey(): string | undefined;
3559
+ /**
3560
+ * Get the provider name (for logging)
3561
+ */
3562
+ protected abstract getProviderName(): string;
3563
+ /**
3564
+ * Get the API key (from instance, parameter, or environment)
3565
+ */
3566
+ protected getApiKey(apiKey?: string): string | undefined;
3567
+ /**
3568
+ * Check if a component contains a Form (data_modification component)
3569
+ * Forms have hardcoded defaultValues that become stale when cached
3570
+ * This checks both single Form components and Forms inside MultiComponentContainer
3571
+ */
3572
+ protected containsFormComponent(component: any): boolean;
3573
+ /**
3574
+ * Match components from text response suggestions and generate follow-up questions
3575
+ * Takes a text response with component suggestions (c1:type format) and matches with available components
3576
+ * Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
3577
+ * All components are placed in a default MultiComponentContainer layout
3578
+ * @param analysisContent - The text response containing component suggestions
3579
+ * @param components - List of available components
3580
+ * @param apiKey - Optional API key
3581
+ * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
3582
+ * @returns Object containing matched components, layout title/description, and follow-up actions
3583
+ */
3584
+ matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
3585
+ components: Component[];
3586
+ layoutTitle: string;
3587
+ layoutDescription: string;
3588
+ actions: Action[];
3589
+ }>;
3590
+ /**
3591
+ * Classify user question into category and detect external tools needed
3592
+ * Determines if question is for data analysis, requires external tools, or needs text response
3593
+ */
3594
+ classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
3595
+ category: 'data_analysis' | 'data_modification' | 'general';
3596
+ externalTools: Array<{
3597
+ type: string;
3598
+ name: string;
3599
+ description: string;
3600
+ parameters: Record<string, any>;
3601
+ }>;
3602
+ dataAnalysisType?: 'visualization' | 'calculation' | 'comparison' | 'trend';
3603
+ reasoning: string;
3604
+ confidence: number;
3605
+ }>;
3606
+ /**
3607
+ * Adapt UI block parameters based on current user question
3608
+ * Takes a matched UI block from semantic search and modifies its props to answer the new question
3609
+ * Also adapts the cached text response to match the new question
3610
+ */
3611
+ adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
3612
+ success: boolean;
3613
+ adaptedComponent?: Component;
3614
+ adaptedTextResponse?: string;
3615
+ parametersChanged?: Array<{
3616
+ field: string;
3617
+ reason: string;
3618
+ }>;
3619
+ explanation: string;
3620
+ }>;
3621
+ /**
3622
+ * Generate text-based response for user question
3623
+ * This provides conversational text responses instead of component generation
3624
+ * Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
3625
+ * After generating text response, if components are provided, matches suggested components
3626
+ */
3627
+ 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>;
3628
+ /**
3629
+ * Main orchestration function with semantic search and multi-step classification
3630
+ * NEW FLOW (Recommended):
3631
+ * 1. Semantic search: Check previous conversations (>60% match)
3632
+ * - If match found → Adapt UI block parameters and return
3633
+ * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
3634
+ * 3. Route appropriately based on category and response mode
3635
+ */
3636
+ 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>;
3637
+ /**
3638
+ * Generate next questions that the user might ask based on the original prompt and generated component
3639
+ * This helps provide intelligent suggestions for follow-up queries
3640
+ * For general/conversational questions without components, pass textResponse instead
3641
+ */
3642
+ generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string, signal?: AbortSignal): Promise<string[]>;
3643
+ }
3644
+
3645
+ interface AnthropicLLMConfig extends BaseLLMConfig {
3646
+ }
3647
+ /**
3648
+ * AnthropicLLM class for handling AI-powered component generation and matching using Anthropic Claude
3649
+ */
3650
+ declare class AnthropicLLM extends BaseLLM {
3651
+ constructor(config?: AnthropicLLMConfig);
3652
+ protected getDefaultModel(): string;
3653
+ protected getDefaultFastModel(): string;
3654
+ protected getDefaultApiKey(): string | undefined;
3655
+ protected getProviderName(): string;
3656
+ }
3657
+ declare const anthropicLLM: AnthropicLLM;
3658
+
3659
+ interface GroqLLMConfig extends BaseLLMConfig {
3660
+ }
3661
+ /**
3662
+ * GroqLLM class for handling AI-powered component generation and matching using Groq
3663
+ */
3664
+ declare class GroqLLM extends BaseLLM {
3665
+ constructor(config?: GroqLLMConfig);
3666
+ protected getDefaultModel(): string;
3667
+ protected getDefaultFastModel(): string;
3668
+ protected getDefaultApiKey(): string | undefined;
3669
+ protected getProviderName(): string;
3670
+ }
3671
+ declare const groqLLM: GroqLLM;
3672
+
3673
+ interface GeminiLLMConfig extends BaseLLMConfig {
3674
+ }
3675
+ /**
3676
+ * GeminiLLM class for handling AI-powered component generation and matching using Google Gemini
3677
+ */
3678
+ declare class GeminiLLM extends BaseLLM {
3679
+ constructor(config?: GeminiLLMConfig);
3680
+ protected getDefaultModel(): string;
3681
+ protected getDefaultFastModel(): string;
3682
+ protected getDefaultApiKey(): string | undefined;
3683
+ protected getProviderName(): string;
3684
+ }
3685
+ declare const geminiLLM: GeminiLLM;
3686
+
3687
+ interface OpenAILLMConfig extends BaseLLMConfig {
3688
+ }
3689
+ /**
3690
+ * OpenAILLM class for handling AI-powered component generation and matching using OpenAI GPT models
3691
+ */
3692
+ declare class OpenAILLM extends BaseLLM {
3693
+ constructor(config?: OpenAILLMConfig);
3694
+ protected getDefaultModel(): string;
3695
+ protected getDefaultFastModel(): string;
3696
+ protected getDefaultApiKey(): string | undefined;
3697
+ protected getProviderName(): string;
3698
+ }
3699
+ declare const openaiLLM: OpenAILLM;
3700
+
3701
+ /**
3702
+ * Query Cache — Two mechanisms:
3703
+ *
3704
+ * 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
3705
+ * of recently validated queries. True LRU eviction: reads bubble entries to the back via
3706
+ * delete+re-set so the oldest *unused* entry is evicted, not the oldest *inserted*.
3707
+ *
3708
+ * 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
3709
+ * No server-side storage needed for SQL mappings. The token is decrypted on each request.
3710
+ * This eliminates the unbounded queryIdCache that previously grew forever and caused
3711
+ * memory bloat (hundreds of MBs after thousands of queries).
3712
+ *
3713
+ * Result data can still be cached temporarily via the data cache (mechanism 1).
3714
+ */
3715
+ declare class QueryCache {
3716
+ private cache;
3717
+ private ttlMs;
3718
+ private maxCacheSize;
3719
+ private cleanupInterval;
3720
+ private readonly algorithm;
3721
+ private encryptionKey;
3722
+ constructor();
3723
+ /**
3724
+ * Set the cache TTL (Time To Live)
3725
+ * @param minutes - TTL in minutes (default: 10)
3726
+ */
3727
+ setTTL(minutes: number): void;
3728
+ /**
3729
+ * Get the current TTL in minutes
3730
+ */
3731
+ getTTL(): number;
3732
+ /**
3733
+ * Store query result in data cache.
3734
+ * If the key already exists, it's removed first so the re-insert places it
3735
+ * at the back of the iteration order (LRU). Eviction only fires when adding
3736
+ * a genuinely new key past the size limit.
3737
+ */
3738
+ set(query: string, data: any): void;
3739
+ /**
3740
+ * Get cached result if exists and not expired.
3741
+ * On hit, re-inserts the entry so it moves to the back of the Map's
3742
+ * iteration order — turning FIFO eviction into true LRU.
3743
+ */
3744
+ get(query: string): any | null;
3745
+ /**
3746
+ * Check if query exists in cache (not expired)
3747
+ */
3748
+ has(query: string): boolean;
3749
+ /**
3750
+ * Remove a specific query from cache
3751
+ */
3752
+ delete(query: string): void;
3753
+ /**
3754
+ * Clear all cached entries
3755
+ */
3756
+ clear(): void;
3757
+ /**
3758
+ * Get cache statistics
3759
+ */
3760
+ getStats(): {
3761
+ size: number;
3762
+ queryIdCount: number;
3763
+ oldestEntryAge: number | null;
3764
+ };
3765
+ /**
3766
+ * Start periodic cleanup of expired data cache entries.
3767
+ */
3768
+ private startCleanup;
3769
+ /**
3770
+ * Encrypt a payload into a self-contained token.
3771
+ */
3772
+ private encrypt;
3773
+ /**
3774
+ * Decrypt a token back to the original payload.
3775
+ */
3776
+ private decrypt;
3777
+ /**
3778
+ * Store a query by generating an encrypted token as queryId.
3779
+ * The SQL is encrypted INTO the token — nothing stored in memory.
3780
+ * If data is provided, it's cached temporarily in the data cache.
3781
+ */
3782
+ storeQuery(query: any, data?: any): string;
3783
+ /**
3784
+ * Get a stored query by decrypting its token.
3785
+ * Returns the SQL + any cached result data.
3786
+ */
3787
+ getQuery(queryId: string): {
3788
+ query: any;
3789
+ data: any;
3790
+ } | null;
3791
+ /**
3792
+ * Update cached data for a queryId token
3793
+ */
3794
+ setQueryData(queryId: string, data: any): void;
3795
+ /**
3796
+ * Stop cleanup interval (for graceful shutdown)
3797
+ */
3798
+ destroy(): void;
3799
+ }
3800
+ declare const queryCache: QueryCache;
3801
+
3802
+ /**
3803
+ * Manages conversation history scoped per user + dashboard.
3804
+ * Each user-dashboard pair has its own isolated history that expires after a configurable TTL.
3805
+ */
3806
+ declare class DashboardConversationHistory {
3807
+ private histories;
3808
+ private ttlMs;
3809
+ private maxEntries;
3810
+ private cleanupInterval;
3811
+ constructor();
3812
+ /**
3813
+ * Set the TTL for dashboard histories
3814
+ * @param minutes - TTL in minutes
3815
+ */
3816
+ setTTL(minutes: number): void;
3817
+ /**
3818
+ * Set max entries per dashboard
3819
+ */
3820
+ setMaxEntries(max: number): void;
3821
+ /**
3822
+ * Add a conversation entry for a user's dashboard
3823
+ */
3824
+ addEntry(dashboardId: string, userPrompt: string, componentSummary: string, userId?: string): void;
3825
+ /**
3826
+ * Get formatted conversation history for a user's dashboard
3827
+ */
3828
+ getHistory(dashboardId: string, userId?: string): string;
3829
+ /**
3830
+ * Clear history for a specific user's dashboard
3831
+ */
3832
+ clearDashboard(dashboardId: string, userId?: string): void;
3833
+ /**
3834
+ * Clear all dashboard histories
3835
+ */
3836
+ clearAll(): void;
3837
+ /**
3838
+ * Start periodic cleanup of expired histories
3839
+ */
3840
+ private startCleanup;
3841
+ /**
3842
+ * Stop cleanup interval (for graceful shutdown)
3843
+ */
3844
+ destroy(): void;
3845
+ }
3846
+ declare const dashboardConversationHistory: DashboardConversationHistory;
3847
+
3848
+ /**
3849
+ * Whole-dashboard generation via Pi, a terminal coding agent — as opposed to
3850
+ * DASH_COMP_REQ's single-widget-at-a-time flow. Runs Pi in-process via its
3851
+ * SDK (createAgentSession), not as a subprocess: no shell, no argument
3852
+ * quoting, no stdin/stdout piping, none of the Windows-specific subprocess
3853
+ * issues that came with spawning the `pi` CLI directly.
3854
+ *
3855
+ * Called from sdk-nodejs/src/dashboardAgent/index.ts (DASHBOARD_AGENT_REQ),
3856
+ * which owns the generic streaming/abort machinery (mirrors USER_PROMPT_REQ)
3857
+ * and passes `signal`/`onProgress` alongside the normal params — this stays
3858
+ * within CollectionHandler's loose (params) => Promise<result> typing, no
3859
+ * change needed to that shared type.
3860
+ *
3861
+ * This mechanism is generic and reusable across any deployment. What's
3862
+ * genuinely project-specific — where AGENTS.md lives, which model to use —
3863
+ * is supplied via `DashboardAgentCollectionConfig`, with defaults sensible
3864
+ * enough that most callers don't need to override them (see below). The
3865
+ * data-source tool list and the dashboard's current state both come from
3866
+ * things sdk-nodejs already exposes generically: `sdk.getTools()` (whatever
3867
+ * this deployment registered via `sdk.setTools()`) and `sdk.callCollection
3868
+ * ('dashboards', 'query', ...)` (whatever this deployment already registered
3869
+ * under that name/shape) — no per-deployment callback needed for either.
3870
+ * Same convention on the way out: after a successful run, the prompt and the
3871
+ * full response text are handed to `sdk.callCollection('dashboard-agent-
3872
+ * conversations', 'create', ...)` if this deployment has registered one —
3873
+ * skipped silently otherwise, since conversation history is optional.
3874
+ *
3875
+ * Pi verifies every query against the live database itself (via whatever
3876
+ * local tool-execution bridge the deployment exposes, e.g. an HTTP bridge
3877
+ * on localhost), but does NOT persist the result itself — it writes the
3878
+ * finished DSL to an absolute path inside `runtimeDir`, told to it explicitly
3879
+ * in the prompt, and stops there. This handler reads that file after the run
3880
+ * finishes and returns its content as `dashboard` in the result. The caller
3881
+ * (frontend) is the one that actually saves it, via whatever authenticated
3882
+ * create/update path any other dashboard edit goes through — Pi has no user
3883
+ * session/auth context of its own, so persistence shouldn't happen from
3884
+ * inside it.
3885
+ *
3886
+ * Session persistence: the FIRST call for a dashboardId pays the full cost
3887
+ * (explore KB, discover schema, plan, verify, build). Every call after that
3888
+ * resumes the same session file (SessionManager.open) so Pi has everything
3889
+ * it already learned — it only needs to reason about the new, smaller ask,
3890
+ * not rediscover the whole dashboard from scratch. The session's file path
3891
+ * (AgentSession.sessionFile) is captured right after creation and persisted
3892
+ * in a small local file, keyed by dashboardId, inside `runtimeDir`.
3893
+ */
3894
+ interface DashboardAgentCollectionConfig {
3895
+ /**
3896
+ * Working directory Pi runs from — must contain AGENTS.md. This is a
3897
+ * version-controlled prompt file, so `cwd` is expected to live somewhere
3898
+ * like a `.prompts/` folder alongside the deployment's other prompts.
3899
+ * Default: `<process.cwd()>/.prompts/dashboard-agent` — the same
3900
+ * process.cwd()-based convention PromptLoader already uses for the main
3901
+ * agent's prompts, which needs no explicit override in the common case
3902
+ * (the backend process's own cwd already is its project root).
3903
+ */
3904
+ cwd?: string;
3905
+ /**
3906
+ * Where drafts/, the session-id map, and dashboard.log get written —
3907
+ * separate from `cwd` deliberately, so this deployment's runtime state
3908
+ * (regenerated per session, safe to gitignore) doesn't sit inside the
3909
+ * same folder as the version-controlled AGENTS.md prompt.
3910
+ * Default: `<process.cwd()>/.pi-dashboard-agent-runtime`.
3911
+ */
3912
+ runtimeDir?: string;
3913
+ /** Model provider (default: process.env.PI_AGENT_PROVIDER || 'openrouter'). */
3914
+ provider?: string;
3915
+ /** Model id (default: process.env.PI_AGENT_MODEL || 'anthropic/claude-sonnet-4.5'). */
3916
+ model?: string;
3917
+ /**
3918
+ * true (default): every request starts a brand-new pi session, with the 2
3919
+ * most recent prior responses (if any) injected into the prompt as
3920
+ * context — bounded cost per request, but pi re-explores schema/KB facts
3921
+ * it already verified in an earlier turn on this same dashboard.
3922
+ * false: resumes the same session file across requests on a given
3923
+ * dashboard — pi keeps everything it already learned, but context (and
3924
+ * cost) grows unbounded across turns (one observed turn: 2M+ cache-read
3925
+ * tokens after a handful of edits on the same dashboard).
3926
+ * Default: process.env.PI_AGENT_FRESH_SESSION !== 'false'.
3927
+ */
3928
+ freshSession?: boolean;
3929
+ }
3930
+ declare function registerDashboardAgentCollection(sdk: SuperatomSDK, config?: DashboardAgentCollectionConfig): void;
3931
+
3932
+ /**
3933
+ * ScriptMatcher — LLM-Based Script Matching + Parameter Extraction
3934
+ *
3935
+ * Uses ONE LLM call to:
3936
+ * 1. Pick the best matching script from the library (or "none")
3937
+ * 2. Extract parameter values from the user question
3938
+ *
3939
+ * Why LLM over embeddings:
3940
+ * - Embeddings capture topic similarity ("overstock" ≈ "inventory" ≈ "revenue")
3941
+ * but can't distinguish structurally different questions about the same domain
3942
+ * - LLM understands that "overstock by warehouse" needs a different script than
3943
+ * "revenue by warehouse" even though they're semantically close
3944
+ * - One call does both matching AND parameter extraction
3945
+ *
3946
+ * When script library grows past ~50, add an embedding pre-filter
3947
+ * (ChromaDB narrows to top 10 → LLM picks from those 10).
3948
+ */
3949
+
3950
+ declare class ScriptMatcher {
3951
+ private store;
3952
+ constructor(store: ScriptStore);
3953
+ /**
3954
+ * Find the best matching script for a user question.
3955
+ * Uses ONE LLM call that picks the script AND extracts parameters.
3956
+ * Returns null if no script matches.
3957
+ */
3958
+ match(userPrompt: string, apiKey?: string, model?: string, signal?: AbortSignal,
3959
+ /**
3960
+ * Recent script-backed answers in this thread, newest first. Presence of at
3961
+ * least one is what makes the `edit` tier reachable at all (see the guards
3962
+ * below), and handing over SEVERAL is what lets an instruction name its own
3963
+ * target instead of always hitting the most recent script.
3964
+ */
3965
+ activeBindings?: ScriptBinding[],
3966
+ /**
3967
+ * Recent conversation turns, most recent last. The gate needs this to tell
3968
+ * "this reply is an edit instruction for the active script" apart from
3969
+ * "this reply is answering a clarifying question about a DIFFERENT,
3970
+ * unresolved topic that never became a script" — a bare parameter-shaped
3971
+ * reply ("April 2025 to March 2026") is textually indistinguishable
3972
+ * between those two cases without seeing what the assistant just asked.
3973
+ * Once this tier is decided, nothing downstream re-checks it — the edit
3974
+ * path hands MainAgent a system prompt that explicitly instructs it to
3975
+ * trust the premise and not treat the turn as a new question — so this
3976
+ * gate is the only place that can catch a mismatch.
3977
+ */
3978
+ conversationHistory?: string): Promise<ScriptMatch | null>;
3979
+ /**
3980
+ * Build the script catalog string for the LLM prompt.
3981
+ * Each script gets: index, ID, name, description, and parameter definitions.
3982
+ */
3983
+ private buildScriptCatalog;
3984
+ /**
3985
+ * The recent script-backed answers in this thread — the bounded set an edit
3986
+ * may target. Rendered as its own prompt section (never merged into the
3987
+ * ranked catalog) so the `edit` rules have an unambiguous referent set, and
3988
+ * numbered newest-first so the prompt's "prefer the most recent when the
3989
+ * instruction is ambiguous" tie-break has something to point at.
3990
+ *
3991
+ * Each entry carries the QUESTION that produced it plus the columns it
3992
+ * returned — that is what lets the matcher resolve "use the mode for the WSP
3993
+ * one" instead of blindly taking the newest.
3994
+ */
3995
+ private buildActiveScriptBlock;
3996
+ }
3997
+
3998
+ /**
3999
+ * ScriptRunner — Execute scripts in an isolated tsx subprocess.
4000
+ *
4001
+ * The subprocess approach replaces the earlier `new Function()` eval and gives us:
4002
+ * - Real sandbox (separate process, SIGKILL on timeout).
4003
+ * - Real TypeScript (tsx transpiles on the fly).
4004
+ * - npm imports available to scripts (clustering, stats, geo, etc.).
4005
+ *
4006
+ * Protocol: NDJSON over the child's stdin/stdout. See script-ipc.ts + backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md.
4007
+ */
4008
+
4009
+ interface RunScriptOptions {
4010
+ /** Data sources the script is allowed to query via ctx.query */
4011
+ externalTools: ExternalTool[];
4012
+ /** Optional — for propagating per-query UI progress to the user */
4013
+ streamBuffer?: StreamBuffer;
4014
+ /** Override the wall-clock timeout (default `SCRIPT_TIMEOUT_MS`, 60s). */
4015
+ timeoutMs?: number;
4016
+ /**
4017
+ * Per-turn cancellation signal. When the user hits "Stop" mid-run, the child
4018
+ * process group is SIGKILLed and the run resolves as an aborted failure (the
4019
+ * caller is already unwinding, so the result is discarded).
4020
+ */
4021
+ signal?: AbortSignal;
4022
+ }
4023
+ /**
4024
+ * Execute a recipe by spawning a tsx child on the script's .ts file.
4025
+ * `scriptPath` is the absolute path to the saved `.ts` body.
4026
+ */
4027
+ declare function runScript(recipe: ScriptRecipe, scriptPath: string, params: Record<string, any>, options: RunScriptOptions): Promise<ScriptResult>;
4028
+
1627
4029
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
1628
4030
  declare class SuperatomSDK {
1629
4031
  private ws;
1630
4032
  private url;
1631
4033
  private apiKey?;
1632
4034
  private projectId;
1633
- private userId;
1634
4035
  private type;
1635
4036
  private bundleDir;
1636
4037
  private messageHandlers;
@@ -1641,12 +4042,18 @@ declare class SuperatomSDK {
1641
4042
  private collections;
1642
4043
  private components;
1643
4044
  private tools;
4045
+ private workflows;
1644
4046
  private anthropicApiKey;
1645
4047
  private groqApiKey;
1646
4048
  private geminiApiKey;
1647
4049
  private openaiApiKey;
1648
4050
  private llmProviders;
1649
4051
  private databaseType;
4052
+ private modelStrategy;
4053
+ private mainAgentModel;
4054
+ private sourceAgentModel;
4055
+ private dashCompModels?;
4056
+ private conversationSimilarityThreshold;
1650
4057
  private userManager;
1651
4058
  private dashboardManager;
1652
4059
  private reportManager;
@@ -1654,6 +4061,8 @@ declare class SuperatomSDK {
1654
4061
  private lastPong;
1655
4062
  private readonly PING_INTERVAL_MS;
1656
4063
  private readonly PONG_TIMEOUT_MS;
4064
+ private pendingOutbox;
4065
+ private readonly MAX_OUTBOX_SIZE;
1657
4066
  constructor(config: SuperatomSDKConfig);
1658
4067
  /**
1659
4068
  * Initialize PromptLoader and load prompts into memory
@@ -1693,9 +4102,25 @@ declare class SuperatomSDK {
1693
4102
  */
1694
4103
  private handleMessage;
1695
4104
  /**
1696
- * Send a message to the Superatom service
4105
+ * Send a message to the Superatom service.
4106
+ * Returns true if the message was sent, false if the WebSocket is not connected.
4107
+ * Does NOT throw on closed connections — callers can check the return value if needed.
4108
+ */
4109
+ send(message: Message): boolean;
4110
+ /**
4111
+ * Queue a message that couldn't be delivered because the socket was down,
4112
+ * to be resent once it reconnects. Drops the oldest entry once the bound is
4113
+ * hit — an outage long enough to fill this queue means the oldest queued
4114
+ * responses are for requests the caller has likely already given up on.
4115
+ */
4116
+ private queuePendingMessage;
4117
+ /**
4118
+ * Resend everything queued while the socket was down, now that it's back
4119
+ * up. Uses this.ws.send() directly (not send()) so a message that fails
4120
+ * again goes back through queuePendingMessage() rather than being silently
4121
+ * dropped a second time.
1697
4122
  */
1698
- send(message: Message): void;
4123
+ private flushPendingOutbox;
1699
4124
  /**
1700
4125
  * Register a message handler to receive all messages
1701
4126
  */
@@ -1735,6 +4160,14 @@ declare class SuperatomSDK {
1735
4160
  */
1736
4161
  private handlePong;
1737
4162
  private storeComponents;
4163
+ /**
4164
+ * The live, frontend-registered component catalog (name, type, description,
4165
+ * and full prop schema per component) — the same authoritative source
4166
+ * DASH_COMP_REQ's LLM prompt is built from. Exposed so other integrations
4167
+ * (e.g. the dashboard-agent script bridge) can read real component
4168
+ * contracts instead of maintaining a separate, driftable hand-written copy.
4169
+ */
4170
+ getComponents(): Component[];
1738
4171
  /**
1739
4172
  * Set tools for the SDK instance
1740
4173
  */
@@ -1743,6 +4176,57 @@ declare class SuperatomSDK {
1743
4176
  * Get the stored tools
1744
4177
  */
1745
4178
  getTools(): Tool$1[];
4179
+ /**
4180
+ * Call a registered collection operation in-process — no WebSocket
4181
+ * round-trip, since the caller is already running inside this same SDK
4182
+ * instance. Lets SDK-internal features (e.g. the dashboard agent) reuse
4183
+ * whatever collection a deployment has already registered (e.g.
4184
+ * 'dashboards'.'query') by name/convention, instead of requiring a
4185
+ * separate callback purely to re-expose data a collection already serves.
4186
+ * Throws if the collection or operation isn't registered.
4187
+ */
4188
+ callCollection<TResult = any>(collectionName: string, operation: string, params?: any): Promise<TResult>;
4189
+ /**
4190
+ * Register workflow components for the SDK instance.
4191
+ *
4192
+ * Workflows are pre-built multi-step UI flows the main agent can pick when
4193
+ * the user's prompt matches a workflow's `whenToUse` trigger. Picking a
4194
+ * workflow short-circuits analysis text + dashboard component generation —
4195
+ * the workflow component is returned directly, with the LLM-extracted props.
4196
+ */
4197
+ setWorkflows(workflows: WorkflowDescriptor[]): void;
4198
+ /**
4199
+ * Get the registered workflow components.
4200
+ */
4201
+ getWorkflows(): WorkflowDescriptor[];
4202
+ /**
4203
+ * Apply model strategy to all LLM provider singletons
4204
+ * @param strategy - 'best', 'fast', or 'balanced'
4205
+ */
4206
+ private applyModelStrategy;
4207
+ /**
4208
+ * Set model strategy at runtime
4209
+ * @param strategy - 'best', 'fast', or 'balanced'
4210
+ */
4211
+ setModelStrategy(strategy: ModelStrategy): void;
4212
+ /**
4213
+ * Get current model strategy
4214
+ */
4215
+ getModelStrategy(): ModelStrategy;
4216
+ /**
4217
+ * Apply conversation similarity threshold to all LLM provider singletons
4218
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
4219
+ */
4220
+ private applyConversationSimilarityThreshold;
4221
+ /**
4222
+ * Set conversation similarity threshold at runtime
4223
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
4224
+ */
4225
+ setConversationSimilarityThreshold(threshold: number): void;
4226
+ /**
4227
+ * Get current conversation similarity threshold
4228
+ */
4229
+ getConversationSimilarityThreshold(): number;
1746
4230
  }
1747
4231
 
1748
- export { type Action, BM25L, type BM25LOptions, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, type DatabaseType, 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 };
4232
+ 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 };