@superatomai/sdk-node 0.0.36-mds → 0.0.37-dsp

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,15 +1,846 @@
1
1
  import { z } from 'zod';
2
2
  import Anthropic from '@anthropic-ai/sdk';
3
3
 
4
+ /**
5
+ * StreamBuffer - Buffered streaming utility for smoother text delivery
6
+ * Batches small chunks together and flushes at regular intervals
7
+ */
8
+ type StreamCallback = (chunk: string) => void;
9
+ /**
10
+ * StreamBuffer class for managing buffered streaming output
11
+ * Provides smooth text delivery by batching small chunks
12
+ */
13
+ declare class StreamBuffer {
14
+ private buffer;
15
+ private flushTimer;
16
+ private callback;
17
+ private fullText;
18
+ constructor(callback?: StreamCallback);
19
+ /**
20
+ * Check if the buffer has a callback configured
21
+ */
22
+ hasCallback(): boolean;
23
+ /**
24
+ * Get all text that has been written (including already flushed)
25
+ */
26
+ getFullText(): string;
27
+ /**
28
+ * Write a chunk to the buffer
29
+ * Large chunks or chunks with newlines are flushed immediately
30
+ * Small chunks are batched and flushed after a short interval
31
+ *
32
+ * @param chunk - Text chunk to write
33
+ */
34
+ write(chunk: string): void;
35
+ /**
36
+ * Flush the buffer immediately
37
+ * Call this before tool execution or other operations that need clean output
38
+ */
39
+ flush(): void;
40
+ /**
41
+ * Internal flush implementation
42
+ */
43
+ private flushNow;
44
+ /**
45
+ * Clean up resources
46
+ * Call this when done with the buffer
47
+ */
48
+ dispose(): void;
49
+ }
50
+
51
+ /**
52
+ * ToolExecutorService - Handles execution of SQL queries and external tools
53
+ * Extracted from BaseLLM.generateTextResponse for better separation of concerns
54
+ */
55
+
56
+ /**
57
+ * External tool definition
58
+ */
59
+ interface ExternalTool {
60
+ id: string;
61
+ name: string;
62
+ description?: string;
63
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
64
+ toolType?: 'source' | 'direct';
65
+ /** Full untruncated schema for source agent (all columns visible) */
66
+ fullSchema?: string;
67
+ /** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
68
+ schemaTier?: string;
69
+ /** Schema search function for very_large tier — keyword search over entities */
70
+ schemaSearchFn?: (keywords: string[]) => string;
71
+ fn: (input: any) => Promise<any>;
72
+ limit?: number;
73
+ outputSchema?: any;
74
+ executionType?: 'immediate' | 'deferred';
75
+ userProvidedData?: any;
76
+ params?: Record<string, any>;
77
+ }
78
+ /**
79
+ * Executed tool tracking info
80
+ */
81
+ interface ExecutedToolInfo {
82
+ id: string;
83
+ name: string;
84
+ params: any;
85
+ result: {
86
+ _totalRecords: number;
87
+ _recordsShown: number;
88
+ _metadata?: any;
89
+ _sampleData: any[];
90
+ /** Bounded summary over the FULL fetched result (complete structure). */
91
+ _summary?: any;
92
+ /** Up to MAIN_AGENT_COMPLETE_ROWS rows — the complete result when small. */
93
+ _mainAgentRows?: any[];
94
+ };
95
+ outputSchema?: any;
96
+ sourceSchema?: string;
97
+ sourceType?: string;
98
+ }
99
+
100
+ /**
101
+ * Script Flow Types
102
+ *
103
+ * Defines interfaces for the script-based query architecture:
104
+ * - ScriptRecipe: metadata for matching, validation, and quality tracking
105
+ * - ScriptResult: output from executing a script
106
+ * - ScriptMatch: result from the LLM-based script matcher
107
+ */
108
+ /**
109
+ * Recipe metadata stored alongside each script.
110
+ * Used for matching, validation, and quality tracking.
111
+ */
112
+ interface ScriptRecipe {
113
+ /** Unique script identifier */
114
+ id: string;
115
+ /** Version number (incremented on regeneration) */
116
+ version: number;
117
+ /** Human-readable name (e.g., "Revenue by Dimension") */
118
+ name: string;
119
+ /** Natural language description of what this script does */
120
+ intentDescription: string;
121
+ /** Keyword tags for quick filtering */
122
+ tags: string[];
123
+ /** Source tool IDs this script queries (e.g., ["mssql-abc123_query"]) */
124
+ sourceIds: string[];
125
+ /** Table names used (for future schema drift detection) */
126
+ tables: string[];
127
+ /** Parameter definitions — what can vary */
128
+ parameters: ScriptParameter[];
129
+ /** The script function body as a string. Loaded from disk (scripts-store/<fileBase>.ts). */
130
+ scriptBody: string;
131
+ /**
132
+ * On-disk filename stem for the body: scripts-store/<fileBase>.ts.
133
+ * Editable in the IDE. Decided at authoring time (slug of `name`, with a
134
+ * short id suffix on collision) and stable across promotion.
135
+ */
136
+ fileBase?: string;
137
+ /** sha256 of the on-disk body — lets the runtime detect manual edits. */
138
+ bodyHash?: string;
139
+ /** Project scope (single-VM deployments may leave this undefined). */
140
+ projectId?: string;
141
+ /** Times this script was used successfully */
142
+ successCount: number;
143
+ /** Times this script failed */
144
+ failureCount: number;
145
+ /** ISO timestamp of last usage */
146
+ lastUsed: string;
147
+ /** Original user question that created this script */
148
+ createdFrom: string;
149
+ /** ISO timestamp */
150
+ createdAt: string;
151
+ /** ISO timestamp */
152
+ updatedAt: string;
153
+ /**
154
+ * `recipe.id` of the parent this script was forked from.
155
+ * Undefined for root scripts (those written from scratch by MainAgent).
156
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md.
157
+ */
158
+ parentId?: string;
159
+ /** 0 for root scripts; `parent.forkDepth + 1` for forks. Capped at 3. */
160
+ forkDepth?: number;
161
+ /**
162
+ * Brief description of what this fork changed vs its parent
163
+ * (sourced from the matcher's `modificationHint`).
164
+ */
165
+ forkReason?: string;
166
+ /**
167
+ * Validated component specs captured at authoring time. On a tier-high
168
+ * replay these are rebound to fresh queryIds deterministically — no
169
+ * component-generation LLM call, and the rendered columns can't drift from
170
+ * what was validated when the script was authored. Absent on recipes
171
+ * authored before this landed; those fall back to LLM component generation.
172
+ * See backend/docs/SCRIPT-COMPONENT-CONSISTENCY.md.
173
+ */
174
+ components?: ScriptComponentSpec[];
175
+ /**
176
+ * What the user explicitly asked the output to LOOK like, set by a display
177
+ * edit ("show that as a bar chart", "make the bars horizontal").
178
+ *
179
+ * Deliberately SEPARATE from `components`. Those are validated bindings that
180
+ * must be cleared on a data edit — after "break it down by brand" the axis
181
+ * keys are wrong, and after "use the mode" the stored title still says
182
+ * "Average…". A rendering CHOICE, by contrast, is still valid afterwards.
183
+ * Keeping them in one field meant every data edit silently discarded the
184
+ * user's chart type.
185
+ *
186
+ * Fed to the component generator as a hint whenever specs are (re)generated,
187
+ * so the chosen rendering comes back even after the SQL changes.
188
+ */
189
+ displayPreference?: ScriptDisplayPreference;
190
+ /**
191
+ * Lifecycle stage of this recipe on disk.
192
+ * - 'draft': written by MainAgent's write_script during a turn; filtered out
193
+ * of FTS results (status='verified' only) so the matcher never picks it.
194
+ * Filename is suffixed with `turnId` to keep concurrent turns
195
+ * from clobbering each other's drafts.
196
+ * - 'verified': promoted after `execute_script` succeeded; the matcher sees it.
197
+ * Filename drops the turn suffix unless a verified file with
198
+ * the same slug already exists (collision case keeps the suffix).
199
+ *
200
+ * Recipes loaded from disk without this field default to 'verified' so
201
+ * existing scripts keep working unchanged.
202
+ */
203
+ status?: 'draft' | 'verified';
204
+ /**
205
+ * Per-turn unique suffix used for draft filenames (e.g. `1714745623-x9k2`).
206
+ * Set when the draft is saved; carried until the recipe is promoted.
207
+ */
208
+ turnId?: string;
209
+ /**
210
+ * Last execution error captured by `recordDraftError` while the recipe was
211
+ * still a draft. Lets users open the draft .json file and see why it failed
212
+ * without grepping logs. Cleared on promotion to 'verified'.
213
+ */
214
+ lastError?: {
215
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
216
+ message: string;
217
+ at: string;
218
+ attempt: number;
219
+ };
220
+ /** userId who committed the most recent edit (audit trail — recipes are project-scoped). */
221
+ editedBy?: string;
222
+ /** The instruction that produced the current version. */
223
+ editedFrom?: string;
224
+ /**
225
+ * Prior versions, newest last. The body itself is archived on disk as
226
+ * `<fileBase>.v<version>.ts`; this records what changed and who did it.
227
+ */
228
+ history?: ScriptVersionRecord[];
229
+ }
230
+ /**
231
+ * A durable, user-stated rendering choice for a recipe. Survives data edits.
232
+ */
233
+ interface ScriptDisplayPreference {
234
+ /** Component types the user's chosen rendering resolved to, e.g. ["DynamicBarChart"]. */
235
+ componentTypes: string[];
236
+ /** The instruction itself — carries nuance the types can't ("horizontal", "sorted descending"). */
237
+ instruction: string;
238
+ /** ISO timestamp of the display edit that set this. */
239
+ at: string;
240
+ }
241
+ /** One superseded version of a recipe body (see ScriptStore.commitEdit). */
242
+ interface ScriptVersionRecord {
243
+ /** Version number this record superseded (i.e. the OLD version). */
244
+ version: number;
245
+ /** ISO timestamp of the edit that superseded it. */
246
+ at: string;
247
+ /** userId who made the edit, when known. */
248
+ by?: string;
249
+ /** The edit instruction that caused the supersede. */
250
+ instruction?: string;
251
+ /** One-line summary of what changed, for the version picker. */
252
+ changeSummary?: string;
253
+ /** sha256 of the superseded body — pairs with `<fileBase>.v<version>.ts`. */
254
+ bodyHash?: string;
255
+ }
256
+ interface ScriptParameter {
257
+ /** Parameter name (used in script body as params.name) */
258
+ name: string;
259
+ /** Parameter type */
260
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
261
+ /** Whether this parameter is required */
262
+ required: boolean;
263
+ /** Default value if not provided */
264
+ default?: any;
265
+ /** For enum type — maps user-facing values to internal values */
266
+ enumValues?: Record<string, string>;
267
+ /** Human-readable description (used in the matcher LLM prompt) */
268
+ description: string;
269
+ }
270
+ /**
271
+ * A reusable component binding captured when a script is authored. Stored on
272
+ * the recipe so tier-high replays rebuild components deterministically (rebind
273
+ * to fresh queryIds) instead of re-running the component-picker LLM.
274
+ */
275
+ interface ScriptComponentSpec {
276
+ /** Registered component name (e.g. "DynamicBarChart") — matched against the available component library. */
277
+ componentType: string;
278
+ /** `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). */
279
+ sourceRef: string;
280
+ /** Present only when sourceRef === 'federation' — the DuckDB SQL to re-execute on replay. */
281
+ federationSql?: string;
282
+ /** Present only when sourceRef === 'markdown' — the narrative text to render on replay (markdown has no data source, so its content must be persisted). */
283
+ content?: string;
284
+ title?: string;
285
+ description?: string;
286
+ /** Validated axis/value keys + aggregation — all referencing real columns of the bound source. */
287
+ config: Record<string, any>;
288
+ }
289
+ /**
290
+ * Result from executing a script via ScriptRunner.
291
+ */
292
+ interface ScriptResult {
293
+ /** Whether the script executed successfully */
294
+ success: boolean;
295
+ /** Combined data from all queries */
296
+ data: any[];
297
+ /** Individual query results tracked during execution */
298
+ executedQueries: ScriptQueryResult[];
299
+ /** Error message if failed */
300
+ error?: string;
301
+ /**
302
+ * Where in the lifecycle the error occurred. Lets MainAgent's fix-loop
303
+ * decide between "rewrite the whole draft" (compile) and "patch the
304
+ * specific line" (runtime).
305
+ */
306
+ errorPhase?: 'compile' | 'runtime' | 'timeout' | 'ipc';
307
+ /** Total execution time in milliseconds */
308
+ executionTimeMs: number;
309
+ }
310
+ /**
311
+ * A single query executed during script runtime.
312
+ * Tracked by ScriptContext for component generation and debugging.
313
+ */
314
+ interface ScriptQueryResult {
315
+ /** Source tool ID */
316
+ sourceId: string;
317
+ /** Human-readable source name */
318
+ sourceName: string;
319
+ /** The SQL that was executed */
320
+ sql: string;
321
+ /** Result data rows */
322
+ data: any[];
323
+ /** Number of rows returned */
324
+ count: number;
325
+ /** Total rows that matched before limit (if available) */
326
+ totalCount?: number;
327
+ /** Query execution time in milliseconds */
328
+ executionTimeMs: number;
329
+ /**
330
+ * True for rows that did NOT come from a real SQL execution — either a
331
+ * ctx.emit() dataset or the synthesized "computed:_final" entry that
332
+ * carries the script's post-JS returned data. The component generator
333
+ * uses this to route the resulting component through the script_dataset
334
+ * sentinel toolId so the frontend resolves it via the queryCache short-circuit.
335
+ */
336
+ virtual?: boolean;
337
+ }
338
+ /**
339
+ * Match tier returned by the LLM script matcher.
340
+ *
341
+ * - 'high': the script answers the question directly; only parameter values
342
+ * may differ. The runtime replays it with extracted params (cheapest path).
343
+ * - 'near': the script answers a STRUCTURALLY similar question but needs
344
+ * body modification (different metric, dimension, table, filter shape).
345
+ * The runtime forks the parent and adapts the body via MainAgent's normal
346
+ * write_script + execute_script loop — no SourceAgent dispatch needed.
347
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md for the full design.
348
+ * - 'edit': the user is INSTRUCTING a change to the script that produced the
349
+ * previous answer (not asking a new question). Only reachable when the turn
350
+ * carries a ScriptBinding — without one the matcher coerces it to 'none', so
351
+ * a prompt regression can't turn this into a loose similarity path. The
352
+ * runtime runs MainAgent in edit mode and commits the result in place.
353
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md.
354
+ * - 'none': no script is relevant; full agent flow runs.
355
+ */
356
+ type MatchTier = 'high' | 'near' | 'edit' | 'none';
357
+ /**
358
+ * Which recipe produced the answer the user is currently looking at.
359
+ *
360
+ * Set whenever a turn's answer came from a script (replay, fresh authoring, or
361
+ * a committed edit) and carried on the UIBlock + saved conversation row. Two
362
+ * consumers:
363
+ * 1. The matcher — the 'edit' tier is ONLY reachable when a binding exists, so
364
+ * "use mode instead of mean" resolves to a concrete script instead of being
365
+ * matched on keywords it shares with no script name.
366
+ * 2. Cache invalidation — after an edit commits, conversations bound to that
367
+ * recipeId must be dropped, or the exact-match cache replays the pre-edit
368
+ * answer and the edit looks like a no-op.
369
+ *
370
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
371
+ */
372
+ interface ScriptBinding {
373
+ recipeId: string;
374
+ /** Params the script ran with — the edit's starting point. */
375
+ params: Record<string, any>;
376
+ /** Recipe name at bind time (matcher catalog + user-facing confirmation). */
377
+ name: string;
378
+ /** Columns the last run returned — grounds the editor without a re-query. */
379
+ columns?: string[];
380
+ /**
381
+ * The question that produced this answer. Required for disambiguation when a
382
+ * thread ran several scripts — without it the candidates are just names and
383
+ * the matcher cannot resolve "use the mode for the WSP one".
384
+ */
385
+ userPrompt?: string;
386
+ }
387
+ /**
388
+ * Result from the LLM-based script matcher.
389
+ *
390
+ * For `tier: 'high'`, `extractedParams` carries the values to pass to the
391
+ * existing script. For `tier: 'near'`, `gaps` and `modificationHint` describe
392
+ * what the fork-author needs to change in the parent body.
393
+ */
394
+ interface ScriptMatch {
395
+ /** The matched script recipe */
396
+ recipe: ScriptRecipe;
397
+ /** Match tier — see MatchTier docs */
398
+ tier: MatchTier;
399
+ /** Similarity score (0-1, derived from LLM tier) */
400
+ similarity: number;
401
+ /**
402
+ * Legacy confidence level. Mirrors `tier === 'high'`/`'near'` for now;
403
+ * kept so existing callers compile while we migrate to tier-based logic.
404
+ */
405
+ confidence: 'high' | 'medium';
406
+ /** Parameters extracted from the user question by the LLM (tier='high') */
407
+ extractedParams?: Record<string, any>;
408
+ /**
409
+ * Proper nouns the question named, VERBATIM, with the parameter each fills.
410
+ *
411
+ * The matcher must NOT resolve these itself. Observed live: it substituted the
412
+ * customer name "PREMER ENRGES PHOTOOTAIC" into an id parameter believing that
413
+ * "the runtime will resolve the customer name to its PartyId(s)" — nothing on
414
+ * the replay path does, and `WHERE BillingPartyId IN (PREMER ENRGES
415
+ * PHOTOOTAIC)` reached SQL. Reported here, the runtime resolves them before
416
+ * replay and rejects the match when one cannot be resolved.
417
+ */
418
+ mentions?: Array<{
419
+ text: string;
420
+ param?: string;
421
+ }>;
422
+ /** Business concepts the question relies on (e.g. "outstanding balance"). */
423
+ entityTypes?: string[];
424
+ /** What the user question needs that the parent doesn't cover (tier='near') */
425
+ gaps?: string[];
426
+ /** One-sentence description of the change the fork-author should make (tier='near') */
427
+ modificationHint?: string;
428
+ /**
429
+ * Which HALF of the recipe the edit targets (tier='edit'). A recipe has two
430
+ * independently editable halves:
431
+ * - 'data' — the scriptBody: how the rows are produced (aggregation,
432
+ * filters, joins, grouping). Runs MainAgent in edit mode.
433
+ * - 'display' — the component specs: how those SAME rows are shown (chart
434
+ * type, orientation, columns, labels). Replays the proven SQL
435
+ * and regenerates the specs — never authors a script.
436
+ * Defaults to 'data' when the matcher omits it.
437
+ */
438
+ editTarget?: 'data' | 'display';
439
+ /**
440
+ * Self-contained restatement of the change the user asked for (tier='edit').
441
+ * MUST have pronouns/deixis resolved ("this", "it", "that column") — the edit
442
+ * prompt never sees the conversation history, so an unresolved instruction is
443
+ * unusable downstream.
444
+ */
445
+ editInstruction?: string;
446
+ /** Why the matcher made this choice (for logs and telemetry) */
447
+ reasoning?: string;
448
+ }
449
+
450
+ /**
451
+ * Multi-Agent Architecture Types
452
+ *
453
+ * Defines interfaces for the hierarchical agent system:
454
+ * - Main Agent: ONE LLM.streamWithTools() call with source agent tools
455
+ * - Source Agents: independent agents that query individual data sources
456
+ *
457
+ * The main agent sees only source summaries. When it calls a source tool,
458
+ * the SourceAgent runs independently (own LLM, own retries) and returns clean data.
459
+ */
460
+
461
+ /**
462
+ * Per-entity detail: name, row count, and column names.
463
+ * Gives the main agent enough context to route to the right source.
464
+ */
465
+ interface EntityDetail {
466
+ /** Entity name (table, sheet, endpoint) */
467
+ name: string;
468
+ /** Approximate row count */
469
+ rowCount?: number;
470
+ /** Column/field names */
471
+ columns: string[];
472
+ /** Entity-level semantic summary (what the table means) — for main-agent routing. */
473
+ summary?: string;
474
+ }
475
+ /**
476
+ * Representation of a data source for the main agent.
477
+ * Contains entity names WITH column names so the LLM can route accurately.
478
+ */
479
+ interface SourceSummary {
480
+ /** Source ID (matches tool ID prefix) */
481
+ id: string;
482
+ /** Human-readable source name */
483
+ name: string;
484
+ /** Source type: postgres, excel, rest_api, etc. */
485
+ type: string;
486
+ /** Brief description of what data this source contains */
487
+ description: string;
488
+ /** Detailed entity info with column names for routing */
489
+ entityDetails: EntityDetail[];
490
+ /** The tool ID associated with this source */
491
+ toolId: string;
492
+ }
493
+ /**
494
+ * What a source agent returns after querying its data source.
495
+ * The main agent uses this to analyze and compose the final response.
496
+ */
497
+ interface SourceAgentResult {
498
+ /** Source ID */
499
+ sourceId: string;
500
+ /** Source name */
501
+ sourceName: string;
502
+ /** Whether the query succeeded */
503
+ success: boolean;
504
+ /** Result data rows */
505
+ data: any[];
506
+ /** Metadata about the query execution */
507
+ metadata: SourceAgentMetadata;
508
+ /** Tool execution info for the last successful query (backward compat) */
509
+ executedTool: ExecutedToolInfo;
510
+ /** All successful tool executions (primary + follow-up queries) */
511
+ allExecutedTools?: ExecutedToolInfo[];
512
+ /** Error message if failed */
513
+ error?: string;
514
+ }
515
+ interface SourceAgentMetadata {
516
+ /** Total rows that matched the query (before limit) */
517
+ totalRowsMatched: number;
518
+ /** Rows actually returned (after limit) */
519
+ rowsReturned: number;
520
+ /** Whether the result was truncated by the row limit */
521
+ isLimited: boolean;
522
+ /** The query/params that were executed */
523
+ queryExecuted?: string;
524
+ /** Execution time in milliseconds */
525
+ executionTimeMs: number;
526
+ }
527
+ /**
528
+ * A pre-built, multi-step UI flow registered with the SDK.
529
+ *
530
+ * When the main agent decides a user's question matches a workflow's whenToUse
531
+ * trigger, it picks the workflow instead of running source agents / generating
532
+ * dashboard components. The LLM extracts the workflow's required props from the
533
+ * prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
534
+ * workflow component directly — no analysis text, no chart generation. The
535
+ * frontend renders the registered workflow component with the LLM-extracted
536
+ * props.
537
+ */
538
+ interface WorkflowDescriptor {
539
+ /** Unique workflow id (used as the LLM tool name) */
540
+ id: string;
541
+ /** Component name on the frontend (matches the registered React component) */
542
+ name: string;
543
+ /** Short human-readable description of what this workflow does */
544
+ description: string;
545
+ /**
546
+ * 1–2 sentence trigger condition. The LLM uses this to decide if the
547
+ * user's prompt matches this workflow. Be specific — e.g.
548
+ * "User wants to *initiate* an inventory transfer (review + submit POs),
549
+ * not just see analysis or charts."
550
+ */
551
+ whenToUse: string;
552
+ /**
553
+ * JSON-schema-style description of the props the workflow needs. Becomes
554
+ * the LLM tool's input_schema, so the model fills these from the prompt.
555
+ * Use the same shape as `params` on direct tools — string descriptors with
556
+ * an optional "(optional)" suffix.
557
+ *
558
+ * Example:
559
+ * ```
560
+ * {
561
+ * selectedStore: 'object — { id, name } of the source branch',
562
+ * minROI: 'number (optional) — only show transfers with ROI ≥ this',
563
+ * }
564
+ * ```
565
+ */
566
+ propsSchema: Record<string, string>;
567
+ /**
568
+ * Optional: static prop defaults merged with LLM-extracted props before
569
+ * the component is returned. Useful for things like the embedded
570
+ * `externalTool` config that the workflow uses to fetch its own data.
571
+ */
572
+ defaultProps?: Record<string, any>;
573
+ }
574
+ /**
575
+ * The workflow selection captured during a routing call.
576
+ * Set on AgentResponse when the LLM picks a workflow tool.
577
+ */
578
+ interface SelectedWorkflow {
579
+ /** Component name (matches WorkflowDescriptor.name) */
580
+ name: string;
581
+ /** Props extracted from the prompt + merged with workflow.defaultProps */
582
+ props: Record<string, any>;
583
+ }
584
+ /**
585
+ * Set when this turn applies a user-directed edit to an existing script instead
586
+ * of authoring a new one. MainAgent keeps the SAME harness (tools, loop,
587
+ * write_script/execute_script verification) and swaps only the system prompt —
588
+ * `agent-main-edit` instead of `agent-main`.
589
+ *
590
+ * The two framings contradict each other on whether to query a source first, so
591
+ * they must never be resident in one rendered prompt.
592
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § D3.
593
+ */
594
+ interface EditContext {
595
+ /** Recipe being edited — the shadow draft records it as parentId. */
596
+ recipeId: string;
597
+ parentName: string;
598
+ parentBody: string;
599
+ /** Self-contained restatement of the change (from the matcher). */
600
+ instruction: string;
601
+ /** Columns the last run returned — grounds the edit without a re-query. */
602
+ lastResultColumns?: string[];
603
+ /** Rendered parameter list of the parent, for the prompt. */
604
+ parentParams?: string;
605
+ }
606
+ /**
607
+ * The complete response from the multi-agent system.
608
+ * Contains everything needed for text display + component generation.
609
+ */
610
+ interface AgentResponse {
611
+ /** Generated text response (analysis of the data) */
612
+ text: string;
613
+ /** All executed tools across all source agents (for component generation) */
614
+ executedTools: ExecutedToolInfo[];
615
+ /** Individual results from each source agent */
616
+ sourceResults: SourceAgentResult[];
617
+ /**
618
+ * Populated when MainAgent wrote AND successfully executed a script during its turn.
619
+ * Caller (agent-user-response.ts) persists it via ScriptStore.save().
620
+ * Absent when MainAgent didn't write one (trivial question / all attempts failed).
621
+ */
622
+ savedScript?: AgentWrittenScript;
623
+ /**
624
+ * Set when the LLM routed the question to a registered workflow component.
625
+ * When present, the upstream caller should skip component generation and
626
+ * return this workflow as the response.
627
+ */
628
+ workflow?: SelectedWorkflow;
629
+ /**
630
+ * Validated component specs the agent authored via `render_components`.
631
+ * When present the caller assembles the dashboard from these instead of
632
+ * running the component-generation LLM. Absent when the agent didn't call
633
+ * the tool — the caller then falls back to `generateScriptComponents`.
634
+ * See backend/docs/COMPONENT-GENERATION-V2.md §2.2.
635
+ */
636
+ componentSpecs?: ScriptComponentSpec[];
637
+ /** Layout title/description from the same `render_components` call. */
638
+ componentLayout?: {
639
+ title: string;
640
+ description?: string;
641
+ };
642
+ }
643
+ /**
644
+ * A script MainAgent authored + verified during its turn. Shape aligns with
645
+ * what ScriptStore.save() needs — minus store-assigned fields (id, timestamps, counts).
646
+ */
647
+ interface AgentWrittenScript {
648
+ /**
649
+ * `ScriptRecipe.id` of the draft that was authored + verified during this turn.
650
+ * The caller passes this to `ScriptStore.promoteToVerified(recipeId, …)` to
651
+ * flip the draft to verified status and (when possible) drop the turn-suffix
652
+ * from its filename.
653
+ */
654
+ recipeId: string;
655
+ name: string;
656
+ intentDescription: string;
657
+ tags: string[];
658
+ parameters: Array<{
659
+ name: string;
660
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
661
+ required: boolean;
662
+ default?: any;
663
+ enumValues?: Record<string, string>;
664
+ description: string;
665
+ }>;
666
+ scriptBody: string;
667
+ /** Source IDs referenced by the script (extracted from ctx.query calls) */
668
+ sourceIds: string[];
669
+ /** Tables referenced in the script's SQL (regex-extracted) */
670
+ tables: string[];
671
+ /** Executed queries from the verified run — fed to component generation */
672
+ executedQueries: Array<{
673
+ sourceId: string;
674
+ sourceName: string;
675
+ sql: string;
676
+ data: any[];
677
+ count: number;
678
+ totalCount?: number;
679
+ executionTimeMs: number;
680
+ /**
681
+ * True for synthetic entries (ctx.emit datasets, the computed:_final
682
+ * post-JS data). The component generator routes virtual sources through
683
+ * the script_dataset sentinel toolId so the frontend resolves them via
684
+ * queryCache instead of attempting to re-execute SQL.
685
+ */
686
+ virtual?: boolean;
687
+ }>;
688
+ }
689
+ /**
690
+ * Debug trace for a single chat_agent turn — which KB/schema nodes were
691
+ * retrieved and considered, and which script (if any) produced the answer.
692
+ * Persisted separately from the answer itself (fusion-5's
693
+ * `conversation_traces` table, written via `saveTrace`), never sent through
694
+ * `analyticsClient` (data-residency — see design doc §5).
695
+ */
696
+ interface RunTrace {
697
+ version: 1;
698
+ kbNodes: {
699
+ /**
700
+ * Always-on nodes included regardless of the question (getGlobalKnowledgeBase).
701
+ * `content` is the node's full text AS IT WAS at retrieval time — captured so a
702
+ * later edit/delete of the KB node doesn't erase what the LLM actually saw.
703
+ */
704
+ global: Array<{
705
+ kbId: string;
706
+ title: string;
707
+ content?: string;
708
+ }>;
709
+ /** Semantically matched for this specific question (getKnowledgeBase). Same `content` reasoning as above. */
710
+ query: Array<{
711
+ kbId: string;
712
+ title: string;
713
+ similarity?: number;
714
+ content?: string;
715
+ }>;
716
+ };
717
+ schemaNodes: {
718
+ /** MainAgent's cross-source prefilter — which sources were even considered. */
719
+ routing: Array<{
720
+ sourceId: string;
721
+ sourceName?: string;
722
+ similarity: number;
723
+ }>;
724
+ /** SourceAgent-scope per-source table resolution (MainAgent.preResolveSchema). */
725
+ preResolve: Array<{
726
+ sourceId: string;
727
+ table?: string;
728
+ description?: string;
729
+ similarity: number;
730
+ }>;
731
+ /**
732
+ * The exact {{SOURCE_SUMMARIES}} text injected into MainAgent's system prompt
733
+ * (agent-prompt-builder.ts's formatSummariesForPrompt output) — every
734
+ * registered source's catalog entry, not retrieval-specific, captured once per
735
+ * turn. This is what the main agent actually saw when deciding which source(s)
736
+ * to call.
737
+ */
738
+ mainAgentCatalog?: string;
739
+ /**
740
+ * One entry per SourceAgent dispatch (a source called twice in one turn gets
741
+ * two entries) — the exact {{FULL_SCHEMA}} text injected into that
742
+ * SourceAgent's own system prompt, however it was sourced, plus any
743
+ * search_schema follow-up lookups it made mid-conversation when the schema
744
+ * shown wasn't enough.
745
+ */
746
+ sourceAgentSchemas: Array<{
747
+ sourceId: string;
748
+ sourceName?: string;
749
+ /** How `schemaText` was sourced — see SourceAgent.buildPrompt's fullSchema fallback chain. */
750
+ method: 'preresolved-embedding' | 'tool-full-schema' | 'tool-description' | 'none';
751
+ schemaText: string;
752
+ /** In call order — each search_schema tool call this SourceAgent made, and the exact result text handed back to its own LLM. */
753
+ searchSchemaLookups: Array<{
754
+ keywords: string[];
755
+ result: string;
756
+ }>;
757
+ }>;
758
+ };
759
+ /** The script that produced this answer, if any. Null for a general (no-tool) answer. */
760
+ script: {
761
+ /** True when an existing recipe was replayed unchanged (ScriptMatcher tier='high'). */
762
+ reused: boolean;
763
+ recipeId?: string | null;
764
+ body?: string | null;
765
+ /** Set when reused — the matcher's reasoning for picking this recipe. */
766
+ reasoning?: string | null;
767
+ } | null;
768
+ }
769
+ /**
770
+ * Configuration for the multi-agent system.
771
+ * Controls limits, models, and behavior.
772
+ */
773
+ interface AgentConfig {
774
+ /** Max rows shown to the UI preview / inlined per source (default: 10) */
775
+ maxRowsPerSource: number;
776
+ /**
777
+ * Max rows a source query may FETCH from the DB server-side (default: 2000).
778
+ * Decoupled from what the main agent is shown: the full result is fetched and
779
+ * summarized (bounded), but only a small/complete slice enters LLM context.
780
+ * This lets small lookups (benchmark maps) arrive COMPLETE without letting
781
+ * large results blow up context.
782
+ */
783
+ maxRowsFetched: number;
784
+ /** Model for the main agent (routing + analysis in one LLM call) */
785
+ mainAgentModel: string;
786
+ /** Model for source agent query generation */
787
+ sourceAgentModel: string;
788
+ /** API key for LLM calls */
789
+ apiKey?: string;
790
+ /** Max retry attempts per source agent */
791
+ maxRetries: number;
792
+ /** Max tool calling iterations for the main agent loop */
793
+ maxIterations: number;
794
+ /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
795
+ globalKnowledgeBase?: string;
796
+ /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
797
+ knowledgeBaseContext?: string;
798
+ /** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
799
+ collections?: any;
800
+ /** Optional project ID for scoping embedding searches */
801
+ projectId?: string;
802
+ /**
803
+ * Optional debug-trace accumulator for this turn (Phase 1, chat_agent only).
804
+ * When present, MainAgent-scope retrieval call sites (e.g. preResolveSchema)
805
+ * push their structured results into it. Absent for callers that don't care
806
+ * about trace capture (e.g. headless flows) — every push site must treat
807
+ * this as optional and never let a capture failure affect the real answer.
808
+ */
809
+ trace?: RunTrace;
810
+ }
811
+ /**
812
+ * Default agent configuration
813
+ */
814
+ declare const DEFAULT_AGENT_CONFIG: AgentConfig;
815
+
4
816
  /**
5
817
  * Unified UIBlock structure for database storage
6
- * Used in both bookmarks and user-conversations tables
818
+ * Used in both bookmarks and user-conversations tables.
819
+ *
820
+ * `analysis` always holds whatever real narration exists — the full answer on
821
+ * success, or whatever was actually streamed before a failure (may be empty).
822
+ * `error` is a dedicated field, null on success — it can be a plain string OR
823
+ * a structured object/array (e.g. the agent's raw `errors` list), whatever
824
+ * shape the failure naturally has; it's never coerced into `analysis`.
7
825
  */
