@superatomai/sdk-node 0.0.7-mds → 0.0.7-s

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -741,6 +741,10 @@ declare const ToolSchema: z.ZodObject<{
741
741
  id: z.ZodString;
742
742
  name: z.ZodString;
743
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>;
744
748
  params: z.ZodRecord<z.ZodString, z.ZodString>;
745
749
  fn: z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodAny>;
746
750
  outputSchema: z.ZodOptional<z.ZodObject<{
@@ -773,12 +777,22 @@ declare const ToolSchema: z.ZodObject<{
773
777
  description: string;
774
778
  }[];
775
779
  }>>;
780
+ /** Cache policy. `false` = never cache (live data, write ops). Mirrors HTTP `Cache-Control: no-store`. */
781
+ cache: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<false>, z.ZodObject<{
782
+ ttlMs: z.ZodOptional<z.ZodNumber>;
783
+ }, "strip", z.ZodTypeAny, {
784
+ ttlMs?: number | undefined;
785
+ }, {
786
+ ttlMs?: number | undefined;
787
+ }>]>>;
776
788
  }, "strip", z.ZodTypeAny, {
777
789
  id: string;
778
790
  params: Record<string, string>;
779
791
  name: string;
780
792
  description: string;
781
793
  fn: (args_0: any, ...args: unknown[]) => any;
794
+ toolType?: "source" | "direct" | undefined;
795
+ fullSchema?: string | undefined;
782
796
  outputSchema?: {
783
797
  description: string;
784
798
  fields: {
@@ -787,12 +801,17 @@ declare const ToolSchema: z.ZodObject<{
787
801
  description: string;
788
802
  }[];
789
803
  } | undefined;
804
+ cache?: false | {
805
+ ttlMs?: number | undefined;
806
+ } | undefined;
790
807
  }, {
791
808
  id: string;
792
809
  params: Record<string, string>;
793
810
  name: string;
794
811
  description: string;
795
812
  fn: (args_0: any, ...args: unknown[]) => any;
813
+ toolType?: "source" | "direct" | undefined;
814
+ fullSchema?: string | undefined;
796
815
  outputSchema?: {
797
816
  description: string;
798
817
  fields: {
@@ -801,6 +820,9 @@ declare const ToolSchema: z.ZodObject<{
801
820
  description: string;
802
821
  }[];
803
822
  } | undefined;
823
+ cache?: false | {
824
+ ttlMs?: number | undefined;
825
+ } | undefined;
804
826
  }>;
805
827
  type Tool$1 = z.infer<typeof ToolSchema>;
806
828
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
@@ -852,6 +874,18 @@ interface SuperatomSDKConfig {
852
874
  * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
853
875
  */
854
876
  modelStrategy?: ModelStrategy;
877
+ /**
878
+ * Model for the main agent (routing + analysis).
879
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
880
+ * If not set, uses the provider's default model.
881
+ */
882
+ mainAgentModel?: string;
883
+ /**
884
+ * Model for source agents (per-source query generation).
885
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
886
+ * If not set, uses the provider's default model.
887
+ */
888
+ sourceAgentModel?: string;
855
889
  /**
856
890
  * Separate model configuration for DASH_COMP flow (dashboard component picking)
857
891
  * If not provided, falls back to provider-based model selection
@@ -870,6 +904,12 @@ interface SuperatomSDKConfig {
870
904
  * Default: 5 minutes
871
905
  */
872
906
  queryCacheTTL?: number;
907
+ /**
908
+ * Dashboard conversation history TTL (Time To Live) in minutes
909
+ * Per-dashboard conversation histories expire after this duration
910
+ * Default: 30 minutes
911
+ */
912
+ dashboardHistoryTTL?: number;
873
913
  }
874
914
 
875
915
  declare const KbNodesQueryFiltersSchema: z.ZodObject<{
@@ -877,18 +917,18 @@ declare const KbNodesQueryFiltersSchema: z.ZodObject<{
877
917
  category: z.ZodOptional<z.ZodString>;
878
918
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
879
919
  type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
880
- createdBy: z.ZodOptional<z.ZodNumber>;
920
+ createdBy: z.ZodOptional<z.ZodString>;
881
921
  }, "strip", z.ZodTypeAny, {
882
922
  type?: "query" | "user" | "global" | undefined;
883
923
  query?: string | undefined;
884
924
  category?: string | undefined;
885
- createdBy?: number | undefined;
925
+ createdBy?: string | undefined;
886
926
  tags?: string[] | undefined;
887
927
  }, {
888
928
  type?: "query" | "user" | "global" | undefined;
889
929
  query?: string | undefined;
890
930
  category?: string | undefined;
891
- createdBy?: number | undefined;
931
+ createdBy?: string | undefined;
892
932
  tags?: string[] | undefined;
893
933
  }>;
894
934
  type KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
@@ -901,27 +941,27 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
901
941
  category: z.ZodOptional<z.ZodString>;
902
942
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
903
943
  type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
904
- createdBy: z.ZodOptional<z.ZodNumber>;
905
- updatedBy: z.ZodOptional<z.ZodNumber>;
906
- userId: z.ZodOptional<z.ZodNumber>;
944
+ createdBy: z.ZodOptional<z.ZodString>;
945
+ updatedBy: z.ZodOptional<z.ZodString>;
946
+ userId: z.ZodOptional<z.ZodString>;
907
947
  query: z.ZodOptional<z.ZodString>;
908
948
  filters: z.ZodOptional<z.ZodObject<{
909
949
  query: z.ZodOptional<z.ZodString>;
910
950
  category: z.ZodOptional<z.ZodString>;
911
951
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
912
952
  type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
913
- createdBy: z.ZodOptional<z.ZodNumber>;
953
+ createdBy: z.ZodOptional<z.ZodString>;
914
954
  }, "strip", z.ZodTypeAny, {
915
955
  type?: "query" | "user" | "global" | undefined;
916
956
  query?: string | undefined;
917
957
  category?: string | undefined;
918
- createdBy?: number | undefined;
958
+ createdBy?: string | undefined;
919
959
  tags?: string[] | undefined;
920
960
  }, {
921
961
  type?: "query" | "user" | "global" | undefined;
922
962
  query?: string | undefined;
923
963
  category?: string | undefined;
924
- createdBy?: number | undefined;
964
+ createdBy?: string | undefined;
925
965
  tags?: string[] | undefined;
926
966
  }>>;
927
967
  limit: z.ZodOptional<z.ZodNumber>;
@@ -932,17 +972,17 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
932
972
  query?: string | undefined;
933
973
  title?: string | undefined;
934
974
  category?: string | undefined;
935
- userId?: number | undefined;
975
+ userId?: string | undefined;
936
976
  limit?: number | undefined;
937
977
  filters?: {
938
978
  type?: "query" | "user" | "global" | undefined;
939
979
  query?: string | undefined;
940
980
  category?: string | undefined;
941
- createdBy?: number | undefined;
981
+ createdBy?: string | undefined;
942
982
  tags?: string[] | undefined;
943
983
  } | undefined;
944
- createdBy?: number | undefined;
945
- updatedBy?: number | undefined;
984
+ createdBy?: string | undefined;
985
+ updatedBy?: string | undefined;
946
986
  offset?: number | undefined;
947
987
  tags?: string[] | undefined;
948
988
  content?: string | undefined;
@@ -952,17 +992,17 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
952
992
  query?: string | undefined;
953
993
  title?: string | undefined;
954
994
  category?: string | undefined;
955
- userId?: number | undefined;
995
+ userId?: string | undefined;
956
996
  limit?: number | undefined;
957
997
  filters?: {
958
998
  type?: "query" | "user" | "global" | undefined;
959
999
  query?: string | undefined;
960
1000
  category?: string | undefined;
961
- createdBy?: number | undefined;
1001
+ createdBy?: string | undefined;
962
1002
  tags?: string[] | undefined;
963
1003
  } | undefined;
964
- createdBy?: number | undefined;
965
- updatedBy?: number | undefined;
1004
+ createdBy?: string | undefined;
1005
+ updatedBy?: string | undefined;
966
1006
  offset?: number | undefined;
967
1007
  tags?: string[] | undefined;
968
1008
  content?: string | undefined;
@@ -975,17 +1015,17 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
975
1015
  query?: string | undefined;
976
1016
  title?: string | undefined;
977
1017
  category?: string | undefined;
978
- userId?: number | undefined;
1018
+ userId?: string | undefined;
979
1019
  limit?: number | undefined;
980
1020
  filters?: {
981
1021
  type?: "query" | "user" | "global" | undefined;
982
1022
  query?: string | undefined;
983
1023
  category?: string | undefined;
984
- createdBy?: number | undefined;
1024
+ createdBy?: string | undefined;
985
1025
  tags?: string[] | undefined;
986
1026
  } | undefined;
987
- createdBy?: number | undefined;
988
- updatedBy?: number | undefined;
1027
+ createdBy?: string | undefined;
1028
+ updatedBy?: string | undefined;
989
1029
  offset?: number | undefined;
990
1030
  tags?: string[] | undefined;
991
1031
  content?: string | undefined;
@@ -998,17 +1038,17 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
998
1038
  query?: string | undefined;
999
1039
  title?: string | undefined;
1000
1040
  category?: string | undefined;
1001
- userId?: number | undefined;
1041
+ userId?: string | undefined;
1002
1042
  limit?: number | undefined;
1003
1043
  filters?: {
1004
1044
  type?: "query" | "user" | "global" | undefined;
1005
1045
  query?: string | undefined;
1006
1046
  category?: string | undefined;
1007
- createdBy?: number | undefined;
1047
+ createdBy?: string | undefined;
1008
1048
  tags?: string[] | undefined;
1009
1049
  } | undefined;
1010
- createdBy?: number | undefined;
1011
- updatedBy?: number | undefined;
1050
+ createdBy?: string | undefined;
1051
+ updatedBy?: string | undefined;
1012
1052
  offset?: number | undefined;
1013
1053
  tags?: string[] | undefined;
1014
1054
  content?: string | undefined;
@@ -1280,6 +1320,743 @@ declare class ReportManager {
1280
1320
  getReportCount(): number;
1281
1321
  }
1282
1322
 
1323
+ /**
1324
+ * StreamBuffer - Buffered streaming utility for smoother text delivery
1325
+ * Batches small chunks together and flushes at regular intervals
1326
+ */
1327
+ type StreamCallback = (chunk: string) => void;
1328
+ /**
1329
+ * StreamBuffer class for managing buffered streaming output
1330
+ * Provides smooth text delivery by batching small chunks
1331
+ */
1332
+ declare class StreamBuffer {
1333
+ private buffer;
1334
+ private flushTimer;
1335
+ private callback;
1336
+ private fullText;
1337
+ constructor(callback?: StreamCallback);
1338
+ /**
1339
+ * Check if the buffer has a callback configured
1340
+ */
1341
+ hasCallback(): boolean;
1342
+ /**
1343
+ * Get all text that has been written (including already flushed)
1344
+ */
1345
+ getFullText(): string;
1346
+ /**
1347
+ * Write a chunk to the buffer
1348
+ * Large chunks or chunks with newlines are flushed immediately
1349
+ * Small chunks are batched and flushed after a short interval
1350
+ *
1351
+ * @param chunk - Text chunk to write
1352
+ */
1353
+ write(chunk: string): void;
1354
+ /**
1355
+ * Flush the buffer immediately
1356
+ * Call this before tool execution or other operations that need clean output
1357
+ */
1358
+ flush(): void;
1359
+ /**
1360
+ * Internal flush implementation
1361
+ */
1362
+ private flushNow;
1363
+ /**
1364
+ * Clean up resources
1365
+ * Call this when done with the buffer
1366
+ */
1367
+ dispose(): void;
1368
+ }
1369
+
1370
+ /**
1371
+ * ToolExecutorService - Handles execution of SQL queries and external tools
1372
+ * Extracted from BaseLLM.generateTextResponse for better separation of concerns
1373
+ */
1374
+
1375
+ /**
1376
+ * External tool definition
1377
+ */
1378
+ interface ExternalTool {
1379
+ id: string;
1380
+ name: string;
1381
+ description?: string;
1382
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
1383
+ toolType?: 'source' | 'direct';
1384
+ /** Full untruncated schema for source agent (all columns visible) */
1385
+ fullSchema?: string;
1386
+ /** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
1387
+ schemaTier?: string;
1388
+ /** Schema search function for very_large tier — keyword search over entities */
1389
+ schemaSearchFn?: (keywords: string[]) => string;
1390
+ fn: (input: any) => Promise<any>;
1391
+ limit?: number;
1392
+ outputSchema?: any;
1393
+ executionType?: 'immediate' | 'deferred';
1394
+ userProvidedData?: any;
1395
+ params?: Record<string, any>;
1396
+ }
1397
+ /**
1398
+ * Executed tool tracking info
1399
+ */
1400
+ interface ExecutedToolInfo {
1401
+ id: string;
1402
+ name: string;
1403
+ params: any;
1404
+ result: {
1405
+ _totalRecords: number;
1406
+ _recordsShown: number;
1407
+ _metadata?: any;
1408
+ _sampleData: any[];
1409
+ };
1410
+ outputSchema?: any;
1411
+ sourceSchema?: string;
1412
+ sourceType?: string;
1413
+ }
1414
+
1415
+ /**
1416
+ * Multi-Agent Architecture Types
1417
+ *
1418
+ * Defines interfaces for the hierarchical agent system:
1419
+ * - Main Agent: ONE LLM.streamWithTools() call with source agent tools
1420
+ * - Source Agents: independent agents that query individual data sources
1421
+ *
1422
+ * The main agent sees only source summaries. When it calls a source tool,
1423
+ * the SourceAgent runs independently (own LLM, own retries) and returns clean data.
1424
+ */
1425
+
1426
+ /**
1427
+ * Per-entity detail: name, row count, and column names.
1428
+ * Gives the main agent enough context to route to the right source.
1429
+ */
1430
+ interface EntityDetail {
1431
+ /** Entity name (table, sheet, endpoint) */
1432
+ name: string;
1433
+ /** Approximate row count */
1434
+ rowCount?: number;
1435
+ /** Column/field names */
1436
+ columns: string[];
1437
+ }
1438
+ /**
1439
+ * Representation of a data source for the main agent.
1440
+ * Contains entity names WITH column names so the LLM can route accurately.
1441
+ */
1442
+ interface SourceSummary {
1443
+ /** Source ID (matches tool ID prefix) */
1444
+ id: string;
1445
+ /** Human-readable source name */
1446
+ name: string;
1447
+ /** Source type: postgres, excel, rest_api, etc. */
1448
+ type: string;
1449
+ /** Brief description of what data this source contains */
1450
+ description: string;
1451
+ /** Detailed entity info with column names for routing */
1452
+ entityDetails: EntityDetail[];
1453
+ /** The tool ID associated with this source */
1454
+ toolId: string;
1455
+ }
1456
+ /**
1457
+ * What a source agent returns after querying its data source.
1458
+ * The main agent uses this to analyze and compose the final response.
1459
+ */
1460
+ interface SourceAgentResult {
1461
+ /** Source ID */
1462
+ sourceId: string;
1463
+ /** Source name */
1464
+ sourceName: string;
1465
+ /** Whether the query succeeded */
1466
+ success: boolean;
1467
+ /** Result data rows */
1468
+ data: any[];
1469
+ /** Metadata about the query execution */
1470
+ metadata: SourceAgentMetadata;
1471
+ /** Tool execution info for the last successful query (backward compat) */
1472
+ executedTool: ExecutedToolInfo;
1473
+ /** All successful tool executions (primary + follow-up queries) */
1474
+ allExecutedTools?: ExecutedToolInfo[];
1475
+ /** Error message if failed */
1476
+ error?: string;
1477
+ }
1478
+ interface SourceAgentMetadata {
1479
+ /** Total rows that matched the query (before limit) */
1480
+ totalRowsMatched: number;
1481
+ /** Rows actually returned (after limit) */
1482
+ rowsReturned: number;
1483
+ /** Whether the result was truncated by the row limit */
1484
+ isLimited: boolean;
1485
+ /** The query/params that were executed */
1486
+ queryExecuted?: string;
1487
+ /** Execution time in milliseconds */
1488
+ executionTimeMs: number;
1489
+ }
1490
+ /**
1491
+ * A pre-built, multi-step UI flow registered with the SDK.
1492
+ *
1493
+ * When the main agent decides a user's question matches a workflow's whenToUse
1494
+ * trigger, it picks the workflow instead of running source agents / generating
1495
+ * dashboard components. The LLM extracts the workflow's required props from the
1496
+ * prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
1497
+ * workflow component directly — no analysis text, no chart generation. The
1498
+ * frontend renders the registered workflow component with the LLM-extracted
1499
+ * props.
1500
+ */
1501
+ interface WorkflowDescriptor {
1502
+ /** Unique workflow id (used as the LLM tool name) */
1503
+ id: string;
1504
+ /** Component name on the frontend (matches the registered React component) */
1505
+ name: string;
1506
+ /** Short human-readable description of what this workflow does */
1507
+ description: string;
1508
+ /**
1509
+ * 1–2 sentence trigger condition. The LLM uses this to decide if the
1510
+ * user's prompt matches this workflow. Be specific — e.g.
1511
+ * "User wants to *initiate* an inventory transfer (review + submit POs),
1512
+ * not just see analysis or charts."
1513
+ */
1514
+ whenToUse: string;
1515
+ /**
1516
+ * JSON-schema-style description of the props the workflow needs. Becomes
1517
+ * the LLM tool's input_schema, so the model fills these from the prompt.
1518
+ * Use the same shape as `params` on direct tools — string descriptors with
1519
+ * an optional "(optional)" suffix.
1520
+ *
1521
+ * Example:
1522
+ * ```
1523
+ * {
1524
+ * selectedStore: 'object — { id, name } of the source branch',
1525
+ * minROI: 'number (optional) — only show transfers with ROI ≥ this',
1526
+ * }
1527
+ * ```
1528
+ */
1529
+ propsSchema: Record<string, string>;
1530
+ /**
1531
+ * Optional: static prop defaults merged with LLM-extracted props before
1532
+ * the component is returned. Useful for things like the embedded
1533
+ * `externalTool` config that the workflow uses to fetch its own data.
1534
+ */
1535
+ defaultProps?: Record<string, any>;
1536
+ }
1537
+ /**
1538
+ * The workflow selection captured during a routing call.
1539
+ * Set on AgentResponse when the LLM picks a workflow tool.
1540
+ */
1541
+ interface SelectedWorkflow {
1542
+ /** Component name (matches WorkflowDescriptor.name) */
1543
+ name: string;
1544
+ /** Props extracted from the prompt + merged with workflow.defaultProps */
1545
+ props: Record<string, any>;
1546
+ }
1547
+ /**
1548
+ * The complete response from the multi-agent system.
1549
+ * Contains everything needed for text display + component generation.
1550
+ */
1551
+ interface AgentResponse {
1552
+ /** Generated text response (analysis of the data) */
1553
+ text: string;
1554
+ /** All executed tools across all source agents (for component generation) */
1555
+ executedTools: ExecutedToolInfo[];
1556
+ /** Individual results from each source agent */
1557
+ sourceResults: SourceAgentResult[];
1558
+ /**
1559
+ * Populated when MainAgent wrote AND successfully executed a script during its turn.
1560
+ * Caller (agent-user-response.ts) persists it via ScriptStore.save().
1561
+ * Absent when MainAgent didn't write one (trivial question / all attempts failed).
1562
+ */
1563
+ savedScript?: AgentWrittenScript;
1564
+ /**
1565
+ * Set when the LLM routed the question to a registered workflow component.
1566
+ * When present, the upstream caller should skip component generation and
1567
+ * return this workflow as the response.
1568
+ */
1569
+ workflow?: SelectedWorkflow;
1570
+ }
1571
+ /**
1572
+ * A script MainAgent authored + verified during its turn. Shape aligns with
1573
+ * what ScriptStore.save() needs — minus store-assigned fields (id, timestamps, counts).
1574
+ */
1575
+ interface AgentWrittenScript {
1576
+ /**
1577
+ * `ScriptRecipe.id` of the draft that was authored + verified during this turn.
1578
+ * The caller passes this to `ScriptStore.promoteToVerified(recipeId, …)` to
1579
+ * flip the draft to verified status and (when possible) drop the turn-suffix
1580
+ * from its filename.
1581
+ */
1582
+ recipeId: string;
1583
+ name: string;
1584
+ intentDescription: string;
1585
+ tags: string[];
1586
+ parameters: Array<{
1587
+ name: string;
1588
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
1589
+ required: boolean;
1590
+ default?: any;
1591
+ enumValues?: Record<string, string>;
1592
+ description: string;
1593
+ }>;
1594
+ scriptBody: string;
1595
+ /** Source IDs referenced by the script (extracted from ctx.query calls) */
1596
+ sourceIds: string[];
1597
+ /** Tables referenced in the script's SQL (regex-extracted) */
1598
+ tables: string[];
1599
+ /** Executed queries from the verified run — fed to component generation */
1600
+ executedQueries: Array<{
1601
+ sourceId: string;
1602
+ sourceName: string;
1603
+ sql: string;
1604
+ data: any[];
1605
+ count: number;
1606
+ totalCount?: number;
1607
+ executionTimeMs: number;
1608
+ /**
1609
+ * True for synthetic entries (ctx.emit datasets, the computed:_final
1610
+ * post-JS data). The component generator routes virtual sources through
1611
+ * the script_dataset sentinel toolId so the frontend resolves them via
1612
+ * queryCache instead of attempting to re-execute SQL.
1613
+ */
1614
+ virtual?: boolean;
1615
+ }>;
1616
+ }
1617
+ /**
1618
+ * Configuration for the multi-agent system.
1619
+ * Controls limits, models, and behavior.
1620
+ */
1621
+ interface AgentConfig {
1622
+ /** Max rows a source agent can return (default: 50) */
1623
+ maxRowsPerSource: number;
1624
+ /** Model for the main agent (routing + analysis in one LLM call) */
1625
+ mainAgentModel: string;
1626
+ /** Model for source agent query generation */
1627
+ sourceAgentModel: string;
1628
+ /** API key for LLM calls */
1629
+ apiKey?: string;
1630
+ /** Max retry attempts per source agent */
1631
+ maxRetries: number;
1632
+ /** Max tool calling iterations for the main agent loop */
1633
+ maxIterations: number;
1634
+ /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
1635
+ globalKnowledgeBase?: string;
1636
+ /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
1637
+ knowledgeBaseContext?: string;
1638
+ /** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
1639
+ collections?: any;
1640
+ /** Optional project ID for scoping embedding searches */
1641
+ projectId?: string;
1642
+ }
1643
+ /**
1644
+ * Default agent configuration
1645
+ */
1646
+ declare const DEFAULT_AGENT_CONFIG: AgentConfig;
1647
+
1648
+ /**
1649
+ * Script Flow Types
1650
+ *
1651
+ * Defines interfaces for the script-based query architecture:
1652
+ * - ScriptRecipe: metadata for matching, validation, and quality tracking
1653
+ * - ScriptResult: output from executing a script
1654
+ * - ScriptMatch: result from the LLM-based script matcher
1655
+ */
1656
+ /**
1657
+ * Recipe metadata stored alongside each script.
1658
+ * Used for matching, validation, and quality tracking.
1659
+ */
1660
+ interface ScriptRecipe {
1661
+ /** Unique script identifier */
1662
+ id: string;
1663
+ /** Version number (incremented on regeneration) */
1664
+ version: number;
1665
+ /** Human-readable name (e.g., "Revenue by Dimension") */
1666
+ name: string;
1667
+ /** Natural language description of what this script does */
1668
+ intentDescription: string;
1669
+ /** Keyword tags for quick filtering */
1670
+ tags: string[];
1671
+ /** Source tool IDs this script queries (e.g., ["mssql-abc123_query"]) */
1672
+ sourceIds: string[];
1673
+ /** Table names used (for future schema drift detection) */
1674
+ tables: string[];
1675
+ /** Parameter definitions — what can vary */
1676
+ parameters: ScriptParameter[];
1677
+ /** The script function body as a string */
1678
+ scriptBody: string;
1679
+ /** Times this script was used successfully */
1680
+ successCount: number;
1681
+ /** Times this script failed */
1682
+ failureCount: number;
1683
+ /** ISO timestamp of last usage */
1684
+ lastUsed: string;
1685
+ /** Original user question that created this script */
1686
+ createdFrom: string;
1687
+ /** ISO timestamp */
1688
+ createdAt: string;
1689
+ /** ISO timestamp */
1690
+ updatedAt: string;
1691
+ /**
1692
+ * `recipe.id` of the parent this script was forked from.
1693
+ * Undefined for root scripts (those written from scratch by MainAgent).
1694
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md.
1695
+ */
1696
+ parentId?: string;
1697
+ /** 0 for root scripts; `parent.forkDepth + 1` for forks. Capped at 3. */
1698
+ forkDepth?: number;
1699
+ /**
1700
+ * Brief description of what this fork changed vs its parent
1701
+ * (sourced from the matcher's `modificationHint`).
1702
+ */
1703
+ forkReason?: string;
1704
+ /**
1705
+ * Validated component specs captured at authoring time. On a tier-high
1706
+ * replay these are rebound to fresh queryIds deterministically — no
1707
+ * component-generation LLM call, and the rendered columns can't drift from
1708
+ * what was validated when the script was authored. Absent on recipes
1709
+ * authored before this landed; those fall back to LLM component generation.
1710
+ * See backend/docs/SCRIPT-COMPONENT-CONSISTENCY.md.
1711
+ */
1712
+ components?: ScriptComponentSpec[];
1713
+ /**
1714
+ * Lifecycle stage of this recipe on disk.
1715
+ * - 'draft': written by MainAgent's write_script during a turn; filtered out
1716
+ * of `ScriptStore.getAll()` so the matcher never picks it.
1717
+ * Filename is suffixed with `turnId` to keep concurrent turns
1718
+ * from clobbering each other's drafts.
1719
+ * - 'verified': promoted after `execute_script` succeeded; the matcher sees it.
1720
+ * Filename drops the turn suffix unless a verified file with
1721
+ * the same slug already exists (collision case keeps the suffix).
1722
+ *
1723
+ * Recipes loaded from disk without this field default to 'verified' so
1724
+ * existing scripts keep working unchanged.
1725
+ */
1726
+ status?: 'draft' | 'verified';
1727
+ /**
1728
+ * Per-turn unique suffix used for draft filenames (e.g. `1714745623-x9k2`).
1729
+ * Set when the draft is saved; carried until the recipe is promoted.
1730
+ */
1731
+ turnId?: string;
1732
+ /**
1733
+ * Last execution error captured by `recordDraftError` while the recipe was
1734
+ * still a draft. Lets users open the draft .json file and see why it failed
1735
+ * without grepping logs. Cleared on promotion to 'verified'.
1736
+ */
1737
+ lastError?: {
1738
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
1739
+ message: string;
1740
+ at: string;
1741
+ attempt: number;
1742
+ };
1743
+ }
1744
+ interface ScriptParameter {
1745
+ /** Parameter name (used in script body as params.name) */
1746
+ name: string;
1747
+ /** Parameter type */
1748
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
1749
+ /** Whether this parameter is required */
1750
+ required: boolean;
1751
+ /** Default value if not provided */
1752
+ default?: any;
1753
+ /** For enum type — maps user-facing values to internal values */
1754
+ enumValues?: Record<string, string>;
1755
+ /** Human-readable description (used in the matcher LLM prompt) */
1756
+ description: string;
1757
+ }
1758
+ /**
1759
+ * A reusable component binding captured when a script is authored. Stored on
1760
+ * the recipe so tier-high replays rebuild components deterministically (rebind
1761
+ * to fresh queryIds) instead of re-running the component-picker LLM.
1762
+ */
1763
+ interface ScriptComponentSpec {
1764
+ /** Registered component name (e.g. "DynamicBarChart") — matched against the available component library. */
1765
+ componentType: string;
1766
+ /** `executedQuery.sourceId` to bind to (e.g. a tool id or 'computed:_final'), or 'federation' for a cross-source component. */
1767
+ sourceRef: string;
1768
+ /** Present only when sourceRef === 'federation' — the DuckDB SQL to re-execute on replay. */
1769
+ federationSql?: string;
1770
+ title?: string;
1771
+ description?: string;
1772
+ /** Validated axis/value keys + aggregation — all referencing real columns of the bound source. */
1773
+ config: Record<string, any>;
1774
+ }
1775
+
1776
+ /**
1777
+ * ScriptStore — Persistent Storage for Script Recipes
1778
+ *
1779
+ * Layout:
1780
+ * scripts-store/
1781
+ * metadata/<name>.json ← recipe metadata (params, tables, counts, ...)
1782
+ * <name>.ts ← the getData() function body, editable in your IDE
1783
+ *
1784
+ * Each VM deployment is a single project, so no project ID prefix needed.
1785
+ * Legacy single-file format (JSON with embedded scriptBody) is still loadable
1786
+ * for backwards compatibility and auto-migrated to the split format on next save.
1787
+ */
1788
+
1789
+ /**
1790
+ * Input for `ScriptStore.saveDraft()`. Identifies the draft by `recipeId` so
1791
+ * retries within the same turn overwrite the same files (or omit `recipeId`
1792
+ * on the first call to mint a fresh draft).
1793
+ */
1794
+ interface SaveDraftInput {
1795
+ /** Reuse an existing draft (retry); omit to mint a new one. */
1796
+ recipeId?: string;
1797
+ /** Per-turn unique suffix, stable across retries within the turn. */
1798
+ turnId: string;
1799
+ name: string;
1800
+ intentDescription: string;
1801
+ tags: string[];
1802
+ parameters: ScriptParameter[];
1803
+ scriptBody: string;
1804
+ createdFrom: string;
1805
+ }
1806
+ /**
1807
+ * Lineage + provenance fields applied when a draft is promoted to verified.
1808
+ * MainAgent gathers `sourceIds` and `tables` from the verified execution; the
1809
+ * caller (agent-user-response.ts) supplies the optional fork lineage.
1810
+ */
1811
+ interface PromoteToVerifiedInput {
1812
+ sourceIds: string[];
1813
+ tables: string[];
1814
+ parentId?: string;
1815
+ forkDepth?: number;
1816
+ forkReason?: string;
1817
+ /** Validated component specs to persist on the recipe (component recipe). */
1818
+ components?: ScriptComponentSpec[];
1819
+ }
1820
+ declare class ScriptStore {
1821
+ private recipes;
1822
+ private storeDir;
1823
+ private loaded;
1824
+ constructor(baseDir?: string);
1825
+ private metadataDir;
1826
+ /**
1827
+ * Filename base for a recipe. Drafts include the per-turn suffix so two
1828
+ * concurrent turns can never clobber each other's draft files; verified
1829
+ * recipes use the bare slug.
1830
+ */
1831
+ private fileBaseName;
1832
+ /**
1833
+ * Absolute path to the .ts file for a recipe. Callers (e.g. ScriptRunner,
1834
+ * MainAgent's execute_script) use this to hand off the path to the tsx child.
1835
+ */
1836
+ getScriptPath(recipe: ScriptRecipe): string;
1837
+ /**
1838
+ * Absolute path to the metadata JSON for a recipe.
1839
+ */
1840
+ private getMetadataPath;
1841
+ /**
1842
+ * Get all VERIFIED recipes — drafts are filtered out so the matcher never
1843
+ * considers an unverified script. Loads from disk on first access.
1844
+ */
1845
+ getAll(): ScriptRecipe[];
1846
+ /**
1847
+ * Get a recipe by ID — returns drafts as well as verified scripts.
1848
+ * Used by MainAgent and the promotion path.
1849
+ */
1850
+ get(id: string): ScriptRecipe | null;
1851
+ /**
1852
+ * Number of verified recipes (matches `getAll().length`).
1853
+ */
1854
+ count(): number;
1855
+ /**
1856
+ * Save a recipe (create or update).
1857
+ * File is named after the script: "order-status-distribution.json"
1858
+ */
1859
+ save(recipe: ScriptRecipe): void;
1860
+ /**
1861
+ * Persist (or update) a draft recipe to disk. Always writes immediately so
1862
+ * the `.ts` body is visible in the IDE the moment MainAgent calls
1863
+ * `write_script`. Within one turn, retries that pass the same `recipeId`
1864
+ * overwrite the same files (the LLM rewriting itself); a fresh `recipeId`
1865
+ * is minted only on the first call of the turn.
1866
+ *
1867
+ * Filename includes the `turnId` suffix so concurrent turns never collide.
1868
+ */
1869
+ saveDraft(input: SaveDraftInput): ScriptRecipe;
1870
+ /**
1871
+ * Stamp the draft with the most recent execution failure so it is visible
1872
+ * in the metadata JSON without grepping logs. No-op if the recipe doesn't
1873
+ * exist or has already been promoted.
1874
+ */
1875
+ recordDraftError(recipeId: string, err: {
1876
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
1877
+ message: string;
1878
+ attempt: number;
1879
+ }): void;
1880
+ /**
1881
+ * Promote a successfully-executed draft into a verified script.
1882
+ *
1883
+ * - Renames the on-disk files from `<slug>-<turnId>.{ts,json}` to the bare
1884
+ * `<slug>.{ts,json}`. If a verified file with the same slug already exists
1885
+ * (concurrent turn won the race, or a prior session has it), the recipe
1886
+ * keeps its turn-suffixed filename so we never overwrite verified work —
1887
+ * the matcher keys on `recipe.id`, so two siblings with similar slugs is fine.
1888
+ * - Flips `status: 'verified'`, clears `lastError`, applies provenance
1889
+ * (`sourceIds`, `tables`) and optional fork lineage.
1890
+ */
1891
+ promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): ScriptRecipe | null;
1892
+ /**
1893
+ * Drop a draft from disk + memory (e.g. when an outer error path wants to
1894
+ * clean up). Per the agreed policy, MainAgent's normal failure path does
1895
+ * NOT call this — failed drafts are kept on disk for the user to inspect.
1896
+ */
1897
+ discardDraft(recipeId: string): void;
1898
+ /**
1899
+ * Delete a recipe by ID.
1900
+ */
1901
+ delete(id: string): void;
1902
+ /**
1903
+ * Record a successful execution for a recipe.
1904
+ */
1905
+ recordSuccess(id: string): void;
1906
+ /**
1907
+ * Record a failed execution for a recipe.
1908
+ */
1909
+ recordFailure(id: string): void;
1910
+ /**
1911
+ * Get the failure rate for a recipe (0 to 1).
1912
+ * Returns 0 if the recipe has fewer than 5 total uses.
1913
+ */
1914
+ getFailureRate(id: string): number;
1915
+ private ensureLoaded;
1916
+ /**
1917
+ * Convert a script name to a safe filename.
1918
+ * "Order Status Distribution" → "order-status-distribution"
1919
+ */
1920
+ private toFileName;
1921
+ /**
1922
+ * Load all script files from disk.
1923
+ *
1924
+ * Supports two layouts:
1925
+ * - New (preferred): metadata/<name>.json + <name>.ts
1926
+ * - Legacy: <name>.json with embedded scriptBody (auto-migrated on next save)
1927
+ */
1928
+ private loadAllFromDisk;
1929
+ /**
1930
+ * Save a recipe to disk in split format:
1931
+ * metadata/<name>.json (metadata, no scriptBody)
1932
+ * <name>.ts (just the function body)
1933
+ *
1934
+ * If a legacy top-level <name>.json exists for the same recipe, remove it
1935
+ * so we don't end up with duplicate sources of truth.
1936
+ */
1937
+ private saveRecipeToDisk;
1938
+ /**
1939
+ * Delete a recipe's files from disk (both metadata + body, plus any legacy file).
1940
+ */
1941
+ private deleteRecipeFromDisk;
1942
+ }
1943
+
1944
+ /**
1945
+ * Main Agent (Orchestrator)
1946
+ *
1947
+ * A single LLM.streamWithTools() call that handles everything:
1948
+ * - Routing: decides which source(s) to query based on summaries
1949
+ * - Querying: calls source tools (each wraps an independent SourceAgent)
1950
+ * - Direct tools: calls pre-built function tools directly with LLM-provided params
1951
+ * - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
1952
+ * - Analysis: generates final text response from the data
1953
+ *
1954
+ * Two tool types:
1955
+ * - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
1956
+ * - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
1957
+ */
1958
+
1959
+ declare class MainAgent {
1960
+ private externalTools;
1961
+ private workflows;
1962
+ private config;
1963
+ private streamBuffer;
1964
+ /**
1965
+ * Optional: when provided, MainAgent exposes the `write_script` /
1966
+ * `execute_script` tools to the LLM and persists drafts to disk via the
1967
+ * store. Headless callers (alert analyzer, metric resolver) omit these to
1968
+ * suppress script authoring entirely — drafts would otherwise leak onto
1969
+ * disk with no caller to promote or clean them up.
1970
+ */
1971
+ private scriptStore;
1972
+ private turnId;
1973
+ private createdFromPrompt;
1974
+ private scriptState;
1975
+ constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[]);
1976
+ private get scriptingEnabled();
1977
+ /**
1978
+ * Handle a user question using the multi-agent system.
1979
+ *
1980
+ * This is ONE LLM.streamWithTools() call. The LLM:
1981
+ * 1. Sees source summaries + direct tool descriptions in system prompt
1982
+ * 2. Decides which tool(s) to call (routing)
1983
+ * 3. Source tools → SourceAgent runs independently → returns data
1984
+ * 4. Direct tools → fn() called directly with LLM params → returns data
1985
+ * 5. Generates final analysis text
1986
+ */
1987
+ handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void): Promise<AgentResponse>;
1988
+ private handleWriteScript;
1989
+ private handleExecuteScript;
1990
+ /**
1991
+ * Build the AgentWrittenScript payload the caller will hand to
1992
+ * `ScriptStore.promoteToVerified()`. Only returned when a verified
1993
+ * successful execution is on record.
1994
+ */
1995
+ private buildSavedScript;
1996
+ private normalizeParameterList;
1997
+ /**
1998
+ * Use the schema embedding collection to pre-select relevant tables for
1999
+ * this source + intent. Returns a formatted schema block if confidence is
2000
+ * high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
2001
+ *
2002
+ * When this returns a block, we can skip the SourceAgent's `search_schema`
2003
+ * loop and reduce iteration budget. When it returns null, the SourceAgent
2004
+ * falls back to the existing LLM-driven keyword search (same as today).
2005
+ */
2006
+ private preResolveSchema;
2007
+ /**
2008
+ * Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
2009
+ */
2010
+ private handleDirectTool;
2011
+ /**
2012
+ * Build the main agent's system prompt with source summaries, direct tool descriptions,
2013
+ * and workflow component descriptions.
2014
+ */
2015
+ private buildSystemPrompt;
2016
+ /**
2017
+ * Build tool definitions for source tools — summary-only descriptions.
2018
+ * The full schema is inside the SourceAgent which runs independently.
2019
+ */
2020
+ private buildSourceToolDefinitions;
2021
+ /**
2022
+ * Build tool definitions for direct tools — expose their actual params.
2023
+ * These are called directly by the main agent LLM, no SourceAgent.
2024
+ */
2025
+ private buildDirectToolDefinitions;
2026
+ /**
2027
+ * Capture a workflow selection. We do NOT execute anything — the LLM has
2028
+ * already extracted the props it wants the workflow rendered with. We
2029
+ * record the selection (via the capture callback) and return a short
2030
+ * acknowledgement so the LLM ends its turn cleanly without writing
2031
+ * analysis text or calling more tools.
2032
+ */
2033
+ private handleWorkflow;
2034
+ /**
2035
+ * Build LLM tool definitions for workflow components. The workflow's
2036
+ * propsSchema becomes the tool's input_schema so the LLM extracts props
2037
+ * directly from the prompt — same mechanic as direct tools.
2038
+ */
2039
+ private buildWorkflowToolDefinitions;
2040
+ /**
2041
+ * Format a source agent's result as a clean string for the main agent LLM.
2042
+ */
2043
+ private formatResultForMainAgent;
2044
+ /**
2045
+ * Get source summaries (for external inspection/debugging).
2046
+ */
2047
+ getSourceSummaries(): SourceSummary[];
2048
+ }
2049
+
2050
+ /**
2051
+ * Represents an action that can be performed on a UIBlock
2052
+ */
2053
+ interface Action {
2054
+ id: string;
2055
+ name: string;
2056
+ type: string;
2057
+ [key: string]: any;
2058
+ }
2059
+
1283
2060
  type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
