@superatomai/sdk-node 0.0.39 → 0.0.40-mds

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -59,7 +59,18 @@ declare class Logger {
59
59
  * Log debug message (only shown for verbose level)
60
60
  */
61
61
  debug(...args: any[]): void;
62
+ /**
63
+ * Write to log file
64
+ */
62
65
  file(...args: any[]): void;
66
+ /**
67
+ * Clear the log file (call at start of new user request)
68
+ */
69
+ clearFile(): void;
70
+ /**
71
+ * Log LLM method prompts with clear labeling
72
+ */
73
+ logLLMPrompt(methodName: string, promptType: 'system' | 'user', content: string | object | any[]): void;
63
74
  }
64
75
  declare const logger: Logger;
65
76
 
@@ -615,24 +626,189 @@ declare const IncomingMessageSchema: z.ZodObject<{
615
626
  payload?: unknown;
616
627
  }>;
617
628
  type IncomingMessage = z.infer<typeof IncomingMessageSchema>;
629
+ declare const ComponentSchema: z.ZodObject<{
630
+ id: z.ZodString;
631
+ name: z.ZodString;
632
+ displayName: z.ZodOptional<z.ZodString>;
633
+ isDisplayComp: z.ZodOptional<z.ZodBoolean>;
634
+ type: z.ZodString;
635
+ description: z.ZodString;
636
+ props: z.ZodObject<{
637
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
638
+ title: z.ZodOptional<z.ZodString>;
639
+ description: z.ZodOptional<z.ZodString>;
640
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
641
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
642
+ }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
643
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
644
+ title: z.ZodOptional<z.ZodString>;
645
+ description: z.ZodOptional<z.ZodString>;
646
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
647
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
648
+ }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
649
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
650
+ title: z.ZodOptional<z.ZodString>;
651
+ description: z.ZodOptional<z.ZodString>;
652
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
653
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
654
+ }, z.ZodTypeAny, "passthrough">>;
655
+ category: z.ZodOptional<z.ZodString>;
656
+ keywords: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
657
+ }, "strip", z.ZodTypeAny, {
658
+ id: string;
659
+ type: string;
660
+ name: string;
661
+ description: string;
662
+ props: {
663
+ description?: string | undefined;
664
+ query?: string | {} | null | undefined;
665
+ title?: string | undefined;
666
+ config?: Record<string, unknown> | undefined;
667
+ actions?: any[] | undefined;
668
+ } & {
669
+ [k: string]: unknown;
670
+ };
671
+ displayName?: string | undefined;
672
+ isDisplayComp?: boolean | undefined;
673
+ category?: string | undefined;
674
+ keywords?: string[] | undefined;
675
+ }, {
676
+ id: string;
677
+ type: string;
678
+ name: string;
679
+ description: string;
680
+ props: {
681
+ description?: string | undefined;
682
+ query?: string | {} | null | undefined;
683
+ title?: string | undefined;
684
+ config?: Record<string, unknown> | undefined;
685
+ actions?: any[] | undefined;
686
+ } & {
687
+ [k: string]: unknown;
688
+ };
689
+ displayName?: string | undefined;
690
+ isDisplayComp?: boolean | undefined;
691
+ category?: string | undefined;
692
+ keywords?: string[] | undefined;
693
+ }>;
694
+ type Component = z.infer<typeof ComponentSchema>;
695
+ declare const OutputFieldSchema: z.ZodObject<{
696
+ name: z.ZodString;
697
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
698
+ description: z.ZodString;
699
+ }, "strip", z.ZodTypeAny, {
700
+ type: "string" | "number" | "boolean" | "date";
701
+ name: string;
702
+ description: string;
703
+ }, {
704
+ type: "string" | "number" | "boolean" | "date";
705
+ name: string;
706
+ description: string;
707
+ }>;
708
+ type OutputField = z.infer<typeof OutputFieldSchema>;
709
+ declare const OutputSchema: z.ZodObject<{
710
+ description: z.ZodString;
711
+ fields: z.ZodArray<z.ZodObject<{
712
+ name: z.ZodString;
713
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
714
+ description: z.ZodString;
715
+ }, "strip", z.ZodTypeAny, {
716
+ type: "string" | "number" | "boolean" | "date";
717
+ name: string;
718
+ description: string;
719
+ }, {
720
+ type: "string" | "number" | "boolean" | "date";
721
+ name: string;
722
+ description: string;
723
+ }>, "many">;
724
+ }, "strip", z.ZodTypeAny, {
725
+ description: string;
726
+ fields: {
727
+ type: "string" | "number" | "boolean" | "date";
728
+ name: string;
729
+ description: string;
730
+ }[];
731
+ }, {
732
+ description: string;
733
+ fields: {
734
+ type: "string" | "number" | "boolean" | "date";
735
+ name: string;
736
+ description: string;
737
+ }[];
738
+ }>;
739
+ type ToolOutputSchema = z.infer<typeof OutputSchema>;
618
740
  declare const ToolSchema: z.ZodObject<{
619
741
  id: z.ZodString;
620
742
  name: z.ZodString;
621
743
  description: z.ZodString;
744
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
745
+ toolType: z.ZodOptional<z.ZodEnum<["source", "direct"]>>;
746
+ /** Full untruncated schema for source agent (all columns visible) */
747
+ fullSchema: z.ZodOptional<z.ZodString>;
622
748
  params: z.ZodRecord<z.ZodString, z.ZodString>;
623
749
  fn: z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodAny>;
750
+ outputSchema: z.ZodOptional<z.ZodObject<{
751
+ description: z.ZodString;
752
+ fields: z.ZodArray<z.ZodObject<{
753
+ name: z.ZodString;
754
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
755
+ description: z.ZodString;
756
+ }, "strip", z.ZodTypeAny, {
757
+ type: "string" | "number" | "boolean" | "date";
758
+ name: string;
759
+ description: string;
760
+ }, {
761
+ type: "string" | "number" | "boolean" | "date";
762
+ name: string;
763
+ description: string;
764
+ }>, "many">;
765
+ }, "strip", z.ZodTypeAny, {
766
+ description: string;
767
+ fields: {
768
+ type: "string" | "number" | "boolean" | "date";
769
+ name: string;
770
+ description: string;
771
+ }[];
772
+ }, {
773
+ description: string;
774
+ fields: {
775
+ type: "string" | "number" | "boolean" | "date";
776
+ name: string;
777
+ description: string;
778
+ }[];
779
+ }>>;
624
780
  }, "strip", z.ZodTypeAny, {
625
781
  id: string;
626
782
  params: Record<string, string>;
627
783
  name: string;
628
784
  description: string;
629
785
  fn: (args_0: any, ...args: unknown[]) => any;
786
+ toolType?: "source" | "direct" | undefined;
787
+ fullSchema?: string | undefined;
788
+ outputSchema?: {
789
+ description: string;
790
+ fields: {
791
+ type: "string" | "number" | "boolean" | "date";
792
+ name: string;
793
+ description: string;
794
+ }[];
795
+ } | undefined;
630
796
  }, {
631
797
  id: string;
632
798
  params: Record<string, string>;
633
799
  name: string;
634
800
  description: string;
635
801
  fn: (args_0: any, ...args: unknown[]) => any;
802
+ toolType?: "source" | "direct" | undefined;
803
+ fullSchema?: string | undefined;
804
+ outputSchema?: {
805
+ description: string;
806
+ fields: {
807
+ type: "string" | "number" | "boolean" | "date";
808
+ name: string;
809
+ description: string;
810
+ }[];
811
+ } | undefined;
636
812
  }>;