8
826
  interface DBUIBlock {
9
827
  id: string;
10
828
  component: Record<string, any> | null;
11
829
  analysis: string | null;
12
830
  user_prompt: string;
831
+ error?: unknown | null;
832
+ /**
833
+ * The script recipe that produced this answer, when one did. Read back via
834
+ * `conversation-history.exactMatch` so an edit follow-up still has a target
835
+ * after a reload (the in-memory thread is gone by then), and indexed so
836
+ * committing an edit can purge every cached answer bound to the recipe.
837
+ */
838
+ scriptBinding?: {
839
+ recipeId: string;
840
+ params?: Record<string, any>;
841
+ name?: string;
842
+ columns?: string[];
843
+ };
13
844
  }
14
845
 
15
846
  /**
@@ -160,6 +991,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
160
991
  dependencies?: string[] | undefined;
161
992
  } | undefined;
162
993
  props?: Record<string, any> | undefined;
994
+ data?: Record<string, any> | undefined;
163
995
  render?: any;
164
996
  states?: Record<string, any> | undefined;
165
997
  methods?: Record<string, {
@@ -170,7 +1002,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
170
1002
  fn: string;
171
1003
  deps?: string[] | undefined;
172
1004
  }[] | undefined;
173
- data?: Record<string, any> | undefined;
174
1005
  pages?: {
175
1006
  id: string;
176
1007
  name: string;
@@ -192,6 +1023,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
192
1023
  dependencies?: string[] | undefined;
193
1024
  } | undefined;
194
1025
  props?: Record<string, any> | undefined;
1026
+ data?: Record<string, any> | undefined;
195
1027
  render?: any;
196
1028
  states?: Record<string, any> | undefined;
197
1029
  methods?: Record<string, {
@@ -202,7 +1034,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
202
1034
  fn: string;
203
1035
  deps?: string[] | undefined;
204
1036
  }[] | undefined;
205
- data?: Record<string, any> | undefined;
206
1037
  pages?: {
207
1038
  id: string;
208
1039
  name: string;
@@ -228,6 +1059,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
228
1059
  dependencies?: string[] | undefined;
229
1060
  } | undefined;
230
1061
  props?: Record<string, any> | undefined;
1062
+ data?: Record<string, any> | undefined;
231
1063
  render?: any;
232
1064
  states?: Record<string, any> | undefined;
233
1065
  methods?: Record<string, {
@@ -238,7 +1070,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
238
1070
  fn: string;
239
1071
  deps?: string[] | undefined;
240
1072
  }[] | undefined;
241
- data?: Record<string, any> | undefined;
242
1073
  pages?: {
243
1074
  id: string;
244
1075
  name: string;
@@ -264,6 +1095,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
264
1095
  dependencies?: string[] | undefined;
265
1096
  } | undefined;
266
1097
  props?: Record<string, any> | undefined;
1098
+ data?: Record<string, any> | undefined;
267
1099
  render?: any;
268
1100
  states?: Record<string, any> | undefined;
269
1101
  methods?: Record<string, {
@@ -274,7 +1106,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
274
1106
  fn: string;
275
1107
  deps?: string[] | undefined;
276
1108
  }[] | undefined;
277
- data?: Record<string, any> | undefined;
278
1109
  pages?: {
279
1110
  id: string;
280
1111
  name: string;
@@ -355,6 +1186,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
355
1186
  dependencies?: string[] | undefined;
356
1187
  } | undefined;
357
1188
  props?: Record<string, any> | undefined;
1189
+ data?: Record<string, any> | undefined;
358
1190
  render?: any;
359
1191
  states?: Record<string, any> | undefined;
360
1192
  methods?: Record<string, {
@@ -365,7 +1197,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
365
1197
  fn: string;
366
1198
  deps?: string[] | undefined;
367
1199
  }[] | undefined;
368
- data?: Record<string, any> | undefined;
369
1200
  }, {
370
1201
  id: string;
371
1202
  name?: string | undefined;
@@ -379,6 +1210,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
379
1210
  dependencies?: string[] | undefined;
380
1211
  } | undefined;
381
1212
  props?: Record<string, any> | undefined;
1213
+ data?: Record<string, any> | undefined;
382
1214
  render?: any;
383
1215
  states?: Record<string, any> | undefined;
384
1216
  methods?: Record<string, {
@@ -389,7 +1221,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
389
1221
  fn: string;
390
1222
  deps?: string[] | undefined;
391
1223
  }[] | undefined;
392
- data?: Record<string, any> | undefined;
393
1224
  }>;
394
1225
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
395
1226
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -407,6 +1238,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
407
1238
  dependencies?: string[] | undefined;
408
1239
  } | undefined;
409
1240
  props?: Record<string, any> | undefined;
1241
+ data?: Record<string, any> | undefined;
410
1242
  render?: any;
411
1243
  states?: Record<string, any> | undefined;
412
1244
  methods?: Record<string, {
@@ -417,7 +1249,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
417
1249
  fn: string;
418
1250
  deps?: string[] | undefined;
419
1251
  }[] | undefined;
420
- data?: Record<string, any> | undefined;
421
1252
  };
422
1253
  data?: Record<string, any> | undefined;
423
1254
  context?: Record<string, any> | undefined;
@@ -435,6 +1266,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
435
1266
  dependencies?: string[] | undefined;
436
1267
  } | undefined;
437
1268
  props?: Record<string, any> | undefined;
1269
+ data?: Record<string, any> | undefined;
438
1270
  render?: any;
439
1271
  states?: Record<string, any> | undefined;
440
1272
  methods?: Record<string, {
@@ -445,7 +1277,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
445
1277
  fn: string;
446
1278
  deps?: string[] | undefined;
447
1279
  }[] | undefined;
448
- data?: Record<string, any> | undefined;
449
1280
  };
450
1281
  data?: Record<string, any> | undefined;
451
1282
  context?: Record<string, any> | undefined;
@@ -777,6 +1608,14 @@ declare const ToolSchema: z.ZodObject<{
777
1608
  description: string;
778
1609
  }[];
779
1610
  }>>;
1611
+ /** Cache policy. `false` = never cache (live data, write ops). Mirrors HTTP `Cache-Control: no-store`. */
1612
+ cache: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<false>, z.ZodObject<{
1613
+ ttlMs: z.ZodOptional<z.ZodNumber>;
1614
+ }, "strip", z.ZodTypeAny, {
1615
+ ttlMs?: number | undefined;
1616
+ }, {
1617
+ ttlMs?: number | undefined;
1618
+ }>]>>;
780
1619
  }, "strip", z.ZodTypeAny, {
781
1620
  id: string;
782
1621
  params: Record<string, string>;
@@ -793,6 +1632,9 @@ declare const ToolSchema: z.ZodObject<{
793
1632
  description: string;
794
1633
  }[];
795
1634
  } | undefined;
