@superatomai/sdk-node 0.0.35 → 0.0.36-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.mts 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
@@ -1049,6 +1310,7 @@ type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
1049
1310
  interface LLMMessages {
1050
1311
  sys: SystemPrompt;
1051
1312
  user: string;
1313
+ prefill?: string;
1052
1314
  }
1053
1315
  interface LLMOptions {
1054
1316
  model?: string;
@@ -1101,6 +1363,11 @@ declare class LLM {
1101
1363
  private static _groqStream;
1102
1364
  private static _geminiText;
1103
1365
  private static _geminiStream;
1366
+ /**
1367
+ * Recursively strip unsupported JSON Schema properties for Gemini
1368
+ * Gemini doesn't support: additionalProperties, $schema, etc.
1369
+ */
1370
+ private static _cleanSchemaForGemini;
1104
1371
  private static _geminiStreamWithTools;
1105
1372
  private static _openaiText;
1106
1373
  private static _openaiStream;
@@ -1385,12 +1652,20 @@ declare class Thread {
1385
1652
 
1386
1653
  /**
1387
1654
  * ThreadManager manages all threads globally
1388
- * Provides methods to create, retrieve, and delete threads
1655
+ * Provides methods to create, retrieve, and delete threads.
1656
+ * Includes automatic cleanup to prevent unbounded memory growth.
1389
1657
  */
1390
1658
  declare class ThreadManager {
1391
1659
  private static instance;
1392
1660
  private threads;
1661
+ private cleanupInterval;
1662
+ private readonly threadTtlMs;
1393
1663
  private constructor();
1664
+ /**
1665
+ * Periodically remove threads older than 7 days.
1666
+ * Runs every hour to avoid frequent iteration over the map.
1667
+ */
1668
+ private startCleanup;
1394
1669
  /**
1395
1670
  * Get singleton instance of ThreadManager
1396
1671
  */
@@ -1547,6 +1822,120 @@ declare const CONTEXT_CONFIG: {
1547
1822
  MAX_CONVERSATION_CONTEXT_BLOCKS: number;
1548
1823
  };
1549
1824
 
1825
+ /**
1826
+ * LLM Usage Logger - Tracks token usage, costs, and timing for all LLM API calls
1827
+ */
1828
+ interface LLMUsageEntry {
1829
+ timestamp: string;
1830
+ requestId: string;
1831
+ provider: string;
1832
+ model: string;
1833
+ method: string;
1834
+ inputTokens: number;
1835
+ outputTokens: number;
1836
+ cacheReadTokens?: number;
1837
+ cacheWriteTokens?: number;
1838
+ totalTokens: number;
1839
+ costUSD: number;
1840
+ durationMs: number;
1841
+ toolCalls?: number;
1842
+ success: boolean;
1843
+ error?: string;
1844
+ }
1845
+ declare class LLMUsageLogger {
1846
+ private logStream;
1847
+ private logPath;
1848
+ private enabled;
1849
+ private sessionStats;
1850
+ constructor();
1851
+ private initLogStream;
1852
+ private writeHeader;
1853
+ /**
1854
+ * Calculate cost based on token usage and model
1855
+ */
1856
+ calculateCost(model: string, inputTokens: number, outputTokens: number, cacheReadTokens?: number, cacheWriteTokens?: number): number;
1857
+ /**
1858
+ * Log an LLM API call
1859
+ */
1860
+ log(entry: LLMUsageEntry): void;
1861
+ /**
1862
+ * Log session summary (call at end of request)
1863
+ */
1864
+ logSessionSummary(requestContext?: string): void;
1865
+ /**
1866
+ * Reset session stats (call at start of new user request)
1867
+ */
1868
+ resetSession(): void;
1869
+ /**
1870
+ * Reset the log file for a new request (clears previous logs)
1871
+ * Call this at the start of each USER_PROMPT_REQ
1872
+ */
1873
+ resetLogFile(requestContext?: string): void;
1874
+ /**
1875
+ * Get current session stats
1876
+ */
1877
+ getSessionStats(): {
1878
+ totalCalls: number;
1879
+ totalInputTokens: number;
1880
+ totalOutputTokens: number;
1881
+ totalCacheReadTokens: number;
1882
+ totalCacheWriteTokens: number;
1883
+ totalCostUSD: number;
1884
+ totalDurationMs: number;
1885
+ };
1886
+ /**
1887
+ * Generate a unique request ID
1888
+ */
1889
+ generateRequestId(): string;
1890
+ }
1891
+ declare const llmUsageLogger: LLMUsageLogger;
1892
+
1893
+ /**
1894
+ * User Prompt Error Logger - Captures detailed errors for USER_PROMPT_REQ
1895
+ * Logs full error details including raw strings for parse failures
1896
+ */
1897
+ declare class UserPromptErrorLogger {
1898
+ private logStream;
1899
+ private logPath;
1900
+ private enabled;
1901
+ private hasErrors;
1902
+ constructor();
1903
+ /**
1904
+ * Reset the error log file for a new request
1905
+ */
1906
+ resetLogFile(requestContext?: string): void;
1907
+ /**
1908
+ * Log a JSON parse error with the raw string that failed
1909
+ */
1910
+ logJsonParseError(context: string, rawString: string, error: Error): void;
1911
+ /**
1912
+ * Log a general error with full details
1913
+ */
1914
+ logError(context: string, error: Error | string, additionalData?: Record<string, any>): void;
1915
+ /**
1916
+ * Log a SQL query error with the full query
1917
+ */
1918
+ logSqlError(query: string, error: Error | string, params?: any[]): void;
1919
+ /**
1920
+ * Log an LLM API error
1921
+ */
1922
+ logLlmError(provider: string, model: string, method: string, error: Error | string, requestData?: any): void;
1923
+ /**
1924
+ * Log tool execution error
1925
+ */
1926
+ logToolError(toolName: string, toolInput: any, error: Error | string): void;
1927
+ /**
1928
+ * Write final summary if there were errors
1929
+ */
1930
+ writeSummary(): void;
1931
+ /**
1932
+ * Check if any errors were logged
1933
+ */
1934
+ hadErrors(): boolean;
1935
+ private write;
1936
+ }
1937
+ declare const userPromptErrorLogger: UserPromptErrorLogger;
1938
+
1550
1939
  /**
1551
1940
  * BM25L Reranker for hybrid semantic search
1552
1941
  *
@@ -1675,14 +2064,718 @@ declare function rerankConversationResults<T extends {
1675
2064
  bm25Score: number;
1676
2065
  }>;
1677
2066
 
1678
- declare const SDK_VERSION = "0.0.8";
2067
+ /**
2068
+ * QueryExecutionService - Handles all query execution, validation, and retry logic
2069
+ * Extracted from BaseLLM for better separation of concerns
2070
+ */
2071
+
2072
+ /**
2073
+ * Context for component when requesting query fix
2074
+ */
2075
+ interface ComponentContext {
2076
+ name: string;
2077
+ type: string;
2078
+ title?: string;
2079
+ }
2080
+ /**
2081
+ * Result of query validation
2082
+ */
2083
+ interface QueryValidationResult {
2084
+ component: Component | null;
2085
+ queryKey: string;
2086
+ result: any;
2087
+ validated: boolean;
2088
+ }
2089
+ /**
2090
+ * Result of batch query validation
2091
+ */
2092
+ interface BatchValidationResult {
2093
+ components: Component[];
2094
+ queryResults: Map<string, any>;
2095
+ }
2096
+ /**
2097
+ * Configuration for QueryExecutionService
2098
+ */
2099
+ interface QueryExecutionServiceConfig {
2100
+ defaultLimit: number;
2101
+ getModelForTask: (taskType: 'simple' | 'complex') => string;
2102
+ getApiKey: (apiKey?: string) => string | undefined;
2103
+ providerName: string;
2104
+ }
2105
+ /**
2106
+ * QueryExecutionService handles all query-related operations
2107
+ */
2108
+ declare class QueryExecutionService {
2109
+ private config;
2110
+ constructor(config: QueryExecutionServiceConfig);
2111
+ /**
2112
+ * Get the cache key for a query
2113
+ * This ensures the cache key matches what the frontend will send
2114
+ */
2115
+ getQueryCacheKey(query: any): string;
2116
+ /**
2117
+ * Execute a query against the database
2118
+ * @param query - The SQL query to execute (string or object with sql/values)
2119
+ * @param collections - Collections object containing database execute function
2120
+ * @returns Object with result data and cache key
2121
+ */
2122
+ executeQuery(query: any, collections: any): Promise<{
2123
+ result: any;
2124
+ cacheKey: string;
2125
+ }>;
2126
+ /**
2127
+ * Request the LLM to fix a failed SQL query
2128
+ * @param failedQuery - The query that failed execution
2129
+ * @param errorMessage - The error message from the failed execution
2130
+ * @param componentContext - Context about the component
2131
+ * @param apiKey - Optional API key
2132
+ * @returns Fixed query string
2133
+ */
2134
+ requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
2135
+ /**
2136
+ * Validate a single component's query with retry logic
2137
+ * @param component - The component to validate
2138
+ * @param collections - Collections object containing database execute function
2139
+ * @param apiKey - Optional API key for LLM calls
2140
+ * @returns Validation result with component, query key, and result
2141
+ */
2142
+ validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
2143
+ /**
2144
+ * Validate multiple component queries in parallel
2145
+ * @param components - Array of components with potential queries
2146
+ * @param collections - Collections object containing database execute function
2147
+ * @param apiKey - Optional API key for LLM calls
2148
+ * @returns Object with validated components and query results map
2149
+ */
2150
+ validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
2151
+ }
2152
+
2153
+ /**
2154
+ * StreamBuffer - Buffered streaming utility for smoother text delivery
2155
+ * Batches small chunks together and flushes at regular intervals
2156
+ */
2157
+ type StreamCallback = (chunk: string) => void;
2158
+ /**
2159
+ * StreamBuffer class for managing buffered streaming output
2160
+ * Provides smooth text delivery by batching small chunks
2161
+ */
2162
+ declare class StreamBuffer {
2163
+ private buffer;
2164
+ private flushTimer;
2165
+ private callback;
2166
+ private fullText;
2167
+ constructor(callback?: StreamCallback);
2168
+ /**
2169
+ * Check if the buffer has a callback configured
2170
+ */
2171
+ hasCallback(): boolean;
2172
+ /**
2173
+ * Get all text that has been written (including already flushed)
2174
+ */
2175
+ getFullText(): string;
2176
+ /**
2177
+ * Write a chunk to the buffer
2178
+ * Large chunks or chunks with newlines are flushed immediately
2179
+ * Small chunks are batched and flushed after a short interval
2180
+ *
2181
+ * @param chunk - Text chunk to write
2182
+ */
2183
+ write(chunk: string): void;
2184
+ /**
2185
+ * Flush the buffer immediately
2186
+ * Call this before tool execution or other operations that need clean output
2187
+ */
2188
+ flush(): void;
2189
+ /**
2190
+ * Internal flush implementation
2191
+ */
2192
+ private flushNow;
2193
+ /**
2194
+ * Clean up resources
2195
+ * Call this when done with the buffer
2196
+ */
2197
+ dispose(): void;
2198
+ }
2199
+
2200
+ /**
2201
+ * ToolExecutorService - Handles execution of SQL queries and external tools
2202
+ * Extracted from BaseLLM.generateTextResponse for better separation of concerns
2203
+ */
2204
+
2205
+ /**
2206
+ * External tool definition
2207
+ */
2208
+ interface ExternalTool {
2209
+ id: string;
2210
+ name: string;
2211
+ description?: string;
2212
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
2213
+ toolType?: 'source' | 'direct';
2214
+ /** Full untruncated schema for source agent (all columns visible) */
2215
+ fullSchema?: string;
2216
+ /** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
2217
+ schemaTier?: string;
2218
+ /** Schema search function for very_large tier — keyword search over entities */
2219
+ schemaSearchFn?: (keywords: string[]) => string;
2220
+ fn: (input: any) => Promise<any>;
2221
+ limit?: number;
2222
+ outputSchema?: any;
2223
+ executionType?: 'immediate' | 'deferred';
2224
+ userProvidedData?: any;
2225
+ params?: Record<string, any>;
2226
+ }
2227
+ /**
2228
+ * Executed tool tracking info
2229
+ */
2230
+ interface ExecutedToolInfo {
2231
+ id: string;
2232
+ name: string;
2233
+ params: any;
2234
+ result: {
2235
+ _totalRecords: number;
2236
+ _recordsShown: number;
2237
+ _metadata?: any;
2238
+ _sampleData: any[];
2239
+ };
2240
+ outputSchema?: any;
2241
+ sourceSchema?: string;
2242
+ sourceType?: string;
2243
+ }
2244
+
2245
+ /**
2246
+ * Task types for model selection
2247
+ * - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
2248
+ * - 'simple': Classification, action generation (uses fast model in balanced mode)
2249
+ */
2250
+ type TaskType = 'complex' | 'simple';
2251
+ interface BaseLLMConfig {
2252
+ model?: string;
2253
+ fastModel?: string;
2254
+ defaultLimit?: number;
2255
+ apiKey?: string;
2256
+ /**
2257
+ * Model selection strategy:
2258
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
2259
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
2260
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
2261
+ */
2262
+ modelStrategy?: ModelStrategy;
2263
+ conversationSimilarityThreshold?: number;
2264
+ }
2265
+ /**
2266
+ * BaseLLM abstract class for AI-powered component generation and matching
2267
+ * Provides common functionality for all LLM providers
2268
+ */
2269
+ declare abstract class BaseLLM {
2270
+ protected model: string;
2271
+ protected fastModel: string;
2272
+ protected defaultLimit: number;
2273
+ protected apiKey?: string;
2274
+ protected modelStrategy: ModelStrategy;
2275
+ protected conversationSimilarityThreshold: number;
2276
+ protected queryService: QueryExecutionService;
2277
+ constructor(config?: BaseLLMConfig);
2278
+ /**
2279
+ * Get the appropriate model based on task type and model strategy
2280
+ * @param taskType - 'complex' for text generation/matching, 'simple' for classification/actions
2281
+ * @returns The model string to use for this task
2282
+ */
2283
+ protected getModelForTask(taskType: TaskType): string;
2284
+ /**
2285
+ * Set the model strategy at runtime
2286
+ * @param strategy - 'best', 'fast', or 'balanced'
2287
+ */
2288
+ setModelStrategy(strategy: ModelStrategy): void;
2289
+ /**
2290
+ * Get the current model strategy
2291
+ * @returns The current model strategy
2292
+ */
2293
+ getModelStrategy(): ModelStrategy;
2294
+ /**
2295
+ * Set the conversation similarity threshold at runtime
2296
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2297
+ */
2298
+ setConversationSimilarityThreshold(threshold: number): void;
2299
+ /**
2300
+ * Get the current conversation similarity threshold
2301
+ * @returns The current threshold value
2302
+ */
2303
+ getConversationSimilarityThreshold(): number;
2304
+ /**
2305
+ * Get the default model for this provider (used for complex tasks like text generation)
2306
+ */
2307
+ protected abstract getDefaultModel(): string;
2308
+ /**
2309
+ * Get the default fast model for this provider (used for simple tasks: classification, matching, actions)
2310
+ * Should return a cheaper/faster model like Haiku for Anthropic
2311
+ */
2312
+ protected abstract getDefaultFastModel(): string;
2313
+ /**
2314
+ * Get the default API key from environment
2315
+ */
2316
+ protected abstract getDefaultApiKey(): string | undefined;
2317
+ /**
2318
+ * Get the provider name (for logging)
2319
+ */
2320
+ protected abstract getProviderName(): string;
2321
+ /**
2322
+ * Get the API key (from instance, parameter, or environment)
2323
+ */
2324
+ protected getApiKey(apiKey?: string): string | undefined;
2325
+ /**
2326
+ * Check if a component contains a Form (data_modification component)
2327
+ * Forms have hardcoded defaultValues that become stale when cached
2328
+ * This checks both single Form components and Forms inside MultiComponentContainer
2329
+ */
2330
+ protected containsFormComponent(component: any): boolean;
2331
+ /**
2332
+ * Match components from text response suggestions and generate follow-up questions
2333
+ * Takes a text response with component suggestions (c1:type format) and matches with available components
2334
+ * Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
2335
+ * All components are placed in a default MultiComponentContainer layout
2336
+ * @param analysisContent - The text response containing component suggestions
2337
+ * @param components - List of available components
2338
+ * @param apiKey - Optional API key
2339
+ * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
2340
+ * @returns Object containing matched components, layout title/description, and follow-up actions
2341
+ */
2342
+ matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
2343
+ components: Component[];
2344
+ layoutTitle: string;
2345
+ layoutDescription: string;
2346
+ actions: Action[];
2347
+ }>;
2348
+ /**
2349
+ * Classify user question into category and detect external tools needed
2350
+ * Determines if question is for data analysis, requires external tools, or needs text response
2351
+ */
2352
+ classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
2353
+ category: 'data_analysis' | 'data_modification' | 'general';
2354
+ externalTools: Array<{
2355
+ type: string;
2356
+ name: string;
2357
+ description: string;
2358
+ parameters: Record<string, any>;
2359
+ }>;
2360
+ dataAnalysisType?: 'visualization' | 'calculation' | 'comparison' | 'trend';
2361
+ reasoning: string;
2362
+ confidence: number;
2363
+ }>;
2364
+ /**
2365
+ * Adapt UI block parameters based on current user question
2366
+ * Takes a matched UI block from semantic search and modifies its props to answer the new question
2367
+ * Also adapts the cached text response to match the new question
2368
+ */
2369
+ adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
2370
+ success: boolean;
2371
+ adaptedComponent?: Component;
2372
+ adaptedTextResponse?: string;
2373
+ parametersChanged?: Array<{
2374
+ field: string;
2375
+ reason: string;
2376
+ }>;
2377
+ explanation: string;
2378
+ }>;
2379
+ /**
2380
+ * Generate text-based response for user question
2381
+ * This provides conversational text responses instead of component generation
2382
+ * Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
2383
+ * After generating text response, if components are provided, matches suggested components
2384
+ */
2385
+ 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>;
2386
+ /**
2387
+ * Main orchestration function with semantic search and multi-step classification
2388
+ * NEW FLOW (Recommended):
2389
+ * 1. Semantic search: Check previous conversations (>60% match)
2390
+ * - If match found → Adapt UI block parameters and return
2391
+ * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
2392
+ * 3. Route appropriately based on category and response mode
2393
+ */
2394
+ 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>;
2395
+ /**
2396
+ * Generate next questions that the user might ask based on the original prompt and generated component
2397
+ * This helps provide intelligent suggestions for follow-up queries
2398
+ * For general/conversational questions without components, pass textResponse instead
2399
+ */
2400
+ generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string): Promise<string[]>;
2401
+ }
2402
+
2403
+ interface AnthropicLLMConfig extends BaseLLMConfig {
2404
+ }
2405
+ /**
2406
+ * AnthropicLLM class for handling AI-powered component generation and matching using Anthropic Claude
2407
+ */
2408
+ declare class AnthropicLLM extends BaseLLM {
2409
+ constructor(config?: AnthropicLLMConfig);
2410
+ protected getDefaultModel(): string;
2411
+ protected getDefaultFastModel(): string;
2412
+ protected getDefaultApiKey(): string | undefined;
2413
+ protected getProviderName(): string;
2414
+ }
2415
+ declare const anthropicLLM: AnthropicLLM;
2416
+
2417
+ interface GroqLLMConfig extends BaseLLMConfig {
2418
+ }
2419
+ /**
2420
+ * GroqLLM class for handling AI-powered component generation and matching using Groq
2421
+ */
2422
+ declare class GroqLLM extends BaseLLM {
2423
+ constructor(config?: GroqLLMConfig);
2424
+ protected getDefaultModel(): string;
2425
+ protected getDefaultFastModel(): string;
2426
+ protected getDefaultApiKey(): string | undefined;
2427
+ protected getProviderName(): string;
2428
+ }
2429
+ declare const groqLLM: GroqLLM;
2430
+
2431
+ interface GeminiLLMConfig extends BaseLLMConfig {
2432
+ }
2433
+ /**
2434
+ * GeminiLLM class for handling AI-powered component generation and matching using Google Gemini
2435
+ */
2436
+ declare class GeminiLLM extends BaseLLM {
2437
+ constructor(config?: GeminiLLMConfig);
2438
+ protected getDefaultModel(): string;
2439
+ protected getDefaultFastModel(): string;
2440
+ protected getDefaultApiKey(): string | undefined;
2441
+ protected getProviderName(): string;
2442
+ }
2443
+ declare const geminiLLM: GeminiLLM;
2444
+
2445
+ interface OpenAILLMConfig extends BaseLLMConfig {
2446
+ }
2447
+ /**
2448
+ * OpenAILLM class for handling AI-powered component generation and matching using OpenAI GPT models
2449
+ */
2450
+ declare class OpenAILLM extends BaseLLM {
2451
+ constructor(config?: OpenAILLMConfig);
2452
+ protected getDefaultModel(): string;
2453
+ protected getDefaultFastModel(): string;
2454
+ protected getDefaultApiKey(): string | undefined;
2455
+ protected getProviderName(): string;
2456
+ }
2457
+ declare const openaiLLM: OpenAILLM;
2458
+
2459
+ /**
2460
+ * Query Cache — Two mechanisms:
2461
+ *
2462
+ * 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
2463
+ * of recently validated queries. LRU eviction when max size exceeded.
2464
+ *
2465
+ * 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
2466
+ * No server-side storage needed for SQL mappings. The token is decrypted on each request.
2467
+ * This eliminates the unbounded queryIdCache that previously grew forever and caused
2468
+ * memory bloat (hundreds of MBs after thousands of queries).
2469
+ *
2470
+ * Result data can still be cached temporarily via the data cache (mechanism 1).
2471
+ */
2472
+ declare class QueryCache {
2473
+ private cache;
2474
+ private ttlMs;
2475
+ private maxCacheSize;
2476
+ private cleanupInterval;
2477
+ private readonly algorithm;
2478
+ private encryptionKey;
2479
+ constructor();
2480
+ /**
2481
+ * Set the cache TTL (Time To Live)
2482
+ * @param minutes - TTL in minutes (default: 10)
2483
+ */
2484
+ setTTL(minutes: number): void;
2485
+ /**
2486
+ * Get the current TTL in minutes
2487
+ */
2488
+ getTTL(): number;
2489
+ /**
2490
+ * Store query result in data cache
2491
+ */
2492
+ set(query: string, data: any): void;
2493
+ /**
2494
+ * Get cached result if exists and not expired
2495
+ */
2496
+ get(query: string): any | null;
2497
+ /**
2498
+ * Check if query exists in cache (not expired)
2499
+ */
2500
+ has(query: string): boolean;
2501
+ /**
2502
+ * Remove a specific query from cache
2503
+ */
2504
+ delete(query: string): void;
2505
+ /**
2506
+ * Clear all cached entries
2507
+ */
2508
+ clear(): void;
2509
+ /**
2510
+ * Get cache statistics
2511
+ */
2512
+ getStats(): {
2513
+ size: number;
2514
+ queryIdCount: number;
2515
+ oldestEntryAge: number | null;
2516
+ };
2517
+ /**
2518
+ * Start periodic cleanup of expired data cache entries.
2519
+ */
2520
+ private startCleanup;
2521
+ /**
2522
+ * Encrypt a payload into a self-contained token.
2523
+ */
2524
+ private encrypt;
2525
+ /**
2526
+ * Decrypt a token back to the original payload.
2527
+ */
2528
+ private decrypt;
2529
+ /**
2530
+ * Store a query by generating an encrypted token as queryId.
2531
+ * The SQL is encrypted INTO the token — nothing stored in memory.
2532
+ * If data is provided, it's cached temporarily in the data cache.
2533
+ */
2534
+ storeQuery(query: any, data?: any): string;
2535
+ /**
2536
+ * Get a stored query by decrypting its token.
2537
+ * Returns the SQL + any cached result data.
2538
+ */
2539
+ getQuery(queryId: string): {
2540
+ query: any;
2541
+ data: any;
2542
+ } | null;
2543
+ /**
2544
+ * Update cached data for a queryId token
2545
+ */
2546
+ setQueryData(queryId: string, data: any): void;
2547
+ /**
2548
+ * Stop cleanup interval (for graceful shutdown)
2549
+ */
2550
+ destroy(): void;
2551
+ }
2552
+ declare const queryCache: QueryCache;
2553
+
2554
+ /**
2555
+ * Manages conversation history scoped per user + dashboard.
2556
+ * Each user-dashboard pair has its own isolated history that expires after a configurable TTL.
2557
+ */
2558
+ declare class DashboardConversationHistory {
2559
+ private histories;
2560
+ private ttlMs;
2561
+ private maxEntries;
2562
+ private cleanupInterval;
2563
+ constructor();
2564
+ /**
2565
+ * Set the TTL for dashboard histories
2566
+ * @param minutes - TTL in minutes
2567
+ */
2568
+ setTTL(minutes: number): void;
2569
+ /**
2570
+ * Set max entries per dashboard
2571
+ */
2572
+ setMaxEntries(max: number): void;
2573
+ /**
2574
+ * Add a conversation entry for a user's dashboard
2575
+ */
2576
+ addEntry(dashboardId: string, userPrompt: string, componentSummary: string, userId?: string): void;
2577
+ /**
2578
+ * Get formatted conversation history for a user's dashboard
2579
+ */
2580
+ getHistory(dashboardId: string, userId?: string): string;
2581
+ /**
2582
+ * Clear history for a specific user's dashboard
2583
+ */
2584
+ clearDashboard(dashboardId: string, userId?: string): void;
2585
+ /**
2586
+ * Clear all dashboard histories
2587
+ */
2588
+ clearAll(): void;
2589
+ /**
2590
+ * Start periodic cleanup of expired histories
2591
+ */
2592
+ private startCleanup;
2593
+ /**
2594
+ * Stop cleanup interval (for graceful shutdown)
2595
+ */
2596
+ destroy(): void;
2597
+ }
2598
+ declare const dashboardConversationHistory: DashboardConversationHistory;
2599
+
2600
+ /**
2601
+ * Multi-Agent Architecture Types
2602
+ *
2603
+ * Defines interfaces for the hierarchical agent system:
2604
+ * - Main Agent: ONE LLM.streamWithTools() call with source agent tools
2605
+ * - Source Agents: independent agents that query individual data sources
2606
+ *
2607
+ * The main agent sees only source summaries. When it calls a source tool,
2608
+ * the SourceAgent runs independently (own LLM, own retries) and returns clean data.
2609
+ */
2610
+
2611
+ /**
2612
+ * Per-entity detail: name, row count, and column names.
2613
+ * Gives the main agent enough context to route to the right source.
2614
+ */
2615
+ interface EntityDetail {
2616
+ /** Entity name (table, sheet, endpoint) */
2617
+ name: string;
2618
+ /** Approximate row count */
2619
+ rowCount?: number;
2620
+ /** Column/field names */
2621
+ columns: string[];
2622
+ }
2623
+ /**
2624
+ * Representation of a data source for the main agent.
2625
+ * Contains entity names WITH column names so the LLM can route accurately.
2626
+ */
2627
+ interface SourceSummary {
2628
+ /** Source ID (matches tool ID prefix) */
2629
+ id: string;
2630
+ /** Human-readable source name */
2631
+ name: string;
2632
+ /** Source type: postgres, excel, rest_api, etc. */
2633
+ type: string;
2634
+ /** Brief description of what data this source contains */
2635
+ description: string;
2636
+ /** Detailed entity info with column names for routing */
2637
+ entityDetails: EntityDetail[];
2638
+ /** The tool ID associated with this source */
2639
+ toolId: string;
2640
+ }
2641
+ /**
2642
+ * What a source agent returns after querying its data source.
2643
+ * The main agent uses this to analyze and compose the final response.
2644
+ */
2645
+ interface SourceAgentResult {
2646
+ /** Source ID */
2647
+ sourceId: string;
2648
+ /** Source name */
2649
+ sourceName: string;
2650
+ /** Whether the query succeeded */
2651
+ success: boolean;
2652
+ /** Result data rows */
2653
+ data: any[];
2654
+ /** Metadata about the query execution */
2655
+ metadata: SourceAgentMetadata;
2656
+ /** Tool execution info for the last successful query (backward compat) */
2657
+ executedTool: ExecutedToolInfo;
2658
+ /** All successful tool executions (primary + follow-up queries) */
2659
+ allExecutedTools?: ExecutedToolInfo[];
2660
+ /** Error message if failed */
2661
+ error?: string;
2662
+ }
2663
+ interface SourceAgentMetadata {
2664
+ /** Total rows that matched the query (before limit) */
2665
+ totalRowsMatched: number;
2666
+ /** Rows actually returned (after limit) */
2667
+ rowsReturned: number;
2668
+ /** Whether the result was truncated by the row limit */
2669
+ isLimited: boolean;
2670
+ /** The query/params that were executed */
2671
+ queryExecuted?: string;
2672
+ /** Execution time in milliseconds */
2673
+ executionTimeMs: number;
2674
+ }
2675
+ /**
2676
+ * The complete response from the multi-agent system.
2677
+ * Contains everything needed for text display + component generation.
2678
+ */
2679
+ interface AgentResponse {
2680
+ /** Generated text response (analysis of the data) */
2681
+ text: string;
2682
+ /** All executed tools across all source agents (for component generation) */
2683
+ executedTools: ExecutedToolInfo[];
2684
+ /** Individual results from each source agent */
2685
+ sourceResults: SourceAgentResult[];
2686
+ }
2687
+ /**
2688
+ * Configuration for the multi-agent system.
2689
+ * Controls limits, models, and behavior.
2690
+ */
2691
+ interface AgentConfig {
2692
+ /** Max rows a source agent can return (default: 50) */
2693
+ maxRowsPerSource: number;
2694
+ /** Model for the main agent (routing + analysis in one LLM call) */
2695
+ mainAgentModel: string;
2696
+ /** Model for source agent query generation */
2697
+ sourceAgentModel: string;
2698
+ /** API key for LLM calls */
2699
+ apiKey?: string;
2700
+ /** Max retry attempts per source agent */
2701
+ maxRetries: number;
2702
+ /** Max tool calling iterations for the main agent loop */
2703
+ maxIterations: number;
2704
+ /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
2705
+ globalKnowledgeBase?: string;
2706
+ /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
2707
+ knowledgeBaseContext?: string;
2708
+ }
2709
+ /**
2710
+ * Default agent configuration
2711
+ */
2712
+ declare const DEFAULT_AGENT_CONFIG: AgentConfig;
2713
+
2714
+ /**
2715
+ * Main Agent (Orchestrator)
2716
+ *
2717
+ * A single LLM.streamWithTools() call that handles everything:
2718
+ * - Routing: decides which source(s) to query based on summaries
2719
+ * - Querying: calls source tools (each wraps an independent SourceAgent)
2720
+ * - Direct tools: calls pre-built function tools directly with LLM-provided params
2721
+ * - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
2722
+ * - Analysis: generates final text response from the data
2723
+ *
2724
+ * Two tool types:
2725
+ * - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
2726
+ * - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
2727
+ */
2728
+
2729
+ declare class MainAgent {
2730
+ private externalTools;
2731
+ private config;
2732
+ private streamBuffer;
2733
+ constructor(externalTools: ExternalTool[], config: AgentConfig, streamBuffer?: StreamBuffer);
2734
+ /**
2735
+ * Handle a user question using the multi-agent system.
2736
+ *
2737
+ * This is ONE LLM.streamWithTools() call. The LLM:
2738
+ * 1. Sees source summaries + direct tool descriptions in system prompt
2739
+ * 2. Decides which tool(s) to call (routing)
2740
+ * 3. Source tools → SourceAgent runs independently → returns data
2741
+ * 4. Direct tools → fn() called directly with LLM params → returns data
2742
+ * 5. Generates final analysis text
2743
+ */
2744
+ handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void): Promise<AgentResponse>;
2745
+ /**
2746
+ * Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
2747
+ */
2748
+ private handleDirectTool;
2749
+ /**
2750
+ * Build the main agent's system prompt with source summaries and direct tool descriptions.
2751
+ */
2752
+ private buildSystemPrompt;
2753
+ /**
2754
+ * Build tool definitions for source tools — summary-only descriptions.
2755
+ * The full schema is inside the SourceAgent which runs independently.
2756
+ */
2757
+ private buildSourceToolDefinitions;
2758
+ /**
2759
+ * Build tool definitions for direct tools — expose their actual params.
2760
+ * These are called directly by the main agent LLM, no SourceAgent.
2761
+ */
2762
+ private buildDirectToolDefinitions;
2763
+ /**
2764
+ * Format a source agent's result as a clean string for the main agent LLM.
2765
+ */
2766
+ private formatResultForMainAgent;
2767
+ /**
2768
+ * Get source summaries (for external inspection/debugging).
2769
+ */
2770
+ getSourceSummaries(): SourceSummary[];
2771
+ }
2772
+
1679
2773
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
1680
2774
  declare class SuperatomSDK {
1681
2775
  private ws;
1682
2776
  private url;
1683
2777
  private apiKey?;
1684
2778
  private projectId;
1685
- private userId;
1686
2779
  private type;
1687
2780
  private bundleDir;
1688
2781
  private messageHandlers;
@@ -1699,6 +2792,11 @@ declare class SuperatomSDK {
1699
2792
  private openaiApiKey;
1700
2793
  private llmProviders;
1701
2794
  private databaseType;
2795
+ private modelStrategy;
2796
+ private mainAgentModel;
2797
+ private sourceAgentModel;
2798
+ private dashCompModels?;
2799
+ private conversationSimilarityThreshold;
1702
2800
  private userManager;
1703
2801
  private dashboardManager;
1704
2802
  private reportManager;
@@ -1745,9 +2843,11 @@ declare class SuperatomSDK {
1745
2843
  */
1746
2844
  private handleMessage;
1747
2845
  /**
1748
- * Send a message to the Superatom service
2846
+ * Send a message to the Superatom service.
2847
+ * Returns true if the message was sent, false if the WebSocket is not connected.
2848
+ * Does NOT throw on closed connections — callers can check the return value if needed.
1749
2849
  */
1750
- send(message: Message): void;
2850
+ send(message: Message): boolean;
1751
2851
  /**
1752
2852
  * Register a message handler to receive all messages
1753
2853
  */
@@ -1795,6 +2895,34 @@ declare class SuperatomSDK {
1795
2895
  * Get the stored tools
1796
2896
  */
1797
2897
  getTools(): Tool$1[];
2898
+ /**
2899
+ * Apply model strategy to all LLM provider singletons
2900
+ * @param strategy - 'best', 'fast', or 'balanced'
2901
+ */
2902
+ private applyModelStrategy;
2903
+ /**
2904
+ * Set model strategy at runtime
2905
+ * @param strategy - 'best', 'fast', or 'balanced'
2906
+ */
2907
+ setModelStrategy(strategy: ModelStrategy): void;
2908
+ /**
2909
+ * Get current model strategy
2910
+ */
2911
+ getModelStrategy(): ModelStrategy;
2912
+ /**
2913
+ * Apply conversation similarity threshold to all LLM provider singletons
2914
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2915
+ */
2916
+ private applyConversationSimilarityThreshold;
2917
+ /**
2918
+ * Set conversation similarity threshold at runtime
2919
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2920
+ */
2921
+ setConversationSimilarityThreshold(threshold: number): void;
2922
+ /**
2923
+ * Get current conversation similarity threshold
2924
+ */
2925
+ getConversationSimilarityThreshold(): number;
1798
2926
  }
1799
2927
 
1800
- 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 };
2928
+ 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, SuperatomSDK, type SuperatomSDKConfig, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, type ToolOutputSchema, UIBlock, UILogCollector, type User, UserManager, type UsersData, anthropicLLM, dashboardConversationHistory, geminiLLM, groqLLM, hybridRerank, llmUsageLogger, logger, openaiLLM, queryCache, rerankChromaResults, rerankConversationResults, userPromptErrorLogger };