637
813
  type Tool$1 = z.infer<typeof ToolSchema>;
638
814
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
@@ -640,11 +816,33 @@ type CollectionHandler<TParams = any, TResult = any> = (params: TParams) => Prom
640
816
  type LLMProvider = 'anthropic' | 'groq' | 'gemini' | 'openai';
641
817
 
642
818
  type DatabaseType = 'postgresql' | 'mssql' | 'snowflake' | 'mysql';
819
+ /**
820
+ * Model strategy for controlling which models are used for different tasks
821
+ * - 'best': Use the best model (e.g., Sonnet) for all tasks - highest quality, higher cost
822
+ * - 'fast': Use the fast model (e.g., Haiku) for all tasks - lower quality, lower cost
823
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
824
+ */
825
+ type ModelStrategy = 'best' | 'fast' | 'balanced';
826
+ /**
827
+ * Model configuration for DASH_COMP flow (dashboard component picking)
828
+ * Allows separate control of models used for component selection
829
+ */
830
+ interface DashCompModelConfig {
831
+ /**
832
+ * Primary model for DASH_COMP requests
833
+ * Format: "provider/model-name" (e.g., "anthropic/claude-sonnet-4-5-20250929")
834
+ */
835
+ model?: string;
836
+ /**
837
+ * Fast model for simpler DASH_COMP tasks (optional)
838
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
839
+ */
840
+ fastModel?: string;
841
+ }
643
842
  interface SuperatomSDKConfig {
644
843
  url?: string;
645
844
  apiKey?: string;
646
845
  projectId: string;
647
- userId?: string;
648
846
  type?: string;
649
847
  bundleDir?: string;
650
848
  promptsDir?: string;
@@ -655,22 +853,68 @@ interface SuperatomSDKConfig {
655
853
  OPENAI_API_KEY?: string;
656
854
  LLM_PROVIDERS?: LLMProvider[];
657
855
  logLevel?: LogLevel;
856
+ /**
857
+ * Model selection strategy for LLM API calls:
858
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
859
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
860
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
861
+ */
862
+ modelStrategy?: ModelStrategy;
863
+ /**
864
+ * Model for the main agent (routing + analysis).
865
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
866
+ * If not set, uses the provider's default model.
867
+ */
868
+ mainAgentModel?: string;
869
+ /**
870
+ * Model for source agents (per-source query generation).
871
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
872
+ * If not set, uses the provider's default model.
873
+ */
874
+ sourceAgentModel?: string;
875
+ /**
876
+ * Separate model configuration for DASH_COMP flow (dashboard component picking)
877
+ * If not provided, falls back to provider-based model selection
878
+ */
879
+ dashCompModels?: DashCompModelConfig;
880
+ /**
881
+ * Similarity threshold for conversation search (semantic matching)
882
+ * Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
883
+ * Higher values require closer matches, lower values allow more distant matches
884
+ * Default: 0.8
885
+ */
886
+ conversationSimilarityThreshold?: number;
887
+ /**
888
+ * Query cache TTL (Time To Live) in minutes
889
+ * Cached query results expire after this duration
890
+ * Default: 5 minutes
891
+ */
892
+ queryCacheTTL?: number;
893
+ /**
894
+ * Dashboard conversation history TTL (Time To Live) in minutes
895
+ * Per-dashboard conversation histories expire after this duration
896
+ * Default: 30 minutes
897
+ */
898
+ dashboardHistoryTTL?: number;
658
899
  }
659
900
 
660
901
  declare const KbNodesQueryFiltersSchema: z.ZodObject<{
661
902
  query: z.ZodOptional<z.ZodString>;
662
903
  category: z.ZodOptional<z.ZodString>;
663
904
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
664
- createdBy: z.ZodOptional<z.ZodNumber>;
905
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
906
+ createdBy: z.ZodOptional<z.ZodString>;
665
907
  }, "strip", z.ZodTypeAny, {
908
+ type?: "query" | "user" | "global" | undefined;
666
909
  query?: string | undefined;
667
910
  category?: string | undefined;
668
- createdBy?: number | undefined;
911
+ createdBy?: string | undefined;
669
912
  tags?: string[] | undefined;
670
913
  }, {
914
+ type?: "query" | "user" | "global" | undefined;
671
915
  query?: string | undefined;
672
916
  category?: string | undefined;
673
- createdBy?: number | undefined;
917
+ createdBy?: string | undefined;
674
918
  tags?: string[] | undefined;
675
919
  }>;
676
920
  type KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
@@ -682,109 +926,126 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
682
926
  content: z.ZodOptional<z.ZodString>;
683
927
  category: z.ZodOptional<z.ZodString>;
684
928
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
685
- createdBy: z.ZodOptional<z.ZodNumber>;
686
- updatedBy: z.ZodOptional<z.ZodNumber>;
687
- userId: z.ZodOptional<z.ZodNumber>;
929
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
930
+ createdBy: z.ZodOptional<z.ZodString>;
931
+ updatedBy: z.ZodOptional<z.ZodString>;
932
+ userId: z.ZodOptional<z.ZodString>;
688
933
  query: z.ZodOptional<z.ZodString>;
689
934
  filters: z.ZodOptional<z.ZodObject<{
690
935
  query: z.ZodOptional<z.ZodString>;
691
936
  category: z.ZodOptional<z.ZodString>;
692
937
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
693
- createdBy: z.ZodOptional<z.ZodNumber>;
938
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
939
+ createdBy: z.ZodOptional<z.ZodString>;
694
940
  }, "strip", z.ZodTypeAny, {
941
+ type?: "query" | "user" | "global" | undefined;
695
942
  query?: string | undefined;
696
943
  category?: string | undefined;
697
- createdBy?: number | undefined;
944
+ createdBy?: string | undefined;
698
945
  tags?: string[] | undefined;
699
946
  }, {
947
+ type?: "query" | "user" | "global" | undefined;
700
948
  query?: string | undefined;
701
949
  category?: string | undefined;
702
- createdBy?: number | undefined;
950
+ createdBy?: string | undefined;
703
951
  tags?: string[] | undefined;
704
952
  }>>;
705
953
  limit: z.ZodOptional<z.ZodNumber>;
706
954
  offset: z.ZodOptional<z.ZodNumber>;
707
955
  }, "strip", z.ZodTypeAny, {
708
956
  id?: number | undefined;
957
+ type?: "query" | "user" | "global" | undefined;
709
958
  query?: string | undefined;
710
959
  title?: string | undefined;
711
960
  category?: string | undefined;
712
- userId?: number | undefined;
961
+ userId?: string | undefined;
713
962
  limit?: number | undefined;
714
963
  filters?: {
964
+ type?: "query" | "user" | "global" | undefined;
715
965
  query?: string | undefined;
716
966
  category?: string | undefined;
717
- createdBy?: number | undefined;
967
+ createdBy?: string | undefined;
718
968
  tags?: string[] | undefined;
719
969
  } | undefined;
720
- createdBy?: number | undefined;
721
- updatedBy?: number | undefined;
970
+ createdBy?: string | undefined;
971
+ updatedBy?: string | undefined;
972
+ offset?: number | undefined;
722
973
  tags?: string[] | undefined;
723
974
  content?: string | undefined;
724
- offset?: number | undefined;
725
975
  }, {
726
976
  id?: number | undefined;
977
+ type?: "query" | "user" | "global" | undefined;
727
978
  query?: string | undefined;
728
979
  title?: string | undefined;
729
980
  category?: string | undefined;
730
- userId?: number | undefined;
981
+ userId?: string | undefined;
731
982
  limit?: number | undefined;
732
983
  filters?: {
984
+ type?: "query" | "user" | "global" | undefined;
733
985
  query?: string | undefined;
734
986
  category?: string | undefined;
735
- createdBy?: number | undefined;
987
+ createdBy?: string | undefined;
736
988
  tags?: string[] | undefined;
737
989
  } | undefined;
738
- createdBy?: number | undefined;
739
- updatedBy?: number | undefined;
990
+ createdBy?: string | undefined;
991
+ updatedBy?: string | undefined;
992
+ offset?: number | undefined;
740
993
  tags?: string[] | undefined;
741
994
  content?: string | undefined;
742
- offset?: number | undefined;
743
995
  }>>;