1635
+ cache?: false | {
1636
+ ttlMs?: number | undefined;
1637
+ } | undefined;
796
1638
  }, {
797
1639
  id: string;
798
1640
  params: Record<string, string>;
@@ -809,6 +1651,9 @@ declare const ToolSchema: z.ZodObject<{
809
1651
  description: string;
810
1652
  }[];
811
1653
  } | undefined;
1654
+ cache?: false | {
1655
+ ttlMs?: number | undefined;
1656
+ } | undefined;
812
1657
  }>;
813
1658
  type Tool$1 = z.infer<typeof ToolSchema>;
814
1659
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
@@ -994,7 +1839,7 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
994
1839
  content?: string | undefined;
995
1840
  }>>;
996
1841
  }, "strip", z.ZodTypeAny, {
997
- operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
1842
+ operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
998
1843
  data?: {
999
1844
  id?: number | undefined;
1000
1845
  type?: "query" | "user" | "global" | undefined;
@@ -1017,7 +1862,7 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
1017
1862
  content?: string | undefined;
1018
1863
  } | undefined;
1019
1864
  }, {
1020
- operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
1865
+ operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
1021
1866
  data?: {
1022
1867
  id?: number | undefined;
1023
1868
  type?: "query" | "user" | "global" | undefined;
@@ -1306,6 +2151,503 @@ declare class ReportManager {
1306
2151
  getReportCount(): number;
1307
2152
  }
1308
2153
 
2154
+ /**
2155
+ * ScriptRecipeStore — injected metadata backend for the script flow.
2156
+ *
2157
+ * The SDK is standalone (no DB dependency). The backend implements this
2158
+ * interface over Postgres (full-text search + atomic counters) and injects it
2159
+ * via `collections['script-recipes']`, exactly like `collections['source-embeddings']`.
2160
+ * `ScriptStore` consumes it for all METADATA operations while keeping the
2161
+ * executable body on disk as scripts-store/<fileBase>.ts.
2162
+ *
2163
+ * All metadata rows are plain JSON (no scriptBody — that lives on disk).
2164
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md (#1, #3, #7).
2165
+ */
2166
+
2167
+ /** One recipe's metadata as stored in Postgres (mirrors the script_recipes table). */
2168
+ interface ScriptRecipeMetaRow {
2169
+ id: string;
2170
+ projectId?: string | null;
2171
+ version: number;
2172
+ name: string;
2173
+ intentDescription: string;
2174
+ tags: string[] | null;
2175
+ createdFrom: string | null;
2176
+ sourceIds: string[] | null;
2177
+ tables: string[] | null;
2178
+ parameters: ScriptParameter[] | null;
2179
+ components?: ScriptComponentSpec[] | null;
2180
+ displayPreference?: ScriptDisplayPreference | null;
2181
+ fileBase: string;
2182
+ bodyHash?: string | null;
2183
+ successCount: number;
2184
+ failureCount: number;
2185
+ lastUsed: string | null;
2186
+ parentId?: string | null;
2187
+ forkDepth?: number | null;
2188
+ forkReason?: string | null;
2189
+ status: 'draft' | 'verified' | string;
2190
+ turnId?: string | null;
2191
+ editedBy?: string | null;
2192
+ editedFrom?: string | null;
2193
+ history?: ScriptVersionRecord[] | null;
2194
+ lastError?: {
2195
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2196
+ message: string;
2197
+ at: string;
2198
+ attempt: number;
2199
+ } | null;
2200
+ createdAt?: string | null;
2201
+ updatedAt?: string | null;
2202
+ }
2203
+ interface ScriptRecipeStore {
2204
+ /** FTS shortlist of healthy verified recipes for the matcher (metadata only). */
2205
+ search(params: {
2206
+ prompt: string;
2207
+ projectId?: string;
2208
+ limit?: number;
2209
+ }): Promise<ScriptRecipeMetaRow[]>;
2210
+ /** Fetch one recipe by id (any status). */
2211
+ getById(id: string): Promise<ScriptRecipeMetaRow | null>;
2212
+ /** Count healthy verified recipes (drives the "any scripts?" gate). */
2213
+ count(params?: {
2214
+ projectId?: string;
2215
+ }): Promise<number>;
2216
+ /** Insert or update a recipe row (keyed by id). */
2217
+ upsert(row: ScriptRecipeMetaRow): Promise<void>;
2218
+ /** Atomically bump counters / last-used. */
2219
+ updateStats(id: string, patch: {
2220
+ successDelta?: number;
2221
+ failureDelta?: number;
2222
+ lastUsed?: string;
2223
+ }): Promise<void>;
2224
+ /** Flip a draft to verified, applying provenance + optional fork lineage. */
2225
+ promote(id: string, patch: {
2226
+ sourceIds: string[];
2227
+ tables: string[];
2228
+ fileBase?: string;
2229
+ parentId?: string;
2230
+ forkDepth?: number;
2231
+ forkReason?: string;
2232
+ components?: ScriptComponentSpec[];
2233
+ }): Promise<ScriptRecipeMetaRow | null>;
2234
+ /**
2235
+ * Commit a verified edit onto an EXISTING recipe: bump `version`, replace the
2236
+ * body-bearing metadata, append a history record, reset health counters, and
2237
+ * clear the component specs (they were validated against the old shape).
2238
+ * Returns the updated row, or null when the target is gone.
2239
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5.
2240
+ */
2241
+ commitEdit?(id: string, patch: {
2242
+ name?: string;
2243
+ intentDescription?: string;
2244
+ tags?: string[];
2245
+ parameters?: ScriptParameter[];
2246
+ bodyHash: string;
2247
+ /** New on-disk stem when the edit renamed the script; omitted otherwise. */
2248
+ fileBase?: string;
2249
+ sourceIds?: string[];
2250
+ tables?: string[];
2251
+ editedBy?: string;
2252
+ editedFrom?: string;
2253
+ historyEntry: {
2254
+ version: number;
2255
+ at: string;
2256
+ by?: string;
2257
+ instruction?: string;
2258
+ changeSummary?: string;
2259
+ bodyHash?: string;
2260
+ };
2261
+ }): Promise<ScriptRecipeMetaRow | null>;
2262
+ /** Stamp a draft's last execution error. */
2263
+ recordDraftError(id: string, err: {
2264
+ phase: string;
2265
+ message: string;
2266
+ attempt: number;
2267
+ at: string;
2268
+ }): Promise<void>;
2269
+ /** Delete a recipe row (body file removed separately). */
2270
+ remove(id: string): Promise<void>;
2271
+ /** True if `fileBase` is taken by a different recipe in this project. */
2272
+ fileBaseTaken(fileBase: string, excludeId: string, projectId?: string): Promise<boolean>;
2273
+ }
2274
+ /** Pull the injected store off the collections bag (or null if not wired). */
2275
+ declare function resolveScriptRecipeStore(collections: any): ScriptRecipeStore | null;
2276
+
2277
+ /**
2278
+ * ScriptStore — Postgres metadata + on-disk body for script recipes.
2279
+ *
2280
+ * Split of responsibilities:
2281
+ * - METADATA → injected `ScriptRecipeStore` (Postgres FTS + atomic counters),
2282
+ * resolved from `collections['script-recipes']`.
2283
+ * - BODY → scripts-store/<fileBase>.ts, editable in your IDE. Written
2284
+ * atomically (temp + rename); `bodyHash` (sha256) detects edits.
2285
+ *
2286
+ * The old "read every file every turn + send the whole catalog to the LLM"
2287
+ * matcher is gone — matching is `store.search(prompt)` (FTS shortlist). The
2288
+ * draft/verified filename dance is gone too: `status` is a DB column and the
2289
+ * file keeps a stable `<fileBase>.ts` name across promotion.
2290
+ *
2291
+ * When no metadata store is injected, the store degrades to a safe no-op
2292
+ * (count 0 → script flow disabled) instead of crashing.
2293
+ *
2294
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md.
2295
+ */
2296
+
2297
+ interface SaveDraftInput {
2298
+ /** Reuse an existing draft (retry); omit to mint a new one. */
2299
+ recipeId?: string;
2300
+ /** Per-turn unique suffix, stable across retries within the turn. */
2301
+ turnId: string;
2302
+ name: string;
2303
+ intentDescription: string;
2304
+ tags: string[];
2305
+ parameters: ScriptParameter[];
2306
+ scriptBody: string;
2307
+ createdFrom: string;
2308
+ /**
2309
+ * Set when this draft is a SHADOW of an existing recipe being edited. The
2310
+ * draft is verified independently and merged back onto the parent via
2311
+ * `commitEdit`, so the working script is never clobbered by an edit that
2312
+ * turns out not to run. See backend/docs/SCRIPT-EDIT-DESIGN.md § D5.
2313
+ */
2314
+ parentId?: string;
2315
+ }
2316
+ interface PromoteToVerifiedInput {
2317
+ sourceIds: string[];
2318
+ tables: string[];
2319
+ parentId?: string;
2320
+ forkDepth?: number;
2321
+ forkReason?: string;
2322
+ components?: ScriptComponentSpec[];
2323
+ }
2324
+ interface ScriptStoreOptions {
2325
+ /** Explicit metadata store, or resolved from `collections['script-recipes']`. */
2326
+ store?: ScriptRecipeStore | null;
2327
+ collections?: any;
2328
+ /** Body directory (defaults to <cwd>/scripts-store). */
2329
+ baseDir?: string;
2330
+ /** Project scope stamped on every row. */
2331
+ projectId?: string;
2332
+ }
2333
+ /**
2334
+ * Normalize a scriptBody into the on-disk form (strip a leading comment block,
2335
+ * ensure `export async function getData`). Exported for MainAgent.
2336
+ */
2337
+ declare function normalizeScriptBody(scriptBody: string): string;
2338
+ declare class ScriptStore {
2339
+ private store;
2340
+ private storeDir;
2341
+ private projectId?;
2342
+ constructor(opts?: ScriptStoreOptions);
2343
+ /** Whether a metadata store is wired (matcher / authoring are gated on this). */
2344
+ hasStore(): boolean;
2345
+ /** Number of healthy verified recipes (gates the script-matching path). */
2346
+ count(): Promise<number>;
2347
+ /**
2348
+ * FTS shortlist for the matcher (metadata only — bodies are loaded lazily by
2349
+ * `get()` once the LLM picks one). Returns verified, healthy recipes ranked
2350
+ * by relevance.
2351
+ */
2352
+ search(prompt: string, limit?: number): Promise<ScriptRecipe[]>;
2353
+ /** Fetch one recipe by id with its body loaded from disk. */
2354
+ get(id: string): Promise<ScriptRecipe | null>;
2355
+ /** Create or update a recipe (metadata upsert + body write when changed). */
2356
+ save(recipe: ScriptRecipe): Promise<void>;
2357
+ /**
2358
+ * Persist (or update) a draft. Within a turn, retries that pass the same
2359
+ * `recipeId` overwrite the same row + file; a fresh `recipeId` mints a new
2360
+ * draft. The body is visible at scripts-store/<fileBase>.ts immediately.
2361
+ */
2362
+ saveDraft(input: SaveDraftInput): Promise<ScriptRecipe>;
2363
+ /** Stamp a draft's last execution error (metadata only). */
2364
+ recordDraftError(recipeId: string, err: {
2365
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2366
+ message: string;
2367
+ attempt: number;
2368
+ }): Promise<void>;
2369
+ /**
2370
+ * Promote a successfully-executed draft into a verified script.
2371
+ * The on-disk body already exists at <fileBase>.ts (written at write_script
2372
+ * time) and keeps its name — only the DB row flips status + provenance.
2373
+ */
2374
+ promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): Promise<ScriptRecipe | null>;
2375
+ /**
2376
+ * Commit a user-directed edit: merge a VERIFIED shadow draft back onto the
2377
+ * recipe it was editing, as version N+1 under the SAME recipe id.
2378
+ *
2379
+ * Keeping the id stable is the point of the whole feature — every cached
2380
+ * conversation, `script_dataset` regeneration descriptor and persisted
2381
+ * component spec already points at it, so the correction applies retroactively
2382
+ * to replays instead of stranding them on the old body.
2383
+ *
2384
+ * Steps (see backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5):
2385
+ * 1. archive the current body as `<fileBase>.v<version>.ts`
2386
+ * 2. write the edited body to the original fileBase (atomic)
2387
+ * 3. version++, copy name/description/params, append a history record
2388
+ * 4. reset health counters — the pre-edit failure history is stale
2389
+ * 5. clear component specs — they were validated against the OLD shape
2390
+ * 6. delete the shadow draft (row + file)
2391
+ *
2392
+ * Returns the updated recipe, or null when the commit could not be applied
2393
+ * (caller should then fall back to treating the draft as a new script).
2394
+ */
2395
+ commitEdit(targetId: string, draft: {
2396
+ recipeId: string;
2397
+ name?: string;
2398
+ intentDescription?: string;
2399
+ tags?: string[];
2400
+ parameters?: ScriptParameter[];
2401
+ scriptBody: string;
2402
+ sourceIds?: string[];
2403
+ tables?: string[];
2404
+ }, meta: {
2405
+ instruction?: string;
2406
+ changeSummary?: string;
2407
+ editedBy?: string;
2408
+ }): Promise<ScriptRecipe | null>;
2409
+ /**
2410
+ * Drop a draft (row + body file). MainAgent calls this at end-of-turn when a
2411
+ * draft was authored but never verified — failed drafts are never matched, so
2412
+ * deleting them immediately avoids unbounded accumulation (#5). No-op if the
2413
+ * recipe isn't a draft (so a promoted/verified script is never removed here).
2414
+ */
2415
+ discardDraft(recipeId: string): Promise<void>;
2416
+ /** Delete a recipe (row + body file). */
2417
+ delete(id: string): Promise<void>;
2418
+ /** Record a successful execution (atomic counter bump). */
2419
+ recordSuccess(id: string): Promise<void>;
2420
+ /** Record a failed execution (atomic counter bump). */
2421
+ recordFailure(id: string): Promise<void>;
2422
+ /** Absolute path to the .ts body for a recipe (used by the runner/MainAgent). */
2423
+ getScriptPath(recipe: ScriptRecipe): string;
2424
+ private removeById;
2425
+ private rowToRecipe;
2426
+ private recipeToRow;
2427
+ /** slug of name, with a short id suffix when the bare slug is already taken. */
2428
+ private computeFileBase;
2429
+ private toSlug;
2430
+ private hash;
2431
+ private bodyPath;
2432
+ private readBody;
2433
+ /** Directory holding superseded bodies. Dot-prefixed so IDEs/`ls` hide it. */
2434
+ private get archiveDir();
2435
+ /**
2436
+ * Archive a superseded body as `.versions/<fileBase>.v<n>.ts`.
2437
+ *
2438
+ * Kept out of the main store directory on purpose — see commitEdit step 1.
2439
+ * To roll back: copy the file back over `scripts-store/<fileBase>.ts`.
2440
+ */
2441
+ private writeArchive;
2442
+ /**
2443
+ * Move a recipe's archived versions to a new prefix when its fileBase changes,
2444
+ * so all versions of one recipe stay grouped. Without this, two renames would
2445
+ * scatter a single recipe's history across three prefixes in `.versions/` with
2446
+ * nothing linking them back to the live script.
2447
+ */
2448
+ private renameArchives;
2449
+ /** Atomic body write (temp + rename) so concurrent reads never see a partial file. */
2450
+ private writeBody;
2451
+ private unlinkBody;
2452
+ }
2453
+
2454
+ /**
2455
+ * Main Agent (Orchestrator)
2456
+ *
2457
+ * A single LLM.streamWithTools() call that handles everything:
2458
+ * - Routing: decides which source(s) to query based on summaries
2459
+ * - Querying: calls source tools (each wraps an independent SourceAgent)
2460
+ * - Direct tools: calls pre-built function tools directly with LLM-provided params
2461
+ * - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
2462
+ * - Analysis: generates final text response from the data
2463
+ *
2464
+ * Two tool types:
2465
+ * - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
2466
+ * - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
2467
+ */
2468
+
2469
+ declare class MainAgent {
2470
+ private externalTools;
2471
+ private workflows;
2472
+ private config;
2473
+ private streamBuffer;
2474
+ /**
2475
+ * Optional: when provided, MainAgent exposes the `write_script` /
2476
+ * `execute_script` tools to the LLM and persists drafts to disk via the
2477
+ * store. Headless callers (alert analyzer, metric resolver) omit these to
2478
+ * suppress script authoring entirely — drafts would otherwise leak onto
2479
+ * disk with no caller to promote or clean them up.
2480
+ */
2481
+ private scriptStore;
2482
+ private turnId;
2483
+ private createdFromPrompt;
2484
+ private scriptState;
2485
+ /** Answer-flow component catalog (filtered + projected by the caller). */
2486
+ private componentCatalog;
2487
+ /** Specs accepted by `render_components` this turn; empty until it succeeds. */
2488
+ /**
2489
+ * Entities resolved this turn, appended verbatim to every source dispatch.
2490
+ *
2491
+ * Not left to the model to copy into its intent prose: observed live, the
2492
+ * MainAgent wrote names instead of ids on the first dispatch AND re-spelled
2493
+ * 'F D C LIMITED' as 'FDC Limited', so the source agent fell back to
2494
+ * `PartyName LIKE '%FDC%'` and found 2 of 3 customers. Carrying the ids
2495
+ * structurally makes that impossible rather than instruction-dependent.
2496
+ */
2497
+ private resolvedEntities;
2498
+ private componentSpecs;
2499
+ private componentLayout;
2500
+ private renderComponentAttempts;
2501
+ /**
2502
+ * Fork mode — set when this turn is adapting a near-matching parent script.
2503
+ * In fork mode there is no legitimate "answer with bare text" outcome: the
2504
+ * only correct first move is a tool call (write_script, or a source tool for
2505
+ * schema discovery). We therefore force tool use on the first LLM iteration
2506
+ * so the model can't end its turn with a bare "I'll adapt…" preamble and zero
2507
+ * tool calls. Never set on the fresh-authoring / general-question path.
2508
+ */
2509
+ private forkMode;
2510
+ /**
2511
+ * Edit mode — set when this turn applies a user-directed change to an
2512
+ * existing script. Swaps the system prompt to `agent-main-edit` and stamps
2513
+ * the shadow draft's parentId. Like fork mode there is no legitimate
2514
+ * "answer with bare text" outcome, so tool use is forced on iteration 1.
2515
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 4.
2516
+ */
2517
+ private editContext;
2518
+ /**
2519
+ * Per-turn cancellation signal (user hit "Stop"). Set at the top of
2520
+ * handleQuestion and read by the tool handler, the SourceAgent dispatch, and
2521
+ * the script subprocess so an abort tears down every layer of the turn.
2522
+ */
2523
+ private abortSignal?;
2524
+ constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[], forkMode?: boolean, editContext?: EditContext, componentCatalog?: Component[]);
2525
+ /** True when the turn is applying a user-directed script edit. */
2526
+ private get editMode();
2527
+ private get scriptingEnabled();
2528
+ /**
2529
+ * Handle a user question using the multi-agent system.
2530
+ *
2531
+ * This is ONE LLM.streamWithTools() call. The LLM:
2532
+ * 1. Sees source summaries + direct tool descriptions in system prompt
2533
+ * 2. Decides which tool(s) to call (routing)
2534
+ * 3. Source tools → SourceAgent runs independently → returns data
2535
+ * 4. Direct tools → fn() called directly with LLM params → returns data
2536
+ * 5. Generates final analysis text
2537
+ */
2538
+ handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, signal?: AbortSignal): Promise<AgentResponse>;
2539
+ /**
2540
+ * Tool definition, with the catalog rendered from the registered `Metadata`
2541
+ * the caller passed in. Generated rather than hand-written so it cannot drift
2542
+ * from what the frontend actually ships.
2543
+ */
2544
+ private buildRenderComponentsToolDef;
2545
+ /**
2546
+ * Validate the agent's component picks against the REAL columns of each bound
2547
+ * dataset. All-or-nothing: any error rejects the whole call and returns the
2548
+ * findings, because a partially-accepted dashboard makes the retry ambiguous.
2549
+ */
2550
+ private handleRenderComponents;
2551
+ private handleWriteScript;
2552
+ private handleExecuteScript;
2553
+ /**
2554
+ * Build the AgentWrittenScript payload the caller will hand to
2555
+ * `ScriptStore.promoteToVerified()`. Only returned when a verified
2556
+ * successful execution is on record.
2557
+ */
2558
+ private buildSavedScript;
2559
+ private normalizeParameterList;
2560
+ /**
2561
+ * Use the schema embedding collection to pre-select relevant tables for
2562
+ * this source + intent. Returns a formatted schema block if confidence is
2563
+ * high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
2564
+ *
2565
+ * When this returns a block, we can skip the SourceAgent's `search_schema`
2566
+ * loop and reduce iteration budget. When it returns null, the SourceAgent
2567
+ * falls back to the existing LLM-driven keyword search (same as today).
2568
+ */
2569
+ /**
2570
+ * Ids + verbatim names for everything resolved this turn, appended by CODE to
2571
+ * each source dispatch so neither omission nor re-spelling by the model can
2572
+ * lose them. Empty string when nothing was resolved, so intents are untouched
2573
+ * for questions that name no entities.
2574
+ */
2575
+ private buildResolvedEntitiesBlock;
2576
+ /** True when the backend registered the entity-search collection. */
2577
+ private get entitySearchEnabled();
2578
+ /**
2579
+ * Compact catalog (type + gloss) for the system prompt. This is what lets the
2580
+ * LLM NAME a concept instead of guessing at our vocabulary — it can infer
2581
+ * that a question is about unpaid money, but not that we call that
2582
+ * `outstanding-balance`. Full `resolution` detail is fetched by the tool.
2583
+ *
2584
+ * Deliberately NOT cached in-process. The token cost is already handled by
2585
+ * prompt caching (the system prompt carries a cache_control breakpoint), and
2586
+ * re-reading a tiny PK-ordered table costs ~nothing. Fetching fresh does not
2587
+ * weaken the prompt cache either: unchanged data renders byte-identical text,
2588
+ * so the prefix still hits. A process cache would only buy a staleness window
2589
+ * in which a newly indexed entity is invisible to the agent.
2590
+ */
2591
+ private loadEntityCatalog;
2592
+ /**
2593
+ * Never throws: a resolver outage must degrade to "nothing resolved" and
2594
+ * leave the agent exactly as it was, not take the whole answer down.
2595
+ */
2596
+ private handleResolveEntities;
2597
+ private preResolveSchema;
2598
+ /**
2599
+ * Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
2600
+ */
2601
+ private handleDirectTool;
2602
+ /**
2603
+ * Build the main agent's system prompt with source summaries, direct tool descriptions,
2604
+ * and workflow component descriptions.
2605
+ */
2606
+ private buildSystemPrompt;
2607
+ /**
2608
+ * Build tool definitions for source tools — summary-only descriptions.
2609
+ * The full schema is inside the SourceAgent which runs independently.
2610
+ */
2611
+ private buildSourceToolDefinitions;
2612
+ /**
2613
+ * Build tool definitions for direct tools — expose their actual params.
2614
+ * These are called directly by the main agent LLM, no SourceAgent.
2615
+ */
2616
+ private buildDirectToolDefinitions;
2617
+ /**
2618
+ * Capture a workflow selection. We do NOT execute anything — the LLM has
2619
+ * already extracted the props it wants the workflow rendered with. We
2620
+ * record the selection (via the capture callback) and return a short
2621
+ * acknowledgement so the LLM ends its turn cleanly without writing
2622
+ * analysis text or calling more tools.
2623
+ */
2624
+ private handleWorkflow;
2625
+ /**
2626
+ * Build LLM tool definitions for workflow components. The workflow's
2627
+ * propsSchema becomes the tool's input_schema so the LLM extracts props
2628
+ * directly from the prompt — same mechanic as direct tools.
2629
+ */
2630
+ private buildWorkflowToolDefinitions;
2631
+ /**
2632
+ * Format a source agent's result as a clean string for the main agent LLM.
2633
+ */
2634
+ private formatResultForMainAgent;
2635
+ /**
2636
+ * Get source summaries (for external inspection/debugging).
2637
+ */
2638
+ getSourceSummaries(): SourceSummary[];
2639
+ }
2640
+
2641
+ /**
2642
+ * Represents an action that can be performed on a UIBlock
2643
+ */
2644
+ interface Action {
2645
+ id: string;
2646
+ name: string;
2647
+ type: string;
2648
+ [key: string]: any;
2649
+ }
2650
+
1309
2651
  type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
