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