744
996
  }, "strip", z.ZodTypeAny, {
745
997
  operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
746
998
  data?: {
747
999
  id?: number | undefined;
1000
+ type?: "query" | "user" | "global" | undefined;
748
1001
  query?: string | undefined;
749
1002
  title?: string | undefined;
750
1003
  category?: string | undefined;
751
- userId?: number | undefined;
1004
+ userId?: string | undefined;
752
1005
  limit?: number | undefined;
753
1006
  filters?: {
1007
+ type?: "query" | "user" | "global" | undefined;
754
1008
  query?: string | undefined;
755
1009
  category?: string | undefined;
756
- createdBy?: number | undefined;
1010
+ createdBy?: string | undefined;
757
1011
  tags?: string[] | undefined;
758
1012
  } | undefined;
759
- createdBy?: number | undefined;
760
- updatedBy?: number | undefined;
1013
+ createdBy?: string | undefined;
1014
+ updatedBy?: string | undefined;
1015
+ offset?: number | undefined;
761
1016
  tags?: string[] | undefined;
762
1017
  content?: string | undefined;
763
- offset?: number | undefined;
764
1018
  } | undefined;
765
1019
  }, {
766
1020
  operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
767
1021
  data?: {
768
1022
  id?: number | undefined;
1023
+ type?: "query" | "user" | "global" | undefined;
769
1024
  query?: string | undefined;
770
1025
  title?: string | undefined;
771
1026
  category?: string | undefined;
772
- userId?: number | undefined;
1027
+ userId?: string | undefined;
773
1028
  limit?: number | undefined;
774
1029
  filters?: {
1030
+ type?: "query" | "user" | "global" | undefined;
775
1031
  query?: string | undefined;
776
1032
  category?: string | undefined;
777
- createdBy?: number | undefined;
1033
+ createdBy?: string | undefined;
778
1034
  tags?: string[] | undefined;
779
1035
  } | undefined;
780
- createdBy?: number | undefined;
781
- updatedBy?: number | undefined;
1036
+ createdBy?: string | undefined;
1037
+ updatedBy?: string | undefined;
1038
+ offset?: number | undefined;
782
1039
  tags?: string[] | undefined;
783
1040
  content?: string | undefined;
784
- offset?: number | undefined;
785
1041
  } | undefined;
786
1042
  }>;
787
1043
  type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
1044
+ interface T_RESPONSE {
1045
+ success: boolean;
1046
+ data?: any;
1047
+ errors: string[];
1048
+ }
788
1049
 