1310
2652
  interface LLMMessages {
1311
2653
  sys: SystemPrompt;
@@ -1318,7 +2660,45 @@ interface LLMOptions {
1318
2660
  temperature?: number;
1319
2661
  topP?: number;
1320
2662
  apiKey?: string;
2663
+ baseURL?: string;
1321
2664
  partial?: (chunk: string) => void;
2665
+ /**
2666
+ * Per-request cancellation. When the caller aborts this signal (user hit
2667
+ * "Stop"), the underlying provider request is cancelled and the call throws
2668
+ * a RequestAbortedError. Threaded into the provider `messages.create` request
2669
+ * options and checked between tool-loop iterations. Currently honored on the
2670
+ * Anthropic path (the agent flow's default provider).
2671
+ */
2672
+ signal?: AbortSignal;
2673
+ /**
2674
+ * Forces a tool call on the FIRST iteration of streamWithTools only
2675
+ * (subsequent iterations revert to auto). Used by fork mode to stop the
2676
+ * model from ending its turn with a bare "I'll adapt the script…" preamble
2677
+ * and zero tool calls. `{ type: 'any' }` lets the model pick which tool
2678
+ * (write_script in the common case, a source tool for schema discovery);
2679
+ * `{ type: 'tool', name }` pins a specific tool. Honored on both the
2680
+ * Anthropic path and the OpenAI/OpenRouter path (mapped to OpenAI's
2681
+ * tool_choice: 'required' / a named function).
2682
+ */
2683
+ firstIterationToolChoice?: {
2684
+ type: 'any';
2685
+ } | {
2686
+ type: 'tool';
2687
+ name: string;
2688
+ };
2689
+ /**
2690
+ * Internal — set only by the OpenRouter wrappers when the target is a Claude
2691
+ * model. Tells the OpenAI-wire path to emit Anthropic `cache_control`
2692
+ * breakpoints (OpenRouter forwards them to Anthropic for prompt caching).
2693
+ * Never set for direct OpenAI/Groq calls, so their requests are unchanged.
2694
+ */
2695
+ _openrouterClaudeCaching?: boolean;
2696
+ /**
2697
+ * Internal — OpenRouter provider-routing preferences (forwarded as the
2698
+ * `provider` body field). Set by the OpenRouter wrappers to steer routing to
2699
+ * a fast backend (e.g. {sort:'throughput'}). Never set for direct OpenAI/Groq.
2700
+ */
2701
+ _openrouterProvider?: Record<string, unknown>;
1322
2702
  }
1323
2703
  interface Tool {
1324
2704
  name: string;
@@ -1340,6 +2720,16 @@ declare class LLM {
1340
2720
  * @returns Normalized system prompt for Anthropic API
1341
2721
  */
1342
2722
  private static _normalizeSystemPrompt;
2723
+ /**
2724
+ * Strip unpaired UTF-16 surrogates from every text field of a message set.
2725
+ *
2726
+ * A lone surrogate (from mid-pair string slicing or corrupt source data)
2727
+ * serializes to a bare `\udXXX` escape that strict JSON parsers — including
2728
+ * the one on Anthropic's API — reject with "no low surrogate in string",
2729
+ * failing the whole request. Sanitizing here, at the single boundary every
2730
+ * provider call flows through, guarantees no request can carry one.
2731
+ */
2732
+ private static _sanitizeMessages;
1343
2733
  /**
1344
2734
  * Log cache usage metrics from Anthropic API response
1345
2735
  * Shows cache hits, costs, and savings
@@ -1356,11 +2746,46 @@ declare class LLM {
1356
2746
  * "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
1357
2747
  */
1358
2748
  private static _parseModel;
2749
+ /**
2750
+ * Map an Anthropic model id (e.g. "claude-sonnet-4-5-20250929") to the OpenRouter slug
2751
+ * (e.g. "claude-sonnet-4.5"). OpenRouter slugs drop the date suffix and use dotted versions.
2752
+ */
2753
+ private static _toOpenRouterSlug;
2754
+ /**
2755
+ * Per-provider proxy base URL. Returns `${SUPERATOM_LLM_PROXY_URL}/<provider>`
2756
+ * when our Cloudflare LLM proxy is configured, else undefined (→ talk to the
2757
+ * provider directly, legacy behaviour). An explicit options.baseURL (e.g.
2758
+ * OpenRouter) always wins and is never overridden. See backend/docs/llm-proxy.md.
2759
+ */
2760
+ private static _proxyBaseURL;
2761
+ private static _openrouterOptions;
2762
+ private static _isRetryableProviderError;
2763
+ private static _withOpenrouterRetry;
2764
+ private static _openrouterText;
2765
+ private static _openrouterStream;
2766
+ private static _openrouterStreamWithTools;
2767
+ /**
2768
+ * Build an Anthropic client. Routes through our Cloudflare LLM proxy when
2769
+ * SUPERATOM_LLM_PROXY_URL is set (each client ships a per-client proxy key as
2770
+ * ANTHROPIC_API_KEY and never holds the real key); otherwise talks to
2771
+ * api.anthropic.com directly. See backend/docs/llm-proxy.md.
2772
+ */
2773
+ private static _anthropicClient;
2774
+ /** True when OpenRouter is configured as a fail-open fallback for Claude. */
2775
+ private static _openrouterAvailable;
2776
+ /** Remap an Anthropic model id to the OpenRouter model path for fail-open. */
2777
+ private static _anthropicFallbackModel;
1359
2778
  private static _anthropicText;
1360
2779
  private static _anthropicStream;
1361
2780
  private static _anthropicStreamWithTools;
1362
2781
  private static _groqText;
1363
2782
  private static _groqStream;
2783
+ /**
2784
+ * Gemini request options carrying the proxy base URL, or undefined → talk to
2785
+ * generativelanguage.googleapis.com directly. The Google SDK takes baseUrl as a
2786
+ * per-model request option, not a constructor arg. See backend/docs/llm-proxy.md.
2787
+ */
2788
+ private static _geminiRequestOptions;
1364
2789
  private static _geminiText;
1365
2790
  private static _geminiStream;
1366
2791
  /**
@@ -1369,8 +2794,28 @@ declare class LLM {
1369
2794
  */
1370
2795
  private static _cleanSchemaForGemini;
1371
2796
  private static _geminiStreamWithTools;
2797
+ /** True for Anthropic/Claude model ids — gates OpenRouter prompt caching. */
2798
+ private static _isClaudeModel;
2799
+ /**
2800
+ * Build the OpenAI-wire system message. For OpenRouter + Claude
2801
+ * (cacheClaude=true) it emits content parts carrying Anthropic
2802
+ * `cache_control` breakpoints (preserving any the caller set, else marking
2803
+ * the last block), so OpenRouter forwards them to Anthropic for prompt
2804
+ * caching. Otherwise it returns a plain flattened string — unchanged for
2805
+ * direct OpenAI/Groq.
2806
+ */
2807
+ private static _openaiSystemMessage;
2808
+ /**
2809
+ * Split an OpenAI-wire usage object. `prompt_tokens` INCLUDES cached tokens,
2810
+ * so we subtract them out (Anthropic-style: input excludes cache reads) and
2811
+ * report cached separately — this makes calculateCost price cache reads at
2812
+ * the discounted rate and reflects OpenRouter prompt-cache savings in logs.
2813
+ */
2814
+ private static _openaiUsage;
1372
2815
  private static _openaiText;
1373
2816
  private static _openaiStream;
2817
+ /** Map the Anthropic-style firstIterationToolChoice to OpenAI's tool_choice. */
2818
+ private static _openaiToolChoice;
1374
2819
  private static _openaiStreamWithTools;
1375
2820
  /**
1376
2821
  * Parse JSON string, handling markdown code blocks and surrounding text
@@ -1460,16 +2905,6 @@ declare class UILogCollector {
1460
2905
  setUIBlockId(uiBlockId: string): void;
1461
2906
  }
1462
2907
 
1463
- /**
1464
- * Represents an action that can be performed on a UIBlock
1465
- */
1466
- interface Action {
1467
- id: string;
1468
- name: string;
1469
- type: string;
1470
- [key: string]: any;
1471
- }
1472
-
1473
2908
  /**
1474
2909
  * UIBlock represents a single user and assistant message block in a thread
1475
2910
  * Contains user question, component metadata, component data, text response, and available actions
@@ -1482,6 +2917,13 @@ declare class UIBlock {
1482
2917
  private textResponse;
1483
2918
  private actions;
1484
2919
  private createdAt;
2920
+ /**
2921
+ * Which script recipe produced this answer, when a script did. Read on the
2922
+ * NEXT turn so the user can say "use mode instead" and have the matcher
2923
+ * resolve it to a concrete script (the `edit` tier is unreachable without it).
2924
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
2925
+ */
2926
+ private scriptBinding;
1485
2927
  /**
1486
2928
  * Creates a new UIBlock instance
1487
2929
  * @param userQuestion - The user's question or input
@@ -1576,6 +3018,14 @@ declare class UIBlock {
1576
3018
  /**
1577
3019
  * Get creation timestamp
1578
3020
  */
3021
+ /**
3022
+ * Bind this block to the script recipe that produced its answer.
3023
+ */
3024
+ setScriptBinding(binding: Record<string, any> | null): void;
3025
+ /**
3026
+ * The script recipe bound to this block, if any.
3027
+ */
3028
+ getScriptBinding(): Record<string, any> | null;
1579
3029
  getCreatedAt(): Date;
1580
3030
  /**
1581
3031
  * Convert UIBlock to JSON-serializable object
@@ -1643,6 +3093,32 @@ declare class Thread {
1643
3093
  * @param currentUIBlockId - ID of current UIBlock to exclude from context (optional)
1644
3094
  * @returns Formatted conversation history string
1645
3095
  */
3096
+ /**
3097
+ * The script recipe bound to the most recent completed UIBlock — i.e. the
3098
+ * script behind the answer the user is currently looking at. Drives the
3099
+ * matcher's `edit` tier: without it, "use mode instead" has no target and
3100
+ * falls through to regeneration.
3101
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3102
+ */
3103
+ getActiveScriptBinding(currentUIBlockId?: string): Record<string, any> | null;
3104
+ /**
3105
+ * The recent script-backed answers in this thread, newest first — the
3106
+ * candidate set a user-directed edit can target.
3107
+ *
3108
+ * Returning several rather than only the newest is what lets an instruction
3109
+ * name its own target ("use the mode for the WSP one"). With a single
3110
+ * candidate every edit lands on the most recent script, which silently edits
3111
+ * the wrong recipe whenever the user meant an earlier one.
3112
+ *
3113
+ * Deduped by recipeId (newest occurrence wins) so a long editing session on
3114
+ * one script doesn't crowd out the others. Each entry carries the question
3115
+ * that produced it — without that the candidates are indistinguishable.
3116
+ *
3117
+ * In-memory only: dies with the process. The caller falls back to the
3118
+ * persisted bindings when this comes back empty.
3119
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3120
+ */
3121
+ getScriptBindings(limit?: number, currentUIBlockId?: string): Record<string, any>[];
1646
3122
  getConversationContext(limit?: number, currentUIBlockId?: string): string;
1647
3123
  /**
1648
3124
  * Convert Thread to JSON-serializable object
@@ -2119,127 +3595,35 @@ declare class QueryExecutionService {
2119
3595
  * @param collections - Collections object containing database execute function
2120
3596
  * @returns Object with result data and cache key
2121
3597
  */
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;
3598
+ executeQuery(query: any, collections: any): Promise<{
3599
+ result: any;
3600
+ cacheKey: string;
3601
+ }>;
2184
3602
  /**
2185
- * Flush the buffer immediately
2186
- * Call this before tool execution or other operations that need clean output
3603
+ * Request the LLM to fix a failed SQL query
3604
+ * @param failedQuery - The query that failed execution
3605
+ * @param errorMessage - The error message from the failed execution
3606
+ * @param componentContext - Context about the component
3607
+ * @param apiKey - Optional API key
3608
+ * @returns Fixed query string
2187
3609
  */
2188
- flush(): void;
3610
+ requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
2189
3611
  /**
2190
- * Internal flush implementation
3612
+ * Validate a single component's query with retry logic
3613
+ * @param component - The component to validate
3614
+ * @param collections - Collections object containing database execute function
3615
+ * @param apiKey - Optional API key for LLM calls
3616
+ * @returns Validation result with component, query key, and result
2191
3617
  */
2192
- private flushNow;
3618
+ validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
2193
3619
  /**
2194
- * Clean up resources
2195
- * Call this when done with the buffer
3620
+ * Validate multiple component queries in parallel
3621
+ * @param components - Array of components with potential queries
3622
+ * @param collections - Collections object containing database execute function
3623
+ * @param apiKey - Optional API key for LLM calls
3624
+ * @returns Object with validated components and query results map
2196
3625
  */
2197
- dispose(): void;
2198
- }
2199
-
2200
- /**
2201
- * ToolExecutorService - Handles execution of SQL queries and external tools
2202
- * Extracted from BaseLLM.generateTextResponse for better separation of concerns
2203
- */
2204
-
2205
- /**
2206
- * External tool definition
2207
- */
2208
- interface ExternalTool {
2209
- id: string;
2210
- name: string;
2211
- description?: string;
2212
- /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
2213
- toolType?: 'source' | 'direct';
2214
- /** Full untruncated schema for source agent (all columns visible) */
2215
- fullSchema?: string;
2216
- /** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
2217
- schemaTier?: string;
2218
- /** Schema search function for very_large tier — keyword search over entities */
2219
- schemaSearchFn?: (keywords: string[]) => string;
2220
- fn: (input: any) => Promise<any>;
2221
- limit?: number;
2222
- outputSchema?: any;
2223
- executionType?: 'immediate' | 'deferred';
2224
- userProvidedData?: any;
2225
- params?: Record<string, any>;
2226
- }
2227
- /**
2228
- * Executed tool tracking info
2229
- */
2230
- interface ExecutedToolInfo {
2231
- id: string;
2232
- name: string;
2233
- params: any;
2234
- result: {
2235
- _totalRecords: number;
2236
- _recordsShown: number;
2237
- _metadata?: any;
2238
- _sampleData: any[];
2239
- };
2240
- outputSchema?: any;
2241
- sourceSchema?: string;
2242
- sourceType?: string;
3626
+ validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
2243
3627
  }
2244
3628
 
2245
3629
  /**
@@ -2397,7 +3781,7 @@ declare abstract class BaseLLM {
2397
3781
  * This helps provide intelligent suggestions for follow-up queries
2398
3782
  * For general/conversational questions without components, pass textResponse instead
2399
3783
  */
2400
- generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string): Promise<string[]>;
3784
+ generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string, signal?: AbortSignal): Promise<string[]>;
2401
3785
  }
