@superatomai/sdk-node 0.0.39-mds → 0.0.40-dsp

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,15 +1,929 @@
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
+ * The prior-turn conversation context injected into this turn's prompt as
829
+ * CONVERSATION_HISTORY — exactly what each flow already builds for itself
830
+ * (chat: thread.getConversationContext(); report/dashboard: their own
831
+ * equivalents), captured as-is. Every call site sets this unconditionally
832
+ * (empty string '' when there's no prior context — new thread, or history
833
+ * trimmed to nothing), so an empty turn is visibly "no history" in the
834
+ * saved trace rather than a silently missing key. Optional only because
835
+ * traces saved before this field existed won't have it at all.
836
+ */
837
+ conversationHistory?: string;
838
+ /**
839
+ * The exact {{USER_ACCESS_CONTEXT}} text injected into MainAgent's system
840
+ * prompt — the per-user authorization config (sa-api users.config)
841
+ * rendered by buildUserAccessContext, as-is. Captured once (MainAgent's
842
+ * prompt is what SourceAgent's identical value is derived from — no need
843
+ * to duplicate it per source dispatch). Set unconditionally (empty string
844
+ * '' when there's no config for this user), so "no restrictions" is
845
+ * visible in the saved trace rather than a silently missing key. Optional
846
+ * only because traces saved before this field existed won't have it.
847
+ */
848
+ userAccessContext?: string;
849
+ }
850
+ /**
851
+ * Configuration for the multi-agent system.
852
+ * Controls limits, models, and behavior.
853
+ */
854
+ interface AgentConfig {
855
+ /** Max rows shown to the UI preview / inlined per source (default: 10) */
856
+ maxRowsPerSource: number;
857
+ /**
858
+ * Max rows a source query may FETCH from the DB server-side (default: 2000).
859
+ * Decoupled from what the main agent is shown: the full result is fetched and
860
+ * summarized (bounded), but only a small/complete slice enters LLM context.
861
+ * This lets small lookups (benchmark maps) arrive COMPLETE without letting
862
+ * large results blow up context.
863
+ */
864
+ maxRowsFetched: number;
865
+ /** Model for the main agent (routing + analysis in one LLM call) */
866
+ mainAgentModel: string;
867
+ /** Model for source agent query generation */
868
+ sourceAgentModel: string;
869
+ /** API key for LLM calls */
870
+ apiKey?: string;
871
+ /** Max retry attempts per source agent */
872
+ maxRetries: number;
873
+ /** Max tool calling iterations for the main agent loop */
874
+ maxIterations: number;
875
+ /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
876
+ globalKnowledgeBase?: string;
877
+ /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
878
+ knowledgeBaseContext?: string;
879
+ /** Per-user authorization config (sa-api users.config), rendered to text — see buildUserAccessContext */
880
+ userAccessContext?: string;
881
+ /** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
882
+ collections?: any;
883
+ /** Optional project ID for scoping embedding searches */
884
+ projectId?: string;
885
+ /**
886
+ * Optional debug-trace accumulator for this turn (Phase 1, chat_agent only).
887
+ * When present, MainAgent-scope retrieval call sites (e.g. preResolveSchema)
888
+ * push their structured results into it. Absent for callers that don't care
889
+ * about trace capture (e.g. headless flows) — every push site must treat
890
+ * this as optional and never let a capture failure affect the real answer.
891
+ */
892
+ trace?: RunTrace;
893
+ }
894
+ /**
895
+ * Default agent configuration
896
+ */
897
+ declare const DEFAULT_AGENT_CONFIG: AgentConfig;
898
+
4
899
  /**
5
900
  * Unified UIBlock structure for database storage
6
- * Used in both bookmarks and user-conversations tables
901
+ * Used in both bookmarks and user-conversations tables.
902
+ *
903
+ * `analysis` always holds whatever real narration exists — the full answer on
904
+ * success, or whatever was actually streamed before a failure (may be empty).
905
+ * `error` is a dedicated field, null on success — it can be a plain string OR
906
+ * a structured object/array (e.g. the agent's raw `errors` list), whatever
907
+ * shape the failure naturally has; it's never coerced into `analysis`.
7
908
  */
8
909
  interface DBUIBlock {
9
910
  id: string;
10
911
  component: Record<string, any> | null;
11
912
  analysis: string | null;
12
913
  user_prompt: string;
914
+ error?: unknown | null;
915
+ /**
916
+ * The script recipe that produced this answer, when one did. Read back via
917
+ * `conversation-history.exactMatch` so an edit follow-up still has a target
918
+ * after a reload (the in-memory thread is gone by then), and indexed so
919
+ * committing an edit can purge every cached answer bound to the recipe.
920
+ */
921
+ scriptBinding?: {
922
+ recipeId: string;
923
+ params?: Record<string, any>;
924
+ name?: string;
925
+ columns?: string[];
926
+ };
13
927
  }
14
928
 
15
929
  /**
@@ -160,6 +1074,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
160
1074
  dependencies?: string[] | undefined;
161
1075
  } | undefined;
162
1076
  props?: Record<string, any> | undefined;
1077
+ data?: Record<string, any> | undefined;
163
1078
  render?: any;
164
1079
  states?: Record<string, any> | undefined;
165
1080
  methods?: Record<string, {
@@ -170,7 +1085,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
170
1085
  fn: string;
171
1086
  deps?: string[] | undefined;
172
1087
  }[] | undefined;
173
- data?: Record<string, any> | undefined;
174
1088
  pages?: {
175
1089
  id: string;
176
1090
  name: string;
@@ -192,6 +1106,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
192
1106
  dependencies?: string[] | undefined;
193
1107
  } | undefined;
194
1108
  props?: Record<string, any> | undefined;
1109
+ data?: Record<string, any> | undefined;
195
1110
  render?: any;
196
1111
  states?: Record<string, any> | undefined;
197
1112
  methods?: Record<string, {
@@ -202,7 +1117,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
202
1117
  fn: string;
203
1118
  deps?: string[] | undefined;
204
1119
  }[] | undefined;
205
- data?: Record<string, any> | undefined;
206
1120
  pages?: {
207
1121
  id: string;
208
1122
  name: string;
@@ -228,6 +1142,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
228
1142
  dependencies?: string[] | undefined;
229
1143
  } | undefined;
230
1144
  props?: Record<string, any> | undefined;
1145
+ data?: Record<string, any> | undefined;
231
1146
  render?: any;
232
1147
  states?: Record<string, any> | undefined;
233
1148
  methods?: Record<string, {
@@ -238,7 +1153,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
238
1153
  fn: string;
239
1154
  deps?: string[] | undefined;
240
1155
  }[] | undefined;
241
- data?: Record<string, any> | undefined;
242
1156
  pages?: {
243
1157
  id: string;
244
1158
  name: string;
@@ -264,6 +1178,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
264
1178
  dependencies?: string[] | undefined;
265
1179
  } | undefined;
266
1180
  props?: Record<string, any> | undefined;
1181
+ data?: Record<string, any> | undefined;
267
1182
  render?: any;
268
1183
  states?: Record<string, any> | undefined;
269
1184
  methods?: Record<string, {
@@ -274,7 +1189,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
274
1189
  fn: string;
275
1190
  deps?: string[] | undefined;
276
1191
  }[] | undefined;
277
- data?: Record<string, any> | undefined;
278
1192
  pages?: {
279
1193
  id: string;
280
1194
  name: string;
@@ -355,6 +1269,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
355
1269
  dependencies?: string[] | undefined;
356
1270
  } | undefined;
357
1271
  props?: Record<string, any> | undefined;
1272
+ data?: Record<string, any> | undefined;
358
1273
  render?: any;
359
1274
  states?: Record<string, any> | undefined;
360
1275
  methods?: Record<string, {
@@ -365,7 +1280,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
365
1280
  fn: string;
366
1281
  deps?: string[] | undefined;
367
1282
  }[] | undefined;
368
- data?: Record<string, any> | undefined;
369
1283
  }, {
370
1284
  id: string;
371
1285
  name?: string | undefined;
@@ -379,6 +1293,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
379
1293
  dependencies?: string[] | undefined;
380
1294
  } | undefined;
381
1295
  props?: Record<string, any> | undefined;
1296
+ data?: Record<string, any> | undefined;
382
1297
  render?: any;
383
1298
  states?: Record<string, any> | undefined;
384
1299
  methods?: Record<string, {
@@ -389,7 +1304,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
389
1304
  fn: string;
390
1305
  deps?: string[] | undefined;
391
1306
  }[] | undefined;
392
- data?: Record<string, any> | undefined;
393
1307
  }>;
394
1308
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
395
1309
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -407,6 +1321,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
407
1321
  dependencies?: string[] | undefined;
408
1322
  } | undefined;
409
1323
  props?: Record<string, any> | undefined;
1324
+ data?: Record<string, any> | undefined;
410
1325
  render?: any;
411
1326
  states?: Record<string, any> | undefined;
412
1327
  methods?: Record<string, {
@@ -417,7 +1332,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
417
1332
  fn: string;
418
1333
  deps?: string[] | undefined;
419
1334
  }[] | undefined;
420
- data?: Record<string, any> | undefined;
421
1335
  };
422
1336
  data?: Record<string, any> | undefined;
423
1337
  context?: Record<string, any> | undefined;
@@ -435,6 +1349,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
435
1349
  dependencies?: string[] | undefined;
436
1350
  } | undefined;
437
1351
  props?: Record<string, any> | undefined;
1352
+ data?: Record<string, any> | undefined;
438
1353
  render?: any;
439
1354
  states?: Record<string, any> | undefined;
440
1355
  methods?: Record<string, {
@@ -445,7 +1360,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
445
1360
  fn: string;
446
1361
  deps?: string[] | undefined;
447
1362
  }[] | undefined;
448
- data?: Record<string, any> | undefined;
449
1363
  };
450
1364
  data?: Record<string, any> | undefined;
451
1365
  context?: Record<string, any> | undefined;
@@ -777,6 +1691,14 @@ declare const ToolSchema: z.ZodObject<{
777
1691
  description: string;
778
1692
  }[];
779
1693
  }>>;
1694
+ /** Cache policy. `false` = never cache (live data, write ops). Mirrors HTTP `Cache-Control: no-store`. */
1695
+ cache: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<false>, z.ZodObject<{
1696
+ ttlMs: z.ZodOptional<z.ZodNumber>;
1697
+ }, "strip", z.ZodTypeAny, {
1698
+ ttlMs?: number | undefined;
1699
+ }, {
1700
+ ttlMs?: number | undefined;
1701
+ }>]>>;
780
1702
  }, "strip", z.ZodTypeAny, {
781
1703
  id: string;
782
1704
  params: Record<string, string>;
@@ -793,6 +1715,9 @@ declare const ToolSchema: z.ZodObject<{
793
1715
  description: string;
794
1716
  }[];
795
1717
  } | undefined;