789
1050
  /**
790
1051
  * UserManager class to handle CRUD operations on users with file persistence
@@ -1045,6 +1306,360 @@ declare class ReportManager {
1045
1306
  getReportCount(): number;
1046
1307
  }
1047
1308
 
1309
+ /**
1310
+ * StreamBuffer - Buffered streaming utility for smoother text delivery
1311
+ * Batches small chunks together and flushes at regular intervals
1312
+ */
1313
+ type StreamCallback = (chunk: string) => void;
1314
+ /**
1315
+ * StreamBuffer class for managing buffered streaming output
1316
+ * Provides smooth text delivery by batching small chunks
1317
+ */
1318
+ declare class StreamBuffer {
1319
+ private buffer;
1320
+ private flushTimer;
1321
+ private callback;
1322
+ private fullText;
1323
+ constructor(callback?: StreamCallback);
1324
+ /**
1325
+ * Check if the buffer has a callback configured
1326
+ */
1327
+ hasCallback(): boolean;
1328
+ /**
1329
+ * Get all text that has been written (including already flushed)
1330
+ */
1331
+ getFullText(): string;
1332
+ /**
1333
+ * Write a chunk to the buffer
1334
+ * Large chunks or chunks with newlines are flushed immediately
1335
+ * Small chunks are batched and flushed after a short interval
1336
+ *
1337
+ * @param chunk - Text chunk to write
1338
+ */
1339
+ write(chunk: string): void;
1340
+ /**
1341
+ * Flush the buffer immediately
1342
+ * Call this before tool execution or other operations that need clean output
1343
+ */
1344
+ flush(): void;
1345
+ /**
1346
+ * Internal flush implementation
1347
+ */
1348
+ private flushNow;
1349
+ /**
1350
+ * Clean up resources
1351
+ * Call this when done with the buffer
1352
+ */
1353
+ dispose(): void;
1354
+ }
1355
+
1356
+ /**
1357
+ * ToolExecutorService - Handles execution of SQL queries and external tools
1358
+ * Extracted from BaseLLM.generateTextResponse for better separation of concerns
1359
+ */
1360
+
1361
+ /**
1362
+ * External tool definition
1363
+ */
1364
+ interface ExternalTool {
1365
+ id: string;
1366
+ name: string;
1367
+ description?: string;
1368
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
1369
+ toolType?: 'source' | 'direct';
1370
+ /** Full untruncated schema for source agent (all columns visible) */
1371
+ fullSchema?: string;
1372
+ /** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
1373
+ schemaTier?: string;
1374
+ /** Schema search function for very_large tier — keyword search over entities */
1375
+ schemaSearchFn?: (keywords: string[]) => string;
1376
+ fn: (input: any) => Promise<any>;
1377
+ limit?: number;
1378
+ outputSchema?: any;
1379
+ executionType?: 'immediate' | 'deferred';
1380
+ userProvidedData?: any;
1381
+ params?: Record<string, any>;
1382
+ }
1383
+ /**
1384
+ * Executed tool tracking info
1385
+ */
1386
+ interface ExecutedToolInfo {
1387
+ id: string;
1388
+ name: string;
1389
+ params: any;
1390
+ result: {
1391
+ _totalRecords: number;
1392
+ _recordsShown: number;
1393
+ _metadata?: any;
1394
+ _sampleData: any[];
1395
+ };
1396
+ outputSchema?: any;
1397
+ sourceSchema?: string;
1398
+ sourceType?: string;
1399
+ }
1400
+
1401
+ /**
1402
+ * Multi-Agent Architecture Types
1403
+ *
1404
+ * Defines interfaces for the hierarchical agent system:
1405
+ * - Main Agent: ONE LLM.streamWithTools() call with source agent tools
1406
+ * - Source Agents: independent agents that query individual data sources
1407
+ *
1408
+ * The main agent sees only source summaries. When it calls a source tool,
1409
+ * the SourceAgent runs independently (own LLM, own retries) and returns clean data.
1410
+ */
1411
+
1412
+ /**
1413
+ * Per-entity detail: name, row count, and column names.
1414
+ * Gives the main agent enough context to route to the right source.
1415
+ */
1416
+ interface EntityDetail {
1417
+ /** Entity name (table, sheet, endpoint) */
1418
+ name: string;
1419
+ /** Approximate row count */
1420
+ rowCount?: number;
1421
+ /** Column/field names */
1422
+ columns: string[];
1423
+ }
1424
+ /**
1425
+ * Representation of a data source for the main agent.
1426
+ * Contains entity names WITH column names so the LLM can route accurately.
1427
+ */
1428
+ interface SourceSummary {
1429
+ /** Source ID (matches tool ID prefix) */
1430
+ id: string;
1431
+ /** Human-readable source name */
1432
+ name: string;
1433
+ /** Source type: postgres, excel, rest_api, etc. */
1434
+ type: string;
1435
+ /** Brief description of what data this source contains */
1436
+ description: string;
1437
+ /** Detailed entity info with column names for routing */
1438
+ entityDetails: EntityDetail[];
1439
+ /** The tool ID associated with this source */
1440
+ toolId: string;
1441
+ }
1442
+ /**
1443
+ * What a source agent returns after querying its data source.
1444
+ * The main agent uses this to analyze and compose the final response.
1445
+ */
1446
+ interface SourceAgentResult {
1447
+ /** Source ID */
1448
+ sourceId: string;
1449
+ /** Source name */
1450
+ sourceName: string;
1451
+ /** Whether the query succeeded */
1452
+ success: boolean;
1453
+ /** Result data rows */
1454
+ data: any[];
1455
+ /** Metadata about the query execution */
1456
+ metadata: SourceAgentMetadata;
1457
+ /** Tool execution info for the last successful query (backward compat) */
1458
+ executedTool: ExecutedToolInfo;
1459
+ /** All successful tool executions (primary + follow-up queries) */
1460
+ allExecutedTools?: ExecutedToolInfo[];
1461
+ /** Error message if failed */
1462
+ error?: string;
1463
+ }
1464
+ interface SourceAgentMetadata {
1465
+ /** Total rows that matched the query (before limit) */
1466
+ totalRowsMatched: number;
1467
+ /** Rows actually returned (after limit) */
1468
+ rowsReturned: number;
1469
+ /** Whether the result was truncated by the row limit */
1470
+ isLimited: boolean;
1471
+ /** The query/params that were executed */
1472
+ queryExecuted?: string;
1473
+ /** Execution time in milliseconds */
1474
+ executionTimeMs: number;
1475
+ }
1476
+ /**
1477
+ * A pre-built, multi-step UI flow registered with the SDK.
1478
+ *
1479
+ * When the main agent decides a user's question matches a workflow's whenToUse
1480
+ * trigger, it picks the workflow instead of running source agents / generating
1481
+ * dashboard components. The LLM extracts the workflow's required props from the
1482
+ * prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
1483
+ * workflow component directly — no analysis text, no chart generation. The
1484
+ * frontend renders the registered workflow component with the LLM-extracted
1485
+ * props.
1486
+ */
1487
+ interface WorkflowDescriptor {
1488
+ /** Unique workflow id (used as the LLM tool name) */
1489
+ id: string;
1490
+ /** Component name on the frontend (matches the registered React component) */
1491
+ name: string;
1492
+ /** Short human-readable description of what this workflow does */
1493
+ description: string;
1494
+ /**
1495
+ * 1–2 sentence trigger condition. The LLM uses this to decide if the
1496
+ * user's prompt matches this workflow. Be specific — e.g.
1497
+ * "User wants to *initiate* an inventory transfer (review + submit POs),
1498
+ * not just see analysis or charts."
1499
+ */
1500
+ whenToUse: string;
1501
+ /**
1502
+ * JSON-schema-style description of the props the workflow needs. Becomes
1503
+ * the LLM tool's input_schema, so the model fills these from the prompt.
1504
+ * Use the same shape as `params` on direct tools — string descriptors with
1505
+ * an optional "(optional)" suffix.
1506
+ *
1507
+ * Example:
1508
+ * ```
1509
+ * {
1510
+ * selectedStore: 'object — { id, name } of the source branch',
1511
+ * minROI: 'number (optional) — only show transfers with ROI ≥ this',
1512
+ * }
1513
+ * ```
1514
+ */
1515
+ propsSchema: Record<string, string>;
1516
+ /**
1517
+ * Optional: static prop defaults merged with LLM-extracted props before
1518
+ * the component is returned. Useful for things like the embedded
1519
+ * `externalTool` config that the workflow uses to fetch its own data.
1520
+ */
1521
+ defaultProps?: Record<string, any>;
1522
+ }
1523
+ /**
1524
+ * The workflow selection captured during a routing call.
1525
+ * Set on AgentResponse when the LLM picks a workflow tool.
1526
+ */
1527
+ interface SelectedWorkflow {
1528
+ /** Component name (matches WorkflowDescriptor.name) */
1529
+ name: string;
1530
+ /** Props extracted from the prompt + merged with workflow.defaultProps */
1531
+ props: Record<string, any>;
1532
+ }
1533
+ /**
1534
+ * The complete response from the multi-agent system.
1535
+ * Contains everything needed for text display + component generation.
1536
+ */
1537
+ interface AgentResponse {
1538
+ /** Generated text response (analysis of the data) */
1539
+ text: string;
1540
+ /** All executed tools across all source agents (for component generation) */
1541
+ executedTools: ExecutedToolInfo[];
1542
+ /** Individual results from each source agent */
1543
+ sourceResults: SourceAgentResult[];
1544
+ /**
1545
+ * Set when the LLM routed the question to a registered workflow component.
1546
+ * When present, the upstream caller should skip component generation and
1547
+ * return this workflow as the response.
1548
+ */
1549
+ workflow?: SelectedWorkflow;
1550
+ }
1551
+ /**
1552
+ * Configuration for the multi-agent system.
1553
+ * Controls limits, models, and behavior.
1554
+ */
1555
+ interface AgentConfig {
1556
+ /** Max rows a source agent can return (default: 50) */
1557
+ maxRowsPerSource: number;
1558
+ /** Model for the main agent (routing + analysis in one LLM call) */
1559
+ mainAgentModel: string;
1560
+ /** Model for source agent query generation */
1561
+ sourceAgentModel: string;
1562
+ /** API key for LLM calls */
1563
+ apiKey?: string;
1564
+ /** Max retry attempts per source agent */
1565
+ maxRetries: number;
1566
+ /** Max tool calling iterations for the main agent loop */
1567
+ maxIterations: number;
1568
+ /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
1569
+ globalKnowledgeBase?: string;
1570
+ /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
1571
+ knowledgeBaseContext?: string;
1572
+ }
1573
+ /**
1574
+ * Default agent configuration
1575
+ */
1576
+ declare const DEFAULT_AGENT_CONFIG: AgentConfig;
1577
+
1578
+ /**
1579
+ * Main Agent (Orchestrator)
1580
+ *
1581
+ * A single LLM.streamWithTools() call that handles everything:
1582
+ * - Routing: decides which source(s) to query based on summaries
1583
+ * - Querying: calls source tools (each wraps an independent SourceAgent)
1584
+ * - Direct tools: calls pre-built function tools directly with LLM-provided params
1585
+ * - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
1586
+ * - Analysis: generates final text response from the data
1587
+ *
1588
+ * Two tool types:
1589
+ * - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
1590
+ * - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
1591
+ */
1592
+
1593
+ declare class MainAgent {
1594
+ private externalTools;
1595
+ private workflows;
1596
+ private config;
1597
+ private streamBuffer;
1598
+ constructor(externalTools: ExternalTool[], config: AgentConfig, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[]);
1599
+ /**
1600
+ * Handle a user question using the multi-agent system.
1601
+ *
1602
+ * This is ONE LLM.streamWithTools() call. The LLM:
1603
+ * 1. Sees source summaries + direct tool descriptions in system prompt
1604
+ * 2. Decides which tool(s) to call (routing)
1605
+ * 3. Source tools → SourceAgent runs independently → returns data
1606
+ * 4. Direct tools → fn() called directly with LLM params → returns data
1607
+ * 5. Generates final analysis text
1608
+ */
1609
+ handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void): Promise<AgentResponse>;
1610
+ /**
1611
+ * Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
1612
+ */
1613
+ private handleDirectTool;
1614
+ /**
1615
+ * Build the main agent's system prompt with source summaries, direct tool descriptions,
1616
+ * and workflow component descriptions.
1617
+ */
1618
+ private buildSystemPrompt;
1619
+ /**
1620
+ * Build tool definitions for source tools — summary-only descriptions.
1621
+ * The full schema is inside the SourceAgent which runs independently.
1622
+ */
1623
+ private buildSourceToolDefinitions;
1624
+ /**
1625
+ * Build tool definitions for direct tools — expose their actual params.
1626
+ * These are called directly by the main agent LLM, no SourceAgent.
1627
+ */
1628
+ private buildDirectToolDefinitions;
1629
+ /**
1630
+ * Capture a workflow selection. We do NOT execute anything — the LLM has
1631
+ * already extracted the props it wants the workflow rendered with. We
1632
+ * record the selection (via the capture callback) and return a short
1633
+ * acknowledgement so the LLM ends its turn cleanly without writing
1634
+ * analysis text or calling more tools.
1635
+ */
1636
+ private handleWorkflow;
1637
+ /**
1638
+ * Build LLM tool definitions for workflow components. The workflow's
1639
+ * propsSchema becomes the tool's input_schema so the LLM extracts props
1640
+ * directly from the prompt — same mechanic as direct tools.
1641
+ */
1642
+ private buildWorkflowToolDefinitions;
1643
+ /**
1644
+ * Format a source agent's result as a clean string for the main agent LLM.
1645
+ */
1646
+ private formatResultForMainAgent;
1647
+ /**
1648
+ * Get source summaries (for external inspection/debugging).
1649
+ */
1650
+ getSourceSummaries(): SourceSummary[];
1651
+ }
1652
+
1653
+ /**
1654
+ * Represents an action that can be performed on a UIBlock
1655
+ */
1656
+ interface Action {
1657
+ id: string;
1658
+ name: string;
1659
+ type: string;
1660
+ [key: string]: any;
1661
+ }
1662
+
1048
1663
  type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