2402
3786
 
2403
3787
  interface AnthropicLLMConfig extends BaseLLMConfig {
@@ -2460,7 +3844,8 @@ declare const openaiLLM: OpenAILLM;
2460
3844
  * Query Cache — Two mechanisms:
2461
3845
  *
2462
3846
  * 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
2463
- * of recently validated queries. LRU eviction when max size exceeded.
3847
+ * of recently validated queries. True LRU eviction: reads bubble entries to the back via
3848
+ * delete+re-set so the oldest *unused* entry is evicted, not the oldest *inserted*.
2464
3849
  *
2465
3850
  * 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
2466
3851
  * No server-side storage needed for SQL mappings. The token is decrypted on each request.
@@ -2487,11 +3872,16 @@ declare class QueryCache {
2487
3872
  */
2488
3873
  getTTL(): number;
2489
3874
  /**
2490
- * Store query result in data cache
3875
+ * Store query result in data cache.
3876
+ * If the key already exists, it's removed first so the re-insert places it
3877
+ * at the back of the iteration order (LRU). Eviction only fires when adding
3878
+ * a genuinely new key past the size limit.
2491
3879
  */
2492
3880
  set(query: string, data: any): void;
2493
3881
  /**
2494
- * Get cached result if exists and not expired
3882
+ * Get cached result if exists and not expired.
3883
+ * On hit, re-inserts the entry so it moves to the back of the Map's
3884
+ * iteration order — turning FIFO eviction into true LRU.
2495
3885
  */
2496
3886
  get(query: string): any | null;
2497
3887
  /**
@@ -2598,177 +3988,185 @@ declare class DashboardConversationHistory {
2598
3988
  declare const dashboardConversationHistory: DashboardConversationHistory;
2599
3989
 
2600
3990
  /**
2601
- * Multi-Agent Architecture Types
3991
+ * Whole-dashboard generation via Pi, a terminal coding agent — as opposed to
3992
+ * DASH_COMP_REQ's single-widget-at-a-time flow. Runs Pi in-process via its
3993
+ * SDK (createAgentSession), not as a subprocess: no shell, no argument
3994
+ * quoting, no stdin/stdout piping, none of the Windows-specific subprocess
3995
+ * issues that came with spawning the `pi` CLI directly.
2602
3996
  *
2603
- * Defines interfaces for the hierarchical agent system:
2604
- * - Main Agent: ONE LLM.streamWithTools() call with source agent tools
2605
- * - Source Agents: independent agents that query individual data sources
3997
+ * Called from sdk-nodejs/src/dashboardAgent/index.ts (DASHBOARD_AGENT_REQ),
3998
+ * which owns the generic streaming/abort machinery (mirrors USER_PROMPT_REQ)
3999
+ * and passes `signal`/`onProgress` alongside the normal params — this stays
4000
+ * within CollectionHandler's loose (params) => Promise<result> typing, no
4001
+ * change needed to that shared type.
2606
4002
  *
2607
- * The main agent sees only source summaries. When it calls a source tool,
2608
- * the SourceAgent runs independently (own LLM, own retries) and returns clean data.
2609
- */
2610
-
2611
- /**
2612
- * Per-entity detail: name, row count, and column names.
2613
- * Gives the main agent enough context to route to the right source.
2614
- */
2615
- interface EntityDetail {
2616
- /** Entity name (table, sheet, endpoint) */
2617
- name: string;
2618
- /** Approximate row count */
2619
- rowCount?: number;
2620
- /** Column/field names */
2621
- columns: string[];
2622
- }
2623
- /**
2624
- * Representation of a data source for the main agent.
2625
- * Contains entity names WITH column names so the LLM can route accurately.
2626
- */
2627
- interface SourceSummary {
2628
- /** Source ID (matches tool ID prefix) */
2629
- id: string;
2630
- /** Human-readable source name */
2631
- name: string;
2632
- /** Source type: postgres, excel, rest_api, etc. */
2633
- type: string;
2634
- /** Brief description of what data this source contains */
2635
- description: string;
2636
- /** Detailed entity info with column names for routing */
2637
- entityDetails: EntityDetail[];
2638
- /** The tool ID associated with this source */
2639
- toolId: string;
2640
- }
2641
- /**
2642
- * What a source agent returns after querying its data source.
2643
- * The main agent uses this to analyze and compose the final response.
2644
- */
2645
- interface SourceAgentResult {
2646
- /** Source ID */
2647
- sourceId: string;
2648
- /** Source name */
2649
- sourceName: string;
2650
- /** Whether the query succeeded */
2651
- success: boolean;
2652
- /** Result data rows */
2653
- data: any[];
2654
- /** Metadata about the query execution */
2655
- metadata: SourceAgentMetadata;
2656
- /** Tool execution info for the last successful query (backward compat) */
2657
- executedTool: ExecutedToolInfo;
2658
- /** All successful tool executions (primary + follow-up queries) */
2659
- allExecutedTools?: ExecutedToolInfo[];
2660
- /** Error message if failed */
2661
- error?: string;
2662
- }
2663
- interface SourceAgentMetadata {
2664
- /** Total rows that matched the query (before limit) */
2665
- totalRowsMatched: number;
2666
- /** Rows actually returned (after limit) */
2667
- rowsReturned: number;
2668
- /** Whether the result was truncated by the row limit */
2669
- isLimited: boolean;
2670
- /** The query/params that were executed */
2671
- queryExecuted?: string;
2672
- /** Execution time in milliseconds */
2673
- executionTimeMs: number;
2674
- }
2675
- /**
2676
- * The complete response from the multi-agent system.
2677
- * Contains everything needed for text display + component generation.
4003
+ * This mechanism is generic and reusable across any deployment. What's
4004
+ * genuinely project-specific — where AGENTS.md lives, which model to use —
4005
+ * is supplied via `DashboardAgentCollectionConfig`, with defaults sensible
4006
+ * enough that most callers don't need to override them (see below). The
4007
+ * data-source tool list and the dashboard's current state both come from
4008
+ * things sdk-nodejs already exposes generically: `sdk.getTools()` (whatever
4009
+ * this deployment registered via `sdk.setTools()`) and `sdk.callCollection
4010
+ * ('dashboards', 'query', ...)` (whatever this deployment already registered
4011
+ * under that name/shape) — no per-deployment callback needed for either.
4012
+ * Same convention on the way out: after a successful run, the prompt and the
4013
+ * full response text are handed to `sdk.callCollection('dashboard-agent-
4014
+ * conversations', 'create', ...)` if this deployment has registered one —
4015
+ * skipped silently otherwise, since conversation history is optional.
4016
+ *
4017
+ * Pi verifies every query against the live database itself (via whatever
4018
+ * local tool-execution bridge the deployment exposes, e.g. an HTTP bridge
4019
+ * on localhost), but does NOT persist the result itself — it writes the
4020
+ * finished DSL to an absolute path inside `runtimeDir`, told to it explicitly
4021
+ * in the prompt, and stops there. This handler reads that file after the run
4022
+ * finishes and returns its content as `dashboard` in the result. The caller
4023
+ * (frontend) is the one that actually saves it, via whatever authenticated
4024
+ * create/update path any other dashboard edit goes through — Pi has no user
4025
+ * session/auth context of its own, so persistence shouldn't happen from
4026
+ * inside it.
4027
+ *
4028
+ * Session persistence: the FIRST call for a dashboardId pays the full cost
4029
+ * (explore KB, discover schema, plan, verify, build). Every call after that
4030
+ * resumes the same session file (SessionManager.open) so Pi has everything
4031
+ * it already learned — it only needs to reason about the new, smaller ask,
4032
+ * not rediscover the whole dashboard from scratch. The session's file path
4033
+ * (AgentSession.sessionFile) is captured right after creation and persisted
4034
+ * in a small local file, keyed by dashboardId, inside `runtimeDir`.
2678
4035
  */
2679
- interface AgentResponse {
2680
- /** Generated text response (analysis of the data) */
2681
- text: string;
2682
- /** All executed tools across all source agents (for component generation) */
2683
- executedTools: ExecutedToolInfo[];
2684
- /** Individual results from each source agent */
2685
- sourceResults: SourceAgentResult[];
4036
+ interface DashboardAgentCollectionConfig {
4037
+ /**
4038
+ * Working directory Pi runs from — must contain AGENTS.md. This is a
4039
+ * version-controlled prompt file, so `cwd` is expected to live somewhere
4040
+ * like a `.prompts/` folder alongside the deployment's other prompts.
4041
+ * Default: `<process.cwd()>/.prompts/dashboard-agent` — the same
4042
+ * process.cwd()-based convention PromptLoader already uses for the main
4043
+ * agent's prompts, which needs no explicit override in the common case
4044
+ * (the backend process's own cwd already is its project root).
4045
+ */
4046
+ cwd?: string;
4047
+ /**
4048
+ * Where drafts/, the session-id map, and dashboard.log get written —
4049
+ * separate from `cwd` deliberately, so this deployment's runtime state
4050
+ * (regenerated per session, safe to gitignore) doesn't sit inside the
4051
+ * same folder as the version-controlled AGENTS.md prompt.
4052
+ * Default: `<process.cwd()>/.pi-dashboard-agent-runtime`.
4053
+ */
4054
+ runtimeDir?: string;
4055
+ /** Model provider (default: process.env.PI_AGENT_PROVIDER || 'openrouter'). */
4056
+ provider?: string;
4057
+ /** Model id (default: process.env.PI_AGENT_MODEL || 'anthropic/claude-sonnet-4.5'). */
4058
+ model?: string;
4059
+ /**
4060
+ * true (default): every request starts a brand-new pi session, with the 2
4061
+ * most recent prior responses (if any) injected into the prompt as
4062
+ * context — bounded cost per request, but pi re-explores schema/KB facts
4063
+ * it already verified in an earlier turn on this same dashboard.
4064
+ * false: resumes the same session file across requests on a given
4065
+ * dashboard — pi keeps everything it already learned, but context (and
4066
+ * cost) grows unbounded across turns (one observed turn: 2M+ cache-read
4067
+ * tokens after a handful of edits on the same dashboard).
4068
+ * Default: process.env.PI_AGENT_FRESH_SESSION !== 'false'.
4069
+ */
4070
+ freshSession?: boolean;
2686
4071
  }
4072
+ declare function registerDashboardAgentCollection(sdk: SuperatomSDK, config?: DashboardAgentCollectionConfig): void;
4073
+
2687
4074
  /**
2688
- * Configuration for the multi-agent system.
2689
- * Controls limits, models, and behavior.
4075
+ * ScriptMatcher — LLM-Based Script Matching + Parameter Extraction
4076
+ *
4077
+ * Uses ONE LLM call to:
4078
+ * 1. Pick the best matching script from the library (or "none")
4079
+ * 2. Extract parameter values from the user question
4080
+ *
4081
+ * Why LLM over embeddings:
4082
+ * - Embeddings capture topic similarity ("overstock" ≈ "inventory" ≈ "revenue")
4083
+ * but can't distinguish structurally different questions about the same domain
4084
+ * - LLM understands that "overstock by warehouse" needs a different script than
4085
+ * "revenue by warehouse" even though they're semantically close
4086
+ * - One call does both matching AND parameter extraction
4087
+ *
4088
+ * When script library grows past ~50, add an embedding pre-filter
4089
+ * (ChromaDB narrows to top 10 → LLM picks from those 10).
2690
4090
  */
2691
- interface AgentConfig {
2692
- /** Max rows a source agent can return (default: 50) */
2693
- maxRowsPerSource: number;
2694
- /** Model for the main agent (routing + analysis in one LLM call) */
2695
- mainAgentModel: string;
2696
- /** Model for source agent query generation */
2697
- sourceAgentModel: string;
2698
- /** API key for LLM calls */
2699
- apiKey?: string;
2700
- /** Max retry attempts per source agent */
2701
- maxRetries: number;
2702
- /** Max tool calling iterations for the main agent loop */
2703
- maxIterations: number;
2704
- /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
2705
- globalKnowledgeBase?: string;
2706
- /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
2707
- knowledgeBaseContext?: string;
4091
+
4092
+ declare class ScriptMatcher {
4093
+ private store;
4094
+ constructor(store: ScriptStore);
4095
+ /**
4096
+ * Find the best matching script for a user question.
4097
+ * Uses ONE LLM call that picks the script AND extracts parameters.
4098
+ * Returns null if no script matches.
4099
+ */
4100
+ match(userPrompt: string, apiKey?: string, model?: string, signal?: AbortSignal,
4101
+ /**
4102
+ * Recent script-backed answers in this thread, newest first. Presence of at
4103
+ * least one is what makes the `edit` tier reachable at all (see the guards
4104
+ * below), and handing over SEVERAL is what lets an instruction name its own
4105
+ * target instead of always hitting the most recent script.
4106
+ */
4107
+ activeBindings?: ScriptBinding[],
4108
+ /**
4109
+ * Recent conversation turns, most recent last. The gate needs this to tell
4110
+ * "this reply is an edit instruction for the active script" apart from
4111
+ * "this reply is answering a clarifying question about a DIFFERENT,
4112
+ * unresolved topic that never became a script" — a bare parameter-shaped
4113
+ * reply ("April 2025 to March 2026") is textually indistinguishable
4114
+ * between those two cases without seeing what the assistant just asked.
4115
+ * Once this tier is decided, nothing downstream re-checks it — the edit
4116
+ * path hands MainAgent a system prompt that explicitly instructs it to
4117
+ * trust the premise and not treat the turn as a new question — so this
4118
+ * gate is the only place that can catch a mismatch.
4119
+ */
4120
+ conversationHistory?: string): Promise<ScriptMatch | null>;
4121
+ /**
4122
+ * Build the script catalog string for the LLM prompt.
4123
+ * Each script gets: index, ID, name, description, and parameter definitions.
4124
+ */
4125
+ private buildScriptCatalog;
4126
+ /**
4127
+ * The recent script-backed answers in this thread — the bounded set an edit
4128
+ * may target. Rendered as its own prompt section (never merged into the
4129
+ * ranked catalog) so the `edit` rules have an unambiguous referent set, and
4130
+ * numbered newest-first so the prompt's "prefer the most recent when the
4131
+ * instruction is ambiguous" tie-break has something to point at.
4132
+ *
4133
+ * Each entry carries the QUESTION that produced it plus the columns it
4134
+ * returned — that is what lets the matcher resolve "use the mode for the WSP
4135
+ * one" instead of blindly taking the newest.
4136
+ */
4137
+ private buildActiveScriptBlock;
2708
4138
  }
2709
- /**
2710
- * Default agent configuration
2711
- */
2712
- declare const DEFAULT_AGENT_CONFIG: AgentConfig;
2713
4139
 
2714
4140
  /**
2715
- * Main Agent (Orchestrator)
4141
+ * ScriptRunner — Execute scripts in an isolated tsx subprocess.
2716
4142
  *
2717
- * A single LLM.streamWithTools() call that handles everything:
2718
- * - Routing: decides which source(s) to query based on summaries
2719
- * - Querying: calls source tools (each wraps an independent SourceAgent)
2720
- * - Direct tools: calls pre-built function tools directly with LLM-provided params
2721
- * - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
2722
- * - Analysis: generates final text response from the data
4143
+ * The subprocess approach replaces the earlier `new Function()` eval and gives us:
4144
+ * - Real sandbox (separate process, SIGKILL on timeout).
4145
+ * - Real TypeScript (tsx transpiles on the fly).
4146
+ * - npm imports available to scripts (clustering, stats, geo, etc.).
2723
4147
  *
2724
- * Two tool types:
2725
- * - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
2726
- * - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
4148
+ * Protocol: NDJSON over the child's stdin/stdout. See script-ipc.ts + backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md.
2727
4149
  */
2728
4150
 
2729
- declare class MainAgent {
2730
- private externalTools;
2731
- private config;
2732
- private streamBuffer;
2733
- constructor(externalTools: ExternalTool[], config: AgentConfig, streamBuffer?: StreamBuffer);
2734
- /**
2735
- * Handle a user question using the multi-agent system.
2736
- *
2737
- * This is ONE LLM.streamWithTools() call. The LLM:
2738
- * 1. Sees source summaries + direct tool descriptions in system prompt
2739
- * 2. Decides which tool(s) to call (routing)
2740
- * 3. Source tools → SourceAgent runs independently → returns data
2741
- * 4. Direct tools → fn() called directly with LLM params → returns data
2742
- * 5. Generates final analysis text
2743
- */
2744
- handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void): Promise<AgentResponse>;
2745
- /**
2746
- * Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
2747
- */
2748
- private handleDirectTool;
2749
- /**
2750
- * Build the main agent's system prompt with source summaries and direct tool descriptions.
2751
- */
2752
- private buildSystemPrompt;
2753
- /**
2754
- * Build tool definitions for source tools — summary-only descriptions.
2755
- * The full schema is inside the SourceAgent which runs independently.
2756
- */
2757
- private buildSourceToolDefinitions;
2758
- /**
2759
- * Build tool definitions for direct tools — expose their actual params.
2760
- * These are called directly by the main agent LLM, no SourceAgent.
2761
- */
2762
- private buildDirectToolDefinitions;
2763
- /**
2764
- * Format a source agent's result as a clean string for the main agent LLM.
2765
- */
2766
- private formatResultForMainAgent;
2767
- /**
2768
- * Get source summaries (for external inspection/debugging).
2769
- */
2770
- getSourceSummaries(): SourceSummary[];
4151
+ interface RunScriptOptions {
4152
+ /** Data sources the script is allowed to query via ctx.query */
4153
+ externalTools: ExternalTool[];
4154
+ /** Optional — for propagating per-query UI progress to the user */
4155
+ streamBuffer?: StreamBuffer;
4156
+ /** Override the wall-clock timeout (default `SCRIPT_TIMEOUT_MS`, 60s). */
4157
+ timeoutMs?: number;
4158
+ /**
4159
+ * Per-turn cancellation signal. When the user hits "Stop" mid-run, the child
4160
+ * process group is SIGKILLed and the run resolves as an aborted failure (the
4161
+ * caller is already unwinding, so the result is discarded).
4162
+ */
4163
+ signal?: AbortSignal;
2771
4164
  }
4165
+ /**
4166
+ * Execute a recipe by spawning a tsx child on the script's .ts file.
4167
+ * `scriptPath` is the absolute path to the saved `.ts` body.
4168
+ */
4169
+ declare function runScript(recipe: ScriptRecipe, scriptPath: string, params: Record<string, any>, options: RunScriptOptions): Promise<ScriptResult>;
2772
4170
 
2773
4171
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
2774
4172
  declare class SuperatomSDK {
@@ -2786,6 +4184,7 @@ declare class SuperatomSDK {
2786
4184
  private collections;
2787
4185
  private components;
2788
4186
  private tools;
4187
+ private workflows;
2789
4188
  private anthropicApiKey;
2790
4189
  private groqApiKey;
2791
4190
  private geminiApiKey;
@@ -2804,6 +4203,8 @@ declare class SuperatomSDK {
2804
4203
  private lastPong;
2805
4204
  private readonly PING_INTERVAL_MS;
2806
4205
  private readonly PONG_TIMEOUT_MS;
4206
+ private pendingOutbox;
4207
+ private readonly MAX_OUTBOX_SIZE;
2807
4208
  constructor(config: SuperatomSDKConfig);
2808
4209
  /**
2809
4210
  * Initialize PromptLoader and load prompts into memory
@@ -2848,6 +4249,20 @@ declare class SuperatomSDK {
2848
4249
  * Does NOT throw on closed connections — callers can check the return value if needed.
2849
4250
  */
2850
4251
  send(message: Message): boolean;
4252
+ /**
4253
+ * Queue a message that couldn't be delivered because the socket was down,
4254
+ * to be resent once it reconnects. Drops the oldest entry once the bound is
4255
+ * hit — an outage long enough to fill this queue means the oldest queued
4256
+ * responses are for requests the caller has likely already given up on.
4257
+ */
4258
+ private queuePendingMessage;
4259
+ /**
4260
+ * Resend everything queued while the socket was down, now that it's back
4261
+ * up. Uses this.ws.send() directly (not send()) so a message that fails
4262
+ * again goes back through queuePendingMessage() rather than being silently
4263
+ * dropped a second time.
4264
+ */
4265
+ private flushPendingOutbox;
2851
4266
  /**
2852
4267
  * Register a message handler to receive all messages
2853
4268
  */
@@ -2887,6 +4302,14 @@ declare class SuperatomSDK {
2887
4302
  */
2888
4303
  private handlePong;
2889
4304
  private storeComponents;
4305
+ /**
4306
+ * The live, frontend-registered component catalog (name, type, description,
4307
+ * and full prop schema per component) — the same authoritative source
4308
+ * DASH_COMP_REQ's LLM prompt is built from. Exposed so other integrations
4309
+ * (e.g. the dashboard-agent script bridge) can read real component
4310
+ * contracts instead of maintaining a separate, driftable hand-written copy.
4311
+ */
4312
+ getComponents(): Component[];
2890
4313
  /**
2891
4314
  * Set tools for the SDK instance
2892
4315
  */
@@ -2895,6 +4318,29 @@ declare class SuperatomSDK {
2895
4318
  * Get the stored tools
2896
4319
  */
2897
4320
  getTools(): Tool$1[];
4321
+ /**
4322
+ * Call a registered collection operation in-process — no WebSocket
4323
+ * round-trip, since the caller is already running inside this same SDK
4324
+ * instance. Lets SDK-internal features (e.g. the dashboard agent) reuse
4325
+ * whatever collection a deployment has already registered (e.g.
4326
+ * 'dashboards'.'query') by name/convention, instead of requiring a
4327
+ * separate callback purely to re-expose data a collection already serves.
4328
+ * Throws if the collection or operation isn't registered.
4329
+ */
4330
+ callCollection<TResult = any>(collectionName: string, operation: string, params?: any): Promise<TResult>;
4331
+ /**
4332
+ * Register workflow components for the SDK instance.
4333
+ *
4334
+ * Workflows are pre-built multi-step UI flows the main agent can pick when
4335
+ * the user's prompt matches a workflow's `whenToUse` trigger. Picking a
4336
+ * workflow short-circuits analysis text + dashboard component generation —
4337
+ * the workflow component is returned directly, with the LLM-extracted props.
4338
+ */
4339
+ setWorkflows(workflows: WorkflowDescriptor[]): void;
4340
+ /**
4341
+ * Get the registered workflow components.
4342
+ */
4343
+ getWorkflows(): WorkflowDescriptor[];
2898
4344
  /**
2899
4345
  * Apply model strategy to all LLM provider singletons
2900
4346
  * @param strategy - 'best', 'fast', or 'balanced'
@@ -2925,4 +4371,4 @@ declare class SuperatomSDK {
2925
4371
  getConversationSimilarityThreshold(): number;
2926
4372
  }
2927
4373
 
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 };
4374
+ 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 };