1718
+ cache?: false | {
1719
+ ttlMs?: number | undefined;
1720
+ } | undefined;
796
1721
  }, {
797
1722
  id: string;
798
1723
  params: Record<string, string>;
@@ -809,6 +1734,9 @@ declare const ToolSchema: z.ZodObject<{
809
1734
  description: string;
810
1735
  }[];
811
1736
  } | undefined;
1737
+ cache?: false | {
1738
+ ttlMs?: number | undefined;
1739
+ } | undefined;
812
1740
  }>;
813
1741
  type Tool$1 = z.infer<typeof ToolSchema>;
814
1742
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
@@ -994,7 +1922,7 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
994
1922
  content?: string | undefined;
995
1923
  }>>;
996
1924
  }, "strip", z.ZodTypeAny, {
997
- operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
1925
+ operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
998
1926
  data?: {
999
1927
  id?: number | undefined;
1000
1928
  type?: "query" | "user" | "global" | undefined;
@@ -1017,7 +1945,7 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
1017
1945
  content?: string | undefined;
1018
1946
  } | undefined;
1019
1947
  }, {
1020
- operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
1948
+ operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
1021
1949
  data?: {
1022
1950
  id?: number | undefined;
1023
1951
  type?: "query" | "user" | "global" | undefined;
@@ -1301,279 +2229,310 @@ declare class ReportManager {
1301
2229
  reportExists(reportId: string): boolean;
1302
2230
  /**
1303
2231
  * Get report count
1304
- * @returns Number of reports
1305
- */
1306
- getReportCount(): number;
1307
- }
1308
-
1309
- /**
1310
- * StreamBuffer - Buffered streaming utility for smoother text delivery
1311
- * Batches small chunks together and flushes at regular intervals
1312
- */
1313
- type StreamCallback = (chunk: string) => void;
1314
- /**
1315
- * StreamBuffer class for managing buffered streaming output
1316
- * Provides smooth text delivery by batching small chunks
1317
- */
1318
- declare class StreamBuffer {
1319
- private buffer;
1320
- private flushTimer;
1321
- private callback;
1322
- private fullText;
1323
- constructor(callback?: StreamCallback);
1324
- /**
1325
- * Check if the buffer has a callback configured
1326
- */
1327
- hasCallback(): boolean;
1328
- /**
1329
- * Get all text that has been written (including already flushed)
1330
- */
1331
- getFullText(): string;
1332
- /**
1333
- * Write a chunk to the buffer
1334
- * Large chunks or chunks with newlines are flushed immediately
1335
- * Small chunks are batched and flushed after a short interval
1336
- *
1337
- * @param chunk - Text chunk to write
1338
- */
1339
- write(chunk: string): void;
1340
- /**
1341
- * Flush the buffer immediately
1342
- * Call this before tool execution or other operations that need clean output
1343
- */
1344
- flush(): void;
1345
- /**
1346
- * Internal flush implementation
1347
- */
1348
- private flushNow;
1349
- /**
1350
- * Clean up resources
1351
- * Call this when done with the buffer
1352
- */
1353
- dispose(): void;
1354
- }
1355
-
1356
- /**
1357
- * ToolExecutorService - Handles execution of SQL queries and external tools
1358
- * Extracted from BaseLLM.generateTextResponse for better separation of concerns
1359
- */
1360
-
1361
- /**
1362
- * External tool definition
1363
- */
1364
- interface ExternalTool {
1365
- id: string;
1366
- name: string;
1367
- description?: string;
1368
- /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
1369
- toolType?: 'source' | 'direct';
1370
- /** Full untruncated schema for source agent (all columns visible) */
1371
- fullSchema?: string;
1372
- /** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
1373
- schemaTier?: string;
1374
- /** Schema search function for very_large tier — keyword search over entities */
1375
- schemaSearchFn?: (keywords: string[]) => string;
1376
- fn: (input: any) => Promise<any>;
1377
- limit?: number;
1378
- outputSchema?: any;
1379
- executionType?: 'immediate' | 'deferred';
1380
- userProvidedData?: any;
1381
- params?: Record<string, any>;
1382
- }
1383
- /**
1384
- * Executed tool tracking info
1385
- */
1386
- interface ExecutedToolInfo {
1387
- id: string;
1388
- name: string;
1389
- params: any;
1390
- result: {
1391
- _totalRecords: number;
1392
- _recordsShown: number;
1393
- _metadata?: any;
1394
- _sampleData: any[];
1395
- };
1396
- outputSchema?: any;
1397
- sourceSchema?: string;
1398
- sourceType?: string;
2232
+ * @returns Number of reports
2233
+ */
2234
+ getReportCount(): number;
1399
2235
  }
1400
2236
 
1401
2237
  /**
1402
- * Multi-Agent Architecture Types
2238
+ * ScriptRecipeStore — injected metadata backend for the script flow.
1403
2239
  *
1404
- * Defines interfaces for the hierarchical agent system:
1405
- * - Main Agent: ONE LLM.streamWithTools() call with source agent tools
1406
- * - Source Agents: independent agents that query individual data sources
2240
+ * The SDK is standalone (no DB dependency). The backend implements this
2241
+ * interface over Postgres (full-text search + atomic counters) and injects it
2242
+ * via `collections['script-recipes']`, exactly like `collections['source-embeddings']`.
2243
+ * `ScriptStore` consumes it for all METADATA operations while keeping the
2244
+ * executable body on disk as scripts-store/<fileBase>.ts.
1407
2245
  *
1408
- * The main agent sees only source summaries. When it calls a source tool,
1409
- * the SourceAgent runs independently (own LLM, own retries) and returns clean data.
2246
+ * All metadata rows are plain JSON (no scriptBody — that lives on disk).
2247
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md (#1, #3, #7).
1410
2248
  */
1411
2249
 
1412
- /**
1413
- * Per-entity detail: name, row count, and column names.
1414
- * Gives the main agent enough context to route to the right source.
1415
- */
1416
- interface EntityDetail {
1417
- /** Entity name (table, sheet, endpoint) */
1418
- name: string;
1419
- /** Approximate row count */
1420
- rowCount?: number;
1421
- /** Column/field names */
1422
- columns: string[];
1423
- }
1424
- /**
1425
- * Representation of a data source for the main agent.
1426
- * Contains entity names WITH column names so the LLM can route accurately.
1427
- */
1428
- interface SourceSummary {
1429
- /** Source ID (matches tool ID prefix) */
2250
+ /** One recipe's metadata as stored in Postgres (mirrors the script_recipes table). */
2251
+ interface ScriptRecipeMetaRow {
1430
2252
  id: string;
1431
- /** Human-readable source name */
2253
+ projectId?: string | null;
2254
+ version: number;
1432
2255
  name: string;
1433
- /** Source type: postgres, excel, rest_api, etc. */
1434
- type: string;
1435
- /** Brief description of what data this source contains */
1436
- description: string;
1437
- /** Detailed entity info with column names for routing */
1438
- entityDetails: EntityDetail[];
1439
- /** The tool ID associated with this source */
1440
- toolId: string;
1441
- }
1442
- /**
1443
- * What a source agent returns after querying its data source.
1444
- * The main agent uses this to analyze and compose the final response.
1445
- */
1446
- interface SourceAgentResult {
1447
- /** Source ID */
1448
- sourceId: string;
1449
- /** Source name */
1450
- sourceName: string;
1451
- /** Whether the query succeeded */
1452
- success: boolean;
1453
- /** Result data rows */
1454
- data: any[];
1455
- /** Metadata about the query execution */
1456
- metadata: SourceAgentMetadata;
1457
- /** Tool execution info for the last successful query (backward compat) */
1458
- executedTool: ExecutedToolInfo;
1459
- /** All successful tool executions (primary + follow-up queries) */
1460
- allExecutedTools?: ExecutedToolInfo[];
1461
- /** Error message if failed */
1462
- error?: string;
2256
+ intentDescription: string;
2257
+ tags: string[] | null;
2258
+ createdFrom: string | null;
2259
+ sourceIds: string[] | null;
2260
+ tables: string[] | null;
2261
+ parameters: ScriptParameter[] | null;
2262
+ components?: ScriptComponentSpec[] | null;
2263
+ displayPreference?: ScriptDisplayPreference | null;
2264
+ fileBase: string;
2265
+ bodyHash?: string | null;
2266
+ successCount: number;
2267
+ failureCount: number;
2268
+ lastUsed: string | null;
2269
+ parentId?: string | null;
2270
+ forkDepth?: number | null;
2271
+ forkReason?: string | null;
2272
+ status: 'draft' | 'verified' | string;
2273
+ turnId?: string | null;
2274
+ editedBy?: string | null;
2275
+ editedFrom?: string | null;
2276
+ history?: ScriptVersionRecord[] | null;
2277
+ lastError?: {
2278
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2279
+ message: string;
2280
+ at: string;
2281
+ attempt: number;
2282
+ } | null;
2283
+ createdAt?: string | null;
2284
+ updatedAt?: string | null;
1463
2285
  }
1464
- interface SourceAgentMetadata {
1465
- /** Total rows that matched the query (before limit) */
1466
- totalRowsMatched: number;
1467
- /** Rows actually returned (after limit) */
1468
- rowsReturned: number;
1469
- /** Whether the result was truncated by the row limit */
1470
- isLimited: boolean;
1471
- /** The query/params that were executed */
1472
- queryExecuted?: string;
1473
- /** Execution time in milliseconds */
1474
- executionTimeMs: number;
2286
+ interface ScriptRecipeStore {
2287
+ /** FTS shortlist of healthy verified recipes for the matcher (metadata only). */
2288
+ search(params: {
2289
+ prompt: string;
2290
+ projectId?: string;
2291
+ limit?: number;
2292
+ }): Promise<ScriptRecipeMetaRow[]>;
2293
+ /** Fetch one recipe by id (any status). */
2294
+ getById(id: string): Promise<ScriptRecipeMetaRow | null>;
2295
+ /** Count healthy verified recipes (drives the "any scripts?" gate). */
2296
+ count(params?: {
2297
+ projectId?: string;
2298
+ }): Promise<number>;
2299
+ /** Insert or update a recipe row (keyed by id). */
2300
+ upsert(row: ScriptRecipeMetaRow): Promise<void>;
2301
+ /** Atomically bump counters / last-used. */
2302
+ updateStats(id: string, patch: {
2303
+ successDelta?: number;
2304
+ failureDelta?: number;
2305
+ lastUsed?: string;
2306
+ }): Promise<void>;
2307
+ /** Flip a draft to verified, applying provenance + optional fork lineage. */
2308
+ promote(id: string, patch: {
2309
+ sourceIds: string[];
2310
+ tables: string[];
2311
+ fileBase?: string;
2312
+ parentId?: string;
2313
+ forkDepth?: number;
2314
+ forkReason?: string;
2315
+ components?: ScriptComponentSpec[];
2316
+ }): Promise<ScriptRecipeMetaRow | null>;
2317
+ /**
2318
+ * Commit a verified edit onto an EXISTING recipe: bump `version`, replace the
2319
+ * body-bearing metadata, append a history record, reset health counters, and
2320
+ * clear the component specs (they were validated against the old shape).
2321
+ * Returns the updated row, or null when the target is gone.
2322
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5.
2323
+ */
2324
+ commitEdit?(id: string, patch: {
2325
+ name?: string;
2326
+ intentDescription?: string;
2327
+ tags?: string[];
2328
+ parameters?: ScriptParameter[];
2329
+ bodyHash: string;
2330
+ /** New on-disk stem when the edit renamed the script; omitted otherwise. */
2331
+ fileBase?: string;
2332
+ sourceIds?: string[];
2333
+ tables?: string[];
2334
+ editedBy?: string;
2335
+ editedFrom?: string;
2336
+ historyEntry: {
2337
+ version: number;
2338
+ at: string;
2339
+ by?: string;
2340
+ instruction?: string;
2341
+ changeSummary?: string;
2342
+ bodyHash?: string;
2343
+ };
2344
+ }): Promise<ScriptRecipeMetaRow | null>;
2345
+ /** Stamp a draft's last execution error. */
2346
+ recordDraftError(id: string, err: {
2347
+ phase: string;
2348
+ message: string;
2349
+ attempt: number;
2350
+ at: string;
2351
+ }): Promise<void>;
2352
+ /** Delete a recipe row (body file removed separately). */
2353
+ remove(id: string): Promise<void>;
2354
+ /** True if `fileBase` is taken by a different recipe in this project. */
2355
+ fileBaseTaken(fileBase: string, excludeId: string, projectId?: string): Promise<boolean>;
1475
2356
  }
2357
+ /** Pull the injected store off the collections bag (or null if not wired). */
2358
+ declare function resolveScriptRecipeStore(collections: any): ScriptRecipeStore | null;
2359
+
1476
2360
  /**
1477
- * A pre-built, multi-step UI flow registered with the SDK.
2361
+ * ScriptStore — Postgres metadata + on-disk body for script recipes.
1478
2362
  *
1479
- * When the main agent decides a user's question matches a workflow's whenToUse
1480
- * trigger, it picks the workflow instead of running source agents / generating
1481
- * dashboard components. The LLM extracts the workflow's required props from the
1482
- * prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
1483
- * workflow component directly — no analysis text, no chart generation. The
1484
- * frontend renders the registered workflow component with the LLM-extracted
1485
- * props.
2363
+ * Split of responsibilities:
2364
+ * - METADATA → injected `ScriptRecipeStore` (Postgres FTS + atomic counters),
2365
+ * resolved from `collections['script-recipes']`.
2366
+ * - BODY → scripts-store/<fileBase>.ts, editable in your IDE. Written
2367
+ * atomically (temp + rename); `bodyHash` (sha256) detects edits.
2368
+ *
2369
+ * The old "read every file every turn + send the whole catalog to the LLM"
2370
+ * matcher is gone — matching is `store.search(prompt)` (FTS shortlist). The
2371
+ * draft/verified filename dance is gone too: `status` is a DB column and the
2372
+ * file keeps a stable `<fileBase>.ts` name across promotion.
2373
+ *
2374
+ * When no metadata store is injected, the store degrades to a safe no-op
2375
+ * (count 0 → script flow disabled) instead of crashing.
2376
+ *
2377
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md.
1486
2378
  */
1487
- interface WorkflowDescriptor {
1488
- /** Unique workflow id (used as the LLM tool name) */
1489
- id: string;
1490
- /** Component name on the frontend (matches the registered React component) */
2379
+
2380
+ interface SaveDraftInput {
2381
+ /** Reuse an existing draft (retry); omit to mint a new one. */
2382
+ recipeId?: string;
2383
+ /** Per-turn unique suffix, stable across retries within the turn. */
2384
+ turnId: string;
1491
2385
  name: string;
1492
- /** Short human-readable description of what this workflow does */
1493
- description: string;
1494
- /**
1495
- * 1–2 sentence trigger condition. The LLM uses this to decide if the
1496
- * user's prompt matches this workflow. Be specific — e.g.
1497
- * "User wants to *initiate* an inventory transfer (review + submit POs),
1498
- * not just see analysis or charts."
1499
- */
1500
- whenToUse: string;
1501
- /**
1502
- * JSON-schema-style description of the props the workflow needs. Becomes
1503
- * the LLM tool's input_schema, so the model fills these from the prompt.
1504
- * Use the same shape as `params` on direct tools — string descriptors with
1505
- * an optional "(optional)" suffix.
1506
- *
1507
- * Example:
1508
- * ```
1509
- * {
1510
- * selectedStore: 'object — { id, name } of the source branch',
1511
- * minROI: 'number (optional) — only show transfers with ROI ≥ this',
1512
- * }
1513
- * ```
1514
- */
1515
- propsSchema: Record<string, string>;
1516
- /**
1517
- * Optional: static prop defaults merged with LLM-extracted props before
1518
- * the component is returned. Useful for things like the embedded
1519
- * `externalTool` config that the workflow uses to fetch its own data.
1520
- */
1521
- defaultProps?: Record<string, any>;
2386
+ intentDescription: string;
2387
+ tags: string[];
2388
+ parameters: ScriptParameter[];
2389
+ scriptBody: string;
2390
+ createdFrom: string;
2391
+ /**
2392
+ * Set when this draft is a SHADOW of an existing recipe being edited. The
2393
+ * draft is verified independently and merged back onto the parent via
2394
+ * `commitEdit`, so the working script is never clobbered by an edit that
2395
+ * turns out not to run. See backend/docs/SCRIPT-EDIT-DESIGN.md § D5.
2396
+ */
2397
+ parentId?: string;
1522
2398
  }
1523
- /**
1524
- * The workflow selection captured during a routing call.
1525
- * Set on AgentResponse when the LLM picks a workflow tool.
1526
- */
1527
- interface SelectedWorkflow {
1528
- /** Component name (matches WorkflowDescriptor.name) */
1529
- name: string;
1530
- /** Props extracted from the prompt + merged with workflow.defaultProps */
1531
- props: Record<string, any>;
2399
+ interface PromoteToVerifiedInput {
2400
+ sourceIds: string[];
2401
+ tables: string[];
2402
+ parentId?: string;
2403
+ forkDepth?: number;
2404
+ forkReason?: string;
2405
+ components?: ScriptComponentSpec[];
2406
+ }
2407
+ interface ScriptStoreOptions {
2408
+ /** Explicit metadata store, or resolved from `collections['script-recipes']`. */
2409
+ store?: ScriptRecipeStore | null;
2410
+ collections?: any;
2411
+ /** Body directory (defaults to <cwd>/scripts-store). */
2412
+ baseDir?: string;
2413
+ /** Project scope stamped on every row. */
2414
+ projectId?: string;
1532
2415
  }
1533
2416
  /**
1534
- * The complete response from the multi-agent system.
1535
- * Contains everything needed for text display + component generation.
2417
+ * Normalize a scriptBody into the on-disk form (strip a leading comment block,
2418
+ * ensure `export async function getData`). Exported for MainAgent.
1536
2419
  */
1537
- interface AgentResponse {
1538
- /** Generated text response (analysis of the data) */
1539
- text: string;
1540
- /** All executed tools across all source agents (for component generation) */
1541
- executedTools: ExecutedToolInfo[];
1542
- /** Individual results from each source agent */
1543
- sourceResults: SourceAgentResult[];
2420
+ declare function normalizeScriptBody(scriptBody: string): string;
2421
+ declare class ScriptStore {
2422
+ private store;
2423
+ private storeDir;
2424
+ private projectId?;
2425
+ constructor(opts?: ScriptStoreOptions);
2426
+ /** Whether a metadata store is wired (matcher / authoring are gated on this). */
2427
+ hasStore(): boolean;
2428
+ /** Number of healthy verified recipes (gates the script-matching path). */
2429
+ count(): Promise<number>;
2430
+ /**
2431
+ * FTS shortlist for the matcher (metadata only — bodies are loaded lazily by
2432
+ * `get()` once the LLM picks one). Returns verified, healthy recipes ranked
2433
+ * by relevance.
2434
+ */
2435
+ search(prompt: string, limit?: number): Promise<ScriptRecipe[]>;
2436
+ /** Fetch one recipe by id with its body loaded from disk. */
2437
+ get(id: string): Promise<ScriptRecipe | null>;
2438
+ /** Create or update a recipe (metadata upsert + body write when changed). */
2439
+ save(recipe: ScriptRecipe): Promise<void>;
2440
+ /**
2441
+ * Persist (or update) a draft. Within a turn, retries that pass the same
2442
+ * `recipeId` overwrite the same row + file; a fresh `recipeId` mints a new
2443
+ * draft. The body is visible at scripts-store/<fileBase>.ts immediately.
2444
+ */
2445
+ saveDraft(input: SaveDraftInput): Promise<ScriptRecipe>;
2446
+ /** Stamp a draft's last execution error (metadata only). */
2447
+ recordDraftError(recipeId: string, err: {
2448
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2449
+ message: string;
2450
+ attempt: number;
2451
+ }): Promise<void>;
2452
+ /**
2453
+ * Promote a successfully-executed draft into a verified script.
2454
+ * The on-disk body already exists at <fileBase>.ts (written at write_script
2455
+ * time) and keeps its name — only the DB row flips status + provenance.
2456
+ */
2457
+ promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): Promise<ScriptRecipe | null>;
2458
+ /**
2459
+ * Commit a user-directed edit: merge a VERIFIED shadow draft back onto the
2460
+ * recipe it was editing, as version N+1 under the SAME recipe id.
2461
+ *
2462
+ * Keeping the id stable is the point of the whole feature — every cached
2463
+ * conversation, `script_dataset` regeneration descriptor and persisted
2464
+ * component spec already points at it, so the correction applies retroactively
2465
+ * to replays instead of stranding them on the old body.
2466
+ *
2467
+ * Steps (see backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5):
2468
+ * 1. archive the current body as `<fileBase>.v<version>.ts`
2469
+ * 2. write the edited body to the original fileBase (atomic)
2470
+ * 3. version++, copy name/description/params, append a history record
2471
+ * 4. reset health counters — the pre-edit failure history is stale
2472
+ * 5. clear component specs — they were validated against the OLD shape
2473
+ * 6. delete the shadow draft (row + file)
2474
+ *
2475
+ * Returns the updated recipe, or null when the commit could not be applied
2476
+ * (caller should then fall back to treating the draft as a new script).
2477
+ */
2478
+ commitEdit(targetId: string, draft: {
2479
+ recipeId: string;
2480
+ name?: string;
2481
+ intentDescription?: string;
2482
+ tags?: string[];
2483
+ parameters?: ScriptParameter[];
2484
+ scriptBody: string;
2485
+ sourceIds?: string[];
2486
+ tables?: string[];
2487
+ }, meta: {
2488
+ instruction?: string;
2489
+ changeSummary?: string;
2490
+ editedBy?: string;
2491
+ }): Promise<ScriptRecipe | null>;
2492
+ /**
2493
+ * Drop a draft (row + body file). MainAgent calls this at end-of-turn when a
2494
+ * draft was authored but never verified — failed drafts are never matched, so
2495
+ * deleting them immediately avoids unbounded accumulation (#5). No-op if the
2496
+ * recipe isn't a draft (so a promoted/verified script is never removed here).
2497
+ */
2498
+ discardDraft(recipeId: string): Promise<void>;
2499
+ /** Delete a recipe (row + body file). */
2500
+ delete(id: string): Promise<void>;
2501
+ /** Record a successful execution (atomic counter bump). */
2502
+ recordSuccess(id: string): Promise<void>;
2503
+ /** Record a failed execution (atomic counter bump). */
2504
+ recordFailure(id: string): Promise<void>;
2505
+ /** Absolute path to the .ts body for a recipe (used by the runner/MainAgent). */
2506
+ getScriptPath(recipe: ScriptRecipe): string;
2507
+ private removeById;
2508
+ private rowToRecipe;
2509
+ private recipeToRow;
2510
+ /** slug of name, with a short id suffix when the bare slug is already taken. */
2511
+ private computeFileBase;
2512
+ private toSlug;
2513
+ private hash;
2514
+ private bodyPath;
2515
+ private readBody;
2516
+ /** Directory holding superseded bodies. Dot-prefixed so IDEs/`ls` hide it. */
2517
+ private get archiveDir();
2518
+ /**
2519
+ * Archive a superseded body as `.versions/<fileBase>.v<n>.ts`.
2520
+ *
2521
+ * Kept out of the main store directory on purpose — see commitEdit step 1.
2522
+ * To roll back: copy the file back over `scripts-store/<fileBase>.ts`.
2523
+ */
2524
+ private writeArchive;
1544
2525
  /**
1545
- * Set when the LLM routed the question to a registered workflow component.
1546
- * When present, the upstream caller should skip component generation and
1547
- * return this workflow as the response.
2526
+ * Move a recipe's archived versions to a new prefix when its fileBase changes,
2527
+ * so all versions of one recipe stay grouped. Without this, two renames would
2528
+ * scatter a single recipe's history across three prefixes in `.versions/` with
2529
+ * nothing linking them back to the live script.
1548
2530
  */
1549
- workflow?: SelectedWorkflow;
1550
- }
1551
- /**
1552
- * Configuration for the multi-agent system.
1553
- * Controls limits, models, and behavior.
1554
- */
1555
- interface AgentConfig {
1556
- /** Max rows a source agent can return (default: 50) */
1557
- maxRowsPerSource: number;
1558
- /** Model for the main agent (routing + analysis in one LLM call) */
1559
- mainAgentModel: string;
1560
- /** Model for source agent query generation */
1561
- sourceAgentModel: string;
1562
- /** API key for LLM calls */
1563
- apiKey?: string;
1564
- /** Max retry attempts per source agent */
1565
- maxRetries: number;
1566
- /** Max tool calling iterations for the main agent loop */
1567
- maxIterations: number;
1568
- /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
1569
- globalKnowledgeBase?: string;
1570
- /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
1571
- knowledgeBaseContext?: string;
2531
+ private renameArchives;
2532
+ /** Atomic body write (temp + rename) so concurrent reads never see a partial file. */
2533
+ private writeBody;
2534
+ private unlinkBody;
1572
2535
  }
1573
- /**
1574
- * Default agent configuration
1575
- */
1576
- declare const DEFAULT_AGENT_CONFIG: AgentConfig;
1577
2536
 
1578
2537
  /**
1579
2538
  * Main Agent (Orchestrator)
@@ -1595,7 +2554,60 @@ declare class MainAgent {
1595
2554
  private workflows;
1596
2555
  private config;
1597
2556
  private streamBuffer;
1598
- constructor(externalTools: ExternalTool[], config: AgentConfig, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[]);
2557
+ /**
2558
+ * Optional: when provided, MainAgent exposes the `write_script` /
2559
+ * `execute_script` tools to the LLM and persists drafts to disk via the
2560
+ * store. Headless callers (alert analyzer, metric resolver) omit these to
2561
+ * suppress script authoring entirely — drafts would otherwise leak onto
2562
+ * disk with no caller to promote or clean them up.
2563
+ */
2564
+ private scriptStore;
2565
+ private turnId;
2566
+ private createdFromPrompt;
2567
+ private scriptState;
2568
+ /** Answer-flow component catalog (filtered + projected by the caller). */
2569
+ private componentCatalog;
2570
+ /** Specs accepted by `render_components` this turn; empty until it succeeds. */
2571
+ /**
2572
+ * Entities resolved this turn, appended verbatim to every source dispatch.
2573
+ *
2574
+ * Not left to the model to copy into its intent prose: observed live, the
2575
+ * MainAgent wrote names instead of ids on the first dispatch AND re-spelled
2576
+ * 'F D C LIMITED' as 'FDC Limited', so the source agent fell back to
2577
+ * `PartyName LIKE '%FDC%'` and found 2 of 3 customers. Carrying the ids
2578
+ * structurally makes that impossible rather than instruction-dependent.
2579
+ */
2580
+ private resolvedEntities;
2581
+ private componentSpecs;
2582
+ private componentLayout;
2583
+ private renderComponentAttempts;
2584
+ /**
2585
+ * Fork mode — set when this turn is adapting a near-matching parent script.
2586
+ * In fork mode there is no legitimate "answer with bare text" outcome: the
2587
+ * only correct first move is a tool call (write_script, or a source tool for
2588
+ * schema discovery). We therefore force tool use on the first LLM iteration
2589
+ * so the model can't end its turn with a bare "I'll adapt…" preamble and zero
2590
+ * tool calls. Never set on the fresh-authoring / general-question path.
2591
+ */
2592
+ private forkMode;
2593
+ /**
2594
+ * Edit mode — set when this turn applies a user-directed change to an
2595
+ * existing script. Swaps the system prompt to `agent-main-edit` and stamps
2596
+ * the shadow draft's parentId. Like fork mode there is no legitimate
2597
+ * "answer with bare text" outcome, so tool use is forced on iteration 1.
2598
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 4.
2599
+ */
2600
+ private editContext;
2601
+ /**
2602
+ * Per-turn cancellation signal (user hit "Stop"). Set at the top of
2603
+ * handleQuestion and read by the tool handler, the SourceAgent dispatch, and
2604
+ * the script subprocess so an abort tears down every layer of the turn.
2605
+ */
2606
+ private abortSignal?;
2607
+ constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[], forkMode?: boolean, editContext?: EditContext, componentCatalog?: Component[]);
2608
+ /** True when the turn is applying a user-directed script edit. */
2609
+ private get editMode();
2610
+ private get scriptingEnabled();
1599
2611
  /**
1600
2612
  * Handle a user question using the multi-agent system.
1601
2613
  *
@@ -1606,7 +2618,66 @@ declare class MainAgent {
1606
2618
  * 4. Direct tools → fn() called directly with LLM params → returns data
1607
2619
  * 5. Generates final analysis text
1608
2620
  */
1609
- handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void): Promise<AgentResponse>;
2621
+ handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, signal?: AbortSignal): Promise<AgentResponse>;
2622
+ /**
2623
+ * Tool definition, with the catalog rendered from the registered `Metadata`
2624
+ * the caller passed in. Generated rather than hand-written so it cannot drift
2625
+ * from what the frontend actually ships.
2626
+ */
2627
+ private buildRenderComponentsToolDef;
2628
+ /**
2629
+ * Validate the agent's component picks against the REAL columns of each bound
2630
+ * dataset. All-or-nothing: any error rejects the whole call and returns the
2631
+ * findings, because a partially-accepted dashboard makes the retry ambiguous.
2632
+ */
2633
+ private handleRenderComponents;
2634
+ private handleWriteScript;
2635
+ private handleExecuteScript;
2636
+ /**
2637
+ * Build the AgentWrittenScript payload the caller will hand to
2638
+ * `ScriptStore.promoteToVerified()`. Only returned when a verified
2639
+ * successful execution is on record.
2640
+ */
2641
+ private buildSavedScript;
2642
+ private normalizeParameterList;
2643
+ /**
2644
+ * Use the schema embedding collection to pre-select relevant tables for
2645
+ * this source + intent. Returns a formatted schema block if confidence is
2646
+ * high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
2647
+ *
2648
+ * When this returns a block, we can skip the SourceAgent's `search_schema`
2649
+ * loop and reduce iteration budget. When it returns null, the SourceAgent
2650
+ * falls back to the existing LLM-driven keyword search (same as today).
2651
+ */
2652
+ /**
2653
+ * Ids + verbatim names for everything resolved this turn, appended by CODE to
2654
+ * each source dispatch so neither omission nor re-spelling by the model can
2655
+ * lose them. Empty string when nothing was resolved, so intents are untouched
2656
+ * for questions that name no entities.
2657
+ */
2658
+ private buildResolvedEntitiesBlock;
2659
+ /** True when the backend registered the entity-search collection. */
2660
+ private get entitySearchEnabled();
2661
+ /**
2662
+ * Compact catalog (type + gloss) for the system prompt. This is what lets the
2663
+ * LLM NAME a concept instead of guessing at our vocabulary — it can infer
2664
+ * that a question is about unpaid money, but not that we call that
2665
+ * `outstanding-balance`. Full `resolution` detail is fetched by the tool.
2666
+ *
2667
+ * Deliberately NOT cached in-process. The token cost is already handled by
2668
+ * prompt caching (the system prompt carries a cache_control breakpoint), and
2669
+ * re-reading a tiny PK-ordered table costs ~nothing. Fetching fresh does not
2670
+ * weaken the prompt cache either: unchanged data renders byte-identical text,
2671
+ * so the prefix still hits. A process cache would only buy a staleness window
2672
+ * in which a newly indexed entity is invisible to the agent.
2673
+ */
2674
+ private loadEntityCatalog;
2675
+ /**
2676
+ * Never throws: a resolver outage must degrade to "nothing resolved" and
2677
+ * leave the agent exactly as it was, not take the whole answer down.
2678
+ */
2679
+ private handleResolveEntities;
2680
+ private preResolveSchema;
1610
2681
  /**
1611
2682
  * Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
1612
2683
  */
@@ -1672,7 +2743,45 @@ interface LLMOptions {
1672
2743
  temperature?: number;
1673
2744
  topP?: number;
1674
2745
  apiKey?: string;
2746
+ baseURL?: string;
1675
2747
  partial?: (chunk: string) => void;
2748
+ /**
2749
+ * Per-request cancellation. When the caller aborts this signal (user hit
2750
+ * "Stop"), the underlying provider request is cancelled and the call throws
2751
+ * a RequestAbortedError. Threaded into the provider `messages.create` request
2752
+ * options and checked between tool-loop iterations. Currently honored on the
2753
+ * Anthropic path (the agent flow's default provider).
2754
+ */
2755
+ signal?: AbortSignal;
2756
+ /**
2757
+ * Forces a tool call on the FIRST iteration of streamWithTools only
2758
+ * (subsequent iterations revert to auto). Used by fork mode to stop the
2759
+ * model from ending its turn with a bare "I'll adapt the script…" preamble
2760
+ * and zero tool calls. `{ type: 'any' }` lets the model pick which tool
2761
+ * (write_script in the common case, a source tool for schema discovery);
2762
+ * `{ type: 'tool', name }` pins a specific tool. Honored on both the
2763
+ * Anthropic path and the OpenAI/OpenRouter path (mapped to OpenAI's
2764
+ * tool_choice: 'required' / a named function).
2765
+ */
2766
+ firstIterationToolChoice?: {
2767
+ type: 'any';
2768
+ } | {
2769
+ type: 'tool';
2770
+ name: string;
2771
+ };
2772
+ /**
2773
+ * Internal — set only by the OpenRouter wrappers when the target is a Claude
2774
+ * model. Tells the OpenAI-wire path to emit Anthropic `cache_control`
2775
+ * breakpoints (OpenRouter forwards them to Anthropic for prompt caching).
2776
+ * Never set for direct OpenAI/Groq calls, so their requests are unchanged.
2777
+ */
2778
+ _openrouterClaudeCaching?: boolean;
2779
+ /**
2780
+ * Internal — OpenRouter provider-routing preferences (forwarded as the
2781
+ * `provider` body field). Set by the OpenRouter wrappers to steer routing to
2782
+ * a fast backend (e.g. {sort:'throughput'}). Never set for direct OpenAI/Groq.
2783
+ */
2784
+ _openrouterProvider?: Record<string, unknown>;
1676
2785
  }
1677
2786
  interface Tool {
1678
2787
  name: string;
@@ -1694,6 +2803,16 @@ declare class LLM {
1694
2803
  * @returns Normalized system prompt for Anthropic API
1695
2804
  */
1696
2805
  private static _normalizeSystemPrompt;
2806
+ /**
2807
+ * Strip unpaired UTF-16 surrogates from every text field of a message set.
2808
+ *
2809
+ * A lone surrogate (from mid-pair string slicing or corrupt source data)
2810
+ * serializes to a bare `\udXXX` escape that strict JSON parsers — including
2811
+ * the one on Anthropic's API — reject with "no low surrogate in string",
2812
+ * failing the whole request. Sanitizing here, at the single boundary every
2813
+ * provider call flows through, guarantees no request can carry one.
2814
+ */
2815
+ private static _sanitizeMessages;
1697
2816
  /**
1698
2817
  * Log cache usage metrics from Anthropic API response
1699
2818
  * Shows cache hits, costs, and savings
@@ -1710,11 +2829,46 @@ declare class LLM {
1710
2829
  * "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
1711
2830
  */
1712
2831
  private static _parseModel;
2832
+ /**
2833
+ * Map an Anthropic model id (e.g. "claude-sonnet-4-5-20250929") to the OpenRouter slug
2834
+ * (e.g. "claude-sonnet-4.5"). OpenRouter slugs drop the date suffix and use dotted versions.
2835
+ */
2836
+ private static _toOpenRouterSlug;
2837
+ /**
2838
+ * Per-provider proxy base URL. Returns `${SUPERATOM_LLM_PROXY_URL}/<provider>`
2839
+ * when our Cloudflare LLM proxy is configured, else undefined (→ talk to the
2840
+ * provider directly, legacy behaviour). An explicit options.baseURL (e.g.
2841
+ * OpenRouter) always wins and is never overridden. See backend/docs/llm-proxy.md.
2842
+ */
2843
+ private static _proxyBaseURL;
2844
+ private static _openrouterOptions;
2845
+ private static _isRetryableProviderError;
2846
+ private static _withOpenrouterRetry;
2847
+ private static _openrouterText;
2848
+ private static _openrouterStream;
2849
+ private static _openrouterStreamWithTools;
2850
+ /**
2851
+ * Build an Anthropic client. Routes through our Cloudflare LLM proxy when
2852
+ * SUPERATOM_LLM_PROXY_URL is set (each client ships a per-client proxy key as
2853
+ * ANTHROPIC_API_KEY and never holds the real key); otherwise talks to
2854
+ * api.anthropic.com directly. See backend/docs/llm-proxy.md.
2855
+ */
2856
+ private static _anthropicClient;
2857
+ /** True when OpenRouter is configured as a fail-open fallback for Claude. */
2858
+ private static _openrouterAvailable;
2859
+ /** Remap an Anthropic model id to the OpenRouter model path for fail-open. */
2860
+ private static _anthropicFallbackModel;
1713
2861
  private static _anthropicText;
1714
2862
  private static _anthropicStream;
1715
2863
  private static _anthropicStreamWithTools;
1716
2864
  private static _groqText;
1717
2865
  private static _groqStream;
2866
+ /**
2867
+ * Gemini request options carrying the proxy base URL, or undefined → talk to
2868
+ * generativelanguage.googleapis.com directly. The Google SDK takes baseUrl as a
2869
+ * per-model request option, not a constructor arg. See backend/docs/llm-proxy.md.
2870
+ */
2871
+ private static _geminiRequestOptions;
1718
2872
  private static _geminiText;
1719
2873
  private static _geminiStream;
1720
2874
  /**
@@ -1723,8 +2877,28 @@ declare class LLM {
1723
2877
  */
1724
2878
  private static _cleanSchemaForGemini;
1725
2879
  private static _geminiStreamWithTools;
2880
+ /** True for Anthropic/Claude model ids — gates OpenRouter prompt caching. */
2881
+ private static _isClaudeModel;
2882
+ /**
2883
+ * Build the OpenAI-wire system message. For OpenRouter + Claude
2884
+ * (cacheClaude=true) it emits content parts carrying Anthropic
2885
+ * `cache_control` breakpoints (preserving any the caller set, else marking
2886
+ * the last block), so OpenRouter forwards them to Anthropic for prompt
2887
+ * caching. Otherwise it returns a plain flattened string — unchanged for
2888
+ * direct OpenAI/Groq.
2889
+ */
2890
+ private static _openaiSystemMessage;
2891
+ /**
2892
+ * Split an OpenAI-wire usage object. `prompt_tokens` INCLUDES cached tokens,
2893
+ * so we subtract them out (Anthropic-style: input excludes cache reads) and
2894
+ * report cached separately — this makes calculateCost price cache reads at
2895
+ * the discounted rate and reflects OpenRouter prompt-cache savings in logs.
2896
+ */
2897
+ private static _openaiUsage;
1726
2898
  private static _openaiText;
1727
2899
  private static _openaiStream;
2900
+ /** Map the Anthropic-style firstIterationToolChoice to OpenAI's tool_choice. */
2901
+ private static _openaiToolChoice;
1728
2902
  private static _openaiStreamWithTools;
1729
2903
  /**
1730
2904
  * Parse JSON string, handling markdown code blocks and surrounding text
@@ -1826,6 +3000,13 @@ declare class UIBlock {
1826
3000
  private textResponse;
1827
3001
  private actions;
1828
3002
  private createdAt;
3003
+ /**
3004
+ * Which script recipe produced this answer, when a script did. Read on the
3005
+ * NEXT turn so the user can say "use mode instead" and have the matcher
3006
+ * resolve it to a concrete script (the `edit` tier is unreachable without it).
3007
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3008
+ */
3009
+ private scriptBinding;
1829
3010
  /**
1830
3011
  * Creates a new UIBlock instance
1831
3012
  * @param userQuestion - The user's question or input
@@ -1920,6 +3101,14 @@ declare class UIBlock {
1920
3101
  /**
1921
3102
  * Get creation timestamp
1922
3103
  */
3104
+ /**
3105
+ * Bind this block to the script recipe that produced its answer.
3106
+ */
3107
+ setScriptBinding(binding: Record<string, any> | null): void;
3108
+ /**
3109
+ * The script recipe bound to this block, if any.
3110
+ */
3111
+ getScriptBinding(): Record<string, any> | null;
1923
3112
  getCreatedAt(): Date;
1924
3113
  /**
1925
3114
  * Convert UIBlock to JSON-serializable object
@@ -1987,6 +3176,32 @@ declare class Thread {
1987
3176
  * @param currentUIBlockId - ID of current UIBlock to exclude from context (optional)
1988
3177
  * @returns Formatted conversation history string
1989
3178
  */
3179
+ /**
3180
+ * The script recipe bound to the most recent completed UIBlock — i.e. the
3181
+ * script behind the answer the user is currently looking at. Drives the
3182
+ * matcher's `edit` tier: without it, "use mode instead" has no target and
3183
+ * falls through to regeneration.
3184
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3185
+ */
3186
+ getActiveScriptBinding(currentUIBlockId?: string): Record<string, any> | null;
3187
+ /**
3188
+ * The recent script-backed answers in this thread, newest first — the
3189
+ * candidate set a user-directed edit can target.
3190
+ *
3191
+ * Returning several rather than only the newest is what lets an instruction
3192
+ * name its own target ("use the mode for the WSP one"). With a single
3193
+ * candidate every edit lands on the most recent script, which silently edits
3194
+ * the wrong recipe whenever the user meant an earlier one.
3195
+ *
3196
+ * Deduped by recipeId (newest occurrence wins) so a long editing session on
3197
+ * one script doesn't crowd out the others. Each entry carries the question
3198
+ * that produced it — without that the candidates are indistinguishable.
3199
+ *
3200
+ * In-memory only: dies with the process. The caller falls back to the
3201
+ * persisted bindings when this comes back empty.
3202
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3203
+ */
3204
+ getScriptBindings(limit?: number, currentUIBlockId?: string): Record<string, any>[];
1990
3205
  getConversationContext(limit?: number, currentUIBlockId?: string): string;
1991
3206
  /**
1992
3207
  * Convert Thread to JSON-serializable object
@@ -2649,7 +3864,7 @@ declare abstract class BaseLLM {
2649
3864
  * This helps provide intelligent suggestions for follow-up queries
2650
3865
  * For general/conversational questions without components, pass textResponse instead
2651
3866
  */
2652
- generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string): Promise<string[]>;
3867
+ generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string, signal?: AbortSignal): Promise<string[]>;
2653
3868
  }
2654
3869
 
2655
3870
  interface AnthropicLLMConfig extends BaseLLMConfig {
@@ -2712,7 +3927,8 @@ declare const openaiLLM: OpenAILLM;
2712
3927
  * Query Cache — Two mechanisms:
2713
3928
  *
2714
3929
  * 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
2715
- * of recently validated queries. LRU eviction when max size exceeded.
3930
+ * of recently validated queries. True LRU eviction: reads bubble entries to the back via
3931
+ * delete+re-set so the oldest *unused* entry is evicted, not the oldest *inserted*.
2716
3932
  *
2717
3933
  * 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
2718
3934
  * No server-side storage needed for SQL mappings. The token is decrypted on each request.
@@ -2739,11 +3955,16 @@ declare class QueryCache {
2739
3955
  */
2740
3956
  getTTL(): number;
2741
3957
  /**
2742
- * Store query result in data cache
3958
+ * Store query result in data cache.
3959
+ * If the key already exists, it's removed first so the re-insert places it
3960
+ * at the back of the iteration order (LRU). Eviction only fires when adding
3961
+ * a genuinely new key past the size limit.
2743
3962
  */
2744
3963
  set(query: string, data: any): void;
2745
3964
  /**
2746
- * Get cached result if exists and not expired
3965
+ * Get cached result if exists and not expired.
3966
+ * On hit, re-inserts the entry so it moves to the back of the Map's
3967
+ * iteration order — turning FIFO eviction into true LRU.
2747
3968
  */
2748
3969
  get(query: string): any | null;
2749
3970
  /**
@@ -2849,6 +4070,187 @@ declare class DashboardConversationHistory {
2849
4070
  }
2850
4071
  declare const dashboardConversationHistory: DashboardConversationHistory;
2851
4072
 
4073
+ /**
4074
+ * Whole-dashboard generation via Pi, a terminal coding agent — as opposed to
4075
+ * DASH_COMP_REQ's single-widget-at-a-time flow. Runs Pi in-process via its
4076
+ * SDK (createAgentSession), not as a subprocess: no shell, no argument
4077
+ * quoting, no stdin/stdout piping, none of the Windows-specific subprocess
4078
+ * issues that came with spawning the `pi` CLI directly.
4079
+ *
4080
+ * Called from sdk-nodejs/src/dashboardAgent/index.ts (DASHBOARD_AGENT_REQ),
4081
+ * which owns the generic streaming/abort machinery (mirrors USER_PROMPT_REQ)
4082
+ * and passes `signal`/`onProgress` alongside the normal params — this stays
4083
+ * within CollectionHandler's loose (params) => Promise<result> typing, no
4084
+ * change needed to that shared type.
4085
+ *
4086
+ * This mechanism is generic and reusable across any deployment. What's
4087
+ * genuinely project-specific — where AGENTS.md lives, which model to use —
4088
+ * is supplied via `DashboardAgentCollectionConfig`, with defaults sensible
4089
+ * enough that most callers don't need to override them (see below). The
4090
+ * data-source tool list and the dashboard's current state both come from
4091
+ * things sdk-nodejs already exposes generically: `sdk.getTools()` (whatever
4092
+ * this deployment registered via `sdk.setTools()`) and `sdk.callCollection
4093
+ * ('dashboards', 'query', ...)` (whatever this deployment already registered
4094
+ * under that name/shape) — no per-deployment callback needed for either.
4095
+ * Same convention on the way out: after a successful run, the prompt and the
4096
+ * full response text are handed to `sdk.callCollection('dashboard-agent-
4097
+ * conversations', 'create', ...)` if this deployment has registered one —
4098
+ * skipped silently otherwise, since conversation history is optional.
4099
+ *
4100
+ * Pi verifies every query against the live database itself (via whatever
4101
+ * local tool-execution bridge the deployment exposes, e.g. an HTTP bridge
4102
+ * on localhost), but does NOT persist the result itself — it writes the
4103
+ * finished DSL to an absolute path inside `runtimeDir`, told to it explicitly
4104
+ * in the prompt, and stops there. This handler reads that file after the run
4105
+ * finishes and returns its content as `dashboard` in the result. The caller
4106
+ * (frontend) is the one that actually saves it, via whatever authenticated
4107
+ * create/update path any other dashboard edit goes through — Pi has no user
4108
+ * session/auth context of its own, so persistence shouldn't happen from
4109
+ * inside it.
4110
+ *
4111
+ * Session persistence: the FIRST call for a dashboardId pays the full cost
4112
+ * (explore KB, discover schema, plan, verify, build). Every call after that
4113
+ * resumes the same session file (SessionManager.open) so Pi has everything
4114
+ * it already learned — it only needs to reason about the new, smaller ask,
4115
+ * not rediscover the whole dashboard from scratch. The session's file path
4116
+ * (AgentSession.sessionFile) is captured right after creation and persisted
4117
+ * in a small local file, keyed by dashboardId, inside `runtimeDir`.
4118
+ */
4119
+ interface DashboardAgentCollectionConfig {
4120
+ /**
4121
+ * Working directory Pi runs from — must contain AGENTS.md. This is a
4122
+ * version-controlled prompt file, so `cwd` is expected to live somewhere
4123
+ * like a `.prompts/` folder alongside the deployment's other prompts.
4124
+ * Default: `<process.cwd()>/.prompts/dashboard-agent` — the same
4125
+ * process.cwd()-based convention PromptLoader already uses for the main
4126
+ * agent's prompts, which needs no explicit override in the common case
4127
+ * (the backend process's own cwd already is its project root).
4128
+ */
4129
+ cwd?: string;
4130
+ /**
4131
+ * Where drafts/, the session-id map, and dashboard.log get written —
4132
+ * separate from `cwd` deliberately, so this deployment's runtime state
4133
+ * (regenerated per session, safe to gitignore) doesn't sit inside the
4134
+ * same folder as the version-controlled AGENTS.md prompt.
4135
+ * Default: `<process.cwd()>/.pi-dashboard-agent-runtime`.
4136
+ */
4137
+ runtimeDir?: string;
4138
+ /** Model provider (default: process.env.PI_AGENT_PROVIDER || 'openrouter'). */
4139
+ provider?: string;
4140
+ /** Model id (default: process.env.PI_AGENT_MODEL || 'anthropic/claude-sonnet-4.5'). */
4141
+ model?: string;
4142
+ /**
4143
+ * true (default): every request starts a brand-new pi session, with the 2
4144
+ * most recent prior responses (if any) injected into the prompt as
4145
+ * context — bounded cost per request, but pi re-explores schema/KB facts
4146
+ * it already verified in an earlier turn on this same dashboard.
4147
+ * false: resumes the same session file across requests on a given
4148
+ * dashboard — pi keeps everything it already learned, but context (and
4149
+ * cost) grows unbounded across turns (one observed turn: 2M+ cache-read
4150
+ * tokens after a handful of edits on the same dashboard).
4151
+ * Default: process.env.PI_AGENT_FRESH_SESSION !== 'false'.
4152
+ */
4153
+ freshSession?: boolean;
4154
+ }
4155
+ declare function registerDashboardAgentCollection(sdk: SuperatomSDK, config?: DashboardAgentCollectionConfig): void;
4156
+
4157
+ /**
4158
+ * ScriptMatcher — LLM-Based Script Matching + Parameter Extraction
4159
+ *
4160
+ * Uses ONE LLM call to:
4161
+ * 1. Pick the best matching script from the library (or "none")
4162
+ * 2. Extract parameter values from the user question
4163
+ *
4164
+ * Why LLM over embeddings:
4165
+ * - Embeddings capture topic similarity ("overstock" ≈ "inventory" ≈ "revenue")
4166
+ * but can't distinguish structurally different questions about the same domain
4167
+ * - LLM understands that "overstock by warehouse" needs a different script than
4168
+ * "revenue by warehouse" even though they're semantically close
4169
+ * - One call does both matching AND parameter extraction
4170
+ *
4171
+ * When script library grows past ~50, add an embedding pre-filter
4172
+ * (ChromaDB narrows to top 10 → LLM picks from those 10).
4173
+ */
4174
+
4175
+ declare class ScriptMatcher {
4176
+ private store;
4177
+ constructor(store: ScriptStore);
4178
+ /**
4179
+ * Find the best matching script for a user question.
4180
+ * Uses ONE LLM call that picks the script AND extracts parameters.
4181
+ * Returns null if no script matches.
4182
+ */
4183
+ match(userPrompt: string, apiKey?: string, model?: string, signal?: AbortSignal,
4184
+ /**
4185
+ * Recent script-backed answers in this thread, newest first. Presence of at
4186
+ * least one is what makes the `edit` tier reachable at all (see the guards
4187
+ * below), and handing over SEVERAL is what lets an instruction name its own
4188
+ * target instead of always hitting the most recent script.
4189
+ */
4190
+ activeBindings?: ScriptBinding[],
4191
+ /**
4192
+ * Recent conversation turns, most recent last. The gate needs this to tell
4193
+ * "this reply is an edit instruction for the active script" apart from
4194
+ * "this reply is answering a clarifying question about a DIFFERENT,
4195
+ * unresolved topic that never became a script" — a bare parameter-shaped
4196
+ * reply ("April 2025 to March 2026") is textually indistinguishable
4197
+ * between those two cases without seeing what the assistant just asked.
4198
+ * Once this tier is decided, nothing downstream re-checks it — the edit
4199
+ * path hands MainAgent a system prompt that explicitly instructs it to
4200
+ * trust the premise and not treat the turn as a new question — so this
4201
+ * gate is the only place that can catch a mismatch.
4202
+ */
4203
+ conversationHistory?: string): Promise<ScriptMatch | null>;
4204
+ /**
4205
+ * Build the script catalog string for the LLM prompt.
4206
+ * Each script gets: index, ID, name, description, and parameter definitions.
4207
+ */
4208
+ private buildScriptCatalog;
4209
+ /**
4210
+ * The recent script-backed answers in this thread — the bounded set an edit
4211
+ * may target. Rendered as its own prompt section (never merged into the
4212
+ * ranked catalog) so the `edit` rules have an unambiguous referent set, and
4213
+ * numbered newest-first so the prompt's "prefer the most recent when the
4214
+ * instruction is ambiguous" tie-break has something to point at.
4215
+ *
4216
+ * Each entry carries the QUESTION that produced it plus the columns it
4217
+ * returned — that is what lets the matcher resolve "use the mode for the WSP
4218
+ * one" instead of blindly taking the newest.
4219
+ */
4220
+ private buildActiveScriptBlock;
4221
+ }
4222
+
4223
+ /**
4224
+ * ScriptRunner — Execute scripts in an isolated tsx subprocess.
4225
+ *
4226
+ * The subprocess approach replaces the earlier `new Function()` eval and gives us:
4227
+ * - Real sandbox (separate process, SIGKILL on timeout).
4228
+ * - Real TypeScript (tsx transpiles on the fly).
4229
+ * - npm imports available to scripts (clustering, stats, geo, etc.).
4230
+ *
4231
+ * Protocol: NDJSON over the child's stdin/stdout. See script-ipc.ts + backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md.
4232
+ */
4233
+
4234
+ interface RunScriptOptions {
4235
+ /** Data sources the script is allowed to query via ctx.query */
4236
+ externalTools: ExternalTool[];
4237
+ /** Optional — for propagating per-query UI progress to the user */
4238
+ streamBuffer?: StreamBuffer;
4239
+ /** Override the wall-clock timeout (default `SCRIPT_TIMEOUT_MS`, 60s). */
4240
+ timeoutMs?: number;
4241
+ /**
4242
+ * Per-turn cancellation signal. When the user hits "Stop" mid-run, the child
4243
+ * process group is SIGKILLed and the run resolves as an aborted failure (the
4244
+ * caller is already unwinding, so the result is discarded).
4245
+ */
4246
+ signal?: AbortSignal;
4247
+ }
4248
+ /**
4249
+ * Execute a recipe by spawning a tsx child on the script's .ts file.
4250
+ * `scriptPath` is the absolute path to the saved `.ts` body.
4251
+ */
4252
+ declare function runScript(recipe: ScriptRecipe, scriptPath: string, params: Record<string, any>, options: RunScriptOptions): Promise<ScriptResult>;
4253
+
2852
4254
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
2853
4255
  declare class SuperatomSDK {
2854
4256
  private ws;
@@ -2884,6 +4286,8 @@ declare class SuperatomSDK {
2884
4286
  private lastPong;
2885
4287
  private readonly PING_INTERVAL_MS;
2886
4288
  private readonly PONG_TIMEOUT_MS;
4289
+ private pendingOutbox;
4290
+ private readonly MAX_OUTBOX_SIZE;
2887
4291
  constructor(config: SuperatomSDKConfig);
2888
4292
  /**
2889
4293
  * Initialize PromptLoader and load prompts into memory
@@ -2928,6 +4332,20 @@ declare class SuperatomSDK {
2928
4332
  * Does NOT throw on closed connections — callers can check the return value if needed.
2929
4333
  */
2930
4334
  send(message: Message): boolean;
4335
+ /**
4336
+ * Queue a message that couldn't be delivered because the socket was down,
4337
+ * to be resent once it reconnects. Drops the oldest entry once the bound is
4338
+ * hit — an outage long enough to fill this queue means the oldest queued
4339
+ * responses are for requests the caller has likely already given up on.
4340
+ */
4341
+ private queuePendingMessage;
4342
+ /**
4343
+ * Resend everything queued while the socket was down, now that it's back
4344
+ * up. Uses this.ws.send() directly (not send()) so a message that fails
4345
+ * again goes back through queuePendingMessage() rather than being silently
4346
+ * dropped a second time.
4347
+ */
4348
+ private flushPendingOutbox;
2931
4349
  /**
2932
4350
  * Register a message handler to receive all messages
2933
4351
  */
@@ -2967,6 +4385,14 @@ declare class SuperatomSDK {
2967
4385
  */
2968
4386
  private handlePong;
2969
4387
  private storeComponents;
4388
+ /**
4389
+ * The live, frontend-registered component catalog (name, type, description,
4390
+ * and full prop schema per component) — the same authoritative source
4391
+ * DASH_COMP_REQ's LLM prompt is built from. Exposed so other integrations
4392
+ * (e.g. the dashboard-agent script bridge) can read real component
4393
+ * contracts instead of maintaining a separate, driftable hand-written copy.
4394
+ */
4395
+ getComponents(): Component[];
2970
4396
  /**
2971
4397
  * Set tools for the SDK instance
2972
4398
  */
@@ -2975,6 +4401,16 @@ declare class SuperatomSDK {
2975
4401
  * Get the stored tools
2976
4402
  */
2977
4403
  getTools(): Tool$1[];
4404
+ /**
4405
+ * Call a registered collection operation in-process — no WebSocket
4406
+ * round-trip, since the caller is already running inside this same SDK
4407
+ * instance. Lets SDK-internal features (e.g. the dashboard agent) reuse
4408
+ * whatever collection a deployment has already registered (e.g.
4409
+ * 'dashboards'.'query') by name/convention, instead of requiring a
4410
+ * separate callback purely to re-expose data a collection already serves.
4411
+ * Throws if the collection or operation isn't registered.
4412
+ */
4413
+ callCollection<TResult = any>(collectionName: string, operation: string, params?: any): Promise<TResult>;
2978
4414
  /**
2979
4415
  * Register workflow components for the SDK instance.
2980
4416
  *
@@ -3018,4 +4454,4 @@ declare class SuperatomSDK {
3018
4454
  getConversationSimilarityThreshold(): number;
3019
4455
  }
3020
4456
 
3021
- export { type Action, type AgentConfig, type AgentResponse, BM25L, type BM25LOptions, type BaseLLMConfig, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, DEFAULT_AGENT_CONFIG, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, MainAgent, type Message, type ModelStrategy, type OutputField, type RerankedResult, STORAGE_CONFIG, type SelectedWorkflow, SuperatomSDK, type SuperatomSDKConfig, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, type ToolOutputSchema, UIBlock, UILogCollector, type User, UserManager, type UsersData, type WorkflowDescriptor, anthropicLLM, dashboardConversationHistory, geminiLLM, groqLLM, hybridRerank, llmUsageLogger, logger, openaiLLM, queryCache, rerankChromaResults, rerankConversationResults, userPromptErrorLogger };
4457
+ 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 };