1049
1664
  interface LLMMessages {
1050
1665
  sys: SystemPrompt;
@@ -1102,6 +1717,11 @@ declare class LLM {
1102
1717
  private static _groqStream;
1103
1718
  private static _geminiText;
1104
1719
  private static _geminiStream;
1720
+ /**
1721
+ * Recursively strip unsupported JSON Schema properties for Gemini
1722
+ * Gemini doesn't support: additionalProperties, $schema, etc.
1723
+ */
1724
+ private static _cleanSchemaForGemini;
1105
1725
  private static _geminiStreamWithTools;
1106
1726
  private static _openaiText;
1107
1727
  private static _openaiStream;
@@ -1194,16 +1814,6 @@ declare class UILogCollector {
1194
1814
  setUIBlockId(uiBlockId: string): void;
1195
1815
  }
1196
1816
 
1197
- /**
1198
- * Represents an action that can be performed on a UIBlock
1199
- */
1200
- interface Action {
1201
- id: string;
1202
- name: string;
1203
- type: string;
1204
- [key: string]: any;
1205
- }
1206
-
1207
1817
  /**
1208
1818
  * UIBlock represents a single user and assistant message block in a thread
1209
1819
  * Contains user question, component metadata, component data, text response, and available actions
@@ -1386,12 +1996,20 @@ declare class Thread {
1386
1996
 
1387
1997
  /**
1388
1998
  * ThreadManager manages all threads globally
1389
- * Provides methods to create, retrieve, and delete threads
1999
+ * Provides methods to create, retrieve, and delete threads.
2000
+ * Includes automatic cleanup to prevent unbounded memory growth.
1390
2001
  */
1391
2002
  declare class ThreadManager {
1392
2003
  private static instance;
1393
2004
  private threads;
2005
+ private cleanupInterval;
2006
+ private readonly threadTtlMs;
1394
2007
  private constructor();
2008
+ /**
2009
+ * Periodically remove threads older than 7 days.
2010
+ * Runs every hour to avoid frequent iteration over the map.
2011
+ */
2012
+ private startCleanup;
1395
2013
  /**
1396
2014
  * Get singleton instance of ThreadManager
1397
2015
  */
@@ -1548,6 +2166,120 @@ declare const CONTEXT_CONFIG: {
1548
2166
  MAX_CONVERSATION_CONTEXT_BLOCKS: number;
1549
2167
  };
1550
2168
 
2169
+ /**
2170
+ * LLM Usage Logger - Tracks token usage, costs, and timing for all LLM API calls
2171
+ */
2172
+ interface LLMUsageEntry {
2173
+ timestamp: string;
2174
+ requestId: string;
2175
+ provider: string;
2176
+ model: string;
2177
+ method: string;
2178
+ inputTokens: number;
2179
+ outputTokens: number;
2180
+ cacheReadTokens?: number;
2181
+ cacheWriteTokens?: number;
2182
+ totalTokens: number;
2183
+ costUSD: number;
2184
+ durationMs: number;
2185
+ toolCalls?: number;
2186
+ success: boolean;
2187
+ error?: string;
2188
+ }
2189
+ declare class LLMUsageLogger {
2190
+ private logStream;
2191
+ private logPath;
2192
+ private enabled;
2193
+ private sessionStats;
2194
+ constructor();
2195
+ private initLogStream;
2196
+ private writeHeader;
2197
+ /**
2198
+ * Calculate cost based on token usage and model
2199
+ */
2200
+ calculateCost(model: string, inputTokens: number, outputTokens: number, cacheReadTokens?: number, cacheWriteTokens?: number): number;
2201
+ /**
2202
+ * Log an LLM API call
2203
+ */
2204
+ log(entry: LLMUsageEntry): void;
2205
+ /**
2206
+ * Log session summary (call at end of request)
2207
+ */
2208
+ logSessionSummary(requestContext?: string): void;
2209
+ /**
2210
+ * Reset session stats (call at start of new user request)
2211
+ */
2212
+ resetSession(): void;
2213
+ /**
2214
+ * Reset the log file for a new request (clears previous logs)
2215
+ * Call this at the start of each USER_PROMPT_REQ
2216
+ */
2217
+ resetLogFile(requestContext?: string): void;
2218
+ /**
2219
+ * Get current session stats
2220
+ */
2221
+ getSessionStats(): {
2222
+ totalCalls: number;
2223
+ totalInputTokens: number;
2224
+ totalOutputTokens: number;
2225
+ totalCacheReadTokens: number;
2226
+ totalCacheWriteTokens: number;
2227
+ totalCostUSD: number;
2228
+ totalDurationMs: number;
2229
+ };
2230
+ /**
2231
+ * Generate a unique request ID
2232
+ */
2233
+ generateRequestId(): string;
2234
+ }
2235
+ declare const llmUsageLogger: LLMUsageLogger;
2236
+
2237
+ /**
2238
+ * User Prompt Error Logger - Captures detailed errors for USER_PROMPT_REQ
2239
+ * Logs full error details including raw strings for parse failures
2240
+ */
2241
+ declare class UserPromptErrorLogger {
2242
+ private logStream;
2243
+ private logPath;
2244
+ private enabled;
2245
+ private hasErrors;
2246
+ constructor();
2247
+ /**
2248
+ * Reset the error log file for a new request
2249
+ */
2250
+ resetLogFile(requestContext?: string): void;
2251
+ /**
2252
+ * Log a JSON parse error with the raw string that failed
2253
+ */
2254
+ logJsonParseError(context: string, rawString: string, error: Error): void;
2255
+ /**
2256
+ * Log a general error with full details
2257
+ */
2258
+ logError(context: string, error: Error | string, additionalData?: Record<string, any>): void;
2259
+ /**
2260
+ * Log a SQL query error with the full query
2261
+ */
2262
+ logSqlError(query: string, error: Error | string, params?: any[]): void;
2263
+ /**
2264
+ * Log an LLM API error
2265
+ */
2266
+ logLlmError(provider: string, model: string, method: string, error: Error | string, requestData?: any): void;
2267
+ /**
2268
+ * Log tool execution error
2269
+ */
2270
+ logToolError(toolName: string, toolInput: any, error: Error | string): void;
2271
+ /**
2272
+ * Write final summary if there were errors
2273
+ */
2274
+ writeSummary(): void;
2275
+ /**
2276
+ * Check if any errors were logged
2277
+ */
2278
+ hadErrors(): boolean;
2279
+ private write;
2280
+ }
2281
+ declare const userPromptErrorLogger: UserPromptErrorLogger;
2282
+
1551
2283
  /**
1552
2284
  * BM25L Reranker for hybrid semantic search
1553
2285
  *
@@ -1676,14 +2408,453 @@ declare function rerankConversationResults<T extends {
1676
2408
  bm25Score: number;
1677
2409
  }>;
1678
2410
 
1679
- declare const SDK_VERSION = "0.0.8";
2411
+ /**
2412
+ * QueryExecutionService - Handles all query execution, validation, and retry logic
2413
+ * Extracted from BaseLLM for better separation of concerns
2414
+ */
2415
+
2416
+ /**
2417
+ * Context for component when requesting query fix
2418
+ */
2419
+ interface ComponentContext {
2420
+ name: string;
2421
+ type: string;
2422
+ title?: string;
2423
+ }
2424
+ /**
2425
+ * Result of query validation
2426
+ */
2427
+ interface QueryValidationResult {
2428
+ component: Component | null;
2429
+ queryKey: string;
2430
+ result: any;
2431
+ validated: boolean;
2432
+ }
2433
+ /**
2434
+ * Result of batch query validation
2435
+ */
2436
+ interface BatchValidationResult {
2437
+ components: Component[];
2438
+ queryResults: Map<string, any>;
2439
+ }
2440
+ /**
2441
+ * Configuration for QueryExecutionService
2442
+ */
2443
+ interface QueryExecutionServiceConfig {
2444
+ defaultLimit: number;
2445
+ getModelForTask: (taskType: 'simple' | 'complex') => string;
2446
+ getApiKey: (apiKey?: string) => string | undefined;
2447
+ providerName: string;
2448
+ }
2449
+ /**
2450
+ * QueryExecutionService handles all query-related operations
2451
+ */
2452
+ declare class QueryExecutionService {
2453
+ private config;
2454
+ constructor(config: QueryExecutionServiceConfig);
2455
+ /**
2456
+ * Get the cache key for a query
2457
+ * This ensures the cache key matches what the frontend will send
2458
+ */
2459
+ getQueryCacheKey(query: any): string;
2460
+ /**
2461
+ * Execute a query against the database
2462
+ * @param query - The SQL query to execute (string or object with sql/values)
2463
+ * @param collections - Collections object containing database execute function
2464
+ * @returns Object with result data and cache key
2465
+ */
2466
+ executeQuery(query: any, collections: any): Promise<{
2467
+ result: any;
2468
+ cacheKey: string;
2469
+ }>;
2470
+ /**
2471
+ * Request the LLM to fix a failed SQL query
2472
+ * @param failedQuery - The query that failed execution
2473
+ * @param errorMessage - The error message from the failed execution
2474
+ * @param componentContext - Context about the component
2475
+ * @param apiKey - Optional API key
2476
+ * @returns Fixed query string
2477
+ */
2478
+ requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
2479
+ /**
2480
+ * Validate a single component's query with retry logic
2481
+ * @param component - The component to validate
2482
+ * @param collections - Collections object containing database execute function
2483
+ * @param apiKey - Optional API key for LLM calls
2484
+ * @returns Validation result with component, query key, and result
2485
+ */
2486
+ validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
2487
+ /**
2488
+ * Validate multiple component queries in parallel
2489
+ * @param components - Array of components with potential queries
2490
+ * @param collections - Collections object containing database execute function
2491
+ * @param apiKey - Optional API key for LLM calls
2492
+ * @returns Object with validated components and query results map
2493
+ */
2494
+ validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
2495
+ }
2496
+
2497
+ /**
2498
+ * Task types for model selection
2499
+ * - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
2500
+ * - 'simple': Classification, action generation (uses fast model in balanced mode)
2501
+ */
2502
+ type TaskType = 'complex' | 'simple';
2503
+ interface BaseLLMConfig {
2504
+ model?: string;
2505
+ fastModel?: string;
2506
+ defaultLimit?: number;
2507
+ apiKey?: string;
2508
+ /**
2509
+ * Model selection strategy:
2510
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
2511
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
2512
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
2513
+ */
2514
+ modelStrategy?: ModelStrategy;
2515
+ conversationSimilarityThreshold?: number;
2516
+ }
2517
+ /**
2518
+ * BaseLLM abstract class for AI-powered component generation and matching
2519
+ * Provides common functionality for all LLM providers
2520
+ */
2521
+ declare abstract class BaseLLM {
2522
+ protected model: string;
2523
+ protected fastModel: string;
2524
+ protected defaultLimit: number;
2525
+ protected apiKey?: string;
2526
+ protected modelStrategy: ModelStrategy;
2527
+ protected conversationSimilarityThreshold: number;
2528
+ protected queryService: QueryExecutionService;
2529
+ constructor(config?: BaseLLMConfig);
2530
+ /**
2531
+ * Get the appropriate model based on task type and model strategy
2532
+ * @param taskType - 'complex' for text generation/matching, 'simple' for classification/actions
2533
+ * @returns The model string to use for this task
2534
+ */
2535
+ protected getModelForTask(taskType: TaskType): string;
2536
+ /**
2537
+ * Set the model strategy at runtime
2538
+ * @param strategy - 'best', 'fast', or 'balanced'
2539
+ */
2540
+ setModelStrategy(strategy: ModelStrategy): void;
2541
+ /**
2542
+ * Get the current model strategy
2543
+ * @returns The current model strategy
2544
+ */
2545
+ getModelStrategy(): ModelStrategy;
2546
+ /**
2547
+ * Set the conversation similarity threshold at runtime
2548
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2549
+ */
2550
+ setConversationSimilarityThreshold(threshold: number): void;
2551
+ /**
2552
+ * Get the current conversation similarity threshold
2553
+ * @returns The current threshold value
2554
+ */
2555
+ getConversationSimilarityThreshold(): number;
2556
+ /**
2557
+ * Get the default model for this provider (used for complex tasks like text generation)
2558
+ */
2559
+ protected abstract getDefaultModel(): string;
2560
+ /**
2561
+ * Get the default fast model for this provider (used for simple tasks: classification, matching, actions)
2562
+ * Should return a cheaper/faster model like Haiku for Anthropic
2563
+ */
2564
+ protected abstract getDefaultFastModel(): string;
2565
+ /**
2566
+ * Get the default API key from environment
2567
+ */
2568
+ protected abstract getDefaultApiKey(): string | undefined;
2569
+ /**
2570
+ * Get the provider name (for logging)
2571
+ */
2572
+ protected abstract getProviderName(): string;
2573
+ /**
2574
+ * Get the API key (from instance, parameter, or environment)
2575
+ */
2576
+ protected getApiKey(apiKey?: string): string | undefined;
2577
+ /**
2578
+ * Check if a component contains a Form (data_modification component)
2579
+ * Forms have hardcoded defaultValues that become stale when cached
2580
+ * This checks both single Form components and Forms inside MultiComponentContainer
2581
+ */
2582
+ protected containsFormComponent(component: any): boolean;
2583
+ /**
2584
+ * Match components from text response suggestions and generate follow-up questions
2585
+ * Takes a text response with component suggestions (c1:type format) and matches with available components
2586
+ * Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
2587
+ * All components are placed in a default MultiComponentContainer layout
2588
+ * @param analysisContent - The text response containing component suggestions
2589
+ * @param components - List of available components
2590
+ * @param apiKey - Optional API key
2591
+ * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
2592
+ * @returns Object containing matched components, layout title/description, and follow-up actions
2593
+ */
2594
+ matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
2595
+ components: Component[];
2596
+ layoutTitle: string;
2597
+ layoutDescription: string;
2598
+ actions: Action[];
2599
+ }>;
2600
+ /**
2601
+ * Classify user question into category and detect external tools needed
2602
+ * Determines if question is for data analysis, requires external tools, or needs text response
2603
+ */
2604
+ classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
2605
+ category: 'data_analysis' | 'data_modification' | 'general';
2606
+ externalTools: Array<{
2607
+ type: string;
2608
+ name: string;
2609
+ description: string;
2610
+ parameters: Record<string, any>;
2611
+ }>;
2612
+ dataAnalysisType?: 'visualization' | 'calculation' | 'comparison' | 'trend';
2613
+ reasoning: string;
2614
+ confidence: number;
2615
+ }>;
2616
+ /**
2617
+ * Adapt UI block parameters based on current user question
2618
+ * Takes a matched UI block from semantic search and modifies its props to answer the new question
2619
+ * Also adapts the cached text response to match the new question
2620
+ */
2621
+ adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
2622
+ success: boolean;
2623
+ adaptedComponent?: Component;
2624
+ adaptedTextResponse?: string;
2625
+ parametersChanged?: Array<{
2626
+ field: string;
2627
+ reason: string;
2628
+ }>;
2629
+ explanation: string;
2630
+ }>;
2631
+ /**
2632
+ * Generate text-based response for user question
2633
+ * This provides conversational text responses instead of component generation
2634
+ * Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
2635
+ * After generating text response, if components are provided, matches suggested components
2636
+ */
2637
+ 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>;
2638
+ /**
2639
+ * Main orchestration function with semantic search and multi-step classification
2640
+ * NEW FLOW (Recommended):
2641
+ * 1. Semantic search: Check previous conversations (>60% match)
2642
+ * - If match found → Adapt UI block parameters and return
2643
+ * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
2644
+ * 3. Route appropriately based on category and response mode
2645
+ */
2646
+ 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>;
2647
+ /**
2648
+ * Generate next questions that the user might ask based on the original prompt and generated component
2649
+ * This helps provide intelligent suggestions for follow-up queries
2650
+ * For general/conversational questions without components, pass textResponse instead
2651
+ */
2652
+ generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string): Promise<string[]>;
2653
+ }
2654
+
2655
+ interface AnthropicLLMConfig extends BaseLLMConfig {
2656
+ }
2657
+ /**
2658
+ * AnthropicLLM class for handling AI-powered component generation and matching using Anthropic Claude
2659
+ */
2660
+ declare class AnthropicLLM extends BaseLLM {
2661
+ constructor(config?: AnthropicLLMConfig);
2662
+ protected getDefaultModel(): string;
2663
+ protected getDefaultFastModel(): string;
2664
+ protected getDefaultApiKey(): string | undefined;
2665
+ protected getProviderName(): string;
2666
+ }
2667
+ declare const anthropicLLM: AnthropicLLM;
2668
+
2669
+ interface GroqLLMConfig extends BaseLLMConfig {
2670
+ }
2671
+ /**
2672
+ * GroqLLM class for handling AI-powered component generation and matching using Groq
2673
+ */
2674
+ declare class GroqLLM extends BaseLLM {
2675
+ constructor(config?: GroqLLMConfig);
2676
+ protected getDefaultModel(): string;
2677
+ protected getDefaultFastModel(): string;
2678
+ protected getDefaultApiKey(): string | undefined;
2679
+ protected getProviderName(): string;
2680
+ }
2681
+ declare const groqLLM: GroqLLM;
2682
+
2683
+ interface GeminiLLMConfig extends BaseLLMConfig {
2684
+ }
2685
+ /**
2686
+ * GeminiLLM class for handling AI-powered component generation and matching using Google Gemini
2687
+ */
2688
+ declare class GeminiLLM extends BaseLLM {
2689
+ constructor(config?: GeminiLLMConfig);
2690
+ protected getDefaultModel(): string;
2691
+ protected getDefaultFastModel(): string;
2692
+ protected getDefaultApiKey(): string | undefined;
2693
+ protected getProviderName(): string;
2694
+ }
2695
+ declare const geminiLLM: GeminiLLM;
2696
+
2697
+ interface OpenAILLMConfig extends BaseLLMConfig {
2698
+ }
2699
+ /**
2700
+ * OpenAILLM class for handling AI-powered component generation and matching using OpenAI GPT models
2701
+ */
2702
+ declare class OpenAILLM extends BaseLLM {
2703
+ constructor(config?: OpenAILLMConfig);
2704
+ protected getDefaultModel(): string;
2705
+ protected getDefaultFastModel(): string;
2706
+ protected getDefaultApiKey(): string | undefined;
2707
+ protected getProviderName(): string;
2708
+ }
2709
+ declare const openaiLLM: OpenAILLM;
2710
+
2711
+ /**
2712
+ * Query Cache — Two mechanisms:
2713
+ *
2714
+ * 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
2715
+ * of recently validated queries. LRU eviction when max size exceeded.
2716
+ *
2717
+ * 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
2718
+ * No server-side storage needed for SQL mappings. The token is decrypted on each request.
2719
+ * This eliminates the unbounded queryIdCache that previously grew forever and caused
2720
+ * memory bloat (hundreds of MBs after thousands of queries).
2721
+ *
2722
+ * Result data can still be cached temporarily via the data cache (mechanism 1).
2723
+ */
2724
+ declare class QueryCache {
2725
+ private cache;
2726
+ private ttlMs;
2727
+ private maxCacheSize;
2728
+ private cleanupInterval;
2729
+ private readonly algorithm;
2730
+ private encryptionKey;
2731
+ constructor();
2732
+ /**
2733
+ * Set the cache TTL (Time To Live)
2734
+ * @param minutes - TTL in minutes (default: 10)
2735
+ */
2736
+ setTTL(minutes: number): void;
2737
+ /**
2738
+ * Get the current TTL in minutes
2739
+ */
2740
+ getTTL(): number;
2741
+ /**
2742
+ * Store query result in data cache
2743
+ */
2744
+ set(query: string, data: any): void;
2745
+ /**
2746
+ * Get cached result if exists and not expired
2747
+ */
2748
+ get(query: string): any | null;
2749
+ /**
2750
+ * Check if query exists in cache (not expired)
2751
+ */
2752
+ has(query: string): boolean;
2753
+ /**
2754
+ * Remove a specific query from cache
2755
+ */
2756
+ delete(query: string): void;
2757
+ /**
2758
+ * Clear all cached entries
2759
+ */
2760
+ clear(): void;
2761
+ /**
2762
+ * Get cache statistics
2763
+ */
2764
+ getStats(): {
2765
+ size: number;
2766
+ queryIdCount: number;
2767
+ oldestEntryAge: number | null;
2768
+ };
2769
+ /**
2770
+ * Start periodic cleanup of expired data cache entries.
2771
+ */
2772
+ private startCleanup;
2773
+ /**
2774
+ * Encrypt a payload into a self-contained token.
2775
+ */
2776
+ private encrypt;
2777
+ /**
2778
+ * Decrypt a token back to the original payload.
2779
+ */
2780
+ private decrypt;
2781
+ /**
2782
+ * Store a query by generating an encrypted token as queryId.
2783
+ * The SQL is encrypted INTO the token — nothing stored in memory.
2784
+ * If data is provided, it's cached temporarily in the data cache.
2785
+ */
2786
+ storeQuery(query: any, data?: any): string;
2787
+ /**
2788
+ * Get a stored query by decrypting its token.
2789
+ * Returns the SQL + any cached result data.
2790
+ */
2791
+ getQuery(queryId: string): {
2792
+ query: any;
2793
+ data: any;
2794
+ } | null;
2795
+ /**
2796
+ * Update cached data for a queryId token
2797
+ */
2798
+ setQueryData(queryId: string, data: any): void;
2799
+ /**
2800
+ * Stop cleanup interval (for graceful shutdown)
2801
+ */
2802
+ destroy(): void;
2803
+ }
2804
+ declare const queryCache: QueryCache;
2805
+
2806
+ /**
2807
+ * Manages conversation history scoped per user + dashboard.
2808
+ * Each user-dashboard pair has its own isolated history that expires after a configurable TTL.
2809
+ */
2810
+ declare class DashboardConversationHistory {
2811
+ private histories;
2812
+ private ttlMs;
2813
+ private maxEntries;
2814
+ private cleanupInterval;
2815
+ constructor();
2816
+ /**
2817
+ * Set the TTL for dashboard histories
2818
+ * @param minutes - TTL in minutes
2819
+ */
2820
+ setTTL(minutes: number): void;
2821
+ /**
2822
+ * Set max entries per dashboard
2823
+ */
2824
+ setMaxEntries(max: number): void;
2825
+ /**
2826
+ * Add a conversation entry for a user's dashboard
2827
+ */
2828
+ addEntry(dashboardId: string, userPrompt: string, componentSummary: string, userId?: string): void;
2829
+ /**
2830
+ * Get formatted conversation history for a user's dashboard
2831
+ */
2832
+ getHistory(dashboardId: string, userId?: string): string;
2833
+ /**
2834
+ * Clear history for a specific user's dashboard
2835
+ */
2836
+ clearDashboard(dashboardId: string, userId?: string): void;
2837
+ /**
2838
+ * Clear all dashboard histories
2839
+ */
2840
+ clearAll(): void;
2841
+ /**
2842
+ * Start periodic cleanup of expired histories
2843
+ */
2844
+ private startCleanup;
2845
+ /**
2846
+ * Stop cleanup interval (for graceful shutdown)
2847
+ */
2848
+ destroy(): void;
2849
+ }
2850
+ declare const dashboardConversationHistory: DashboardConversationHistory;
2851
+
1680
2852
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
1681
2853
  declare class SuperatomSDK {
1682
2854
  private ws;
1683
2855
  private url;
1684
2856
  private apiKey?;
1685
2857
  private projectId;
1686
- private userId;
1687
2858
  private type;
1688
2859
  private bundleDir;
1689
2860
  private messageHandlers;
@@ -1694,12 +2865,18 @@ declare class SuperatomSDK {
1694
2865
  private collections;
1695
2866
  private components;
1696
2867
  private tools;
2868
+ private workflows;
1697
2869
  private anthropicApiKey;
1698
2870
  private groqApiKey;
1699
2871
  private geminiApiKey;
1700
2872
  private openaiApiKey;
1701
2873
  private llmProviders;
1702
2874
  private databaseType;
2875
+ private modelStrategy;
2876
+ private mainAgentModel;
2877
+ private sourceAgentModel;
2878
+ private dashCompModels?;
2879
+ private conversationSimilarityThreshold;
1703
2880
  private userManager;
1704
2881
  private dashboardManager;
1705
2882
  private reportManager;
@@ -1746,9 +2923,11 @@ declare class SuperatomSDK {
1746
2923
  */
1747
2924
  private handleMessage;
1748
2925
  /**
1749
- * Send a message to the Superatom service
2926
+ * Send a message to the Superatom service.
2927
+ * Returns true if the message was sent, false if the WebSocket is not connected.
2928
+ * Does NOT throw on closed connections — callers can check the return value if needed.
1750
2929
  */
1751
- send(message: Message): void;
2930
+ send(message: Message): boolean;
1752
2931
  /**
1753
2932
  * Register a message handler to receive all messages
1754
2933
  */
@@ -1796,6 +2975,47 @@ declare class SuperatomSDK {
1796
2975
  * Get the stored tools
1797
2976
  */
1798
2977
  getTools(): Tool$1[];
2978
+ /**
2979
+ * Register workflow components for the SDK instance.
2980
+ *
2981
+ * Workflows are pre-built multi-step UI flows the main agent can pick when
2982
+ * the user's prompt matches a workflow's `whenToUse` trigger. Picking a
2983
+ * workflow short-circuits analysis text + dashboard component generation —
2984
+ * the workflow component is returned directly, with the LLM-extracted props.
2985
+ */
2986
+ setWorkflows(workflows: WorkflowDescriptor[]): void;
2987
+ /**
2988
+ * Get the registered workflow components.
2989
+ */
2990
+ getWorkflows(): WorkflowDescriptor[];
2991
+ /**
2992
+ * Apply model strategy to all LLM provider singletons
2993
+ * @param strategy - 'best', 'fast', or 'balanced'
2994
+ */
2995
+ private applyModelStrategy;
2996
+ /**
2997
+ * Set model strategy at runtime
2998
+ * @param strategy - 'best', 'fast', or 'balanced'
2999
+ */
3000
+ setModelStrategy(strategy: ModelStrategy): void;
3001
+ /**
3002
+ * Get current model strategy
3003
+ */
3004
+ getModelStrategy(): ModelStrategy;
3005
+ /**
3006
+ * Apply conversation similarity threshold to all LLM provider singletons
3007
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
3008
+ */
3009
+ private applyConversationSimilarityThreshold;
3010
+ /**
3011
+ * Set conversation similarity threshold at runtime
3012
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
3013
+ */
3014
+ setConversationSimilarityThreshold(threshold: number): void;
3015
+ /**
3016
+ * Get current conversation similarity threshold
3017
+ */
3018
+ getConversationSimilarityThreshold(): number;
1799
3019
  }
1800
3020
 
1801
- 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 };
3021
+ export { type Action, type AgentConfig, type AgentResponse, BM25L, type BM25LOptions, type BaseLLMConfig, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, DEFAULT_AGENT_CONFIG, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, MainAgent, type Message, type ModelStrategy, type OutputField, type RerankedResult, STORAGE_CONFIG, type SelectedWorkflow, SuperatomSDK, type SuperatomSDKConfig, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, type ToolOutputSchema, UIBlock, UILogCollector, type User, UserManager, type UsersData, type WorkflowDescriptor, anthropicLLM, dashboardConversationHistory, geminiLLM, groqLLM, hybridRerank, llmUsageLogger, logger, openaiLLM, queryCache, rerankChromaResults, rerankConversationResults, userPromptErrorLogger };