@superatomai/sdk-node 0.0.30-mds → 0.0.31-dsp
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +1692 -419
- package/dist/index.d.ts +1692 -419
- package/dist/index.js +11882 -4181
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +12066 -4364
- package/dist/index.mjs.map +1 -1
- package/dist/userResponse/scripts/script-bootstrap.d.mts +2 -0
- package/dist/userResponse/scripts/script-bootstrap.d.ts +2 -0
- package/dist/userResponse/scripts/script-bootstrap.js +305 -0
- package/dist/userResponse/scripts/script-bootstrap.js.map +1 -0
- package/dist/userResponse/scripts/script-bootstrap.mjs +303 -0
- package/dist/userResponse/scripts/script-bootstrap.mjs.map +1 -0
- package/package.json +3 -1
package/dist/index.d.mts
CHANGED
|
@@ -3,13 +3,32 @@ import Anthropic from '@anthropic-ai/sdk';
|
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Unified UIBlock structure for database storage
|
|
6
|
-
* Used in both bookmarks and user-conversations tables
|
|
6
|
+
* Used in both bookmarks and user-conversations tables.
|
|
7
|
+
*
|
|
8
|
+
* `analysis` always holds whatever real narration exists — the full answer on
|
|
9
|
+
* success, or whatever was actually streamed before a failure (may be empty).
|
|
10
|
+
* `error` is a dedicated field, null on success — it can be a plain string OR
|
|
11
|
+
* a structured object/array (e.g. the agent's raw `errors` list), whatever
|
|
12
|
+
* shape the failure naturally has; it's never coerced into `analysis`.
|
|
7
13
|
*/
|
|
8
14
|
interface DBUIBlock {
|
|
9
15
|
id: string;
|
|
10
16
|
component: Record<string, any> | null;
|
|
11
17
|
analysis: string | null;
|
|
12
18
|
user_prompt: string;
|
|
19
|
+
error?: unknown | null;
|
|
20
|
+
/**
|
|
21
|
+
* The script recipe that produced this answer, when one did. Read back via
|
|
22
|
+
* `conversation-history.exactMatch` so an edit follow-up still has a target
|
|
23
|
+
* after a reload (the in-memory thread is gone by then), and indexed so
|
|
24
|
+
* committing an edit can purge every cached answer bound to the recipe.
|
|
25
|
+
*/
|
|
26
|
+
scriptBinding?: {
|
|
27
|
+
recipeId: string;
|
|
28
|
+
params?: Record<string, any>;
|
|
29
|
+
name?: string;
|
|
30
|
+
columns?: string[];
|
|
31
|
+
};
|
|
13
32
|
}
|
|
14
33
|
|
|
15
34
|
/**
|
|
@@ -777,6 +796,14 @@ declare const ToolSchema: z.ZodObject<{
|
|
|
777
796
|
description: string;
|
|
778
797
|
}[];
|
|
779
798
|
}>>;
|
|
799
|
+
/** Cache policy. `false` = never cache (live data, write ops). Mirrors HTTP `Cache-Control: no-store`. */
|
|
800
|
+
cache: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<false>, z.ZodObject<{
|
|
801
|
+
ttlMs: z.ZodOptional<z.ZodNumber>;
|
|
802
|
+
}, "strip", z.ZodTypeAny, {
|
|
803
|
+
ttlMs?: number | undefined;
|
|
804
|
+
}, {
|
|
805
|
+
ttlMs?: number | undefined;
|
|
806
|
+
}>]>>;
|
|
780
807
|
}, "strip", z.ZodTypeAny, {
|
|
781
808
|
id: string;
|
|
782
809
|
params: Record<string, string>;
|
|
@@ -793,6 +820,9 @@ declare const ToolSchema: z.ZodObject<{
|
|
|
793
820
|
description: string;
|
|
794
821
|
}[];
|
|
795
822
|
} | undefined;
|
|
823
|
+
cache?: false | {
|
|
824
|
+
ttlMs?: number | undefined;
|
|
825
|
+
} | undefined;
|
|
796
826
|
}, {
|
|
797
827
|
id: string;
|
|
798
828
|
params: Record<string, string>;
|
|
@@ -809,6 +839,9 @@ declare const ToolSchema: z.ZodObject<{
|
|
|
809
839
|
description: string;
|
|
810
840
|
}[];
|
|
811
841
|
} | undefined;
|
|
842
|
+
cache?: false | {
|
|
843
|
+
ttlMs?: number | undefined;
|
|
844
|
+
} | undefined;
|
|
812
845
|
}>;
|
|
813
846
|
type Tool$1 = z.infer<typeof ToolSchema>;
|
|
814
847
|
type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
|
|
@@ -1306,172 +1339,1401 @@ declare class ReportManager {
|
|
|
1306
1339
|
getReportCount(): number;
|
|
1307
1340
|
}
|
|
1308
1341
|
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
name: string;
|
|
1325
|
-
description: string;
|
|
1326
|
-
input_schema: {
|
|
1327
|
-
type: string;
|
|
1328
|
-
properties: Record<string, any>;
|
|
1329
|
-
required?: string[];
|
|
1330
|
-
};
|
|
1331
|
-
}
|
|
1332
|
-
declare class LLM {
|
|
1333
|
-
static text(messages: LLMMessages, options?: LLMOptions): Promise<string>;
|
|
1334
|
-
static stream<T = string>(messages: LLMMessages, options?: LLMOptions, json?: boolean): Promise<T extends string ? string : any>;
|
|
1335
|
-
static streamWithTools(messages: LLMMessages, tools: Tool[], toolHandler: (toolName: string, toolInput: any) => Promise<any>, options?: LLMOptions, maxIterations?: number): Promise<string>;
|
|
1342
|
+
/**
|
|
1343
|
+
* StreamBuffer - Buffered streaming utility for smoother text delivery
|
|
1344
|
+
* Batches small chunks together and flushes at regular intervals
|
|
1345
|
+
*/
|
|
1346
|
+
type StreamCallback = (chunk: string) => void;
|
|
1347
|
+
/**
|
|
1348
|
+
* StreamBuffer class for managing buffered streaming output
|
|
1349
|
+
* Provides smooth text delivery by batching small chunks
|
|
1350
|
+
*/
|
|
1351
|
+
declare class StreamBuffer {
|
|
1352
|
+
private buffer;
|
|
1353
|
+
private flushTimer;
|
|
1354
|
+
private callback;
|
|
1355
|
+
private fullText;
|
|
1356
|
+
constructor(callback?: StreamCallback);
|
|
1336
1357
|
/**
|
|
1337
|
-
*
|
|
1338
|
-
* Converts string to array format if needed
|
|
1339
|
-
* @param sys - System prompt (string or array of blocks)
|
|
1340
|
-
* @returns Normalized system prompt for Anthropic API
|
|
1358
|
+
* Check if the buffer has a callback configured
|
|
1341
1359
|
*/
|
|
1342
|
-
|
|
1360
|
+
hasCallback(): boolean;
|
|
1343
1361
|
/**
|
|
1344
|
-
*
|
|
1345
|
-
* Shows cache hits, costs, and savings
|
|
1362
|
+
* Get all text that has been written (including already flushed)
|
|
1346
1363
|
*/
|
|
1347
|
-
|
|
1364
|
+
getFullText(): string;
|
|
1348
1365
|
/**
|
|
1349
|
-
*
|
|
1350
|
-
*
|
|
1351
|
-
*
|
|
1366
|
+
* Write a chunk to the buffer
|
|
1367
|
+
* Large chunks or chunks with newlines are flushed immediately
|
|
1368
|
+
* Small chunks are batched and flushed after a short interval
|
|
1352
1369
|
*
|
|
1353
|
-
* @
|
|
1354
|
-
* "anthropic/claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"]
|
|
1355
|
-
* "groq/openai/gpt-oss-120b" → ["groq", "openai/gpt-oss-120b"]
|
|
1356
|
-
* "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
|
|
1370
|
+
* @param chunk - Text chunk to write
|
|
1357
1371
|
*/
|
|
1358
|
-
|
|
1359
|
-
private static _anthropicText;
|
|
1360
|
-
private static _anthropicStream;
|
|
1361
|
-
private static _anthropicStreamWithTools;
|
|
1362
|
-
private static _groqText;
|
|
1363
|
-
private static _groqStream;
|
|
1364
|
-
private static _geminiText;
|
|
1365
|
-
private static _geminiStream;
|
|
1372
|
+
write(chunk: string): void;
|
|
1366
1373
|
/**
|
|
1367
|
-
*
|
|
1368
|
-
*
|
|
1374
|
+
* Flush the buffer immediately
|
|
1375
|
+
* Call this before tool execution or other operations that need clean output
|
|
1369
1376
|
*/
|
|
1370
|
-
|
|
1371
|
-
private static _geminiStreamWithTools;
|
|
1372
|
-
private static _openaiText;
|
|
1373
|
-
private static _openaiStream;
|
|
1374
|
-
private static _openaiStreamWithTools;
|
|
1377
|
+
flush(): void;
|
|
1375
1378
|
/**
|
|
1376
|
-
*
|
|
1377
|
-
* Enhanced version with jsonrepair to handle malformed JSON from LLMs
|
|
1378
|
-
* @param text - Text that may contain JSON wrapped in ```json...``` or with surrounding text
|
|
1379
|
-
* @returns Parsed JSON object or array
|
|
1379
|
+
* Internal flush implementation
|
|
1380
1380
|
*/
|
|
1381
|
-
private
|
|
1381
|
+
private flushNow;
|
|
1382
|
+
/**
|
|
1383
|
+
* Clean up resources
|
|
1384
|
+
* Call this when done with the buffer
|
|
1385
|
+
*/
|
|
1386
|
+
dispose(): void;
|
|
1382
1387
|
}
|
|
1383
1388
|
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1389
|
+
/**
|
|
1390
|
+
* ToolExecutorService - Handles execution of SQL queries and external tools
|
|
1391
|
+
* Extracted from BaseLLM.generateTextResponse for better separation of concerns
|
|
1392
|
+
*/
|
|
1393
|
+
|
|
1394
|
+
/**
|
|
1395
|
+
* External tool definition
|
|
1396
|
+
*/
|
|
1397
|
+
interface ExternalTool {
|
|
1398
|
+
id: string;
|
|
1399
|
+
name: string;
|
|
1400
|
+
description?: string;
|
|
1401
|
+
/** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
|
|
1402
|
+
toolType?: 'source' | 'direct';
|
|
1403
|
+
/** Full untruncated schema for source agent (all columns visible) */
|
|
1404
|
+
fullSchema?: string;
|
|
1405
|
+
/** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
|
|
1406
|
+
schemaTier?: string;
|
|
1407
|
+
/** Schema search function for very_large tier — keyword search over entities */
|
|
1408
|
+
schemaSearchFn?: (keywords: string[]) => string;
|
|
1409
|
+
fn: (input: any) => Promise<any>;
|
|
1410
|
+
limit?: number;
|
|
1411
|
+
outputSchema?: any;
|
|
1412
|
+
executionType?: 'immediate' | 'deferred';
|
|
1413
|
+
userProvidedData?: any;
|
|
1414
|
+
params?: Record<string, any>;
|
|
1390
1415
|
}
|
|
1391
1416
|
/**
|
|
1392
|
-
*
|
|
1393
|
-
* and sends them to runtime via ui_logs message with uiBlockId as the message id
|
|
1394
|
-
* Logs are sent in real-time for streaming effect in the UI
|
|
1395
|
-
* Respects the global log level configuration
|
|
1417
|
+
* Executed tool tracking info
|
|
1396
1418
|
*/
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
* Only logs that pass the log level filter are captured and sent
|
|
1415
|
-
*/
|
|
1416
|
-
private addLog;
|
|
1417
|
-
/**
|
|
1418
|
-
* Send a single log to runtime immediately
|
|
1419
|
-
*/
|
|
1420
|
-
private sendLogImmediately;
|
|
1421
|
-
/**
|
|
1422
|
-
* Log info message
|
|
1423
|
-
*/
|
|
1424
|
-
info(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
|
|
1425
|
-
/**
|
|
1426
|
-
* Log error message
|
|
1427
|
-
*/
|
|
1428
|
-
error(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
|
|
1429
|
-
/**
|
|
1430
|
-
* Log warning message
|
|
1431
|
-
*/
|
|
1432
|
-
warn(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
|
|
1433
|
-
/**
|
|
1434
|
-
* Log debug message
|
|
1435
|
-
*/
|
|
1436
|
-
debug(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
|
|
1437
|
-
/**
|
|
1438
|
-
* Log LLM explanation with typed metadata
|
|
1439
|
-
*/
|
|
1440
|
-
logExplanation(message: string, explanation: string, data?: Record<string, any>): void;
|
|
1441
|
-
/**
|
|
1442
|
-
* Log generated query with typed metadata
|
|
1443
|
-
*/
|
|
1444
|
-
logQuery(message: string, query: string, data?: Record<string, any>): void;
|
|
1445
|
-
/**
|
|
1446
|
-
* Send all collected logs at once (optional, for final summary)
|
|
1447
|
-
*/
|
|
1448
|
-
sendAllLogs(): void;
|
|
1449
|
-
/**
|
|
1450
|
-
* Get all collected logs
|
|
1451
|
-
*/
|
|
1452
|
-
getLogs(): CapturedLog[];
|
|
1453
|
-
/**
|
|
1454
|
-
* Clear all logs
|
|
1455
|
-
*/
|
|
1456
|
-
clearLogs(): void;
|
|
1457
|
-
/**
|
|
1458
|
-
* Set uiBlockId (in case it's provided later)
|
|
1459
|
-
*/
|
|
1460
|
-
setUIBlockId(uiBlockId: string): void;
|
|
1419
|
+
interface ExecutedToolInfo {
|
|
1420
|
+
id: string;
|
|
1421
|
+
name: string;
|
|
1422
|
+
params: any;
|
|
1423
|
+
result: {
|
|
1424
|
+
_totalRecords: number;
|
|
1425
|
+
_recordsShown: number;
|
|
1426
|
+
_metadata?: any;
|
|
1427
|
+
_sampleData: any[];
|
|
1428
|
+
/** Bounded summary over the FULL fetched result (complete structure). */
|
|
1429
|
+
_summary?: any;
|
|
1430
|
+
/** Up to MAIN_AGENT_COMPLETE_ROWS rows — the complete result when small. */
|
|
1431
|
+
_mainAgentRows?: any[];
|
|
1432
|
+
};
|
|
1433
|
+
outputSchema?: any;
|
|
1434
|
+
sourceSchema?: string;
|
|
1435
|
+
sourceType?: string;
|
|
1461
1436
|
}
|
|
1462
1437
|
|
|
1463
1438
|
/**
|
|
1464
|
-
*
|
|
1439
|
+
* Multi-Agent Architecture Types
|
|
1440
|
+
*
|
|
1441
|
+
* Defines interfaces for the hierarchical agent system:
|
|
1442
|
+
* - Main Agent: ONE LLM.streamWithTools() call with source agent tools
|
|
1443
|
+
* - Source Agents: independent agents that query individual data sources
|
|
1444
|
+
*
|
|
1445
|
+
* The main agent sees only source summaries. When it calls a source tool,
|
|
1446
|
+
* the SourceAgent runs independently (own LLM, own retries) and returns clean data.
|
|
1465
1447
|
*/
|
|
1466
|
-
|
|
1448
|
+
|
|
1449
|
+
/**
|
|
1450
|
+
* Per-entity detail: name, row count, and column names.
|
|
1451
|
+
* Gives the main agent enough context to route to the right source.
|
|
1452
|
+
*/
|
|
1453
|
+
interface EntityDetail {
|
|
1454
|
+
/** Entity name (table, sheet, endpoint) */
|
|
1455
|
+
name: string;
|
|
1456
|
+
/** Approximate row count */
|
|
1457
|
+
rowCount?: number;
|
|
1458
|
+
/** Column/field names */
|
|
1459
|
+
columns: string[];
|
|
1460
|
+
/** Entity-level semantic summary (what the table means) — for main-agent routing. */
|
|
1461
|
+
summary?: string;
|
|
1462
|
+
}
|
|
1463
|
+
/**
|
|
1464
|
+
* Representation of a data source for the main agent.
|
|
1465
|
+
* Contains entity names WITH column names so the LLM can route accurately.
|
|
1466
|
+
*/
|
|
1467
|
+
interface SourceSummary {
|
|
1468
|
+
/** Source ID (matches tool ID prefix) */
|
|
1467
1469
|
id: string;
|
|
1470
|
+
/** Human-readable source name */
|
|
1468
1471
|
name: string;
|
|
1472
|
+
/** Source type: postgres, excel, rest_api, etc. */
|
|
1469
1473
|
type: string;
|
|
1470
|
-
|
|
1474
|
+
/** Brief description of what data this source contains */
|
|
1475
|
+
description: string;
|
|
1476
|
+
/** Detailed entity info with column names for routing */
|
|
1477
|
+
entityDetails: EntityDetail[];
|
|
1478
|
+
/** The tool ID associated with this source */
|
|
1479
|
+
toolId: string;
|
|
1471
1480
|
}
|
|
1472
|
-
|
|
1473
1481
|
/**
|
|
1474
|
-
*
|
|
1482
|
+
* What a source agent returns after querying its data source.
|
|
1483
|
+
* The main agent uses this to analyze and compose the final response.
|
|
1484
|
+
*/
|
|
1485
|
+
interface SourceAgentResult {
|
|
1486
|
+
/** Source ID */
|
|
1487
|
+
sourceId: string;
|
|
1488
|
+
/** Source name */
|
|
1489
|
+
sourceName: string;
|
|
1490
|
+
/** Whether the query succeeded */
|
|
1491
|
+
success: boolean;
|
|
1492
|
+
/** Result data rows */
|
|
1493
|
+
data: any[];
|
|
1494
|
+
/** Metadata about the query execution */
|
|
1495
|
+
metadata: SourceAgentMetadata;
|
|
1496
|
+
/** Tool execution info for the last successful query (backward compat) */
|
|
1497
|
+
executedTool: ExecutedToolInfo;
|
|
1498
|
+
/** All successful tool executions (primary + follow-up queries) */
|
|
1499
|
+
allExecutedTools?: ExecutedToolInfo[];
|
|
1500
|
+
/** Error message if failed */
|
|
1501
|
+
error?: string;
|
|
1502
|
+
}
|
|
1503
|
+
interface SourceAgentMetadata {
|
|
1504
|
+
/** Total rows that matched the query (before limit) */
|
|
1505
|
+
totalRowsMatched: number;
|
|
1506
|
+
/** Rows actually returned (after limit) */
|
|
1507
|
+
rowsReturned: number;
|
|
1508
|
+
/** Whether the result was truncated by the row limit */
|
|
1509
|
+
isLimited: boolean;
|
|
1510
|
+
/** The query/params that were executed */
|
|
1511
|
+
queryExecuted?: string;
|
|
1512
|
+
/** Execution time in milliseconds */
|
|
1513
|
+
executionTimeMs: number;
|
|
1514
|
+
}
|
|
1515
|
+
/**
|
|
1516
|
+
* A pre-built, multi-step UI flow registered with the SDK.
|
|
1517
|
+
*
|
|
1518
|
+
* When the main agent decides a user's question matches a workflow's whenToUse
|
|
1519
|
+
* trigger, it picks the workflow instead of running source agents / generating
|
|
1520
|
+
* dashboard components. The LLM extracts the workflow's required props from the
|
|
1521
|
+
* prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
|
|
1522
|
+
* workflow component directly — no analysis text, no chart generation. The
|
|
1523
|
+
* frontend renders the registered workflow component with the LLM-extracted
|
|
1524
|
+
* props.
|
|
1525
|
+
*/
|
|
1526
|
+
interface WorkflowDescriptor {
|
|
1527
|
+
/** Unique workflow id (used as the LLM tool name) */
|
|
1528
|
+
id: string;
|
|
1529
|
+
/** Component name on the frontend (matches the registered React component) */
|
|
1530
|
+
name: string;
|
|
1531
|
+
/** Short human-readable description of what this workflow does */
|
|
1532
|
+
description: string;
|
|
1533
|
+
/**
|
|
1534
|
+
* 1–2 sentence trigger condition. The LLM uses this to decide if the
|
|
1535
|
+
* user's prompt matches this workflow. Be specific — e.g.
|
|
1536
|
+
* "User wants to *initiate* an inventory transfer (review + submit POs),
|
|
1537
|
+
* not just see analysis or charts."
|
|
1538
|
+
*/
|
|
1539
|
+
whenToUse: string;
|
|
1540
|
+
/**
|
|
1541
|
+
* JSON-schema-style description of the props the workflow needs. Becomes
|
|
1542
|
+
* the LLM tool's input_schema, so the model fills these from the prompt.
|
|
1543
|
+
* Use the same shape as `params` on direct tools — string descriptors with
|
|
1544
|
+
* an optional "(optional)" suffix.
|
|
1545
|
+
*
|
|
1546
|
+
* Example:
|
|
1547
|
+
* ```
|
|
1548
|
+
* {
|
|
1549
|
+
* selectedStore: 'object — { id, name } of the source branch',
|
|
1550
|
+
* minROI: 'number (optional) — only show transfers with ROI ≥ this',
|
|
1551
|
+
* }
|
|
1552
|
+
* ```
|
|
1553
|
+
*/
|
|
1554
|
+
propsSchema: Record<string, string>;
|
|
1555
|
+
/**
|
|
1556
|
+
* Optional: static prop defaults merged with LLM-extracted props before
|
|
1557
|
+
* the component is returned. Useful for things like the embedded
|
|
1558
|
+
* `externalTool` config that the workflow uses to fetch its own data.
|
|
1559
|
+
*/
|
|
1560
|
+
defaultProps?: Record<string, any>;
|
|
1561
|
+
}
|
|
1562
|
+
/**
|
|
1563
|
+
* The workflow selection captured during a routing call.
|
|
1564
|
+
* Set on AgentResponse when the LLM picks a workflow tool.
|
|
1565
|
+
*/
|
|
1566
|
+
interface SelectedWorkflow {
|
|
1567
|
+
/** Component name (matches WorkflowDescriptor.name) */
|
|
1568
|
+
name: string;
|
|
1569
|
+
/** Props extracted from the prompt + merged with workflow.defaultProps */
|
|
1570
|
+
props: Record<string, any>;
|
|
1571
|
+
}
|
|
1572
|
+
/**
|
|
1573
|
+
* Set when this turn applies a user-directed edit to an existing script instead
|
|
1574
|
+
* of authoring a new one. MainAgent keeps the SAME harness (tools, loop,
|
|
1575
|
+
* write_script/execute_script verification) and swaps only the system prompt —
|
|
1576
|
+
* `agent-main-edit` instead of `agent-main`.
|
|
1577
|
+
*
|
|
1578
|
+
* The two framings contradict each other on whether to query a source first, so
|
|
1579
|
+
* they must never be resident in one rendered prompt.
|
|
1580
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § D3.
|
|
1581
|
+
*/
|
|
1582
|
+
interface EditContext {
|
|
1583
|
+
/** Recipe being edited — the shadow draft records it as parentId. */
|
|
1584
|
+
recipeId: string;
|
|
1585
|
+
parentName: string;
|
|
1586
|
+
parentBody: string;
|
|
1587
|
+
/** Self-contained restatement of the change (from the matcher). */
|
|
1588
|
+
instruction: string;
|
|
1589
|
+
/** Columns the last run returned — grounds the edit without a re-query. */
|
|
1590
|
+
lastResultColumns?: string[];
|
|
1591
|
+
/** Rendered parameter list of the parent, for the prompt. */
|
|
1592
|
+
parentParams?: string;
|
|
1593
|
+
}
|
|
1594
|
+
/**
|
|
1595
|
+
* The complete response from the multi-agent system.
|
|
1596
|
+
* Contains everything needed for text display + component generation.
|
|
1597
|
+
*/
|
|
1598
|
+
interface AgentResponse {
|
|
1599
|
+
/** Generated text response (analysis of the data) */
|
|
1600
|
+
text: string;
|
|
1601
|
+
/** All executed tools across all source agents (for component generation) */
|
|
1602
|
+
executedTools: ExecutedToolInfo[];
|
|
1603
|
+
/** Individual results from each source agent */
|
|
1604
|
+
sourceResults: SourceAgentResult[];
|
|
1605
|
+
/**
|
|
1606
|
+
* Populated when MainAgent wrote AND successfully executed a script during its turn.
|
|
1607
|
+
* Caller (agent-user-response.ts) persists it via ScriptStore.save().
|
|
1608
|
+
* Absent when MainAgent didn't write one (trivial question / all attempts failed).
|
|
1609
|
+
*/
|
|
1610
|
+
savedScript?: AgentWrittenScript;
|
|
1611
|
+
/**
|
|
1612
|
+
* Set when the LLM routed the question to a registered workflow component.
|
|
1613
|
+
* When present, the upstream caller should skip component generation and
|
|
1614
|
+
* return this workflow as the response.
|
|
1615
|
+
*/
|
|
1616
|
+
workflow?: SelectedWorkflow;
|
|
1617
|
+
}
|
|
1618
|
+
/**
|
|
1619
|
+
* A script MainAgent authored + verified during its turn. Shape aligns with
|
|
1620
|
+
* what ScriptStore.save() needs — minus store-assigned fields (id, timestamps, counts).
|
|
1621
|
+
*/
|
|
1622
|
+
interface AgentWrittenScript {
|
|
1623
|
+
/**
|
|
1624
|
+
* `ScriptRecipe.id` of the draft that was authored + verified during this turn.
|
|
1625
|
+
* The caller passes this to `ScriptStore.promoteToVerified(recipeId, …)` to
|
|
1626
|
+
* flip the draft to verified status and (when possible) drop the turn-suffix
|
|
1627
|
+
* from its filename.
|
|
1628
|
+
*/
|
|
1629
|
+
recipeId: string;
|
|
1630
|
+
name: string;
|
|
1631
|
+
intentDescription: string;
|
|
1632
|
+
tags: string[];
|
|
1633
|
+
parameters: Array<{
|
|
1634
|
+
name: string;
|
|
1635
|
+
type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
|
|
1636
|
+
required: boolean;
|
|
1637
|
+
default?: any;
|
|
1638
|
+
enumValues?: Record<string, string>;
|
|
1639
|
+
description: string;
|
|
1640
|
+
}>;
|
|
1641
|
+
scriptBody: string;
|
|
1642
|
+
/** Source IDs referenced by the script (extracted from ctx.query calls) */
|
|
1643
|
+
sourceIds: string[];
|
|
1644
|
+
/** Tables referenced in the script's SQL (regex-extracted) */
|
|
1645
|
+
tables: string[];
|
|
1646
|
+
/** Executed queries from the verified run — fed to component generation */
|
|
1647
|
+
executedQueries: Array<{
|
|
1648
|
+
sourceId: string;
|
|
1649
|
+
sourceName: string;
|
|
1650
|
+
sql: string;
|
|
1651
|
+
data: any[];
|
|
1652
|
+
count: number;
|
|
1653
|
+
totalCount?: number;
|
|
1654
|
+
executionTimeMs: number;
|
|
1655
|
+
/**
|
|
1656
|
+
* True for synthetic entries (ctx.emit datasets, the computed:_final
|
|
1657
|
+
* post-JS data). The component generator routes virtual sources through
|
|
1658
|
+
* the script_dataset sentinel toolId so the frontend resolves them via
|
|
1659
|
+
* queryCache instead of attempting to re-execute SQL.
|
|
1660
|
+
*/
|
|
1661
|
+
virtual?: boolean;
|
|
1662
|
+
}>;
|
|
1663
|
+
}
|
|
1664
|
+
/**
|
|
1665
|
+
* Configuration for the multi-agent system.
|
|
1666
|
+
* Controls limits, models, and behavior.
|
|
1667
|
+
*/
|
|
1668
|
+
interface AgentConfig {
|
|
1669
|
+
/** Max rows shown to the UI preview / inlined per source (default: 10) */
|
|
1670
|
+
maxRowsPerSource: number;
|
|
1671
|
+
/**
|
|
1672
|
+
* Max rows a source query may FETCH from the DB server-side (default: 2000).
|
|
1673
|
+
* Decoupled from what the main agent is shown: the full result is fetched and
|
|
1674
|
+
* summarized (bounded), but only a small/complete slice enters LLM context.
|
|
1675
|
+
* This lets small lookups (benchmark maps) arrive COMPLETE without letting
|
|
1676
|
+
* large results blow up context.
|
|
1677
|
+
*/
|
|
1678
|
+
maxRowsFetched: number;
|
|
1679
|
+
/** Model for the main agent (routing + analysis in one LLM call) */
|
|
1680
|
+
mainAgentModel: string;
|
|
1681
|
+
/** Model for source agent query generation */
|
|
1682
|
+
sourceAgentModel: string;
|
|
1683
|
+
/** API key for LLM calls */
|
|
1684
|
+
apiKey?: string;
|
|
1685
|
+
/** Max retry attempts per source agent */
|
|
1686
|
+
maxRetries: number;
|
|
1687
|
+
/** Max tool calling iterations for the main agent loop */
|
|
1688
|
+
maxIterations: number;
|
|
1689
|
+
/** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
|
|
1690
|
+
globalKnowledgeBase?: string;
|
|
1691
|
+
/** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
|
|
1692
|
+
knowledgeBaseContext?: string;
|
|
1693
|
+
/** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
|
|
1694
|
+
collections?: any;
|
|
1695
|
+
/** Optional project ID for scoping embedding searches */
|
|
1696
|
+
projectId?: string;
|
|
1697
|
+
}
|
|
1698
|
+
/**
|
|
1699
|
+
* Default agent configuration
|
|
1700
|
+
*/
|
|
1701
|
+
declare const DEFAULT_AGENT_CONFIG: AgentConfig;
|
|
1702
|
+
|
|
1703
|
+
/**
|
|
1704
|
+
* Script Flow Types
|
|
1705
|
+
*
|
|
1706
|
+
* Defines interfaces for the script-based query architecture:
|
|
1707
|
+
* - ScriptRecipe: metadata for matching, validation, and quality tracking
|
|
1708
|
+
* - ScriptResult: output from executing a script
|
|
1709
|
+
* - ScriptMatch: result from the LLM-based script matcher
|
|
1710
|
+
*/
|
|
1711
|
+
/**
|
|
1712
|
+
* Recipe metadata stored alongside each script.
|
|
1713
|
+
* Used for matching, validation, and quality tracking.
|
|
1714
|
+
*/
|
|
1715
|
+
interface ScriptRecipe {
|
|
1716
|
+
/** Unique script identifier */
|
|
1717
|
+
id: string;
|
|
1718
|
+
/** Version number (incremented on regeneration) */
|
|
1719
|
+
version: number;
|
|
1720
|
+
/** Human-readable name (e.g., "Revenue by Dimension") */
|
|
1721
|
+
name: string;
|
|
1722
|
+
/** Natural language description of what this script does */
|
|
1723
|
+
intentDescription: string;
|
|
1724
|
+
/** Keyword tags for quick filtering */
|
|
1725
|
+
tags: string[];
|
|
1726
|
+
/** Source tool IDs this script queries (e.g., ["mssql-abc123_query"]) */
|
|
1727
|
+
sourceIds: string[];
|
|
1728
|
+
/** Table names used (for future schema drift detection) */
|
|
1729
|
+
tables: string[];
|
|
1730
|
+
/** Parameter definitions — what can vary */
|
|
1731
|
+
parameters: ScriptParameter[];
|
|
1732
|
+
/** The script function body as a string. Loaded from disk (scripts-store/<fileBase>.ts). */
|
|
1733
|
+
scriptBody: string;
|
|
1734
|
+
/**
|
|
1735
|
+
* On-disk filename stem for the body: scripts-store/<fileBase>.ts.
|
|
1736
|
+
* Editable in the IDE. Decided at authoring time (slug of `name`, with a
|
|
1737
|
+
* short id suffix on collision) and stable across promotion.
|
|
1738
|
+
*/
|
|
1739
|
+
fileBase?: string;
|
|
1740
|
+
/** sha256 of the on-disk body — lets the runtime detect manual edits. */
|
|
1741
|
+
bodyHash?: string;
|
|
1742
|
+
/** Project scope (single-VM deployments may leave this undefined). */
|
|
1743
|
+
projectId?: string;
|
|
1744
|
+
/** Times this script was used successfully */
|
|
1745
|
+
successCount: number;
|
|
1746
|
+
/** Times this script failed */
|
|
1747
|
+
failureCount: number;
|
|
1748
|
+
/** ISO timestamp of last usage */
|
|
1749
|
+
lastUsed: string;
|
|
1750
|
+
/** Original user question that created this script */
|
|
1751
|
+
createdFrom: string;
|
|
1752
|
+
/** ISO timestamp */
|
|
1753
|
+
createdAt: string;
|
|
1754
|
+
/** ISO timestamp */
|
|
1755
|
+
updatedAt: string;
|
|
1756
|
+
/**
|
|
1757
|
+
* `recipe.id` of the parent this script was forked from.
|
|
1758
|
+
* Undefined for root scripts (those written from scratch by MainAgent).
|
|
1759
|
+
* See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md.
|
|
1760
|
+
*/
|
|
1761
|
+
parentId?: string;
|
|
1762
|
+
/** 0 for root scripts; `parent.forkDepth + 1` for forks. Capped at 3. */
|
|
1763
|
+
forkDepth?: number;
|
|
1764
|
+
/**
|
|
1765
|
+
* Brief description of what this fork changed vs its parent
|
|
1766
|
+
* (sourced from the matcher's `modificationHint`).
|
|
1767
|
+
*/
|
|
1768
|
+
forkReason?: string;
|
|
1769
|
+
/**
|
|
1770
|
+
* Validated component specs captured at authoring time. On a tier-high
|
|
1771
|
+
* replay these are rebound to fresh queryIds deterministically — no
|
|
1772
|
+
* component-generation LLM call, and the rendered columns can't drift from
|
|
1773
|
+
* what was validated when the script was authored. Absent on recipes
|
|
1774
|
+
* authored before this landed; those fall back to LLM component generation.
|
|
1775
|
+
* See backend/docs/SCRIPT-COMPONENT-CONSISTENCY.md.
|
|
1776
|
+
*/
|
|
1777
|
+
components?: ScriptComponentSpec[];
|
|
1778
|
+
/**
|
|
1779
|
+
* What the user explicitly asked the output to LOOK like, set by a display
|
|
1780
|
+
* edit ("show that as a bar chart", "make the bars horizontal").
|
|
1781
|
+
*
|
|
1782
|
+
* Deliberately SEPARATE from `components`. Those are validated bindings that
|
|
1783
|
+
* must be cleared on a data edit — after "break it down by brand" the axis
|
|
1784
|
+
* keys are wrong, and after "use the mode" the stored title still says
|
|
1785
|
+
* "Average…". A rendering CHOICE, by contrast, is still valid afterwards.
|
|
1786
|
+
* Keeping them in one field meant every data edit silently discarded the
|
|
1787
|
+
* user's chart type.
|
|
1788
|
+
*
|
|
1789
|
+
* Fed to the component generator as a hint whenever specs are (re)generated,
|
|
1790
|
+
* so the chosen rendering comes back even after the SQL changes.
|
|
1791
|
+
*/
|
|
1792
|
+
displayPreference?: ScriptDisplayPreference;
|
|
1793
|
+
/**
|
|
1794
|
+
* Lifecycle stage of this recipe on disk.
|
|
1795
|
+
* - 'draft': written by MainAgent's write_script during a turn; filtered out
|
|
1796
|
+
* of FTS results (status='verified' only) so the matcher never picks it.
|
|
1797
|
+
* Filename is suffixed with `turnId` to keep concurrent turns
|
|
1798
|
+
* from clobbering each other's drafts.
|
|
1799
|
+
* - 'verified': promoted after `execute_script` succeeded; the matcher sees it.
|
|
1800
|
+
* Filename drops the turn suffix unless a verified file with
|
|
1801
|
+
* the same slug already exists (collision case keeps the suffix).
|
|
1802
|
+
*
|
|
1803
|
+
* Recipes loaded from disk without this field default to 'verified' so
|
|
1804
|
+
* existing scripts keep working unchanged.
|
|
1805
|
+
*/
|
|
1806
|
+
status?: 'draft' | 'verified';
|
|
1807
|
+
/**
|
|
1808
|
+
* Per-turn unique suffix used for draft filenames (e.g. `1714745623-x9k2`).
|
|
1809
|
+
* Set when the draft is saved; carried until the recipe is promoted.
|
|
1810
|
+
*/
|
|
1811
|
+
turnId?: string;
|
|
1812
|
+
/**
|
|
1813
|
+
* Last execution error captured by `recordDraftError` while the recipe was
|
|
1814
|
+
* still a draft. Lets users open the draft .json file and see why it failed
|
|
1815
|
+
* without grepping logs. Cleared on promotion to 'verified'.
|
|
1816
|
+
*/
|
|
1817
|
+
lastError?: {
|
|
1818
|
+
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
1819
|
+
message: string;
|
|
1820
|
+
at: string;
|
|
1821
|
+
attempt: number;
|
|
1822
|
+
};
|
|
1823
|
+
/** userId who committed the most recent edit (audit trail — recipes are project-scoped). */
|
|
1824
|
+
editedBy?: string;
|
|
1825
|
+
/** The instruction that produced the current version. */
|
|
1826
|
+
editedFrom?: string;
|
|
1827
|
+
/**
|
|
1828
|
+
* Prior versions, newest last. The body itself is archived on disk as
|
|
1829
|
+
* `<fileBase>.v<version>.ts`; this records what changed and who did it.
|
|
1830
|
+
*/
|
|
1831
|
+
history?: ScriptVersionRecord[];
|
|
1832
|
+
}
|
|
1833
|
+
/**
|
|
1834
|
+
* A durable, user-stated rendering choice for a recipe. Survives data edits.
|
|
1835
|
+
*/
|
|
1836
|
+
interface ScriptDisplayPreference {
|
|
1837
|
+
/** Component types the user's chosen rendering resolved to, e.g. ["DynamicBarChart"]. */
|
|
1838
|
+
componentTypes: string[];
|
|
1839
|
+
/** The instruction itself — carries nuance the types can't ("horizontal", "sorted descending"). */
|
|
1840
|
+
instruction: string;
|
|
1841
|
+
/** ISO timestamp of the display edit that set this. */
|
|
1842
|
+
at: string;
|
|
1843
|
+
}
|
|
1844
|
+
/** One superseded version of a recipe body (see ScriptStore.commitEdit). */
|
|
1845
|
+
interface ScriptVersionRecord {
|
|
1846
|
+
/** Version number this record superseded (i.e. the OLD version). */
|
|
1847
|
+
version: number;
|
|
1848
|
+
/** ISO timestamp of the edit that superseded it. */
|
|
1849
|
+
at: string;
|
|
1850
|
+
/** userId who made the edit, when known. */
|
|
1851
|
+
by?: string;
|
|
1852
|
+
/** The edit instruction that caused the supersede. */
|
|
1853
|
+
instruction?: string;
|
|
1854
|
+
/** One-line summary of what changed, for the version picker. */
|
|
1855
|
+
changeSummary?: string;
|
|
1856
|
+
/** sha256 of the superseded body — pairs with `<fileBase>.v<version>.ts`. */
|
|
1857
|
+
bodyHash?: string;
|
|
1858
|
+
}
|
|
1859
|
+
interface ScriptParameter {
|
|
1860
|
+
/** Parameter name (used in script body as params.name) */
|
|
1861
|
+
name: string;
|
|
1862
|
+
/** Parameter type */
|
|
1863
|
+
type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
|
|
1864
|
+
/** Whether this parameter is required */
|
|
1865
|
+
required: boolean;
|
|
1866
|
+
/** Default value if not provided */
|
|
1867
|
+
default?: any;
|
|
1868
|
+
/** For enum type — maps user-facing values to internal values */
|
|
1869
|
+
enumValues?: Record<string, string>;
|
|
1870
|
+
/** Human-readable description (used in the matcher LLM prompt) */
|
|
1871
|
+
description: string;
|
|
1872
|
+
}
|
|
1873
|
+
/**
|
|
1874
|
+
* A reusable component binding captured when a script is authored. Stored on
|
|
1875
|
+
* the recipe so tier-high replays rebuild components deterministically (rebind
|
|
1876
|
+
* to fresh queryIds) instead of re-running the component-picker LLM.
|
|
1877
|
+
*/
|
|
1878
|
+
interface ScriptComponentSpec {
|
|
1879
|
+
/** Registered component name (e.g. "DynamicBarChart") — matched against the available component library. */
|
|
1880
|
+
componentType: string;
|
|
1881
|
+
/** `executedQuery.sourceId` to bind to (e.g. a tool id or 'computed:_final'), 'federation' for a cross-source component, or 'markdown' for a content-only narrative block (no data source). */
|
|
1882
|
+
sourceRef: string;
|
|
1883
|
+
/** Present only when sourceRef === 'federation' — the DuckDB SQL to re-execute on replay. */
|
|
1884
|
+
federationSql?: string;
|
|
1885
|
+
/** Present only when sourceRef === 'markdown' — the narrative text to render on replay (markdown has no data source, so its content must be persisted). */
|
|
1886
|
+
content?: string;
|
|
1887
|
+
title?: string;
|
|
1888
|
+
description?: string;
|
|
1889
|
+
/** Validated axis/value keys + aggregation — all referencing real columns of the bound source. */
|
|
1890
|
+
config: Record<string, any>;
|
|
1891
|
+
}
|
|
1892
|
+
/**
|
|
1893
|
+
* Result from executing a script via ScriptRunner.
|
|
1894
|
+
*/
|
|
1895
|
+
interface ScriptResult {
|
|
1896
|
+
/** Whether the script executed successfully */
|
|
1897
|
+
success: boolean;
|
|
1898
|
+
/** Combined data from all queries */
|
|
1899
|
+
data: any[];
|
|
1900
|
+
/** Individual query results tracked during execution */
|
|
1901
|
+
executedQueries: ScriptQueryResult[];
|
|
1902
|
+
/** Error message if failed */
|
|
1903
|
+
error?: string;
|
|
1904
|
+
/**
|
|
1905
|
+
* Where in the lifecycle the error occurred. Lets MainAgent's fix-loop
|
|
1906
|
+
* decide between "rewrite the whole draft" (compile) and "patch the
|
|
1907
|
+
* specific line" (runtime).
|
|
1908
|
+
*/
|
|
1909
|
+
errorPhase?: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
1910
|
+
/** Total execution time in milliseconds */
|
|
1911
|
+
executionTimeMs: number;
|
|
1912
|
+
}
|
|
1913
|
+
/**
|
|
1914
|
+
* A single query executed during script runtime.
|
|
1915
|
+
* Tracked by ScriptContext for component generation and debugging.
|
|
1916
|
+
*/
|
|
1917
|
+
interface ScriptQueryResult {
|
|
1918
|
+
/** Source tool ID */
|
|
1919
|
+
sourceId: string;
|
|
1920
|
+
/** Human-readable source name */
|
|
1921
|
+
sourceName: string;
|
|
1922
|
+
/** The SQL that was executed */
|
|
1923
|
+
sql: string;
|
|
1924
|
+
/** Result data rows */
|
|
1925
|
+
data: any[];
|
|
1926
|
+
/** Number of rows returned */
|
|
1927
|
+
count: number;
|
|
1928
|
+
/** Total rows that matched before limit (if available) */
|
|
1929
|
+
totalCount?: number;
|
|
1930
|
+
/** Query execution time in milliseconds */
|
|
1931
|
+
executionTimeMs: number;
|
|
1932
|
+
/**
|
|
1933
|
+
* True for rows that did NOT come from a real SQL execution — either a
|
|
1934
|
+
* ctx.emit() dataset or the synthesized "computed:_final" entry that
|
|
1935
|
+
* carries the script's post-JS returned data. The component generator
|
|
1936
|
+
* uses this to route the resulting component through the script_dataset
|
|
1937
|
+
* sentinel toolId so the frontend resolves it via the queryCache short-circuit.
|
|
1938
|
+
*/
|
|
1939
|
+
virtual?: boolean;
|
|
1940
|
+
}
|
|
1941
|
+
/**
|
|
1942
|
+
* Match tier returned by the LLM script matcher.
|
|
1943
|
+
*
|
|
1944
|
+
* - 'high': the script answers the question directly; only parameter values
|
|
1945
|
+
* may differ. The runtime replays it with extracted params (cheapest path).
|
|
1946
|
+
* - 'near': the script answers a STRUCTURALLY similar question but needs
|
|
1947
|
+
* body modification (different metric, dimension, table, filter shape).
|
|
1948
|
+
* The runtime forks the parent and adapts the body via MainAgent's normal
|
|
1949
|
+
* write_script + execute_script loop — no SourceAgent dispatch needed.
|
|
1950
|
+
* See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md for the full design.
|
|
1951
|
+
* - 'edit': the user is INSTRUCTING a change to the script that produced the
|
|
1952
|
+
* previous answer (not asking a new question). Only reachable when the turn
|
|
1953
|
+
* carries a ScriptBinding — without one the matcher coerces it to 'none', so
|
|
1954
|
+
* a prompt regression can't turn this into a loose similarity path. The
|
|
1955
|
+
* runtime runs MainAgent in edit mode and commits the result in place.
|
|
1956
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md.
|
|
1957
|
+
* - 'none': no script is relevant; full agent flow runs.
|
|
1958
|
+
*/
|
|
1959
|
+
type MatchTier = 'high' | 'near' | 'edit' | 'none';
|
|
1960
|
+
/**
|
|
1961
|
+
* Which recipe produced the answer the user is currently looking at.
|
|
1962
|
+
*
|
|
1963
|
+
* Set whenever a turn's answer came from a script (replay, fresh authoring, or
|
|
1964
|
+
* a committed edit) and carried on the UIBlock + saved conversation row. Two
|
|
1965
|
+
* consumers:
|
|
1966
|
+
* 1. The matcher — the 'edit' tier is ONLY reachable when a binding exists, so
|
|
1967
|
+
* "use mode instead of mean" resolves to a concrete script instead of being
|
|
1968
|
+
* matched on keywords it shares with no script name.
|
|
1969
|
+
* 2. Cache invalidation — after an edit commits, conversations bound to that
|
|
1970
|
+
* recipeId must be dropped, or the exact-match cache replays the pre-edit
|
|
1971
|
+
* answer and the edit looks like a no-op.
|
|
1972
|
+
*
|
|
1973
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
1974
|
+
*/
|
|
1975
|
+
interface ScriptBinding {
|
|
1976
|
+
recipeId: string;
|
|
1977
|
+
/** Params the script ran with — the edit's starting point. */
|
|
1978
|
+
params: Record<string, any>;
|
|
1979
|
+
/** Recipe name at bind time (matcher catalog + user-facing confirmation). */
|
|
1980
|
+
name: string;
|
|
1981
|
+
/** Columns the last run returned — grounds the editor without a re-query. */
|
|
1982
|
+
columns?: string[];
|
|
1983
|
+
/**
|
|
1984
|
+
* The question that produced this answer. Required for disambiguation when a
|
|
1985
|
+
* thread ran several scripts — without it the candidates are just names and
|
|
1986
|
+
* the matcher cannot resolve "use the mode for the WSP one".
|
|
1987
|
+
*/
|
|
1988
|
+
userPrompt?: string;
|
|
1989
|
+
}
|
|
1990
|
+
/**
|
|
1991
|
+
* Result from the LLM-based script matcher.
|
|
1992
|
+
*
|
|
1993
|
+
* For `tier: 'high'`, `extractedParams` carries the values to pass to the
|
|
1994
|
+
* existing script. For `tier: 'near'`, `gaps` and `modificationHint` describe
|
|
1995
|
+
* what the fork-author needs to change in the parent body.
|
|
1996
|
+
*/
|
|
1997
|
+
interface ScriptMatch {
|
|
1998
|
+
/** The matched script recipe */
|
|
1999
|
+
recipe: ScriptRecipe;
|
|
2000
|
+
/** Match tier — see MatchTier docs */
|
|
2001
|
+
tier: MatchTier;
|
|
2002
|
+
/** Similarity score (0-1, derived from LLM tier) */
|
|
2003
|
+
similarity: number;
|
|
2004
|
+
/**
|
|
2005
|
+
* Legacy confidence level. Mirrors `tier === 'high'`/`'near'` for now;
|
|
2006
|
+
* kept so existing callers compile while we migrate to tier-based logic.
|
|
2007
|
+
*/
|
|
2008
|
+
confidence: 'high' | 'medium';
|
|
2009
|
+
/** Parameters extracted from the user question by the LLM (tier='high') */
|
|
2010
|
+
extractedParams?: Record<string, any>;
|
|
2011
|
+
/** What the user question needs that the parent doesn't cover (tier='near') */
|
|
2012
|
+
gaps?: string[];
|
|
2013
|
+
/** One-sentence description of the change the fork-author should make (tier='near') */
|
|
2014
|
+
modificationHint?: string;
|
|
2015
|
+
/**
|
|
2016
|
+
* Which HALF of the recipe the edit targets (tier='edit'). A recipe has two
|
|
2017
|
+
* independently editable halves:
|
|
2018
|
+
* - 'data' — the scriptBody: how the rows are produced (aggregation,
|
|
2019
|
+
* filters, joins, grouping). Runs MainAgent in edit mode.
|
|
2020
|
+
* - 'display' — the component specs: how those SAME rows are shown (chart
|
|
2021
|
+
* type, orientation, columns, labels). Replays the proven SQL
|
|
2022
|
+
* and regenerates the specs — never authors a script.
|
|
2023
|
+
* Defaults to 'data' when the matcher omits it.
|
|
2024
|
+
*/
|
|
2025
|
+
editTarget?: 'data' | 'display';
|
|
2026
|
+
/**
|
|
2027
|
+
* Self-contained restatement of the change the user asked for (tier='edit').
|
|
2028
|
+
* MUST have pronouns/deixis resolved ("this", "it", "that column") — the edit
|
|
2029
|
+
* prompt never sees the conversation history, so an unresolved instruction is
|
|
2030
|
+
* unusable downstream.
|
|
2031
|
+
*/
|
|
2032
|
+
editInstruction?: string;
|
|
2033
|
+
/** Why the matcher made this choice (for logs and telemetry) */
|
|
2034
|
+
reasoning?: string;
|
|
2035
|
+
}
|
|
2036
|
+
|
|
2037
|
+
/**
|
|
2038
|
+
* ScriptRecipeStore — injected metadata backend for the script flow.
|
|
2039
|
+
*
|
|
2040
|
+
* The SDK is standalone (no DB dependency). The backend implements this
|
|
2041
|
+
* interface over Postgres (full-text search + atomic counters) and injects it
|
|
2042
|
+
* via `collections['script-recipes']`, exactly like `collections['source-embeddings']`.
|
|
2043
|
+
* `ScriptStore` consumes it for all METADATA operations while keeping the
|
|
2044
|
+
* executable body on disk as scripts-store/<fileBase>.ts.
|
|
2045
|
+
*
|
|
2046
|
+
* All metadata rows are plain JSON (no scriptBody — that lives on disk).
|
|
2047
|
+
* See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md (#1, #3, #7).
|
|
2048
|
+
*/
|
|
2049
|
+
|
|
2050
|
+
/** One recipe's metadata as stored in Postgres (mirrors the script_recipes table). */
|
|
2051
|
+
interface ScriptRecipeMetaRow {
|
|
2052
|
+
id: string;
|
|
2053
|
+
projectId?: string | null;
|
|
2054
|
+
version: number;
|
|
2055
|
+
name: string;
|
|
2056
|
+
intentDescription: string;
|
|
2057
|
+
tags: string[] | null;
|
|
2058
|
+
createdFrom: string | null;
|
|
2059
|
+
sourceIds: string[] | null;
|
|
2060
|
+
tables: string[] | null;
|
|
2061
|
+
parameters: ScriptParameter[] | null;
|
|
2062
|
+
components?: ScriptComponentSpec[] | null;
|
|
2063
|
+
displayPreference?: ScriptDisplayPreference | null;
|
|
2064
|
+
fileBase: string;
|
|
2065
|
+
bodyHash?: string | null;
|
|
2066
|
+
successCount: number;
|
|
2067
|
+
failureCount: number;
|
|
2068
|
+
lastUsed: string | null;
|
|
2069
|
+
parentId?: string | null;
|
|
2070
|
+
forkDepth?: number | null;
|
|
2071
|
+
forkReason?: string | null;
|
|
2072
|
+
status: 'draft' | 'verified' | string;
|
|
2073
|
+
turnId?: string | null;
|
|
2074
|
+
editedBy?: string | null;
|
|
2075
|
+
editedFrom?: string | null;
|
|
2076
|
+
history?: ScriptVersionRecord[] | null;
|
|
2077
|
+
lastError?: {
|
|
2078
|
+
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
2079
|
+
message: string;
|
|
2080
|
+
at: string;
|
|
2081
|
+
attempt: number;
|
|
2082
|
+
} | null;
|
|
2083
|
+
createdAt?: string | null;
|
|
2084
|
+
updatedAt?: string | null;
|
|
2085
|
+
}
|
|
2086
|
+
interface ScriptRecipeStore {
|
|
2087
|
+
/** FTS shortlist of healthy verified recipes for the matcher (metadata only). */
|
|
2088
|
+
search(params: {
|
|
2089
|
+
prompt: string;
|
|
2090
|
+
projectId?: string;
|
|
2091
|
+
limit?: number;
|
|
2092
|
+
}): Promise<ScriptRecipeMetaRow[]>;
|
|
2093
|
+
/** Fetch one recipe by id (any status). */
|
|
2094
|
+
getById(id: string): Promise<ScriptRecipeMetaRow | null>;
|
|
2095
|
+
/** Count healthy verified recipes (drives the "any scripts?" gate). */
|
|
2096
|
+
count(params?: {
|
|
2097
|
+
projectId?: string;
|
|
2098
|
+
}): Promise<number>;
|
|
2099
|
+
/** Insert or update a recipe row (keyed by id). */
|
|
2100
|
+
upsert(row: ScriptRecipeMetaRow): Promise<void>;
|
|
2101
|
+
/** Atomically bump counters / last-used. */
|
|
2102
|
+
updateStats(id: string, patch: {
|
|
2103
|
+
successDelta?: number;
|
|
2104
|
+
failureDelta?: number;
|
|
2105
|
+
lastUsed?: string;
|
|
2106
|
+
}): Promise<void>;
|
|
2107
|
+
/** Flip a draft to verified, applying provenance + optional fork lineage. */
|
|
2108
|
+
promote(id: string, patch: {
|
|
2109
|
+
sourceIds: string[];
|
|
2110
|
+
tables: string[];
|
|
2111
|
+
fileBase?: string;
|
|
2112
|
+
parentId?: string;
|
|
2113
|
+
forkDepth?: number;
|
|
2114
|
+
forkReason?: string;
|
|
2115
|
+
components?: ScriptComponentSpec[];
|
|
2116
|
+
}): Promise<ScriptRecipeMetaRow | null>;
|
|
2117
|
+
/**
|
|
2118
|
+
* Commit a verified edit onto an EXISTING recipe: bump `version`, replace the
|
|
2119
|
+
* body-bearing metadata, append a history record, reset health counters, and
|
|
2120
|
+
* clear the component specs (they were validated against the old shape).
|
|
2121
|
+
* Returns the updated row, or null when the target is gone.
|
|
2122
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5.
|
|
2123
|
+
*/
|
|
2124
|
+
commitEdit?(id: string, patch: {
|
|
2125
|
+
name?: string;
|
|
2126
|
+
intentDescription?: string;
|
|
2127
|
+
tags?: string[];
|
|
2128
|
+
parameters?: ScriptParameter[];
|
|
2129
|
+
bodyHash: string;
|
|
2130
|
+
/** New on-disk stem when the edit renamed the script; omitted otherwise. */
|
|
2131
|
+
fileBase?: string;
|
|
2132
|
+
sourceIds?: string[];
|
|
2133
|
+
tables?: string[];
|
|
2134
|
+
editedBy?: string;
|
|
2135
|
+
editedFrom?: string;
|
|
2136
|
+
historyEntry: {
|
|
2137
|
+
version: number;
|
|
2138
|
+
at: string;
|
|
2139
|
+
by?: string;
|
|
2140
|
+
instruction?: string;
|
|
2141
|
+
changeSummary?: string;
|
|
2142
|
+
bodyHash?: string;
|
|
2143
|
+
};
|
|
2144
|
+
}): Promise<ScriptRecipeMetaRow | null>;
|
|
2145
|
+
/** Stamp a draft's last execution error. */
|
|
2146
|
+
recordDraftError(id: string, err: {
|
|
2147
|
+
phase: string;
|
|
2148
|
+
message: string;
|
|
2149
|
+
attempt: number;
|
|
2150
|
+
at: string;
|
|
2151
|
+
}): Promise<void>;
|
|
2152
|
+
/** Delete a recipe row (body file removed separately). */
|
|
2153
|
+
remove(id: string): Promise<void>;
|
|
2154
|
+
/** True if `fileBase` is taken by a different recipe in this project. */
|
|
2155
|
+
fileBaseTaken(fileBase: string, excludeId: string, projectId?: string): Promise<boolean>;
|
|
2156
|
+
}
|
|
2157
|
+
/** Pull the injected store off the collections bag (or null if not wired). */
|
|
2158
|
+
declare function resolveScriptRecipeStore(collections: any): ScriptRecipeStore | null;
|
|
2159
|
+
|
|
2160
|
+
/**
|
|
2161
|
+
* ScriptStore — Postgres metadata + on-disk body for script recipes.
|
|
2162
|
+
*
|
|
2163
|
+
* Split of responsibilities:
|
|
2164
|
+
* - METADATA → injected `ScriptRecipeStore` (Postgres FTS + atomic counters),
|
|
2165
|
+
* resolved from `collections['script-recipes']`.
|
|
2166
|
+
* - BODY → scripts-store/<fileBase>.ts, editable in your IDE. Written
|
|
2167
|
+
* atomically (temp + rename); `bodyHash` (sha256) detects edits.
|
|
2168
|
+
*
|
|
2169
|
+
* The old "read every file every turn + send the whole catalog to the LLM"
|
|
2170
|
+
* matcher is gone — matching is `store.search(prompt)` (FTS shortlist). The
|
|
2171
|
+
* draft/verified filename dance is gone too: `status` is a DB column and the
|
|
2172
|
+
* file keeps a stable `<fileBase>.ts` name across promotion.
|
|
2173
|
+
*
|
|
2174
|
+
* When no metadata store is injected, the store degrades to a safe no-op
|
|
2175
|
+
* (count 0 → script flow disabled) instead of crashing.
|
|
2176
|
+
*
|
|
2177
|
+
* See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md.
|
|
2178
|
+
*/
|
|
2179
|
+
|
|
2180
|
+
interface SaveDraftInput {
|
|
2181
|
+
/** Reuse an existing draft (retry); omit to mint a new one. */
|
|
2182
|
+
recipeId?: string;
|
|
2183
|
+
/** Per-turn unique suffix, stable across retries within the turn. */
|
|
2184
|
+
turnId: string;
|
|
2185
|
+
name: string;
|
|
2186
|
+
intentDescription: string;
|
|
2187
|
+
tags: string[];
|
|
2188
|
+
parameters: ScriptParameter[];
|
|
2189
|
+
scriptBody: string;
|
|
2190
|
+
createdFrom: string;
|
|
2191
|
+
/**
|
|
2192
|
+
* Set when this draft is a SHADOW of an existing recipe being edited. The
|
|
2193
|
+
* draft is verified independently and merged back onto the parent via
|
|
2194
|
+
* `commitEdit`, so the working script is never clobbered by an edit that
|
|
2195
|
+
* turns out not to run. See backend/docs/SCRIPT-EDIT-DESIGN.md § D5.
|
|
2196
|
+
*/
|
|
2197
|
+
parentId?: string;
|
|
2198
|
+
}
|
|
2199
|
+
interface PromoteToVerifiedInput {
|
|
2200
|
+
sourceIds: string[];
|
|
2201
|
+
tables: string[];
|
|
2202
|
+
parentId?: string;
|
|
2203
|
+
forkDepth?: number;
|
|
2204
|
+
forkReason?: string;
|
|
2205
|
+
components?: ScriptComponentSpec[];
|
|
2206
|
+
}
|
|
2207
|
+
interface ScriptStoreOptions {
|
|
2208
|
+
/** Explicit metadata store, or resolved from `collections['script-recipes']`. */
|
|
2209
|
+
store?: ScriptRecipeStore | null;
|
|
2210
|
+
collections?: any;
|
|
2211
|
+
/** Body directory (defaults to <cwd>/scripts-store). */
|
|
2212
|
+
baseDir?: string;
|
|
2213
|
+
/** Project scope stamped on every row. */
|
|
2214
|
+
projectId?: string;
|
|
2215
|
+
}
|
|
2216
|
+
/**
|
|
2217
|
+
* Normalize a scriptBody into the on-disk form (strip a leading comment block,
|
|
2218
|
+
* ensure `export async function getData`). Exported for MainAgent.
|
|
2219
|
+
*/
|
|
2220
|
+
declare function normalizeScriptBody(scriptBody: string): string;
|
|
2221
|
+
declare class ScriptStore {
|
|
2222
|
+
private store;
|
|
2223
|
+
private storeDir;
|
|
2224
|
+
private projectId?;
|
|
2225
|
+
constructor(opts?: ScriptStoreOptions);
|
|
2226
|
+
/** Whether a metadata store is wired (matcher / authoring are gated on this). */
|
|
2227
|
+
hasStore(): boolean;
|
|
2228
|
+
/** Number of healthy verified recipes (gates the script-matching path). */
|
|
2229
|
+
count(): Promise<number>;
|
|
2230
|
+
/**
|
|
2231
|
+
* FTS shortlist for the matcher (metadata only — bodies are loaded lazily by
|
|
2232
|
+
* `get()` once the LLM picks one). Returns verified, healthy recipes ranked
|
|
2233
|
+
* by relevance.
|
|
2234
|
+
*/
|
|
2235
|
+
search(prompt: string, limit?: number): Promise<ScriptRecipe[]>;
|
|
2236
|
+
/** Fetch one recipe by id with its body loaded from disk. */
|
|
2237
|
+
get(id: string): Promise<ScriptRecipe | null>;
|
|
2238
|
+
/** Create or update a recipe (metadata upsert + body write when changed). */
|
|
2239
|
+
save(recipe: ScriptRecipe): Promise<void>;
|
|
2240
|
+
/**
|
|
2241
|
+
* Persist (or update) a draft. Within a turn, retries that pass the same
|
|
2242
|
+
* `recipeId` overwrite the same row + file; a fresh `recipeId` mints a new
|
|
2243
|
+
* draft. The body is visible at scripts-store/<fileBase>.ts immediately.
|
|
2244
|
+
*/
|
|
2245
|
+
saveDraft(input: SaveDraftInput): Promise<ScriptRecipe>;
|
|
2246
|
+
/** Stamp a draft's last execution error (metadata only). */
|
|
2247
|
+
recordDraftError(recipeId: string, err: {
|
|
2248
|
+
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
2249
|
+
message: string;
|
|
2250
|
+
attempt: number;
|
|
2251
|
+
}): Promise<void>;
|
|
2252
|
+
/**
|
|
2253
|
+
* Promote a successfully-executed draft into a verified script.
|
|
2254
|
+
* The on-disk body already exists at <fileBase>.ts (written at write_script
|
|
2255
|
+
* time) and keeps its name — only the DB row flips status + provenance.
|
|
2256
|
+
*/
|
|
2257
|
+
promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): Promise<ScriptRecipe | null>;
|
|
2258
|
+
/**
|
|
2259
|
+
* Commit a user-directed edit: merge a VERIFIED shadow draft back onto the
|
|
2260
|
+
* recipe it was editing, as version N+1 under the SAME recipe id.
|
|
2261
|
+
*
|
|
2262
|
+
* Keeping the id stable is the point of the whole feature — every cached
|
|
2263
|
+
* conversation, `script_dataset` regeneration descriptor and persisted
|
|
2264
|
+
* component spec already points at it, so the correction applies retroactively
|
|
2265
|
+
* to replays instead of stranding them on the old body.
|
|
2266
|
+
*
|
|
2267
|
+
* Steps (see backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5):
|
|
2268
|
+
* 1. archive the current body as `<fileBase>.v<version>.ts`
|
|
2269
|
+
* 2. write the edited body to the original fileBase (atomic)
|
|
2270
|
+
* 3. version++, copy name/description/params, append a history record
|
|
2271
|
+
* 4. reset health counters — the pre-edit failure history is stale
|
|
2272
|
+
* 5. clear component specs — they were validated against the OLD shape
|
|
2273
|
+
* 6. delete the shadow draft (row + file)
|
|
2274
|
+
*
|
|
2275
|
+
* Returns the updated recipe, or null when the commit could not be applied
|
|
2276
|
+
* (caller should then fall back to treating the draft as a new script).
|
|
2277
|
+
*/
|
|
2278
|
+
commitEdit(targetId: string, draft: {
|
|
2279
|
+
recipeId: string;
|
|
2280
|
+
name?: string;
|
|
2281
|
+
intentDescription?: string;
|
|
2282
|
+
tags?: string[];
|
|
2283
|
+
parameters?: ScriptParameter[];
|
|
2284
|
+
scriptBody: string;
|
|
2285
|
+
sourceIds?: string[];
|
|
2286
|
+
tables?: string[];
|
|
2287
|
+
}, meta: {
|
|
2288
|
+
instruction?: string;
|
|
2289
|
+
changeSummary?: string;
|
|
2290
|
+
editedBy?: string;
|
|
2291
|
+
}): Promise<ScriptRecipe | null>;
|
|
2292
|
+
/**
|
|
2293
|
+
* Drop a draft (row + body file). MainAgent calls this at end-of-turn when a
|
|
2294
|
+
* draft was authored but never verified — failed drafts are never matched, so
|
|
2295
|
+
* deleting them immediately avoids unbounded accumulation (#5). No-op if the
|
|
2296
|
+
* recipe isn't a draft (so a promoted/verified script is never removed here).
|
|
2297
|
+
*/
|
|
2298
|
+
discardDraft(recipeId: string): Promise<void>;
|
|
2299
|
+
/** Delete a recipe (row + body file). */
|
|
2300
|
+
delete(id: string): Promise<void>;
|
|
2301
|
+
/** Record a successful execution (atomic counter bump). */
|
|
2302
|
+
recordSuccess(id: string): Promise<void>;
|
|
2303
|
+
/** Record a failed execution (atomic counter bump). */
|
|
2304
|
+
recordFailure(id: string): Promise<void>;
|
|
2305
|
+
/** Absolute path to the .ts body for a recipe (used by the runner/MainAgent). */
|
|
2306
|
+
getScriptPath(recipe: ScriptRecipe): string;
|
|
2307
|
+
private removeById;
|
|
2308
|
+
private rowToRecipe;
|
|
2309
|
+
private recipeToRow;
|
|
2310
|
+
/** slug of name, with a short id suffix when the bare slug is already taken. */
|
|
2311
|
+
private computeFileBase;
|
|
2312
|
+
private toSlug;
|
|
2313
|
+
private hash;
|
|
2314
|
+
private bodyPath;
|
|
2315
|
+
private readBody;
|
|
2316
|
+
/** Directory holding superseded bodies. Dot-prefixed so IDEs/`ls` hide it. */
|
|
2317
|
+
private get archiveDir();
|
|
2318
|
+
/**
|
|
2319
|
+
* Archive a superseded body as `.versions/<fileBase>.v<n>.ts`.
|
|
2320
|
+
*
|
|
2321
|
+
* Kept out of the main store directory on purpose — see commitEdit step 1.
|
|
2322
|
+
* To roll back: copy the file back over `scripts-store/<fileBase>.ts`.
|
|
2323
|
+
*/
|
|
2324
|
+
private writeArchive;
|
|
2325
|
+
/**
|
|
2326
|
+
* Move a recipe's archived versions to a new prefix when its fileBase changes,
|
|
2327
|
+
* so all versions of one recipe stay grouped. Without this, two renames would
|
|
2328
|
+
* scatter a single recipe's history across three prefixes in `.versions/` with
|
|
2329
|
+
* nothing linking them back to the live script.
|
|
2330
|
+
*/
|
|
2331
|
+
private renameArchives;
|
|
2332
|
+
/** Atomic body write (temp + rename) so concurrent reads never see a partial file. */
|
|
2333
|
+
private writeBody;
|
|
2334
|
+
private unlinkBody;
|
|
2335
|
+
}
|
|
2336
|
+
|
|
2337
|
+
/**
|
|
2338
|
+
* Main Agent (Orchestrator)
|
|
2339
|
+
*
|
|
2340
|
+
* A single LLM.streamWithTools() call that handles everything:
|
|
2341
|
+
* - Routing: decides which source(s) to query based on summaries
|
|
2342
|
+
* - Querying: calls source tools (each wraps an independent SourceAgent)
|
|
2343
|
+
* - Direct tools: calls pre-built function tools directly with LLM-provided params
|
|
2344
|
+
* - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
|
|
2345
|
+
* - Analysis: generates final text response from the data
|
|
2346
|
+
*
|
|
2347
|
+
* Two tool types:
|
|
2348
|
+
* - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
|
|
2349
|
+
* - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
|
|
2350
|
+
*/
|
|
2351
|
+
|
|
2352
|
+
declare class MainAgent {
|
|
2353
|
+
private externalTools;
|
|
2354
|
+
private workflows;
|
|
2355
|
+
private config;
|
|
2356
|
+
private streamBuffer;
|
|
2357
|
+
/**
|
|
2358
|
+
* Optional: when provided, MainAgent exposes the `write_script` /
|
|
2359
|
+
* `execute_script` tools to the LLM and persists drafts to disk via the
|
|
2360
|
+
* store. Headless callers (alert analyzer, metric resolver) omit these to
|
|
2361
|
+
* suppress script authoring entirely — drafts would otherwise leak onto
|
|
2362
|
+
* disk with no caller to promote or clean them up.
|
|
2363
|
+
*/
|
|
2364
|
+
private scriptStore;
|
|
2365
|
+
private turnId;
|
|
2366
|
+
private createdFromPrompt;
|
|
2367
|
+
private scriptState;
|
|
2368
|
+
/**
|
|
2369
|
+
* Fork mode — set when this turn is adapting a near-matching parent script.
|
|
2370
|
+
* In fork mode there is no legitimate "answer with bare text" outcome: the
|
|
2371
|
+
* only correct first move is a tool call (write_script, or a source tool for
|
|
2372
|
+
* schema discovery). We therefore force tool use on the first LLM iteration
|
|
2373
|
+
* so the model can't end its turn with a bare "I'll adapt…" preamble and zero
|
|
2374
|
+
* tool calls. Never set on the fresh-authoring / general-question path.
|
|
2375
|
+
*/
|
|
2376
|
+
private forkMode;
|
|
2377
|
+
/**
|
|
2378
|
+
* Edit mode — set when this turn applies a user-directed change to an
|
|
2379
|
+
* existing script. Swaps the system prompt to `agent-main-edit` and stamps
|
|
2380
|
+
* the shadow draft's parentId. Like fork mode there is no legitimate
|
|
2381
|
+
* "answer with bare text" outcome, so tool use is forced on iteration 1.
|
|
2382
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 4.
|
|
2383
|
+
*/
|
|
2384
|
+
private editContext;
|
|
2385
|
+
/**
|
|
2386
|
+
* Per-turn cancellation signal (user hit "Stop"). Set at the top of
|
|
2387
|
+
* handleQuestion and read by the tool handler, the SourceAgent dispatch, and
|
|
2388
|
+
* the script subprocess so an abort tears down every layer of the turn.
|
|
2389
|
+
*/
|
|
2390
|
+
private abortSignal?;
|
|
2391
|
+
constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[], forkMode?: boolean, editContext?: EditContext);
|
|
2392
|
+
/** True when the turn is applying a user-directed script edit. */
|
|
2393
|
+
private get editMode();
|
|
2394
|
+
private get scriptingEnabled();
|
|
2395
|
+
/**
|
|
2396
|
+
* Handle a user question using the multi-agent system.
|
|
2397
|
+
*
|
|
2398
|
+
* This is ONE LLM.streamWithTools() call. The LLM:
|
|
2399
|
+
* 1. Sees source summaries + direct tool descriptions in system prompt
|
|
2400
|
+
* 2. Decides which tool(s) to call (routing)
|
|
2401
|
+
* 3. Source tools → SourceAgent runs independently → returns data
|
|
2402
|
+
* 4. Direct tools → fn() called directly with LLM params → returns data
|
|
2403
|
+
* 5. Generates final analysis text
|
|
2404
|
+
*/
|
|
2405
|
+
handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, signal?: AbortSignal): Promise<AgentResponse>;
|
|
2406
|
+
private handleWriteScript;
|
|
2407
|
+
private handleExecuteScript;
|
|
2408
|
+
/**
|
|
2409
|
+
* Build the AgentWrittenScript payload the caller will hand to
|
|
2410
|
+
* `ScriptStore.promoteToVerified()`. Only returned when a verified
|
|
2411
|
+
* successful execution is on record.
|
|
2412
|
+
*/
|
|
2413
|
+
private buildSavedScript;
|
|
2414
|
+
private normalizeParameterList;
|
|
2415
|
+
/**
|
|
2416
|
+
* Use the schema embedding collection to pre-select relevant tables for
|
|
2417
|
+
* this source + intent. Returns a formatted schema block if confidence is
|
|
2418
|
+
* high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
|
|
2419
|
+
*
|
|
2420
|
+
* When this returns a block, we can skip the SourceAgent's `search_schema`
|
|
2421
|
+
* loop and reduce iteration budget. When it returns null, the SourceAgent
|
|
2422
|
+
* falls back to the existing LLM-driven keyword search (same as today).
|
|
2423
|
+
*/
|
|
2424
|
+
private preResolveSchema;
|
|
2425
|
+
/**
|
|
2426
|
+
* Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
|
|
2427
|
+
*/
|
|
2428
|
+
private handleDirectTool;
|
|
2429
|
+
/**
|
|
2430
|
+
* Build the main agent's system prompt with source summaries, direct tool descriptions,
|
|
2431
|
+
* and workflow component descriptions.
|
|
2432
|
+
*/
|
|
2433
|
+
private buildSystemPrompt;
|
|
2434
|
+
/**
|
|
2435
|
+
* Build tool definitions for source tools — summary-only descriptions.
|
|
2436
|
+
* The full schema is inside the SourceAgent which runs independently.
|
|
2437
|
+
*/
|
|
2438
|
+
private buildSourceToolDefinitions;
|
|
2439
|
+
/**
|
|
2440
|
+
* Build tool definitions for direct tools — expose their actual params.
|
|
2441
|
+
* These are called directly by the main agent LLM, no SourceAgent.
|
|
2442
|
+
*/
|
|
2443
|
+
private buildDirectToolDefinitions;
|
|
2444
|
+
/**
|
|
2445
|
+
* Capture a workflow selection. We do NOT execute anything — the LLM has
|
|
2446
|
+
* already extracted the props it wants the workflow rendered with. We
|
|
2447
|
+
* record the selection (via the capture callback) and return a short
|
|
2448
|
+
* acknowledgement so the LLM ends its turn cleanly without writing
|
|
2449
|
+
* analysis text or calling more tools.
|
|
2450
|
+
*/
|
|
2451
|
+
private handleWorkflow;
|
|
2452
|
+
/**
|
|
2453
|
+
* Build LLM tool definitions for workflow components. The workflow's
|
|
2454
|
+
* propsSchema becomes the tool's input_schema so the LLM extracts props
|
|
2455
|
+
* directly from the prompt — same mechanic as direct tools.
|
|
2456
|
+
*/
|
|
2457
|
+
private buildWorkflowToolDefinitions;
|
|
2458
|
+
/**
|
|
2459
|
+
* Format a source agent's result as a clean string for the main agent LLM.
|
|
2460
|
+
*/
|
|
2461
|
+
private formatResultForMainAgent;
|
|
2462
|
+
/**
|
|
2463
|
+
* Get source summaries (for external inspection/debugging).
|
|
2464
|
+
*/
|
|
2465
|
+
getSourceSummaries(): SourceSummary[];
|
|
2466
|
+
}
|
|
2467
|
+
|
|
2468
|
+
/**
|
|
2469
|
+
* Represents an action that can be performed on a UIBlock
|
|
2470
|
+
*/
|
|
2471
|
+
interface Action {
|
|
2472
|
+
id: string;
|
|
2473
|
+
name: string;
|
|
2474
|
+
type: string;
|
|
2475
|
+
[key: string]: any;
|
|
2476
|
+
}
|
|
2477
|
+
|
|
2478
|
+
type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
|
|
2479
|
+
interface LLMMessages {
|
|
2480
|
+
sys: SystemPrompt;
|
|
2481
|
+
user: string;
|
|
2482
|
+
prefill?: string;
|
|
2483
|
+
}
|
|
2484
|
+
interface LLMOptions {
|
|
2485
|
+
model?: string;
|
|
2486
|
+
maxTokens?: number;
|
|
2487
|
+
temperature?: number;
|
|
2488
|
+
topP?: number;
|
|
2489
|
+
apiKey?: string;
|
|
2490
|
+
baseURL?: string;
|
|
2491
|
+
partial?: (chunk: string) => void;
|
|
2492
|
+
/**
|
|
2493
|
+
* Per-request cancellation. When the caller aborts this signal (user hit
|
|
2494
|
+
* "Stop"), the underlying provider request is cancelled and the call throws
|
|
2495
|
+
* a RequestAbortedError. Threaded into the provider `messages.create` request
|
|
2496
|
+
* options and checked between tool-loop iterations. Currently honored on the
|
|
2497
|
+
* Anthropic path (the agent flow's default provider).
|
|
2498
|
+
*/
|
|
2499
|
+
signal?: AbortSignal;
|
|
2500
|
+
/**
|
|
2501
|
+
* Forces a tool call on the FIRST iteration of streamWithTools only
|
|
2502
|
+
* (subsequent iterations revert to auto). Used by fork mode to stop the
|
|
2503
|
+
* model from ending its turn with a bare "I'll adapt the script…" preamble
|
|
2504
|
+
* and zero tool calls. `{ type: 'any' }` lets the model pick which tool
|
|
2505
|
+
* (write_script in the common case, a source tool for schema discovery);
|
|
2506
|
+
* `{ type: 'tool', name }` pins a specific tool. Honored on both the
|
|
2507
|
+
* Anthropic path and the OpenAI/OpenRouter path (mapped to OpenAI's
|
|
2508
|
+
* tool_choice: 'required' / a named function).
|
|
2509
|
+
*/
|
|
2510
|
+
firstIterationToolChoice?: {
|
|
2511
|
+
type: 'any';
|
|
2512
|
+
} | {
|
|
2513
|
+
type: 'tool';
|
|
2514
|
+
name: string;
|
|
2515
|
+
};
|
|
2516
|
+
/**
|
|
2517
|
+
* Internal — set only by the OpenRouter wrappers when the target is a Claude
|
|
2518
|
+
* model. Tells the OpenAI-wire path to emit Anthropic `cache_control`
|
|
2519
|
+
* breakpoints (OpenRouter forwards them to Anthropic for prompt caching).
|
|
2520
|
+
* Never set for direct OpenAI/Groq calls, so their requests are unchanged.
|
|
2521
|
+
*/
|
|
2522
|
+
_openrouterClaudeCaching?: boolean;
|
|
2523
|
+
/**
|
|
2524
|
+
* Internal — OpenRouter provider-routing preferences (forwarded as the
|
|
2525
|
+
* `provider` body field). Set by the OpenRouter wrappers to steer routing to
|
|
2526
|
+
* a fast backend (e.g. {sort:'throughput'}). Never set for direct OpenAI/Groq.
|
|
2527
|
+
*/
|
|
2528
|
+
_openrouterProvider?: Record<string, unknown>;
|
|
2529
|
+
}
|
|
2530
|
+
interface Tool {
|
|
2531
|
+
name: string;
|
|
2532
|
+
description: string;
|
|
2533
|
+
input_schema: {
|
|
2534
|
+
type: string;
|
|
2535
|
+
properties: Record<string, any>;
|
|
2536
|
+
required?: string[];
|
|
2537
|
+
};
|
|
2538
|
+
}
|
|
2539
|
+
declare class LLM {
|
|
2540
|
+
static text(messages: LLMMessages, options?: LLMOptions): Promise<string>;
|
|
2541
|
+
static stream<T = string>(messages: LLMMessages, options?: LLMOptions, json?: boolean): Promise<T extends string ? string : any>;
|
|
2542
|
+
static streamWithTools(messages: LLMMessages, tools: Tool[], toolHandler: (toolName: string, toolInput: any) => Promise<any>, options?: LLMOptions, maxIterations?: number): Promise<string>;
|
|
2543
|
+
/**
|
|
2544
|
+
* Normalize system prompt to Anthropic format
|
|
2545
|
+
* Converts string to array format if needed
|
|
2546
|
+
* @param sys - System prompt (string or array of blocks)
|
|
2547
|
+
* @returns Normalized system prompt for Anthropic API
|
|
2548
|
+
*/
|
|
2549
|
+
private static _normalizeSystemPrompt;
|
|
2550
|
+
/**
|
|
2551
|
+
* Strip unpaired UTF-16 surrogates from every text field of a message set.
|
|
2552
|
+
*
|
|
2553
|
+
* A lone surrogate (from mid-pair string slicing or corrupt source data)
|
|
2554
|
+
* serializes to a bare `\udXXX` escape that strict JSON parsers — including
|
|
2555
|
+
* the one on Anthropic's API — reject with "no low surrogate in string",
|
|
2556
|
+
* failing the whole request. Sanitizing here, at the single boundary every
|
|
2557
|
+
* provider call flows through, guarantees no request can carry one.
|
|
2558
|
+
*/
|
|
2559
|
+
private static _sanitizeMessages;
|
|
2560
|
+
/**
|
|
2561
|
+
* Log cache usage metrics from Anthropic API response
|
|
2562
|
+
* Shows cache hits, costs, and savings
|
|
2563
|
+
*/
|
|
2564
|
+
private static _logCacheUsage;
|
|
2565
|
+
/**
|
|
2566
|
+
* Parse model string to extract provider and model name
|
|
2567
|
+
* @param modelString - Format: "provider/model-name" or just "model-name"
|
|
2568
|
+
* @returns [provider, modelName]
|
|
2569
|
+
*
|
|
2570
|
+
* @example
|
|
2571
|
+
* "anthropic/claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"]
|
|
2572
|
+
* "groq/openai/gpt-oss-120b" → ["groq", "openai/gpt-oss-120b"]
|
|
2573
|
+
* "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
|
|
2574
|
+
*/
|
|
2575
|
+
private static _parseModel;
|
|
2576
|
+
/**
|
|
2577
|
+
* Map an Anthropic model id (e.g. "claude-sonnet-4-5-20250929") to the OpenRouter slug
|
|
2578
|
+
* (e.g. "claude-sonnet-4.5"). OpenRouter slugs drop the date suffix and use dotted versions.
|
|
2579
|
+
*/
|
|
2580
|
+
private static _toOpenRouterSlug;
|
|
2581
|
+
/**
|
|
2582
|
+
* Per-provider proxy base URL. Returns `${SUPERATOM_LLM_PROXY_URL}/<provider>`
|
|
2583
|
+
* when our Cloudflare LLM proxy is configured, else undefined (→ talk to the
|
|
2584
|
+
* provider directly, legacy behaviour). An explicit options.baseURL (e.g.
|
|
2585
|
+
* OpenRouter) always wins and is never overridden. See backend/docs/llm-proxy.md.
|
|
2586
|
+
*/
|
|
2587
|
+
private static _proxyBaseURL;
|
|
2588
|
+
private static _openrouterOptions;
|
|
2589
|
+
private static _isRetryableProviderError;
|
|
2590
|
+
private static _withOpenrouterRetry;
|
|
2591
|
+
private static _openrouterText;
|
|
2592
|
+
private static _openrouterStream;
|
|
2593
|
+
private static _openrouterStreamWithTools;
|
|
2594
|
+
/**
|
|
2595
|
+
* Build an Anthropic client. Routes through our Cloudflare LLM proxy when
|
|
2596
|
+
* SUPERATOM_LLM_PROXY_URL is set (each client ships a per-client proxy key as
|
|
2597
|
+
* ANTHROPIC_API_KEY and never holds the real key); otherwise talks to
|
|
2598
|
+
* api.anthropic.com directly. See backend/docs/llm-proxy.md.
|
|
2599
|
+
*/
|
|
2600
|
+
private static _anthropicClient;
|
|
2601
|
+
/** True when OpenRouter is configured as a fail-open fallback for Claude. */
|
|
2602
|
+
private static _openrouterAvailable;
|
|
2603
|
+
/** Remap an Anthropic model id to the OpenRouter model path for fail-open. */
|
|
2604
|
+
private static _anthropicFallbackModel;
|
|
2605
|
+
private static _anthropicText;
|
|
2606
|
+
private static _anthropicStream;
|
|
2607
|
+
private static _anthropicStreamWithTools;
|
|
2608
|
+
private static _groqText;
|
|
2609
|
+
private static _groqStream;
|
|
2610
|
+
/**
|
|
2611
|
+
* Gemini request options carrying the proxy base URL, or undefined → talk to
|
|
2612
|
+
* generativelanguage.googleapis.com directly. The Google SDK takes baseUrl as a
|
|
2613
|
+
* per-model request option, not a constructor arg. See backend/docs/llm-proxy.md.
|
|
2614
|
+
*/
|
|
2615
|
+
private static _geminiRequestOptions;
|
|
2616
|
+
private static _geminiText;
|
|
2617
|
+
private static _geminiStream;
|
|
2618
|
+
/**
|
|
2619
|
+
* Recursively strip unsupported JSON Schema properties for Gemini
|
|
2620
|
+
* Gemini doesn't support: additionalProperties, $schema, etc.
|
|
2621
|
+
*/
|
|
2622
|
+
private static _cleanSchemaForGemini;
|
|
2623
|
+
private static _geminiStreamWithTools;
|
|
2624
|
+
/** True for Anthropic/Claude model ids — gates OpenRouter prompt caching. */
|
|
2625
|
+
private static _isClaudeModel;
|
|
2626
|
+
/**
|
|
2627
|
+
* Build the OpenAI-wire system message. For OpenRouter + Claude
|
|
2628
|
+
* (cacheClaude=true) it emits content parts carrying Anthropic
|
|
2629
|
+
* `cache_control` breakpoints (preserving any the caller set, else marking
|
|
2630
|
+
* the last block), so OpenRouter forwards them to Anthropic for prompt
|
|
2631
|
+
* caching. Otherwise it returns a plain flattened string — unchanged for
|
|
2632
|
+
* direct OpenAI/Groq.
|
|
2633
|
+
*/
|
|
2634
|
+
private static _openaiSystemMessage;
|
|
2635
|
+
/**
|
|
2636
|
+
* Split an OpenAI-wire usage object. `prompt_tokens` INCLUDES cached tokens,
|
|
2637
|
+
* so we subtract them out (Anthropic-style: input excludes cache reads) and
|
|
2638
|
+
* report cached separately — this makes calculateCost price cache reads at
|
|
2639
|
+
* the discounted rate and reflects OpenRouter prompt-cache savings in logs.
|
|
2640
|
+
*/
|
|
2641
|
+
private static _openaiUsage;
|
|
2642
|
+
private static _openaiText;
|
|
2643
|
+
private static _openaiStream;
|
|
2644
|
+
/** Map the Anthropic-style firstIterationToolChoice to OpenAI's tool_choice. */
|
|
2645
|
+
private static _openaiToolChoice;
|
|
2646
|
+
private static _openaiStreamWithTools;
|
|
2647
|
+
/**
|
|
2648
|
+
* Parse JSON string, handling markdown code blocks and surrounding text
|
|
2649
|
+
* Enhanced version with jsonrepair to handle malformed JSON from LLMs
|
|
2650
|
+
* @param text - Text that may contain JSON wrapped in ```json...``` or with surrounding text
|
|
2651
|
+
* @returns Parsed JSON object or array
|
|
2652
|
+
*/
|
|
2653
|
+
private static _parseJSON;
|
|
2654
|
+
}
|
|
2655
|
+
|
|
2656
|
+
interface CapturedLog {
|
|
2657
|
+
timestamp: number;
|
|
2658
|
+
level: 'info' | 'error' | 'warn' | 'debug';
|
|
2659
|
+
message: string;
|
|
2660
|
+
type?: 'explanation' | 'query' | 'general';
|
|
2661
|
+
data?: Record<string, any>;
|
|
2662
|
+
}
|
|
2663
|
+
/**
|
|
2664
|
+
* UILogCollector captures logs during user prompt processing
|
|
2665
|
+
* and sends them to runtime via ui_logs message with uiBlockId as the message id
|
|
2666
|
+
* Logs are sent in real-time for streaming effect in the UI
|
|
2667
|
+
* Respects the global log level configuration
|
|
2668
|
+
*/
|
|
2669
|
+
declare class UILogCollector {
|
|
2670
|
+
private logs;
|
|
2671
|
+
private uiBlockId;
|
|
2672
|
+
private clientId;
|
|
2673
|
+
private sendMessage;
|
|
2674
|
+
private currentLogLevel;
|
|
2675
|
+
constructor(clientId: string, sendMessage: (message: Message) => void, uiBlockId?: string);
|
|
2676
|
+
/**
|
|
2677
|
+
* Check if logging is enabled (uiBlockId is provided)
|
|
2678
|
+
*/
|
|
2679
|
+
isEnabled(): boolean;
|
|
2680
|
+
/**
|
|
2681
|
+
* Check if a message should be logged based on current log level
|
|
2682
|
+
*/
|
|
2683
|
+
private shouldLog;
|
|
2684
|
+
/**
|
|
2685
|
+
* Add a log entry with timestamp and immediately send to runtime
|
|
2686
|
+
* Only logs that pass the log level filter are captured and sent
|
|
2687
|
+
*/
|
|
2688
|
+
private addLog;
|
|
2689
|
+
/**
|
|
2690
|
+
* Send a single log to runtime immediately
|
|
2691
|
+
*/
|
|
2692
|
+
private sendLogImmediately;
|
|
2693
|
+
/**
|
|
2694
|
+
* Log info message
|
|
2695
|
+
*/
|
|
2696
|
+
info(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
|
|
2697
|
+
/**
|
|
2698
|
+
* Log error message
|
|
2699
|
+
*/
|
|
2700
|
+
error(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
|
|
2701
|
+
/**
|
|
2702
|
+
* Log warning message
|
|
2703
|
+
*/
|
|
2704
|
+
warn(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
|
|
2705
|
+
/**
|
|
2706
|
+
* Log debug message
|
|
2707
|
+
*/
|
|
2708
|
+
debug(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
|
|
2709
|
+
/**
|
|
2710
|
+
* Log LLM explanation with typed metadata
|
|
2711
|
+
*/
|
|
2712
|
+
logExplanation(message: string, explanation: string, data?: Record<string, any>): void;
|
|
2713
|
+
/**
|
|
2714
|
+
* Log generated query with typed metadata
|
|
2715
|
+
*/
|
|
2716
|
+
logQuery(message: string, query: string, data?: Record<string, any>): void;
|
|
2717
|
+
/**
|
|
2718
|
+
* Send all collected logs at once (optional, for final summary)
|
|
2719
|
+
*/
|
|
2720
|
+
sendAllLogs(): void;
|
|
2721
|
+
/**
|
|
2722
|
+
* Get all collected logs
|
|
2723
|
+
*/
|
|
2724
|
+
getLogs(): CapturedLog[];
|
|
2725
|
+
/**
|
|
2726
|
+
* Clear all logs
|
|
2727
|
+
*/
|
|
2728
|
+
clearLogs(): void;
|
|
2729
|
+
/**
|
|
2730
|
+
* Set uiBlockId (in case it's provided later)
|
|
2731
|
+
*/
|
|
2732
|
+
setUIBlockId(uiBlockId: string): void;
|
|
2733
|
+
}
|
|
2734
|
+
|
|
2735
|
+
/**
|
|
2736
|
+
* UIBlock represents a single user and assistant message block in a thread
|
|
1475
2737
|
* Contains user question, component metadata, component data, text response, and available actions
|
|
1476
2738
|
*/
|
|
1477
2739
|
declare class UIBlock {
|
|
@@ -1482,6 +2744,13 @@ declare class UIBlock {
|
|
|
1482
2744
|
private textResponse;
|
|
1483
2745
|
private actions;
|
|
1484
2746
|
private createdAt;
|
|
2747
|
+
/**
|
|
2748
|
+
* Which script recipe produced this answer, when a script did. Read on the
|
|
2749
|
+
* NEXT turn so the user can say "use mode instead" and have the matcher
|
|
2750
|
+
* resolve it to a concrete script (the `edit` tier is unreachable without it).
|
|
2751
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
2752
|
+
*/
|
|
2753
|
+
private scriptBinding;
|
|
1485
2754
|
/**
|
|
1486
2755
|
* Creates a new UIBlock instance
|
|
1487
2756
|
* @param userQuestion - The user's question or input
|
|
@@ -1576,6 +2845,14 @@ declare class UIBlock {
|
|
|
1576
2845
|
/**
|
|
1577
2846
|
* Get creation timestamp
|
|
1578
2847
|
*/
|
|
2848
|
+
/**
|
|
2849
|
+
* Bind this block to the script recipe that produced its answer.
|
|
2850
|
+
*/
|
|
2851
|
+
setScriptBinding(binding: Record<string, any> | null): void;
|
|
2852
|
+
/**
|
|
2853
|
+
* The script recipe bound to this block, if any.
|
|
2854
|
+
*/
|
|
2855
|
+
getScriptBinding(): Record<string, any> | null;
|
|
1579
2856
|
getCreatedAt(): Date;
|
|
1580
2857
|
/**
|
|
1581
2858
|
* Convert UIBlock to JSON-serializable object
|
|
@@ -1643,6 +2920,32 @@ declare class Thread {
|
|
|
1643
2920
|
* @param currentUIBlockId - ID of current UIBlock to exclude from context (optional)
|
|
1644
2921
|
* @returns Formatted conversation history string
|
|
1645
2922
|
*/
|
|
2923
|
+
/**
|
|
2924
|
+
* The script recipe bound to the most recent completed UIBlock — i.e. the
|
|
2925
|
+
* script behind the answer the user is currently looking at. Drives the
|
|
2926
|
+
* matcher's `edit` tier: without it, "use mode instead" has no target and
|
|
2927
|
+
* falls through to regeneration.
|
|
2928
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
2929
|
+
*/
|
|
2930
|
+
getActiveScriptBinding(currentUIBlockId?: string): Record<string, any> | null;
|
|
2931
|
+
/**
|
|
2932
|
+
* The recent script-backed answers in this thread, newest first — the
|
|
2933
|
+
* candidate set a user-directed edit can target.
|
|
2934
|
+
*
|
|
2935
|
+
* Returning several rather than only the newest is what lets an instruction
|
|
2936
|
+
* name its own target ("use the mode for the WSP one"). With a single
|
|
2937
|
+
* candidate every edit lands on the most recent script, which silently edits
|
|
2938
|
+
* the wrong recipe whenever the user meant an earlier one.
|
|
2939
|
+
*
|
|
2940
|
+
* Deduped by recipeId (newest occurrence wins) so a long editing session on
|
|
2941
|
+
* one script doesn't crowd out the others. Each entry carries the question
|
|
2942
|
+
* that produced it — without that the candidates are indistinguishable.
|
|
2943
|
+
*
|
|
2944
|
+
* In-memory only: dies with the process. The caller falls back to the
|
|
2945
|
+
* persisted bindings when this comes back empty.
|
|
2946
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
2947
|
+
*/
|
|
2948
|
+
getScriptBindings(limit?: number, currentUIBlockId?: string): Record<string, any>[];
|
|
1646
2949
|
getConversationContext(limit?: number, currentUIBlockId?: string): string;
|
|
1647
2950
|
/**
|
|
1648
2951
|
* Convert Thread to JSON-serializable object
|
|
@@ -2119,127 +3422,35 @@ declare class QueryExecutionService {
|
|
|
2119
3422
|
* @param collections - Collections object containing database execute function
|
|
2120
3423
|
* @returns Object with result data and cache key
|
|
2121
3424
|
*/
|
|
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;
|
|
3425
|
+
executeQuery(query: any, collections: any): Promise<{
|
|
3426
|
+
result: any;
|
|
3427
|
+
cacheKey: string;
|
|
3428
|
+
}>;
|
|
2184
3429
|
/**
|
|
2185
|
-
*
|
|
2186
|
-
*
|
|
3430
|
+
* Request the LLM to fix a failed SQL query
|
|
3431
|
+
* @param failedQuery - The query that failed execution
|
|
3432
|
+
* @param errorMessage - The error message from the failed execution
|
|
3433
|
+
* @param componentContext - Context about the component
|
|
3434
|
+
* @param apiKey - Optional API key
|
|
3435
|
+
* @returns Fixed query string
|
|
2187
3436
|
*/
|
|
2188
|
-
|
|
3437
|
+
requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
|
|
2189
3438
|
/**
|
|
2190
|
-
*
|
|
3439
|
+
* Validate a single component's query with retry logic
|
|
3440
|
+
* @param component - The component to validate
|
|
3441
|
+
* @param collections - Collections object containing database execute function
|
|
3442
|
+
* @param apiKey - Optional API key for LLM calls
|
|
3443
|
+
* @returns Validation result with component, query key, and result
|
|
2191
3444
|
*/
|
|
2192
|
-
|
|
3445
|
+
validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
|
|
2193
3446
|
/**
|
|
2194
|
-
*
|
|
2195
|
-
*
|
|
3447
|
+
* Validate multiple component queries in parallel
|
|
3448
|
+
* @param components - Array of components with potential queries
|
|
3449
|
+
* @param collections - Collections object containing database execute function
|
|
3450
|
+
* @param apiKey - Optional API key for LLM calls
|
|
3451
|
+
* @returns Object with validated components and query results map
|
|
2196
3452
|
*/
|
|
2197
|
-
|
|
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;
|
|
3453
|
+
validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
|
|
2243
3454
|
}
|
|
2244
3455
|
|
|
2245
3456
|
/**
|
|
@@ -2397,7 +3608,7 @@ declare abstract class BaseLLM {
|
|
|
2397
3608
|
* This helps provide intelligent suggestions for follow-up queries
|
|
2398
3609
|
* For general/conversational questions without components, pass textResponse instead
|
|
2399
3610
|
*/
|
|
2400
|
-
generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string): Promise<string[]>;
|
|
3611
|
+
generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string, signal?: AbortSignal): Promise<string[]>;
|
|
2401
3612
|
}
|
|
2402
3613
|
|
|
2403
3614
|
interface AnthropicLLMConfig extends BaseLLMConfig {
|
|
@@ -2460,7 +3671,8 @@ declare const openaiLLM: OpenAILLM;
|
|
|
2460
3671
|
* Query Cache — Two mechanisms:
|
|
2461
3672
|
*
|
|
2462
3673
|
* 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
|
|
2463
|
-
* of recently validated queries. LRU eviction
|
|
3674
|
+
* of recently validated queries. True LRU eviction: reads bubble entries to the back via
|
|
3675
|
+
* delete+re-set so the oldest *unused* entry is evicted, not the oldest *inserted*.
|
|
2464
3676
|
*
|
|
2465
3677
|
* 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
|
|
2466
3678
|
* No server-side storage needed for SQL mappings. The token is decrypted on each request.
|
|
@@ -2487,11 +3699,16 @@ declare class QueryCache {
|
|
|
2487
3699
|
*/
|
|
2488
3700
|
getTTL(): number;
|
|
2489
3701
|
/**
|
|
2490
|
-
* Store query result in data cache
|
|
3702
|
+
* Store query result in data cache.
|
|
3703
|
+
* If the key already exists, it's removed first so the re-insert places it
|
|
3704
|
+
* at the back of the iteration order (LRU). Eviction only fires when adding
|
|
3705
|
+
* a genuinely new key past the size limit.
|
|
2491
3706
|
*/
|
|
2492
3707
|
set(query: string, data: any): void;
|
|
2493
3708
|
/**
|
|
2494
|
-
* Get cached result if exists and not expired
|
|
3709
|
+
* Get cached result if exists and not expired.
|
|
3710
|
+
* On hit, re-inserts the entry so it moves to the back of the Map's
|
|
3711
|
+
* iteration order — turning FIFO eviction into true LRU.
|
|
2495
3712
|
*/
|
|
2496
3713
|
get(query: string): any | null;
|
|
2497
3714
|
/**
|
|
@@ -2598,177 +3815,185 @@ declare class DashboardConversationHistory {
|
|
|
2598
3815
|
declare const dashboardConversationHistory: DashboardConversationHistory;
|
|
2599
3816
|
|
|
2600
3817
|
/**
|
|
2601
|
-
*
|
|
3818
|
+
* Whole-dashboard generation via Pi, a terminal coding agent — as opposed to
|
|
3819
|
+
* DASH_COMP_REQ's single-widget-at-a-time flow. Runs Pi in-process via its
|
|
3820
|
+
* SDK (createAgentSession), not as a subprocess: no shell, no argument
|
|
3821
|
+
* quoting, no stdin/stdout piping, none of the Windows-specific subprocess
|
|
3822
|
+
* issues that came with spawning the `pi` CLI directly.
|
|
2602
3823
|
*
|
|
2603
|
-
*
|
|
2604
|
-
*
|
|
2605
|
-
*
|
|
3824
|
+
* Called from sdk-nodejs/src/dashboardAgent/index.ts (DASHBOARD_AGENT_REQ),
|
|
3825
|
+
* which owns the generic streaming/abort machinery (mirrors USER_PROMPT_REQ)
|
|
3826
|
+
* and passes `signal`/`onProgress` alongside the normal params — this stays
|
|
3827
|
+
* within CollectionHandler's loose (params) => Promise<result> typing, no
|
|
3828
|
+
* change needed to that shared type.
|
|
2606
3829
|
*
|
|
2607
|
-
*
|
|
2608
|
-
*
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
*
|
|
2613
|
-
*
|
|
2614
|
-
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
*
|
|
2625
|
-
*
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
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.
|
|
3830
|
+
* This mechanism is generic and reusable across any deployment. What's
|
|
3831
|
+
* genuinely project-specific — where AGENTS.md lives, which model to use —
|
|
3832
|
+
* is supplied via `DashboardAgentCollectionConfig`, with defaults sensible
|
|
3833
|
+
* enough that most callers don't need to override them (see below). The
|
|
3834
|
+
* data-source tool list and the dashboard's current state both come from
|
|
3835
|
+
* things sdk-nodejs already exposes generically: `sdk.getTools()` (whatever
|
|
3836
|
+
* this deployment registered via `sdk.setTools()`) and `sdk.callCollection
|
|
3837
|
+
* ('dashboards', 'query', ...)` (whatever this deployment already registered
|
|
3838
|
+
* under that name/shape) — no per-deployment callback needed for either.
|
|
3839
|
+
* Same convention on the way out: after a successful run, the prompt and the
|
|
3840
|
+
* full response text are handed to `sdk.callCollection('dashboard-agent-
|
|
3841
|
+
* conversations', 'create', ...)` if this deployment has registered one —
|
|
3842
|
+
* skipped silently otherwise, since conversation history is optional.
|
|
3843
|
+
*
|
|
3844
|
+
* Pi verifies every query against the live database itself (via whatever
|
|
3845
|
+
* local tool-execution bridge the deployment exposes, e.g. an HTTP bridge
|
|
3846
|
+
* on localhost), but does NOT persist the result itself — it writes the
|
|
3847
|
+
* finished DSL to an absolute path inside `runtimeDir`, told to it explicitly
|
|
3848
|
+
* in the prompt, and stops there. This handler reads that file after the run
|
|
3849
|
+
* finishes and returns its content as `dashboard` in the result. The caller
|
|
3850
|
+
* (frontend) is the one that actually saves it, via whatever authenticated
|
|
3851
|
+
* create/update path any other dashboard edit goes through — Pi has no user
|
|
3852
|
+
* session/auth context of its own, so persistence shouldn't happen from
|
|
3853
|
+
* inside it.
|
|
3854
|
+
*
|
|
3855
|
+
* Session persistence: the FIRST call for a dashboardId pays the full cost
|
|
3856
|
+
* (explore KB, discover schema, plan, verify, build). Every call after that
|
|
3857
|
+
* resumes the same session file (SessionManager.open) so Pi has everything
|
|
3858
|
+
* it already learned — it only needs to reason about the new, smaller ask,
|
|
3859
|
+
* not rediscover the whole dashboard from scratch. The session's file path
|
|
3860
|
+
* (AgentSession.sessionFile) is captured right after creation and persisted
|
|
3861
|
+
* in a small local file, keyed by dashboardId, inside `runtimeDir`.
|
|
2678
3862
|
*/
|
|
2679
|
-
interface
|
|
2680
|
-
/**
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
3863
|
+
interface DashboardAgentCollectionConfig {
|
|
3864
|
+
/**
|
|
3865
|
+
* Working directory Pi runs from — must contain AGENTS.md. This is a
|
|
3866
|
+
* version-controlled prompt file, so `cwd` is expected to live somewhere
|
|
3867
|
+
* like a `.prompts/` folder alongside the deployment's other prompts.
|
|
3868
|
+
* Default: `<process.cwd()>/.prompts/dashboard-agent` — the same
|
|
3869
|
+
* process.cwd()-based convention PromptLoader already uses for the main
|
|
3870
|
+
* agent's prompts, which needs no explicit override in the common case
|
|
3871
|
+
* (the backend process's own cwd already is its project root).
|
|
3872
|
+
*/
|
|
3873
|
+
cwd?: string;
|
|
3874
|
+
/**
|
|
3875
|
+
* Where drafts/, the session-id map, and dashboard.log get written —
|
|
3876
|
+
* separate from `cwd` deliberately, so this deployment's runtime state
|
|
3877
|
+
* (regenerated per session, safe to gitignore) doesn't sit inside the
|
|
3878
|
+
* same folder as the version-controlled AGENTS.md prompt.
|
|
3879
|
+
* Default: `<process.cwd()>/.pi-dashboard-agent-runtime`.
|
|
3880
|
+
*/
|
|
3881
|
+
runtimeDir?: string;
|
|
3882
|
+
/** Model provider (default: process.env.PI_AGENT_PROVIDER || 'openrouter'). */
|
|
3883
|
+
provider?: string;
|
|
3884
|
+
/** Model id (default: process.env.PI_AGENT_MODEL || 'anthropic/claude-sonnet-4.5'). */
|
|
3885
|
+
model?: string;
|
|
3886
|
+
/**
|
|
3887
|
+
* true (default): every request starts a brand-new pi session, with the 2
|
|
3888
|
+
* most recent prior responses (if any) injected into the prompt as
|
|
3889
|
+
* context — bounded cost per request, but pi re-explores schema/KB facts
|
|
3890
|
+
* it already verified in an earlier turn on this same dashboard.
|
|
3891
|
+
* false: resumes the same session file across requests on a given
|
|
3892
|
+
* dashboard — pi keeps everything it already learned, but context (and
|
|
3893
|
+
* cost) grows unbounded across turns (one observed turn: 2M+ cache-read
|
|
3894
|
+
* tokens after a handful of edits on the same dashboard).
|
|
3895
|
+
* Default: process.env.PI_AGENT_FRESH_SESSION !== 'false'.
|
|
3896
|
+
*/
|
|
3897
|
+
freshSession?: boolean;
|
|
2686
3898
|
}
|
|
3899
|
+
declare function registerDashboardAgentCollection(sdk: SuperatomSDK, config?: DashboardAgentCollectionConfig): void;
|
|
3900
|
+
|
|
2687
3901
|
/**
|
|
2688
|
-
*
|
|
2689
|
-
*
|
|
3902
|
+
* ScriptMatcher — LLM-Based Script Matching + Parameter Extraction
|
|
3903
|
+
*
|
|
3904
|
+
* Uses ONE LLM call to:
|
|
3905
|
+
* 1. Pick the best matching script from the library (or "none")
|
|
3906
|
+
* 2. Extract parameter values from the user question
|
|
3907
|
+
*
|
|
3908
|
+
* Why LLM over embeddings:
|
|
3909
|
+
* - Embeddings capture topic similarity ("overstock" ≈ "inventory" ≈ "revenue")
|
|
3910
|
+
* but can't distinguish structurally different questions about the same domain
|
|
3911
|
+
* - LLM understands that "overstock by warehouse" needs a different script than
|
|
3912
|
+
* "revenue by warehouse" even though they're semantically close
|
|
3913
|
+
* - One call does both matching AND parameter extraction
|
|
3914
|
+
*
|
|
3915
|
+
* When script library grows past ~50, add an embedding pre-filter
|
|
3916
|
+
* (ChromaDB narrows to top 10 → LLM picks from those 10).
|
|
2690
3917
|
*/
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
3918
|
+
|
|
3919
|
+
declare class ScriptMatcher {
|
|
3920
|
+
private store;
|
|
3921
|
+
constructor(store: ScriptStore);
|
|
3922
|
+
/**
|
|
3923
|
+
* Find the best matching script for a user question.
|
|
3924
|
+
* Uses ONE LLM call that picks the script AND extracts parameters.
|
|
3925
|
+
* Returns null if no script matches.
|
|
3926
|
+
*/
|
|
3927
|
+
match(userPrompt: string, apiKey?: string, model?: string, signal?: AbortSignal,
|
|
3928
|
+
/**
|
|
3929
|
+
* Recent script-backed answers in this thread, newest first. Presence of at
|
|
3930
|
+
* least one is what makes the `edit` tier reachable at all (see the guards
|
|
3931
|
+
* below), and handing over SEVERAL is what lets an instruction name its own
|
|
3932
|
+
* target instead of always hitting the most recent script.
|
|
3933
|
+
*/
|
|
3934
|
+
activeBindings?: ScriptBinding[],
|
|
3935
|
+
/**
|
|
3936
|
+
* Recent conversation turns, most recent last. The gate needs this to tell
|
|
3937
|
+
* "this reply is an edit instruction for the active script" apart from
|
|
3938
|
+
* "this reply is answering a clarifying question about a DIFFERENT,
|
|
3939
|
+
* unresolved topic that never became a script" — a bare parameter-shaped
|
|
3940
|
+
* reply ("April 2025 to March 2026") is textually indistinguishable
|
|
3941
|
+
* between those two cases without seeing what the assistant just asked.
|
|
3942
|
+
* Once this tier is decided, nothing downstream re-checks it — the edit
|
|
3943
|
+
* path hands MainAgent a system prompt that explicitly instructs it to
|
|
3944
|
+
* trust the premise and not treat the turn as a new question — so this
|
|
3945
|
+
* gate is the only place that can catch a mismatch.
|
|
3946
|
+
*/
|
|
3947
|
+
conversationHistory?: string): Promise<ScriptMatch | null>;
|
|
3948
|
+
/**
|
|
3949
|
+
* Build the script catalog string for the LLM prompt.
|
|
3950
|
+
* Each script gets: index, ID, name, description, and parameter definitions.
|
|
3951
|
+
*/
|
|
3952
|
+
private buildScriptCatalog;
|
|
3953
|
+
/**
|
|
3954
|
+
* The recent script-backed answers in this thread — the bounded set an edit
|
|
3955
|
+
* may target. Rendered as its own prompt section (never merged into the
|
|
3956
|
+
* ranked catalog) so the `edit` rules have an unambiguous referent set, and
|
|
3957
|
+
* numbered newest-first so the prompt's "prefer the most recent when the
|
|
3958
|
+
* instruction is ambiguous" tie-break has something to point at.
|
|
3959
|
+
*
|
|
3960
|
+
* Each entry carries the QUESTION that produced it plus the columns it
|
|
3961
|
+
* returned — that is what lets the matcher resolve "use the mode for the WSP
|
|
3962
|
+
* one" instead of blindly taking the newest.
|
|
3963
|
+
*/
|
|
3964
|
+
private buildActiveScriptBlock;
|
|
2708
3965
|
}
|
|
2709
|
-
/**
|
|
2710
|
-
* Default agent configuration
|
|
2711
|
-
*/
|
|
2712
|
-
declare const DEFAULT_AGENT_CONFIG: AgentConfig;
|
|
2713
3966
|
|
|
2714
3967
|
/**
|
|
2715
|
-
*
|
|
3968
|
+
* ScriptRunner — Execute scripts in an isolated tsx subprocess.
|
|
2716
3969
|
*
|
|
2717
|
-
*
|
|
2718
|
-
*
|
|
2719
|
-
*
|
|
2720
|
-
*
|
|
2721
|
-
* - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
|
|
2722
|
-
* - Analysis: generates final text response from the data
|
|
3970
|
+
* The subprocess approach replaces the earlier `new Function()` eval and gives us:
|
|
3971
|
+
* - Real sandbox (separate process, SIGKILL on timeout).
|
|
3972
|
+
* - Real TypeScript (tsx transpiles on the fly).
|
|
3973
|
+
* - npm imports available to scripts (clustering, stats, geo, etc.).
|
|
2723
3974
|
*
|
|
2724
|
-
*
|
|
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)
|
|
3975
|
+
* Protocol: NDJSON over the child's stdin/stdout. See script-ipc.ts + backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md.
|
|
2727
3976
|
*/
|
|
2728
3977
|
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
/**
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
*
|
|
2738
|
-
*
|
|
2739
|
-
*
|
|
2740
|
-
|
|
2741
|
-
|
|
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[];
|
|
3978
|
+
interface RunScriptOptions {
|
|
3979
|
+
/** Data sources the script is allowed to query via ctx.query */
|
|
3980
|
+
externalTools: ExternalTool[];
|
|
3981
|
+
/** Optional — for propagating per-query UI progress to the user */
|
|
3982
|
+
streamBuffer?: StreamBuffer;
|
|
3983
|
+
/** Override the wall-clock timeout (default `SCRIPT_TIMEOUT_MS`, 60s). */
|
|
3984
|
+
timeoutMs?: number;
|
|
3985
|
+
/**
|
|
3986
|
+
* Per-turn cancellation signal. When the user hits "Stop" mid-run, the child
|
|
3987
|
+
* process group is SIGKILLed and the run resolves as an aborted failure (the
|
|
3988
|
+
* caller is already unwinding, so the result is discarded).
|
|
3989
|
+
*/
|
|
3990
|
+
signal?: AbortSignal;
|
|
2771
3991
|
}
|
|
3992
|
+
/**
|
|
3993
|
+
* Execute a recipe by spawning a tsx child on the script's .ts file.
|
|
3994
|
+
* `scriptPath` is the absolute path to the saved `.ts` body.
|
|
3995
|
+
*/
|
|
3996
|
+
declare function runScript(recipe: ScriptRecipe, scriptPath: string, params: Record<string, any>, options: RunScriptOptions): Promise<ScriptResult>;
|
|
2772
3997
|
|
|
2773
3998
|
type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
|
|
2774
3999
|
declare class SuperatomSDK {
|
|
@@ -2786,6 +4011,7 @@ declare class SuperatomSDK {
|
|
|
2786
4011
|
private collections;
|
|
2787
4012
|
private components;
|
|
2788
4013
|
private tools;
|
|
4014
|
+
private workflows;
|
|
2789
4015
|
private anthropicApiKey;
|
|
2790
4016
|
private groqApiKey;
|
|
2791
4017
|
private geminiApiKey;
|
|
@@ -2804,6 +4030,8 @@ declare class SuperatomSDK {
|
|
|
2804
4030
|
private lastPong;
|
|
2805
4031
|
private readonly PING_INTERVAL_MS;
|
|
2806
4032
|
private readonly PONG_TIMEOUT_MS;
|
|
4033
|
+
private pendingOutbox;
|
|
4034
|
+
private readonly MAX_OUTBOX_SIZE;
|
|
2807
4035
|
constructor(config: SuperatomSDKConfig);
|
|
2808
4036
|
/**
|
|
2809
4037
|
* Initialize PromptLoader and load prompts into memory
|
|
@@ -2848,6 +4076,20 @@ declare class SuperatomSDK {
|
|
|
2848
4076
|
* Does NOT throw on closed connections — callers can check the return value if needed.
|
|
2849
4077
|
*/
|
|
2850
4078
|
send(message: Message): boolean;
|
|
4079
|
+
/**
|
|
4080
|
+
* Queue a message that couldn't be delivered because the socket was down,
|
|
4081
|
+
* to be resent once it reconnects. Drops the oldest entry once the bound is
|
|
4082
|
+
* hit — an outage long enough to fill this queue means the oldest queued
|
|
4083
|
+
* responses are for requests the caller has likely already given up on.
|
|
4084
|
+
*/
|
|
4085
|
+
private queuePendingMessage;
|
|
4086
|
+
/**
|
|
4087
|
+
* Resend everything queued while the socket was down, now that it's back
|
|
4088
|
+
* up. Uses this.ws.send() directly (not send()) so a message that fails
|
|
4089
|
+
* again goes back through queuePendingMessage() rather than being silently
|
|
4090
|
+
* dropped a second time.
|
|
4091
|
+
*/
|
|
4092
|
+
private flushPendingOutbox;
|
|
2851
4093
|
/**
|
|
2852
4094
|
* Register a message handler to receive all messages
|
|
2853
4095
|
*/
|
|
@@ -2887,6 +4129,14 @@ declare class SuperatomSDK {
|
|
|
2887
4129
|
*/
|
|
2888
4130
|
private handlePong;
|
|
2889
4131
|
private storeComponents;
|
|
4132
|
+
/**
|
|
4133
|
+
* The live, frontend-registered component catalog (name, type, description,
|
|
4134
|
+
* and full prop schema per component) — the same authoritative source
|
|
4135
|
+
* DASH_COMP_REQ's LLM prompt is built from. Exposed so other integrations
|
|
4136
|
+
* (e.g. the dashboard-agent script bridge) can read real component
|
|
4137
|
+
* contracts instead of maintaining a separate, driftable hand-written copy.
|
|
4138
|
+
*/
|
|
4139
|
+
getComponents(): Component[];
|
|
2890
4140
|
/**
|
|
2891
4141
|
* Set tools for the SDK instance
|
|
2892
4142
|
*/
|
|
@@ -2895,6 +4145,29 @@ declare class SuperatomSDK {
|
|
|
2895
4145
|
* Get the stored tools
|
|
2896
4146
|
*/
|
|
2897
4147
|
getTools(): Tool$1[];
|
|
4148
|
+
/**
|
|
4149
|
+
* Call a registered collection operation in-process — no WebSocket
|
|
4150
|
+
* round-trip, since the caller is already running inside this same SDK
|
|
4151
|
+
* instance. Lets SDK-internal features (e.g. the dashboard agent) reuse
|
|
4152
|
+
* whatever collection a deployment has already registered (e.g.
|
|
4153
|
+
* 'dashboards'.'query') by name/convention, instead of requiring a
|
|
4154
|
+
* separate callback purely to re-expose data a collection already serves.
|
|
4155
|
+
* Throws if the collection or operation isn't registered.
|
|
4156
|
+
*/
|
|
4157
|
+
callCollection<TResult = any>(collectionName: string, operation: string, params?: any): Promise<TResult>;
|
|
4158
|
+
/**
|
|
4159
|
+
* Register workflow components for the SDK instance.
|
|
4160
|
+
*
|
|
4161
|
+
* Workflows are pre-built multi-step UI flows the main agent can pick when
|
|
4162
|
+
* the user's prompt matches a workflow's `whenToUse` trigger. Picking a
|
|
4163
|
+
* workflow short-circuits analysis text + dashboard component generation —
|
|
4164
|
+
* the workflow component is returned directly, with the LLM-extracted props.
|
|
4165
|
+
*/
|
|
4166
|
+
setWorkflows(workflows: WorkflowDescriptor[]): void;
|
|
4167
|
+
/**
|
|
4168
|
+
* Get the registered workflow components.
|
|
4169
|
+
*/
|
|
4170
|
+
getWorkflows(): WorkflowDescriptor[];
|
|
2898
4171
|
/**
|
|
2899
4172
|
* Apply model strategy to all LLM provider singletons
|
|
2900
4173
|
* @param strategy - 'best', 'fast', or 'balanced'
|
|
@@ -2925,4 +4198,4 @@ declare class SuperatomSDK {
|
|
|
2925
4198
|
getConversationSimilarityThreshold(): number;
|
|
2926
4199
|
}
|
|
2927
4200
|
|
|
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 };
|
|
4201
|
+
export { type Action, type AgentConfig, type AgentResponse, BM25L, type BM25LOptions, type BaseLLMConfig, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, DEFAULT_AGENT_CONFIG, type DashboardAgentCollectionConfig, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, MainAgent, type Message, type ModelStrategy, type OutputField, type RerankedResult, STORAGE_CONFIG, type ScriptComponentSpec, ScriptMatcher, type ScriptParameter, type ScriptRecipe, type ScriptRecipeMetaRow, type ScriptRecipeStore, type ScriptResult, ScriptStore, type ScriptStoreOptions, type SelectedWorkflow, SuperatomSDK, type SuperatomSDKConfig, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, type ToolOutputSchema, UIBlock, UILogCollector, type User, UserManager, type UsersData, type WorkflowDescriptor, anthropicLLM, dashboardConversationHistory, geminiLLM, groqLLM, hybridRerank, llmUsageLogger, logger, normalizeScriptBody, openaiLLM, queryCache, registerDashboardAgentCollection, rerankChromaResults, rerankConversationResults, resolveScriptRecipeStore, runScript, userPromptErrorLogger };
|