1284
2061
  interface LLMMessages {
1285
2062
  sys: SystemPrompt;
@@ -1314,6 +2091,16 @@ declare class LLM {
1314
2091
  * @returns Normalized system prompt for Anthropic API
1315
2092
  */
1316
2093
  private static _normalizeSystemPrompt;
2094
+ /**
2095
+ * Strip unpaired UTF-16 surrogates from every text field of a message set.
2096
+ *
2097
+ * A lone surrogate (from mid-pair string slicing or corrupt source data)
2098
+ * serializes to a bare `\udXXX` escape that strict JSON parsers — including
2099
+ * the one on Anthropic's API — reject with "no low surrogate in string",
2100
+ * failing the whole request. Sanitizing here, at the single boundary every
2101
+ * provider call flows through, guarantees no request can carry one.
2102
+ */
2103
+ private static _sanitizeMessages;
1317
2104
  /**
1318
2105
  * Log cache usage metrics from Anthropic API response
1319
2106
  * Shows cache hits, costs, and savings
@@ -1434,16 +2221,6 @@ declare class UILogCollector {
1434
2221
  setUIBlockId(uiBlockId: string): void;
1435
2222
  }
1436
2223
 
1437
- /**
1438
- * Represents an action that can be performed on a UIBlock
1439
- */
1440
- interface Action {
1441
- id: string;
1442
- name: string;
1443
- type: string;
1444
- [key: string]: any;
1445
- }
1446
-
1447
2224
  /**
1448
2225
  * UIBlock represents a single user and assistant message block in a thread
1449
2226
  * Contains user question, component metadata, component data, text response, and available actions
@@ -1626,12 +2403,20 @@ declare class Thread {
1626
2403
 
1627
2404
  /**
1628
2405
  * ThreadManager manages all threads globally
1629
- * Provides methods to create, retrieve, and delete threads
2406
+ * Provides methods to create, retrieve, and delete threads.
2407
+ * Includes automatic cleanup to prevent unbounded memory growth.
1630
2408
  */
1631
2409
  declare class ThreadManager {
1632
2410
  private static instance;
1633
2411
  private threads;
2412
+ private cleanupInterval;
2413
+ private readonly threadTtlMs;
1634
2414
  private constructor();
2415
+ /**
2416
+ * Periodically remove threads older than 7 days.
2417
+ * Runs every hour to avoid frequent iteration over the map.
2418
+ */
2419
+ private startCleanup;
1635
2420
  /**
1636
2421
  * Get singleton instance of ThreadManager
1637
2422
  */
@@ -2331,18 +3116,30 @@ declare class OpenAILLM extends BaseLLM {
2331
3116
  declare const openaiLLM: OpenAILLM;
2332
3117
 
2333
3118
  /**
2334
- * Query Cache - Stores query results with configurable TTL
2335
- * Used to avoid re-executing queries that were already validated
3119
+ * Query Cache Two mechanisms:
3120
+ *
3121
+ * 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
3122
+ * of recently validated queries. True LRU eviction: reads bubble entries to the back via
3123
+ * delete+re-set so the oldest *unused* entry is evicted, not the oldest *inserted*.
3124
+ *
3125
+ * 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
3126
+ * No server-side storage needed for SQL mappings. The token is decrypted on each request.
3127
+ * This eliminates the unbounded queryIdCache that previously grew forever and caused
3128
+ * memory bloat (hundreds of MBs after thousands of queries).
3129
+ *
3130
+ * Result data can still be cached temporarily via the data cache (mechanism 1).
2336
3131
  */
2337
3132
  declare class QueryCache {
2338
3133
  private cache;
2339
- private queryIdCache;
2340
3134
  private ttlMs;
3135
+ private maxCacheSize;
2341
3136
  private cleanupInterval;
3137
+ private readonly algorithm;
3138
+ private encryptionKey;
2342
3139
  constructor();
2343
3140
  /**
2344
3141
  * Set the cache TTL (Time To Live)
2345
- * @param minutes - TTL in minutes (default: 5)
3142
+ * @param minutes - TTL in minutes (default: 10)
2346
3143
  */
2347
3144
  setTTL(minutes: number): void;
2348
3145
  /**
@@ -2350,12 +3147,16 @@ declare class QueryCache {
2350
3147
  */
2351
3148
  getTTL(): number;
2352
3149
  /**
2353
- * Store query result in cache
2354
- * Key is the exact query string (or JSON for parameterized queries)
3150
+ * Store query result in data cache.
3151
+ * If the key already exists, it's removed first so the re-insert places it
3152
+ * at the back of the iteration order (LRU). Eviction only fires when adding
3153
+ * a genuinely new key past the size limit.
2355
3154
  */
2356
3155
  set(query: string, data: any): void;
2357
3156
  /**
2358
- * Get cached result if exists and not expired
3157
+ * Get cached result if exists and not expired.
3158
+ * On hit, re-inserts the entry so it moves to the back of the Map's
3159
+ * iteration order — turning FIFO eviction into true LRU.
2359
3160
  */
2360
3161
  get(query: string): any | null;
2361
3162
  /**
@@ -2375,30 +3176,37 @@ declare class QueryCache {
2375
3176
  */
2376
3177
  getStats(): {
2377
3178
  size: number;
3179
+ queryIdCount: number;
2378
3180
  oldestEntryAge: number | null;
2379
3181
  };
2380
3182
  /**
2381
- * Start periodic cleanup of expired entries
3183
+ * Start periodic cleanup of expired data cache entries.
2382
3184
  */
2383
3185
  private startCleanup;
2384
3186
  /**
2385
- * Generate a unique query ID
3187
+ * Encrypt a payload into a self-contained token.
2386
3188
  */
2387
- private generateQueryId;
3189
+ private encrypt;
2388
3190
  /**
2389
- * Store a query by ID. Returns the generated queryId.
2390
- * The query is stored server-side; only the queryId is sent to the frontend.
3191
+ * Decrypt a token back to the original payload.
3192
+ */
3193
+ private decrypt;
3194
+ /**
3195
+ * Store a query by generating an encrypted token as queryId.
3196
+ * The SQL is encrypted INTO the token — nothing stored in memory.
3197
+ * If data is provided, it's cached temporarily in the data cache.
2391
3198
  */
2392
3199
  storeQuery(query: any, data?: any): string;
2393
3200
  /**
2394
- * Get a stored query by its ID (not expired)
3201
+ * Get a stored query by decrypting its token.
3202
+ * Returns the SQL + any cached result data.
2395
3203
  */
2396
3204
  getQuery(queryId: string): {
2397
3205
  query: any;
2398
3206
  data: any;
2399
3207
  } | null;
2400
3208
  /**
2401
- * Update cached data for a queryId
3209
+ * Update cached data for a queryId token
2402
3210
  */
2403
3211
  setQueryData(queryId: string, data: any): void;
2404
3212
  /**
@@ -2408,6 +3216,52 @@ declare class QueryCache {
2408
3216
  }
2409
3217
  declare const queryCache: QueryCache;
2410
3218
 
3219
+ /**
3220
+ * Manages conversation history scoped per user + dashboard.
3221
+ * Each user-dashboard pair has its own isolated history that expires after a configurable TTL.
3222
+ */
3223
+ declare class DashboardConversationHistory {
3224
+ private histories;
3225
+ private ttlMs;
3226
+ private maxEntries;
3227
+ private cleanupInterval;
3228
+ constructor();
3229
+ /**
3230
+ * Set the TTL for dashboard histories
3231
+ * @param minutes - TTL in minutes
3232
+ */
3233
+ setTTL(minutes: number): void;
3234
+ /**
3235
+ * Set max entries per dashboard
3236
+ */
3237
+ setMaxEntries(max: number): void;
3238
+ /**
3239
+ * Add a conversation entry for a user's dashboard
3240
+ */
3241
+ addEntry(dashboardId: string, userPrompt: string, componentSummary: string, userId?: string): void;
3242
+ /**
3243
+ * Get formatted conversation history for a user's dashboard
3244
+ */
3245
+ getHistory(dashboardId: string, userId?: string): string;
3246
+ /**
3247
+ * Clear history for a specific user's dashboard
3248
+ */
3249
+ clearDashboard(dashboardId: string, userId?: string): void;
3250
+ /**
3251
+ * Clear all dashboard histories
3252
+ */
3253
+ clearAll(): void;
3254
+ /**
3255
+ * Start periodic cleanup of expired histories
3256
+ */
3257
+ private startCleanup;
3258
+ /**
3259
+ * Stop cleanup interval (for graceful shutdown)
3260
+ */
3261
+ destroy(): void;
3262
+ }
3263
+ declare const dashboardConversationHistory: DashboardConversationHistory;
3264
+
2411
3265
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
2412
3266
  declare class SuperatomSDK {
2413
3267
  private ws;
@@ -2424,6 +3278,7 @@ declare class SuperatomSDK {
2424
3278
  private collections;
2425
3279
  private components;
2426
3280
  private tools;
3281
+ private workflows;
2427
3282
  private anthropicApiKey;
2428
3283
  private groqApiKey;
2429
3284
  private geminiApiKey;
@@ -2431,6 +3286,9 @@ declare class SuperatomSDK {
2431
3286
  private llmProviders;
2432
3287
  private databaseType;
2433
3288
  private modelStrategy;
3289
+ private mainAgentModel;
3290
+ private sourceAgentModel;
3291
+ private dashCompModels?;
2434
3292
  private conversationSimilarityThreshold;
2435
3293
  private userManager;
2436
3294
  private dashboardManager;
@@ -2530,6 +3388,19 @@ declare class SuperatomSDK {
2530
3388
  * Get the stored tools
2531
3389
  */
2532
3390
  getTools(): Tool$1[];
3391
+ /**
3392
+ * Register workflow components for the SDK instance.
3393
+ *
3394
+ * Workflows are pre-built multi-step UI flows the main agent can pick when
3395
+ * the user's prompt matches a workflow's `whenToUse` trigger. Picking a
3396
+ * workflow short-circuits analysis text + dashboard component generation —
3397
+ * the workflow component is returned directly, with the LLM-extracted props.
3398
+ */
3399
+ setWorkflows(workflows: WorkflowDescriptor[]): void;
3400
+ /**
3401
+ * Get the registered workflow components.
3402
+ */
3403
+ getWorkflows(): WorkflowDescriptor[];
2533
3404
  /**
2534
3405
  * Apply model strategy to all LLM provider singletons
2535
3406
  * @param strategy - 'best', 'fast', or 'balanced'
@@ -2560,4 +3431,4 @@ declare class SuperatomSDK {
2560
3431
  getConversationSimilarityThreshold(): number;
2561
3432
  }
2562
3433
 
2563
- export { type Action, BM25L, type BM25LOptions, type BaseLLMConfig, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, 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, geminiLLM, groqLLM, hybridRerank, llmUsageLogger, logger, openaiLLM, queryCache, rerankChromaResults, rerankConversationResults, userPromptErrorLogger };
3434
+ 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 };