@superatomai/sdk-node 0.0.49 → 0.0.50-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,1042 @@
1
1
  import { z } from 'zod';
2
2
  import Anthropic from '@anthropic-ai/sdk';
3
3
 
4
+ /**
5
+ * Script Flow Types
6
+ *
7
+ * Defines interfaces for the script-based query architecture:
8
+ * - ScriptRecipe: metadata for matching, validation, and quality tracking
9
+ * - ScriptResult: output from executing a script
10
+ * - ScriptMatch: result from the LLM-based script matcher
11
+ */
12
+
13
+ /**
14
+ * Recipe metadata stored alongside each script.
15
+ * Used for matching, validation, and quality tracking.
16
+ */
17
+ interface ScriptRecipe {
18
+ /** Unique script identifier */
19
+ id: string;
20
+ /** Version number (incremented on regeneration) */
21
+ version: number;
22
+ /** Human-readable name (e.g., "Revenue by Dimension") */
23
+ name: string;
24
+ /** Natural language description of what this script does */
25
+ intentDescription: string;
26
+ /** Keyword tags for quick filtering */
27
+ tags: string[];
28
+ /** Source tool IDs this script queries (e.g., ["mssql-abc123_query"]) */
29
+ sourceIds: string[];
30
+ /** Table names used (for future schema drift detection) */
31
+ tables: string[];
32
+ /** Parameter definitions — what can vary */
33
+ parameters: ScriptParameter[];
34
+ /** The script function body as a string. Loaded from disk (scripts-store/<fileBase>.ts). */
35
+ scriptBody: string;
36
+ /**
37
+ * On-disk filename stem for the body: scripts-store/<fileBase>.ts.
38
+ * Editable in the IDE. Decided at authoring time (slug of `name`, with a
39
+ * short id suffix on collision) and stable across promotion.
40
+ */
41
+ fileBase?: string;
42
+ /** sha256 of the on-disk body — lets the runtime detect manual edits. */
43
+ bodyHash?: string;
44
+ /** Project scope (single-VM deployments may leave this undefined). */
45
+ projectId?: string;
46
+ /** Times this script was used successfully */
47
+ successCount: number;
48
+ /** Times this script failed */
49
+ failureCount: number;
50
+ /** ISO timestamp of last usage */
51
+ lastUsed: string;
52
+ /** Original user question that created this script */
53
+ createdFrom: string;
54
+ /** ISO timestamp */
55
+ createdAt: string;
56
+ /** ISO timestamp */
57
+ updatedAt: string;
58
+ /**
59
+ * `recipe.id` of the parent this script was forked from.
60
+ * Undefined for root scripts (those written from scratch by MainAgent).
61
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md.
62
+ */
63
+ parentId?: string;
64
+ /** 0 for root scripts; `parent.forkDepth + 1` for forks. Capped at 3. */
65
+ forkDepth?: number;
66
+ /**
67
+ * Brief description of what this fork changed vs its parent
68
+ * (sourced from the matcher's `modificationHint`).
69
+ */
70
+ forkReason?: string;
71
+ /**
72
+ * Validated component specs captured at authoring time. On a tier-high
73
+ * replay these are rebound to fresh queryIds deterministically — no
74
+ * component-generation LLM call, and the rendered columns can't drift from
75
+ * what was validated when the script was authored. Absent on recipes
76
+ * authored before this landed; those fall back to LLM component generation.
77
+ * See backend/docs/SCRIPT-COMPONENT-CONSISTENCY.md.
78
+ */
79
+ components?: ScriptComponentSpec[];
80
+ /**
81
+ * What the user explicitly asked the output to LOOK like, set by a display
82
+ * edit ("show that as a bar chart", "make the bars horizontal").
83
+ *
84
+ * Deliberately SEPARATE from `components`. Those are validated bindings that
85
+ * must be cleared on a data edit — after "break it down by brand" the axis
86
+ * keys are wrong, and after "use the mode" the stored title still says
87
+ * "Average…". A rendering CHOICE, by contrast, is still valid afterwards.
88
+ * Keeping them in one field meant every data edit silently discarded the
89
+ * user's chart type.
90
+ *
91
+ * Fed to the component generator as a hint whenever specs are (re)generated,
92
+ * so the chosen rendering comes back even after the SQL changes.
93
+ */
94
+ displayPreference?: ScriptDisplayPreference;
95
+ /**
96
+ * Lifecycle stage of this recipe on disk.
97
+ * - 'draft': written by MainAgent's write_script during a turn; filtered out
98
+ * of FTS results (status='verified' only) so the matcher never picks it.
99
+ * Filename is suffixed with `turnId` to keep concurrent turns
100
+ * from clobbering each other's drafts.
101
+ * - 'verified': promoted after `execute_script` succeeded; the matcher sees it.
102
+ * Filename drops the turn suffix unless a verified file with
103
+ * the same slug already exists (collision case keeps the suffix).
104
+ *
105
+ * Recipes loaded from disk without this field default to 'verified' so
106
+ * existing scripts keep working unchanged.
107
+ */
108
+ status?: 'draft' | 'verified';
109
+ /**
110
+ * Per-turn unique suffix used for draft filenames (e.g. `1714745623-x9k2`).
111
+ * Set when the draft is saved; carried until the recipe is promoted.
112
+ */
113
+ turnId?: string;
114
+ /**
115
+ * Last execution error captured by `recordDraftError` while the recipe was
116
+ * still a draft. Lets users open the draft .json file and see why it failed
117
+ * without grepping logs. Cleared on promotion to 'verified'.
118
+ */
119
+ lastError?: {
120
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
121
+ message: string;
122
+ at: string;
123
+ attempt: number;
124
+ };
125
+ /** userId who committed the most recent edit (audit trail — recipes are project-scoped). */
126
+ editedBy?: string;
127
+ /** The instruction that produced the current version. */
128
+ editedFrom?: string;
129
+ /**
130
+ * Prior versions, newest last. The body itself is archived on disk as
131
+ * `<fileBase>.v<version>.ts`; this records what changed and who did it.
132
+ */
133
+ history?: ScriptVersionRecord[];
134
+ }
135
+ /**
136
+ * A durable, user-stated rendering choice for a recipe. Survives data edits.
137
+ */
138
+ interface ScriptDisplayPreference {
139
+ /** Component types the user's chosen rendering resolved to, e.g. ["DynamicBarChart"]. */
140
+ componentTypes: string[];
141
+ /** The instruction itself — carries nuance the types can't ("horizontal", "sorted descending"). */
142
+ instruction: string;
143
+ /** ISO timestamp of the display edit that set this. */
144
+ at: string;
145
+ }
146
+ /** One superseded version of a recipe body (see ScriptStore.commitEdit). */
147
+ interface ScriptVersionRecord {
148
+ /** Version number this record superseded (i.e. the OLD version). */
149
+ version: number;
150
+ /** ISO timestamp of the edit that superseded it. */
151
+ at: string;
152
+ /** userId who made the edit, when known. */
153
+ by?: string;
154
+ /** The edit instruction that caused the supersede. */
155
+ instruction?: string;
156
+ /** One-line summary of what changed, for the version picker. */
157
+ changeSummary?: string;
158
+ /** sha256 of the superseded body — pairs with `<fileBase>.v<version>.ts`. */
159
+ bodyHash?: string;
160
+ }
161
+ interface ScriptParameter {
162
+ /** Parameter name (used in script body as params.name) */
163
+ name: string;
164
+ /** Parameter type */
165
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
166
+ /** Whether this parameter is required */
167
+ required: boolean;
168
+ /** Default value if not provided */
169
+ default?: any;
170
+ /** For enum type — maps user-facing values to internal values */
171
+ enumValues?: Record<string, string>;
172
+ /** Human-readable description (used in the matcher LLM prompt) */
173
+ description: string;
174
+ }
175
+ /**
176
+ * A reusable component binding captured when a script is authored. Stored on
177
+ * the recipe so tier-high replays rebuild components deterministically (rebind
178
+ * to fresh queryIds) instead of re-running the component-picker LLM.
179
+ */
180
+ interface ScriptComponentSpec {
181
+ /** Registered component name (e.g. "DynamicBarChart") — matched against the available component library. */
182
+ componentType: string;
183
+ /** `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). */
184
+ sourceRef: string;
185
+ /** Present only when sourceRef === 'federation' — the DuckDB SQL to re-execute on replay. */
186
+ federationSql?: string;
187
+ /** Present only when sourceRef === 'markdown' — the narrative text to render on replay (markdown has no data source, so its content must be persisted). */
188
+ content?: string;
189
+ title?: string;
190
+ description?: string;
191
+ /** Validated axis/value keys + aggregation — all referencing real columns of the bound source. */
192
+ config: Record<string, any>;
193
+ }
194
+ /**
195
+ * Result from executing a script via ScriptRunner.
196
+ */
197
+ interface ScriptResult {
198
+ /** Whether the script executed successfully */
199
+ success: boolean;
200
+ /** Combined data from all queries */
201
+ data: any[];
202
+ /** Program-generated narrative, when the script exports getAnalysis. */
203
+ analysis?: AnalysisOutput;
204
+ /**
205
+ * getAnalysis threw. `success` stays true — the data is valid, so the caller
206
+ * falls back to LLM prose rather than losing the answer.
207
+ */
208
+ analysisError?: string;
209
+ /** Program-generated component specs, when the script exports getComponents. */
210
+ components?: ScriptComponentSpec[];
211
+ /**
212
+ * getComponents threw or returned a non-array. `success` stays true — the data
213
+ * is valid, so the caller falls back to the recipe's stored specs and then to
214
+ * LLM generation rather than losing the dashboard.
215
+ */
216
+ componentsError?: string;
217
+ /** Individual query results tracked during execution */
218
+ executedQueries: ScriptQueryResult[];
219
+ /** Error message if failed */
220
+ error?: string;
221
+ /**
222
+ * Where in the lifecycle the error occurred. Lets MainAgent's fix-loop
223
+ * decide between "rewrite the whole draft" (compile) and "patch the
224
+ * specific line" (runtime).
225
+ */
226
+ errorPhase?: 'compile' | 'runtime' | 'timeout' | 'ipc';
227
+ /** Total execution time in milliseconds */
228
+ executionTimeMs: number;
229
+ }
230
+ /**
231
+ * A single query executed during script runtime.
232
+ * Tracked by ScriptContext for component generation and debugging.
233
+ */
234
+ interface ScriptQueryResult {
235
+ /** Source tool ID */
236
+ sourceId: string;
237
+ /** Human-readable source name */
238
+ sourceName: string;
239
+ /** The SQL that was executed */
240
+ sql: string;
241
+ /** Result data rows */
242
+ data: any[];
243
+ /** Number of rows returned */
244
+ count: number;
245
+ /** Total rows that matched before limit (if available) */
246
+ totalCount?: number;
247
+ /** Query execution time in milliseconds */
248
+ executionTimeMs: number;
249
+ /**
250
+ * True for rows that did NOT come from a real SQL execution — either a
251
+ * ctx.emit() dataset or the synthesized "computed:_final" entry that
252
+ * carries the script's post-JS returned data. The component generator
253
+ * uses this to route the resulting component through the script_dataset
254
+ * sentinel toolId so the frontend resolves it via the queryCache short-circuit.
255
+ */
256
+ virtual?: boolean;
257
+ }
258
+ /**
259
+ * Match tier returned by the LLM script matcher.
260
+ *
261
+ * - 'high': the script answers the question directly; only parameter values
262
+ * may differ. The runtime replays it with extracted params (cheapest path).
263
+ * - 'near': the script answers a STRUCTURALLY similar question but needs
264
+ * body modification (different metric, dimension, table, filter shape).
265
+ * The runtime forks the parent and adapts the body via MainAgent's normal
266
+ * write_script + execute_script loop — no SourceAgent dispatch needed.
267
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md for the full design.
268
+ * - 'edit': the user is INSTRUCTING a change to the script that produced the
269
+ * previous answer (not asking a new question). Only reachable when the turn
270
+ * carries a ScriptBinding — without one the matcher coerces it to 'none', so
271
+ * a prompt regression can't turn this into a loose similarity path. The
272
+ * runtime runs MainAgent in edit mode and commits the result in place.
273
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md.
274
+ * - 'none': no script is relevant; full agent flow runs.
275
+ */
276
+ type MatchTier = 'high' | 'near' | 'edit' | 'none';
277
+ /**
278
+ * Which recipe produced the answer the user is currently looking at.
279
+ *
280
+ * Set whenever a turn's answer came from a script (replay, fresh authoring, or
281
+ * a committed edit) and carried on the UIBlock + saved conversation row. Two
282
+ * consumers:
283
+ * 1. The matcher — the 'edit' tier is ONLY reachable when a binding exists, so
284
+ * "use mode instead of mean" resolves to a concrete script instead of being
285
+ * matched on keywords it shares with no script name.
286
+ * 2. Cache invalidation — after an edit commits, conversations bound to that
287
+ * recipeId must be dropped, or the exact-match cache replays the pre-edit
288
+ * answer and the edit looks like a no-op.
289
+ *
290
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
291
+ */
292
+ interface ScriptBinding {
293
+ recipeId: string;
294
+ /** Params the script ran with — the edit's starting point. */
295
+ params: Record<string, any>;
296
+ /** Recipe name at bind time (matcher catalog + user-facing confirmation). */
297
+ name: string;
298
+ /** Columns the last run returned — grounds the editor without a re-query. */
299
+ columns?: string[];
300
+ /**
301
+ * The question that produced this answer. Required for disambiguation when a
302
+ * thread ran several scripts — without it the candidates are just names and
303
+ * the matcher cannot resolve "use the mode for the WSP one".
304
+ */
305
+ userPrompt?: string;
306
+ /**
307
+ * The polished analysis text this script actually produced last time it ran
308
+ * (the same programAnswer Thread.getConversationContext() shows elsewhere).
309
+ * Carried alongside the script's own shape (columns, params) so the matcher
310
+ * sees "what did this script actually say" right next to "what can I ask it
311
+ * to change", instead of needing a separate conversation-history transcript
312
+ * that would otherwise just repeat the same question this block already
313
+ * states. This is why ScriptMatcher's own prompt no longer receives a raw
314
+ * conversation-history transcript at all — this field is what replaced it.
315
+ */
316
+ answerSummary?: string;
317
+ }
318
+ /**
319
+ * Result from the LLM-based script matcher.
320
+ *
321
+ * For `tier: 'high'`, `extractedParams` carries the values to pass to the
322
+ * existing script. For `tier: 'near'`, `gaps` and `modificationHint` describe
323
+ * what the fork-author needs to change in the parent body.
324
+ */
325
+ interface ScriptMatch {
326
+ /** The matched script recipe */
327
+ recipe: ScriptRecipe;
328
+ /** Match tier — see MatchTier docs */
329
+ tier: MatchTier;
330
+ /** Similarity score (0-1, derived from LLM tier) */
331
+ similarity: number;
332
+ /**
333
+ * Legacy confidence level. Mirrors `tier === 'high'`/`'near'` for now;
334
+ * kept so existing callers compile while we migrate to tier-based logic.
335
+ */
336
+ confidence: 'high' | 'medium';
337
+ /** Parameters extracted from the user question by the LLM (tier='high') */
338
+ extractedParams?: Record<string, any>;
339
+ /**
340
+ * Proper nouns the question named, VERBATIM, with the parameter each fills.
341
+ *
342
+ * The matcher must NOT resolve these itself. Observed live: it substituted the
343
+ * customer name "PREMER ENRGES PHOTOOTAIC" into an id parameter believing that
344
+ * "the runtime will resolve the customer name to its PartyId(s)" — nothing on
345
+ * the replay path does, and `WHERE BillingPartyId IN (PREMER ENRGES
346
+ * PHOTOOTAIC)` reached SQL. Reported here, the runtime resolves them before
347
+ * replay and rejects the match when one cannot be resolved.
348
+ */
349
+ mentions?: Array<{
350
+ text: string;
351
+ param?: string;
352
+ }>;
353
+ /** Business concepts the question relies on (e.g. "outstanding balance"). */
354
+ entityTypes?: string[];
355
+ /** What the user question needs that the parent doesn't cover (tier='near') */
356
+ gaps?: string[];
357
+ /** One-sentence description of the change the fork-author should make (tier='near') */
358
+ modificationHint?: string;
359
+ /**
360
+ * Which HALF of the recipe the edit targets (tier='edit'). A recipe has two
361
+ * independently editable halves:
362
+ * - 'data' — the scriptBody: how the rows are produced (aggregation,
363
+ * filters, joins, grouping). Runs MainAgent in edit mode.
364
+ * - 'display' — the component specs: how those SAME rows are shown (chart
365
+ * type, orientation, columns, labels). Replays the proven SQL
366
+ * and regenerates the specs — never authors a script.
367
+ * Defaults to 'data' when the matcher omits it.
368
+ */
369
+ editTarget?: 'data' | 'display';
370
+ /**
371
+ * Self-contained restatement of the change the user asked for (tier='edit').
372
+ * MUST have pronouns/deixis resolved ("this", "it", "that column") — the edit
373
+ * prompt never sees the conversation history, so an unresolved instruction is
374
+ * unusable downstream.
375
+ */
376
+ editInstruction?: string;
377
+ /** Why the matcher made this choice (for logs and telemetry) */
378
+ reasoning?: string;
379
+ }
380
+
381
+ /**
382
+ * script-ipc.ts — Protocol definitions for parent/child IPC.
383
+ *
384
+ * Transport: newline-delimited JSON over the child's stdin/stdout.
385
+ * stderr is passed through for uncaught exceptions and compile errors.
386
+ *
387
+ * See backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md § IPC Bridge.
388
+ */
389
+
390
+ /**
391
+ * What getAnalysis returns. `analysis` is the narrative and `summary` the short
392
+ * bullets the markdown block binds to — siblings over one dataset, never a
393
+ * summary OF the narrative. See backend/docs/ANALYSIS-AS-PROGRAM-DESIGN.md § 4.3.
394
+ */
395
+ interface AnalysisOutput {
396
+ analysis?: string;
397
+ summary?: string[];
398
+ method?: string;
399
+ }
400
+
401
+ /**
402
+ * StreamBuffer - Buffered streaming utility for smoother text delivery
403
+ * Batches small chunks together and flushes at regular intervals
404
+ */
405
+ type StreamCallback = (chunk: string) => void;
406
+ /**
407
+ * StreamBuffer class for managing buffered streaming output
408
+ * Provides smooth text delivery by batching small chunks
409
+ */
410
+ declare class StreamBuffer {
411
+ private buffer;
412
+ private flushTimer;
413
+ private callback;
414
+ private fullText;
415
+ constructor(callback?: StreamCallback);
416
+ /**
417
+ * Check if the buffer has a callback configured
418
+ */
419
+ hasCallback(): boolean;
420
+ /**
421
+ * Get all text that has been written (including already flushed)
422
+ */
423
+ getFullText(): string;
424
+ /**
425
+ * Write a chunk to the buffer
426
+ * Large chunks or chunks with newlines are flushed immediately
427
+ * Small chunks are batched and flushed after a short interval
428
+ *
429
+ * @param chunk - Text chunk to write
430
+ */
431
+ write(chunk: string): void;
432
+ /**
433
+ * Flush the buffer immediately
434
+ * Call this before tool execution or other operations that need clean output
435
+ */
436
+ flush(): void;
437
+ /**
438
+ * Internal flush implementation
439
+ */
440
+ private flushNow;
441
+ /**
442
+ * Clean up resources
443
+ * Call this when done with the buffer
444
+ */
445
+ dispose(): void;
446
+ }
447
+
448
+ /**
449
+ * ToolExecutorService - Handles execution of SQL queries and external tools
450
+ * Extracted from BaseLLM.generateTextResponse for better separation of concerns
451
+ */
452
+
453
+ /**
454
+ * External tool definition
455
+ */
456
+ interface ExternalTool {
457
+ id: string;
458
+ name: string;
459
+ description?: string;
460
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
461
+ toolType?: 'source' | 'direct';
462
+ /** Full untruncated schema for source agent (all columns visible) */
463
+ fullSchema?: string;
464
+ /** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
465
+ schemaTier?: string;
466
+ /** Schema search function for very_large tier — keyword search over entities */
467
+ schemaSearchFn?: (keywords: string[]) => string;
468
+ /** `signal` fires when the user hits Stop mid-query — passed through to the backend's SourceTool.fn. */
469
+ fn: (input: any, signal?: AbortSignal) => Promise<any>;
470
+ limit?: number;
471
+ outputSchema?: any;
472
+ executionType?: 'immediate' | 'deferred';
473
+ userProvidedData?: any;
474
+ params?: Record<string, any>;
475
+ }
476
+ /**
477
+ * Executed tool tracking info
478
+ */
479
+ interface ExecutedToolInfo {
480
+ id: string;
481
+ name: string;
482
+ params: any;
483
+ result: {
484
+ _totalRecords: number;
485
+ _recordsShown: number;
486
+ _metadata?: any;
487
+ _sampleData: any[];
488
+ /** Bounded summary over the FULL fetched result (complete structure). */
489
+ _summary?: any;
490
+ /** Up to MAIN_AGENT_COMPLETE_ROWS rows — the complete result when small. */
491
+ _mainAgentRows?: any[];
492
+ };
493
+ outputSchema?: any;
494
+ sourceSchema?: string;
495
+ sourceType?: string;
496
+ }
497
+
498
+ /**
499
+ * Multi-Agent Architecture Types
500
+ *
501
+ * Defines interfaces for the hierarchical agent system:
502
+ * - Main Agent: ONE LLM.streamWithTools() call with source agent tools
503
+ * - Source Agents: independent agents that query individual data sources
504
+ *
505
+ * The main agent sees only source summaries. When it calls a source tool,
506
+ * the SourceAgent runs independently (own LLM, own retries) and returns clean data.
507
+ */
508
+
509
+ /**
510
+ * Per-entity detail: name, row count, and column names.
511
+ * Gives the main agent enough context to route to the right source.
512
+ */
513
+ interface EntityDetail {
514
+ /** Entity name (table, sheet, endpoint) */
515
+ name: string;
516
+ /** Approximate row count */
517
+ rowCount?: number;
518
+ /** Column/field names */
519
+ columns: string[];
520
+ /** Entity-level semantic summary (what the table means) — for main-agent routing. */
521
+ summary?: string;
522
+ }
523
+ /**
524
+ * Representation of a data source for the main agent.
525
+ * Contains entity names WITH column names so the LLM can route accurately.
526
+ */
527
+ interface SourceSummary {
528
+ /** Source ID (matches tool ID prefix) */
529
+ id: string;
530
+ /** Human-readable source name */
531
+ name: string;
532
+ /** Source type: postgres, excel, rest_api, etc. */
533
+ type: string;
534
+ /** Brief description of what data this source contains */
535
+ description: string;
536
+ /** Detailed entity info with column names for routing */
537
+ entityDetails: EntityDetail[];
538
+ /** The tool ID associated with this source */
539
+ toolId: string;
540
+ }
541
+ /**
542
+ * What a source agent returns after querying its data source.
543
+ * The main agent uses this to analyze and compose the final response.
544
+ */
545
+ interface SourceAgentResult {
546
+ /** Source ID */
547
+ sourceId: string;
548
+ /** Source name */
549
+ sourceName: string;
550
+ /** Whether the query succeeded */
551
+ success: boolean;
552
+ /** Result data rows */
553
+ data: any[];
554
+ /** Metadata about the query execution */
555
+ metadata: SourceAgentMetadata;
556
+ /** Tool execution info for the last successful query (backward compat) */
557
+ executedTool: ExecutedToolInfo;
558
+ /** All successful tool executions (primary + follow-up queries) */
559
+ allExecutedTools?: ExecutedToolInfo[];
560
+ /** Error message if failed */
561
+ error?: string;
562
+ }
563
+ interface SourceAgentMetadata {
564
+ /** Total rows that matched the query (before limit) */
565
+ totalRowsMatched: number;
566
+ /** Rows actually returned (after limit) */
567
+ rowsReturned: number;
568
+ /** Whether the result was truncated by the row limit */
569
+ isLimited: boolean;
570
+ /** The query/params that were executed */
571
+ queryExecuted?: string;
572
+ /** Execution time in milliseconds */
573
+ executionTimeMs: number;
574
+ }
575
+ /**
576
+ * A pre-built, multi-step UI flow registered with the SDK.
577
+ *
578
+ * When the main agent decides a user's question matches a workflow's whenToUse
579
+ * trigger, it picks the workflow instead of running source agents / generating
580
+ * dashboard components. The LLM extracts the workflow's required props from the
581
+ * prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
582
+ * workflow component directly — no analysis text, no chart generation. The
583
+ * frontend renders the registered workflow component with the LLM-extracted
584
+ * props.
585
+ */
586
+ interface WorkflowDescriptor {
587
+ /** Unique workflow id (used as the LLM tool name) */
588
+ id: string;
589
+ /** Component name on the frontend (matches the registered React component) */
590
+ name: string;
591
+ /** Short human-readable description of what this workflow does */
592
+ description: string;
593
+ /**
594
+ * 1–2 sentence trigger condition. The LLM uses this to decide if the
595
+ * user's prompt matches this workflow. Be specific — e.g.
596
+ * "User wants to *initiate* an inventory transfer (review + submit POs),
597
+ * not just see analysis or charts."
598
+ */
599
+ whenToUse: string;
600
+ /**
601
+ * JSON-schema-style description of the props the workflow needs. Becomes
602
+ * the LLM tool's input_schema, so the model fills these from the prompt.
603
+ * Use the same shape as `params` on direct tools — string descriptors with
604
+ * an optional "(optional)" suffix.
605
+ *
606
+ * Example:
607
+ * ```
608
+ * {
609
+ * selectedStore: 'object — { id, name } of the source branch',
610
+ * minROI: 'number (optional) — only show transfers with ROI ≥ this',
611
+ * }
612
+ * ```
613
+ */
614
+ propsSchema: Record<string, string>;
615
+ /**
616
+ * Optional: static prop defaults merged with LLM-extracted props before
617
+ * the component is returned. Useful for things like the embedded
618
+ * `externalTool` config that the workflow uses to fetch its own data.
619
+ */
620
+ defaultProps?: Record<string, any>;
621
+ }
622
+ /**
623
+ * The workflow selection captured during a routing call.
624
+ * Set on AgentResponse when the LLM picks a workflow tool.
625
+ */
626
+ interface SelectedWorkflow {
627
+ /** Component name (matches WorkflowDescriptor.name) */
628
+ name: string;
629
+ /** Props extracted from the prompt + merged with workflow.defaultProps */
630
+ props: Record<string, any>;
631
+ }
632
+ /**
633
+ * Set when this turn applies a user-directed edit to an existing script instead
634
+ * of authoring a new one. MainAgent keeps the SAME harness (tools, loop,
635
+ * write_script/execute_script verification) and swaps only the system prompt —
636
+ * `agent-main-edit` instead of `agent-main`.
637
+ *
638
+ * The two framings contradict each other on whether to query a source first, so
639
+ * they must never be resident in one rendered prompt.
640
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § D3.
641
+ */
642
+ interface EditContext {
643
+ /** Recipe being edited — the shadow draft records it as parentId. */
644
+ recipeId: string;
645
+ parentName: string;
646
+ parentBody: string;
647
+ /** Self-contained restatement of the change (from the matcher). */
648
+ instruction: string;
649
+ /** Columns the last run returned — grounds the edit without a re-query. */
650
+ lastResultColumns?: string[];
651
+ /** Rendered parameter list of the parent, for the prompt. */
652
+ parentParams?: string;
653
+ }
654
+ /**
655
+ * The complete response from the multi-agent system.
656
+ * Contains everything needed for text display + component generation.
657
+ */
658
+ interface AgentResponse {
659
+ /** Generated text response (analysis of the data) */
660
+ text: string;
661
+ /**
662
+ * Program-generated narrative when the script exported getAnalysis. `text`
663
+ * already carries `analysis.analysis`; this also exposes `summary`, which
664
+ * the markdown block binds to instead of being an LLM summary of the prose.
665
+ */
666
+ analysis?: AnalysisOutput;
667
+ /** All executed tools across all source agents (for component generation) */
668
+ executedTools: ExecutedToolInfo[];
669
+ /** Individual results from each source agent */
670
+ sourceResults: SourceAgentResult[];
671
+ /**
672
+ * Populated when MainAgent wrote AND successfully executed a script during its turn.
673
+ * Caller (agent-user-response.ts) persists it via ScriptStore.save().
674
+ * Absent when MainAgent didn't write one (trivial question / all attempts failed).
675
+ */
676
+ savedScript?: AgentWrittenScript;
677
+ /** Failed execute_script tool_result texts this turn, in order — see RunTrace.script.failedAttempts. */
678
+ failedScriptAttempts?: string[];
679
+ /**
680
+ * Set when the LLM routed the question to a registered workflow component.
681
+ * When present, the upstream caller should skip component generation and
682
+ * return this workflow as the response.
683
+ */
684
+ workflow?: SelectedWorkflow;
685
+ /**
686
+ * Validated component specs the agent authored via `write_components`.
687
+ * When present the caller assembles the dashboard from these instead of
688
+ * running the component-generation LLM. Absent when the agent didn't call
689
+ * the tool — the caller then falls back to `generateScriptComponents`.
690
+ * See backend/docs/COMPONENT-GENERATION-V2.md §2.2.
691
+ */
692
+ componentSpecs?: ScriptComponentSpec[];
693
+ /** Layout title/description from the same `write_components` call. */
694
+ componentLayout?: {
695
+ title: string;
696
+ description?: string;
697
+ };
698
+ }
699
+ /**
700
+ * A script MainAgent authored + verified during its turn. Shape aligns with
701
+ * what ScriptStore.save() needs — minus store-assigned fields (id, timestamps, counts).
702
+ */
703
+ interface AgentWrittenScript {
704
+ /**
705
+ * `ScriptRecipe.id` of the draft that was authored + verified during this turn.
706
+ * The caller passes this to `ScriptStore.promoteToVerified(recipeId, …)` to
707
+ * flip the draft to verified status and (when possible) drop the turn-suffix
708
+ * from its filename.
709
+ */
710
+ recipeId: string;
711
+ name: string;
712
+ intentDescription: string;
713
+ tags: string[];
714
+ parameters: Array<{
715
+ name: string;
716
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
717
+ required: boolean;
718
+ default?: any;
719
+ enumValues?: Record<string, string>;
720
+ description: string;
721
+ }>;
722
+ scriptBody: string;
723
+ /** Source IDs referenced by the script (extracted from ctx.query calls) */
724
+ sourceIds: string[];
725
+ /** Tables referenced in the script's SQL (regex-extracted) */
726
+ tables: string[];
727
+ /** Executed queries from the verified run — fed to component generation */
728
+ executedQueries: Array<{
729
+ sourceId: string;
730
+ sourceName: string;
731
+ sql: string;
732
+ data: any[];
733
+ count: number;
734
+ totalCount?: number;
735
+ executionTimeMs: number;
736
+ /**
737
+ * True for synthetic entries (ctx.emit datasets, the computed:_final
738
+ * post-JS data). The component generator routes virtual sources through
739
+ * the script_dataset sentinel toolId so the frontend resolves them via
740
+ * queryCache instead of attempting to re-execute SQL.
741
+ */
742
+ virtual?: boolean;
743
+ }>;
744
+ /** The tool_result JSON MainAgent's LLM got back from execute_script — see RunTrace.script.executionResult. */
745
+ executionResult?: string;
746
+ }
747
+ /**
748
+ * Debug trace for a single chat_agent turn — which KB/schema nodes were
749
+ * retrieved and considered, and which script (if any) produced the answer.
750
+ * Persisted separately from the answer itself (fusion-5's
751
+ * `conversation_traces` table, written via `saveTrace`), never sent through
752
+ * `analyticsClient` (data-residency — see design doc §5).
753
+ */
754
+ interface RunTrace {
755
+ version: 1;
756
+ kbNodes: {
757
+ /**
758
+ * Always-on nodes included regardless of the question (getGlobalKnowledgeBase).
759
+ * `content` is the node's full text AS IT WAS at retrieval time — captured so a
760
+ * later edit/delete of the KB node doesn't erase what the LLM actually saw.
761
+ */
762
+ global: Array<{
763
+ kbId: string;
764
+ title: string;
765
+ content?: string;
766
+ }>;
767
+ /** Semantically matched for this specific question (getKnowledgeBase). Same `content` reasoning as above. */
768
+ query: Array<{
769
+ kbId: string;
770
+ title: string;
771
+ similarity?: number;
772
+ content?: string;
773
+ }>;
774
+ };
775
+ schemaNodes: {
776
+ /** MainAgent's cross-source prefilter — which sources were even considered. */
777
+ routing: Array<{
778
+ sourceId: string;
779
+ sourceName?: string;
780
+ similarity: number;
781
+ }>;
782
+ /** SourceAgent-scope per-source table resolution (MainAgent.preResolveSchema). */
783
+ preResolve: Array<{
784
+ sourceId: string;
785
+ table?: string;
786
+ description?: string;
787
+ similarity: number;
788
+ }>;
789
+ /**
790
+ * The exact {{SOURCE_SUMMARIES}} text injected into MainAgent's system prompt
791
+ * (agent-prompt-builder.ts's formatSummariesForPrompt output) — every
792
+ * registered source's catalog entry, not retrieval-specific, captured once per
793
+ * turn. This is what the main agent actually saw when deciding which source(s)
794
+ * to call.
795
+ */
796
+ mainAgentCatalog?: string;
797
+ /**
798
+ * One entry per SourceAgent dispatch (a source called twice in one turn gets
799
+ * two entries) — the exact {{FULL_SCHEMA}} text injected into that
800
+ * SourceAgent's own system prompt, however it was sourced, plus any
801
+ * search_schema follow-up lookups it made mid-conversation when the schema
802
+ * shown wasn't enough.
803
+ */
804
+ sourceAgentSchemas: Array<{
805
+ sourceId: string;
806
+ sourceName?: string;
807
+ /**
808
+ * The exact intent text MainAgent wrote for this dispatch (before the
809
+ * resolved-entities block gets appended by code — see
810
+ * buildResolvedEntitiesBlock) — what MainAgent actually asked this
811
+ * source agent to go find.
812
+ */
813
+ intent: string;
814
+ /** How `schemaText` was sourced — see SourceAgent.buildPrompt's fullSchema fallback chain. */
815
+ method: 'preresolved-embedding' | 'tool-full-schema' | 'tool-description' | 'none';
816
+ schemaText: string;
817
+ /** In call order — each search_schema tool call this SourceAgent made, and the exact result text handed back to its own LLM. */
818
+ searchSchemaLookups: Array<{
819
+ keywords: string[];
820
+ result: string;
821
+ }>;
822
+ /** The tool_result text MainAgent's LLM read back for this dispatch (formatResultForMainAgent output). */
823
+ result?: string;
824
+ }>;
825
+ };
826
+ /** The script that produced this answer, if any. Null for a general (no-tool) answer. */
827
+ script: {
828
+ /** True when an existing recipe was replayed unchanged (ScriptMatcher tier='high'). */
829
+ reused: boolean;
830
+ recipeId?: string | null;
831
+ body?: string | null;
832
+ /** Set when reused — the matcher's reasoning for picking this recipe. */
833
+ reasoning?: string | null;
834
+ /** The winning execute_script tool_result text. Only set when reused=false — a replay never re-runs execute_script. Failed attempts aren't kept. */
835
+ executionResult?: string | null;
836
+ /** Failed execute_script tool_result texts this turn, in order (before the winning one, if any). */
837
+ failedAttempts?: string[];
838
+ } | null;
839
+ /**
840
+ * Everything ScriptMatcher.match() built and sent to its one LLM call this
841
+ * turn — Step 2 of the request flow, immediately after Step 1's exact-match
842
+ * check misses. Captured even when short-circuited before any LLM call, or
843
+ * when the call itself errored, so "why didn't this reuse a script" can
844
+ * always be answered from the trace alone, not just the outcome in `script`.
845
+ * See backend/docs/user-prompt-req-flow/SCRIPT-MATCH-IMPROVEMENTS.md.
846
+ */
847
+ scriptMatcher: {
848
+ /**
849
+ * Exactly what went INTO the one LLM call — every placeholder value
850
+ * substituted into `.prompts/script-match/system.md`, plus the routing
851
+ * facts (isExplicitEdit, the two counts) that aren't literal prompt text
852
+ * but explain WHY the catalog/active-script blocks look the way they do.
853
+ */
854
+ sent: {
855
+ /** Whether the raw prompt carried the explicit "edit :" prefix (see parseEditPrefix). */
856
+ isExplicitEdit: boolean;
857
+ /** The prefix-stripped question actually shown to the LLM (the USER_PROMPT placeholder). */
858
+ userPrompt: string;
859
+ /** The Edit Signal text handed to the LLM this turn (CONFIRMED/NOT CONFIRMED wording). */
860
+ editSignal: string;
861
+ /** The rendered "Scripts From Your Past Questions" catalog text (SCRIPT_CATALOG placeholder). */
862
+ scriptCatalog: string;
863
+ /** Distinct scripts actually in scriptCatalog, after health-filtering and the MAX_CATALOG_RECIPES cap. */
864
+ catalogRecipeCount: number;
865
+ /** The rendered "EDITABLE SCRIPTS" block text (ACTIVE_SCRIPT placeholder) — '' when the thread has no active bindings. */
866
+ activeScript: string;
867
+ /** Active bindings offered as edit candidates this turn. */
868
+ activeBindingCount: number;
869
+ };
870
+ /**
871
+ * Everything that came back OUT — the LLM's raw answer plus what the
872
+ * runtime decided to do with it. `tier` here is the FINAL tier after
873
+ * every coercion (near→none, the edit-prefix gate, candidate checks) —
874
+ * it can legitimately differ from `rawResponse.tier`.
875
+ */
876
+ received: {
877
+ /** False when short-circuited before any LLM call (no catalog match AND no active bindings) — `rawResponse`/`tier` below don't apply. */
878
+ calledLLM: boolean;
879
+ /** The raw JSON the LLM returned, when calledLLM is true and the call didn't throw. */
880
+ rawResponse?: any;
881
+ /** Set when calledLLM is true and the call threw, or the response named an unknown script id. */
882
+ error?: string;
883
+ /** Final tier after ALL coercions. Null when short-circuited, errored, or the call/coercions landed on no match. */
884
+ tier: MatchTier | null;
885
+ };
886
+ } | null;
887
+ /**
888
+ * `resolve_entities` tool activity this turn (see main-agent.ts's
889
+ * RESOLVE_ENTITIES_TOOL_DEF / handleResolveEntities) — names/identifiers the
890
+ * user mentioned, resolved to database ids before any SQL was written.
891
+ * Absent/empty entirely for a project with no entity-search collection
892
+ * registered, or a turn that named nothing.
893
+ */
894
+ entityResolution: {
895
+ /**
896
+ * The entity-type catalog text injected into MainAgent's system prompt
897
+ * (loadEntityCatalog's output) — what let the LLM name a concept instead
898
+ * of guessing the project's vocabulary. Captured once per turn.
899
+ */
900
+ catalogText?: string;
901
+ /**
902
+ * One entry per `resolve_entities` tool call this turn (a turn can call it
903
+ * more than once) — the FULL raw response from the entity-search
904
+ * collection, not just the trimmed {mention,entityType,instanceId,
905
+ * displayName} MainAgent keeps for itself to build the dispatch block.
906
+ * `score`/`ambiguous`/`alternatives` only exist here, nowhere else.
907
+ */
908
+ calls: Array<{
909
+ mentions: Array<{
910
+ text: string;
911
+ entityType?: string;
912
+ }>;
913
+ entityTypes: string[];
914
+ resolved: Array<{
915
+ mention: string;
916
+ entityType: string;
917
+ instanceId: string;
918
+ displayName: string;
919
+ attrs?: Record<string, any>;
920
+ score?: number;
921
+ ambiguous?: boolean;
922
+ alternatives?: Array<{
923
+ instanceId: string;
924
+ displayName: string;
925
+ score: number;
926
+ }>;
927
+ }>;
928
+ unresolved: string[];
929
+ entityMap: Record<string, any>;
930
+ unmatchedEntityTypes?: Array<{
931
+ requested: string;
932
+ candidates?: string[];
933
+ }>;
934
+ /** Set when the collection call itself failed (fails open — see handleResolveEntities). */
935
+ error?: string;
936
+ /** Set on an early return (unavailable / nothing named) so the call is still visible in the trace, not indistinguishable from never having run. */
937
+ note?: string;
938
+ }>;
939
+ };
940
+ /**
941
+ * The prior-turn conversation context injected into this turn's prompt as
942
+ * CONVERSATION_HISTORY — exactly what each flow already builds for itself
943
+ * (chat: thread.getConversationContext(); report/dashboard: their own
944
+ * equivalents), captured as-is. Every call site sets this unconditionally
945
+ * (empty string '' when there's no prior context — new thread, or history
946
+ * trimmed to nothing), so an empty turn is visibly "no history" in the
947
+ * saved trace rather than a silently missing key. Optional only because
948
+ * traces saved before this field existed won't have it at all.
949
+ */
950
+ conversationHistory?: string;
951
+ /**
952
+ * The exact {{USER_ACCESS_CONTEXT}} text injected into MainAgent's system
953
+ * prompt — the per-user authorization config (sa-api users.config)
954
+ * rendered by buildUserAccessContext, as-is. Captured once (MainAgent's
955
+ * prompt is what SourceAgent's identical value is derived from — no need
956
+ * to duplicate it per source dispatch). Set unconditionally (empty string
957
+ * '' when there's no config for this user), so "no restrictions" is
958
+ * visible in the saved trace rather than a silently missing key. Optional
959
+ * only because traces saved before this field existed won't have it.
960
+ */
961
+ userAccessContext?: string;
962
+ }
963
+ /**
964
+ * Configuration for the multi-agent system.
965
+ * Controls limits, models, and behavior.
966
+ */
967
+ interface AgentConfig {
968
+ /** Max rows shown to the UI preview / inlined per source (default: 10) */
969
+ maxRowsPerSource: number;
970
+ /**
971
+ * Max rows a source query may FETCH from the DB server-side (default: 2000).
972
+ * Decoupled from what the main agent is shown: the full result is fetched and
973
+ * summarized (bounded), but only a small/complete slice enters LLM context.
974
+ * This lets small lookups (benchmark maps) arrive COMPLETE without letting
975
+ * large results blow up context.
976
+ */
977
+ maxRowsFetched: number;
978
+ /** Model for the main agent (routing + analysis in one LLM call) */
979
+ mainAgentModel: string;
980
+ /** Model for source agent query generation */
981
+ sourceAgentModel: string;
982
+ /** API key for LLM calls */
983
+ apiKey?: string;
984
+ /** Max retry attempts per source agent */
985
+ maxRetries: number;
986
+ /** Max tool calling iterations for the main agent loop */
987
+ maxIterations: number;
988
+ /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
989
+ globalKnowledgeBase?: string;
990
+ /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
991
+ knowledgeBaseContext?: string;
992
+ /** Per-user authorization config (sa-api users.config), rendered to text — see buildUserAccessContext */
993
+ userAccessContext?: string;
994
+ /** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
995
+ collections?: any;
996
+ /** Optional project ID for scoping embedding searches */
997
+ projectId?: string;
998
+ /**
999
+ * Optional debug-trace accumulator for this turn (Phase 1, chat_agent only).
1000
+ * When present, MainAgent-scope retrieval call sites (e.g. preResolveSchema)
1001
+ * push their structured results into it. Absent for callers that don't care
1002
+ * about trace capture (e.g. headless flows) — every push site must treat
1003
+ * this as optional and never let a capture failure affect the real answer.
1004
+ */
1005
+ trace?: RunTrace;
1006
+ }
1007
+ /**
1008
+ * Default agent configuration
1009
+ */
1010
+ declare const DEFAULT_AGENT_CONFIG: AgentConfig;
1011
+
4
1012
  /**
5
1013
  * Unified UIBlock structure for database storage
6
- * Used in both bookmarks and user-conversations tables
1014
+ * Used in both bookmarks and user-conversations tables.
1015
+ *
1016
+ * `analysis` always holds whatever real narration exists — the full answer on
1017
+ * success, or whatever was actually streamed before a failure (may be empty).
1018
+ * `error` is a dedicated field, null on success — it can be a plain string OR
1019
+ * a structured object/array (e.g. the agent's raw `errors` list), whatever
1020
+ * shape the failure naturally has; it's never coerced into `analysis`.
7
1021
  */
8
1022
  interface DBUIBlock {
9
1023
  id: string;
10
1024
  component: Record<string, any> | null;
11
1025
  analysis: string | null;
12
1026
  user_prompt: string;
1027
+ error?: unknown | null;
1028
+ /**
1029
+ * The script recipe that produced this answer, when one did. Read back via
1030
+ * `conversation-history.exactMatch` so an edit follow-up still has a target
1031
+ * after a reload (the in-memory thread is gone by then), and indexed so
1032
+ * committing an edit can purge every cached answer bound to the recipe.
1033
+ */
1034
+ scriptBinding?: {
1035
+ recipeId: string;
1036
+ params?: Record<string, any>;
1037
+ name?: string;
1038
+ columns?: string[];
1039
+ };
13
1040
  }
14
1041
 
15
1042
  /**
@@ -59,7 +1086,18 @@ declare class Logger {
59
1086
  * Log debug message (only shown for verbose level)
60
1087
  */
61
1088
  debug(...args: any[]): void;
1089
+ /**
1090
+ * Write to log file
1091
+ */
62
1092
  file(...args: any[]): void;
1093
+ /**
1094
+ * Clear the log file (call at start of new user request)
1095
+ */
1096
+ clearFile(): void;
1097
+ /**
1098
+ * Log LLM method prompts with clear labeling
1099
+ */
1100
+ logLLMPrompt(methodName: string, promptType: 'system' | 'user', content: string | object | any[]): void;
63
1101
  }
64
1102
  declare const logger: Logger;
65
1103
 
@@ -149,6 +1187,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
149
1187
  dependencies?: string[] | undefined;
150
1188
  } | undefined;
151
1189
  props?: Record<string, any> | undefined;
1190
+ data?: Record<string, any> | undefined;
152
1191
  render?: any;
153
1192
  states?: Record<string, any> | undefined;
154
1193
  methods?: Record<string, {
@@ -159,7 +1198,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
159
1198
  fn: string;
160
1199
  deps?: string[] | undefined;
161
1200
  }[] | undefined;
162
- data?: Record<string, any> | undefined;
163
1201
  pages?: {
164
1202
  id: string;
165
1203
  name: string;
@@ -181,6 +1219,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
181
1219
  dependencies?: string[] | undefined;
182
1220
  } | undefined;
183
1221
  props?: Record<string, any> | undefined;
1222
+ data?: Record<string, any> | undefined;
184
1223
  render?: any;
185
1224
  states?: Record<string, any> | undefined;
186
1225
  methods?: Record<string, {
@@ -191,7 +1230,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
191
1230
  fn: string;
192
1231
  deps?: string[] | undefined;
193
1232
  }[] | undefined;
194
- data?: Record<string, any> | undefined;
195
1233
  pages?: {
196
1234
  id: string;
197
1235
  name: string;
@@ -217,6 +1255,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
217
1255
  dependencies?: string[] | undefined;
218
1256
  } | undefined;
219
1257
  props?: Record<string, any> | undefined;
1258
+ data?: Record<string, any> | undefined;
220
1259
  render?: any;
221
1260
  states?: Record<string, any> | undefined;
222
1261
  methods?: Record<string, {
@@ -227,7 +1266,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
227
1266
  fn: string;
228
1267
  deps?: string[] | undefined;
229
1268
  }[] | undefined;
230
- data?: Record<string, any> | undefined;
231
1269
  pages?: {
232
1270
  id: string;
233
1271
  name: string;
@@ -253,6 +1291,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
253
1291
  dependencies?: string[] | undefined;
254
1292
  } | undefined;
255
1293
  props?: Record<string, any> | undefined;
1294
+ data?: Record<string, any> | undefined;
256
1295
  render?: any;
257
1296
  states?: Record<string, any> | undefined;
258
1297
  methods?: Record<string, {
@@ -263,7 +1302,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
263
1302
  fn: string;
264
1303
  deps?: string[] | undefined;
265
1304
  }[] | undefined;
266
- data?: Record<string, any> | undefined;
267
1305
  pages?: {
268
1306
  id: string;
269
1307
  name: string;
@@ -344,6 +1382,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
344
1382
  dependencies?: string[] | undefined;
345
1383
  } | undefined;
346
1384
  props?: Record<string, any> | undefined;
1385
+ data?: Record<string, any> | undefined;
347
1386
  render?: any;
348
1387
  states?: Record<string, any> | undefined;
349
1388
  methods?: Record<string, {
@@ -354,7 +1393,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
354
1393
  fn: string;
355
1394
  deps?: string[] | undefined;
356
1395
  }[] | undefined;
357
- data?: Record<string, any> | undefined;
358
1396
  }, {
359
1397
  id: string;
360
1398
  name?: string | undefined;
@@ -368,6 +1406,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
368
1406
  dependencies?: string[] | undefined;
369
1407
  } | undefined;
370
1408
  props?: Record<string, any> | undefined;
1409
+ data?: Record<string, any> | undefined;
371
1410
  render?: any;
372
1411
  states?: Record<string, any> | undefined;
373
1412
  methods?: Record<string, {
@@ -378,7 +1417,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
378
1417
  fn: string;
379
1418
  deps?: string[] | undefined;
380
1419
  }[] | undefined;
381
- data?: Record<string, any> | undefined;
382
1420
  }>;
383
1421
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
384
1422
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -396,6 +1434,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
396
1434
  dependencies?: string[] | undefined;
397
1435
  } | undefined;
398
1436
  props?: Record<string, any> | undefined;
1437
+ data?: Record<string, any> | undefined;
399
1438
  render?: any;
400
1439
  states?: Record<string, any> | undefined;
401
1440
  methods?: Record<string, {
@@ -406,7 +1445,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
406
1445
  fn: string;
407
1446
  deps?: string[] | undefined;
408
1447
  }[] | undefined;
409
- data?: Record<string, any> | undefined;
410
1448
  };
411
1449
  data?: Record<string, any> | undefined;
412
1450
  context?: Record<string, any> | undefined;
@@ -424,6 +1462,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
424
1462
  dependencies?: string[] | undefined;
425
1463
  } | undefined;
426
1464
  props?: Record<string, any> | undefined;
1465
+ data?: Record<string, any> | undefined;
427
1466
  render?: any;
428
1467
  states?: Record<string, any> | undefined;
429
1468
  methods?: Record<string, {
@@ -434,7 +1473,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
434
1473
  fn: string;
435
1474
  deps?: string[] | undefined;
436
1475
  }[] | undefined;
437
- data?: Record<string, any> | undefined;
438
1476
  };
439
1477
  data?: Record<string, any> | undefined;
440
1478
  context?: Record<string, any> | undefined;
@@ -623,19 +1661,19 @@ declare const ComponentSchema: z.ZodObject<{
623
1661
  type: z.ZodString;
624
1662
  description: z.ZodString;
625
1663
  props: z.ZodObject<{
626
- query: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>;
1664
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
627
1665
  title: z.ZodOptional<z.ZodString>;
628
1666
  description: z.ZodOptional<z.ZodString>;
629
1667
  config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
630
1668
  actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
631
1669
  }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
632
- query: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>;
1670
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
633
1671
  title: z.ZodOptional<z.ZodString>;
634
1672
  description: z.ZodOptional<z.ZodString>;
635
1673
  config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
636
1674
  actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
637
1675
  }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
638
- query: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>;
1676
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
639
1677
  title: z.ZodOptional<z.ZodString>;
640
1678
  description: z.ZodOptional<z.ZodString>;
641
1679
  config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
@@ -650,7 +1688,7 @@ declare const ComponentSchema: z.ZodObject<{
650
1688
  description: string;
651
1689
  props: {
652
1690
  description?: string | undefined;
653
- query?: string | {} | undefined;
1691
+ query?: string | {} | null | undefined;
654
1692
  title?: string | undefined;
655
1693
  config?: Record<string, unknown> | undefined;
656
1694
  actions?: any[] | undefined;
@@ -668,7 +1706,7 @@ declare const ComponentSchema: z.ZodObject<{
668
1706
  description: string;
669
1707
  props: {
670
1708
  description?: string | undefined;
671
- query?: string | {} | undefined;
1709
+ query?: string | {} | null | undefined;
672
1710
  title?: string | undefined;
673
1711
  config?: Record<string, unknown> | undefined;
674
1712
  actions?: any[] | undefined;
@@ -730,6 +1768,10 @@ declare const ToolSchema: z.ZodObject<{
730
1768
  id: z.ZodString;
731
1769
  name: z.ZodString;
732
1770
  description: z.ZodString;
1771
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
1772
+ toolType: z.ZodOptional<z.ZodEnum<["source", "direct"]>>;
1773
+ /** Full untruncated schema for source agent (all columns visible) */
1774
+ fullSchema: z.ZodOptional<z.ZodString>;
733
1775
  params: z.ZodRecord<z.ZodString, z.ZodString>;
734
1776
  fn: z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodAny>;
735
1777
  outputSchema: z.ZodOptional<z.ZodObject<{
@@ -762,12 +1804,22 @@ declare const ToolSchema: z.ZodObject<{
762
1804
  description: string;
763
1805
  }[];
764
1806
  }>>;
1807
+ /** Cache policy. `false` = never cache (live data, write ops). Mirrors HTTP `Cache-Control: no-store`. */
1808
+ cache: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<false>, z.ZodObject<{
1809
+ ttlMs: z.ZodOptional<z.ZodNumber>;
1810
+ }, "strip", z.ZodTypeAny, {
1811
+ ttlMs?: number | undefined;
1812
+ }, {
1813
+ ttlMs?: number | undefined;
1814
+ }>]>>;
765
1815
  }, "strip", z.ZodTypeAny, {
766
1816
  id: string;
767
1817
  params: Record<string, string>;
768
1818
  name: string;
769
1819
  description: string;
770
1820
  fn: (args_0: any, ...args: unknown[]) => any;
1821
+ toolType?: "source" | "direct" | undefined;
1822
+ fullSchema?: string | undefined;
771
1823
  outputSchema?: {
772
1824
  description: string;
773
1825
  fields: {
@@ -776,12 +1828,17 @@ declare const ToolSchema: z.ZodObject<{
776
1828
  description: string;
777
1829
  }[];
778
1830
  } | undefined;
1831
+ cache?: false | {
1832
+ ttlMs?: number | undefined;
1833
+ } | undefined;
779
1834
  }, {
780
1835
  id: string;
781
1836
  params: Record<string, string>;
782
1837
  name: string;
783
1838
  description: string;
784
1839
  fn: (args_0: any, ...args: unknown[]) => any;
1840
+ toolType?: "source" | "direct" | undefined;
1841
+ fullSchema?: string | undefined;
785
1842
  outputSchema?: {
786
1843
  description: string;
787
1844
  fields: {
@@ -790,6 +1847,9 @@ declare const ToolSchema: z.ZodObject<{
790
1847
  description: string;
791
1848
  }[];
792
1849
  } | undefined;
1850
+ cache?: false | {
1851
+ ttlMs?: number | undefined;
1852
+ } | undefined;
793
1853
  }>;
794
1854
  type Tool$1 = z.infer<typeof ToolSchema>;
795
1855
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
@@ -828,6 +1888,10 @@ interface SuperatomSDKConfig {
828
1888
  bundleDir?: string;
829
1889
  promptsDir?: string;
830
1890
  databaseType?: DatabaseType;
1891
+ /** BCP-47 locale for `fmt` in generated analyses, e.g. 'en-IN', 'en-US'. Defaults to 'en-IN'. */
1892
+ locale?: string;
1893
+ /** ISO-4217 currency for `fmt`, e.g. 'INR', 'USD'. Defaults to 'INR'. */
1894
+ currency?: string;
831
1895
  ANTHROPIC_API_KEY?: string;
832
1896
  GROQ_API_KEY?: string;
833
1897
  GEMINI_API_KEY?: string;
@@ -841,27 +1905,61 @@ interface SuperatomSDKConfig {
841
1905
  * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
842
1906
  */
843
1907
  modelStrategy?: ModelStrategy;
1908
+ /**
1909
+ * Model for the main agent (routing + analysis).
1910
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
1911
+ * If not set, uses the provider's default model.
1912
+ */
1913
+ mainAgentModel?: string;
1914
+ /**
1915
+ * Model for source agents (per-source query generation).
1916
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
1917
+ * If not set, uses the provider's default model.
1918
+ */
1919
+ sourceAgentModel?: string;
844
1920
  /**
845
1921
  * Separate model configuration for DASH_COMP flow (dashboard component picking)
846
1922
  * If not provided, falls back to provider-based model selection
847
1923
  */
848
1924
  dashCompModels?: DashCompModelConfig;
1925
+ /**
1926
+ * Similarity threshold for conversation search (semantic matching)
1927
+ * Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
1928
+ * Higher values require closer matches, lower values allow more distant matches
1929
+ * Default: 0.8
1930
+ */
1931
+ conversationSimilarityThreshold?: number;
1932
+ /**
1933
+ * Query cache TTL (Time To Live) in minutes
1934
+ * Cached query results expire after this duration
1935
+ * Default: 5 minutes
1936
+ */
1937
+ queryCacheTTL?: number;
1938
+ /**
1939
+ * Dashboard conversation history TTL (Time To Live) in minutes
1940
+ * Per-dashboard conversation histories expire after this duration
1941
+ * Default: 30 minutes
1942
+ */
1943
+ dashboardHistoryTTL?: number;
849
1944
  }
850
1945
 
851
1946
  declare const KbNodesQueryFiltersSchema: z.ZodObject<{
852
1947
  query: z.ZodOptional<z.ZodString>;
853
1948
  category: z.ZodOptional<z.ZodString>;
854
1949
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
855
- createdBy: z.ZodOptional<z.ZodNumber>;
1950
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
1951
+ createdBy: z.ZodOptional<z.ZodString>;
856
1952
  }, "strip", z.ZodTypeAny, {
1953
+ type?: "query" | "user" | "global" | undefined;
857
1954
  query?: string | undefined;
858
1955
  category?: string | undefined;
859
- createdBy?: number | undefined;
1956
+ createdBy?: string | undefined;
860
1957
  tags?: string[] | undefined;
861
1958
  }, {
1959
+ type?: "query" | "user" | "global" | undefined;
862
1960
  query?: string | undefined;
863
1961
  category?: string | undefined;
864
- createdBy?: number | undefined;
1962
+ createdBy?: string | undefined;
865
1963
  tags?: string[] | undefined;
866
1964
  }>;
867
1965
  type KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
@@ -873,106 +1971,118 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
873
1971
  content: z.ZodOptional<z.ZodString>;
874
1972
  category: z.ZodOptional<z.ZodString>;
875
1973
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
876
- createdBy: z.ZodOptional<z.ZodNumber>;
877
- updatedBy: z.ZodOptional<z.ZodNumber>;
878
- userId: z.ZodOptional<z.ZodNumber>;
1974
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
1975
+ createdBy: z.ZodOptional<z.ZodString>;
1976
+ updatedBy: z.ZodOptional<z.ZodString>;
1977
+ userId: z.ZodOptional<z.ZodString>;
879
1978
  query: z.ZodOptional<z.ZodString>;
880
1979
  filters: z.ZodOptional<z.ZodObject<{
881
1980
  query: z.ZodOptional<z.ZodString>;
882
1981
  category: z.ZodOptional<z.ZodString>;
883
1982
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
884
- createdBy: z.ZodOptional<z.ZodNumber>;
1983
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
1984
+ createdBy: z.ZodOptional<z.ZodString>;
885
1985
  }, "strip", z.ZodTypeAny, {
1986
+ type?: "query" | "user" | "global" | undefined;
886
1987
  query?: string | undefined;
887
1988
  category?: string | undefined;
888
- createdBy?: number | undefined;
1989
+ createdBy?: string | undefined;
889
1990
  tags?: string[] | undefined;
890
1991
  }, {
1992
+ type?: "query" | "user" | "global" | undefined;
891
1993
  query?: string | undefined;
892
1994
  category?: string | undefined;
893
- createdBy?: number | undefined;
1995
+ createdBy?: string | undefined;
894
1996
  tags?: string[] | undefined;
895
1997
  }>>;
896
1998
  limit: z.ZodOptional<z.ZodNumber>;
897
1999
  offset: z.ZodOptional<z.ZodNumber>;
898
2000
  }, "strip", z.ZodTypeAny, {
899
2001
  id?: number | undefined;
2002
+ type?: "query" | "user" | "global" | undefined;
900
2003
  query?: string | undefined;
901
2004
  title?: string | undefined;
902
2005
  category?: string | undefined;
903
- userId?: number | undefined;
2006
+ userId?: string | undefined;
904
2007
  limit?: number | undefined;
905
2008
  filters?: {
2009
+ type?: "query" | "user" | "global" | undefined;
906
2010
  query?: string | undefined;
907
2011
  category?: string | undefined;
908
- createdBy?: number | undefined;
2012
+ createdBy?: string | undefined;
909
2013
  tags?: string[] | undefined;
910
2014
  } | undefined;
911
- createdBy?: number | undefined;
912
- updatedBy?: number | undefined;
2015
+ createdBy?: string | undefined;
2016
+ updatedBy?: string | undefined;
2017
+ offset?: number | undefined;
913
2018
  tags?: string[] | undefined;
914
2019
  content?: string | undefined;
915
- offset?: number | undefined;
916
2020
  }, {
917
2021
  id?: number | undefined;
2022
+ type?: "query" | "user" | "global" | undefined;
918
2023
  query?: string | undefined;
919
2024
  title?: string | undefined;
920
2025
  category?: string | undefined;
921
- userId?: number | undefined;
2026
+ userId?: string | undefined;
922
2027
  limit?: number | undefined;
923
2028
  filters?: {
2029
+ type?: "query" | "user" | "global" | undefined;
924
2030
  query?: string | undefined;
925
2031
  category?: string | undefined;
926
- createdBy?: number | undefined;
2032
+ createdBy?: string | undefined;
927
2033
  tags?: string[] | undefined;
928
2034
  } | undefined;
929
- createdBy?: number | undefined;
930
- updatedBy?: number | undefined;
2035
+ createdBy?: string | undefined;
2036
+ updatedBy?: string | undefined;
2037
+ offset?: number | undefined;
931
2038
  tags?: string[] | undefined;
932
2039
  content?: string | undefined;
933
- offset?: number | undefined;
934
2040
  }>>;
935
2041
  }, "strip", z.ZodTypeAny, {
936
- operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
2042
+ operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
937
2043
  data?: {
938
2044
  id?: number | undefined;
2045
+ type?: "query" | "user" | "global" | undefined;
939
2046
  query?: string | undefined;
940
2047
  title?: string | undefined;
941
2048
  category?: string | undefined;
942
- userId?: number | undefined;
2049
+ userId?: string | undefined;
943
2050
  limit?: number | undefined;
944
2051
  filters?: {
2052
+ type?: "query" | "user" | "global" | undefined;
945
2053
  query?: string | undefined;
946
2054
  category?: string | undefined;
947
- createdBy?: number | undefined;
2055
+ createdBy?: string | undefined;
948
2056
  tags?: string[] | undefined;
949
2057
  } | undefined;
950
- createdBy?: number | undefined;
951
- updatedBy?: number | undefined;
2058
+ createdBy?: string | undefined;
2059
+ updatedBy?: string | undefined;
2060
+ offset?: number | undefined;
952
2061
  tags?: string[] | undefined;
953
2062
  content?: string | undefined;
954
- offset?: number | undefined;
955
2063
  } | undefined;
956
2064
  }, {
957
- operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
2065
+ operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
958
2066
  data?: {
959
2067
  id?: number | undefined;
2068
+ type?: "query" | "user" | "global" | undefined;
960
2069
  query?: string | undefined;
961
2070
  title?: string | undefined;
962
2071
  category?: string | undefined;
963
- userId?: number | undefined;
2072
+ userId?: string | undefined;
964
2073
  limit?: number | undefined;
965
2074
  filters?: {
2075
+ type?: "query" | "user" | "global" | undefined;
966
2076
  query?: string | undefined;
967
2077
  category?: string | undefined;
968
- createdBy?: number | undefined;
2078
+ createdBy?: string | undefined;
969
2079
  tags?: string[] | undefined;
970
2080
  } | undefined;
971
- createdBy?: number | undefined;
972
- updatedBy?: number | undefined;
2081
+ createdBy?: string | undefined;
2082
+ updatedBy?: string | undefined;
2083
+ offset?: number | undefined;
973
2084
  tags?: string[] | undefined;
974
2085
  content?: string | undefined;
975
- offset?: number | undefined;
976
2086
  } | undefined;
977
2087
  }>;
978
2088
  type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
@@ -1241,24 +2351,705 @@ declare class ReportManager {
1241
2351
  getReportCount(): number;
1242
2352
  }
1243
2353
 
1244
- type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
1245
- interface LLMMessages {
1246
- sys: SystemPrompt;
1247
- user: string;
1248
- prefill?: string;
2354
+ /**
2355
+ * ScriptRecipeStore — injected metadata backend for the script flow.
2356
+ *
2357
+ * The SDK is standalone (no DB dependency). The backend implements this
2358
+ * interface over Postgres (full-text search + atomic counters) and injects it
2359
+ * via `collections['script-recipes']`, exactly like `collections['source-embeddings']`.
2360
+ * `ScriptStore` consumes it for all METADATA operations while keeping the
2361
+ * executable body on disk as scripts-store/<fileBase>.ts.
2362
+ *
2363
+ * All metadata rows are plain JSON (no scriptBody — that lives on disk).
2364
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md (#1, #3, #7).
2365
+ */
2366
+
2367
+ /** One recipe's metadata as stored in Postgres (mirrors the script_recipes table). */
2368
+ interface ScriptRecipeMetaRow {
2369
+ id: string;
2370
+ projectId?: string | null;
2371
+ version: number;
2372
+ name: string;
2373
+ intentDescription: string;
2374
+ tags: string[] | null;
2375
+ createdFrom: string | null;
2376
+ sourceIds: string[] | null;
2377
+ tables: string[] | null;
2378
+ parameters: ScriptParameter[] | null;
2379
+ components?: ScriptComponentSpec[] | null;
2380
+ displayPreference?: ScriptDisplayPreference | null;
2381
+ fileBase: string;
2382
+ bodyHash?: string | null;
2383
+ successCount: number;
2384
+ failureCount: number;
2385
+ lastUsed: string | null;
2386
+ parentId?: string | null;
2387
+ forkDepth?: number | null;
2388
+ forkReason?: string | null;
2389
+ status: 'draft' | 'verified' | string;
2390
+ turnId?: string | null;
2391
+ editedBy?: string | null;
2392
+ editedFrom?: string | null;
2393
+ history?: ScriptVersionRecord[] | null;
2394
+ lastError?: {
2395
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2396
+ message: string;
2397
+ at: string;
2398
+ attempt: number;
2399
+ } | null;
2400
+ createdAt?: string | null;
2401
+ updatedAt?: string | null;
1249
2402
  }
1250
- interface LLMOptions {
1251
- model?: string;
1252
- maxTokens?: number;
1253
- temperature?: number;
1254
- topP?: number;
1255
- apiKey?: string;
1256
- partial?: (chunk: string) => void;
2403
+ interface ScriptRecipeStore {
2404
+ /** FTS shortlist of healthy verified recipes for the matcher (metadata only). */
2405
+ search(params: {
2406
+ prompt: string;
2407
+ projectId?: string;
2408
+ limit?: number;
2409
+ }): Promise<ScriptRecipeMetaRow[]>;
2410
+ /** Fetch one recipe by id (any status). */
2411
+ getById(id: string): Promise<ScriptRecipeMetaRow | null>;
2412
+ /** Count healthy verified recipes (drives the "any scripts?" gate). */
2413
+ count(params?: {
2414
+ projectId?: string;
2415
+ }): Promise<number>;
2416
+ /** Insert or update a recipe row (keyed by id). */
2417
+ upsert(row: ScriptRecipeMetaRow): Promise<void>;
2418
+ /** Atomically bump counters / last-used. */
2419
+ updateStats(id: string, patch: {
2420
+ successDelta?: number;
2421
+ failureDelta?: number;
2422
+ lastUsed?: string;
2423
+ }): Promise<void>;
2424
+ /** Flip a draft to verified, applying provenance + optional fork lineage. */
2425
+ promote(id: string, patch: {
2426
+ sourceIds: string[];
2427
+ tables: string[];
2428
+ fileBase?: string;
2429
+ parentId?: string;
2430
+ forkDepth?: number;
2431
+ forkReason?: string;
2432
+ components?: ScriptComponentSpec[];
2433
+ }): Promise<ScriptRecipeMetaRow | null>;
2434
+ /**
2435
+ * Commit a verified edit onto an EXISTING recipe: bump `version`, replace the
2436
+ * body-bearing metadata, append a history record, reset health counters, and
2437
+ * clear the component specs (they were validated against the old shape).
2438
+ * Returns the updated row, or null when the target is gone.
2439
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5.
2440
+ */
2441
+ commitEdit?(id: string, patch: {
2442
+ name?: string;
2443
+ intentDescription?: string;
2444
+ tags?: string[];
2445
+ parameters?: ScriptParameter[];
2446
+ bodyHash: string;
2447
+ /** New on-disk stem when the edit renamed the script; omitted otherwise. */
2448
+ fileBase?: string;
2449
+ sourceIds?: string[];
2450
+ tables?: string[];
2451
+ editedBy?: string;
2452
+ editedFrom?: string;
2453
+ historyEntry: {
2454
+ version: number;
2455
+ at: string;
2456
+ by?: string;
2457
+ instruction?: string;
2458
+ changeSummary?: string;
2459
+ bodyHash?: string;
2460
+ };
2461
+ }): Promise<ScriptRecipeMetaRow | null>;
2462
+ /** Stamp a draft's last execution error. */
2463
+ recordDraftError(id: string, err: {
2464
+ phase: string;
2465
+ message: string;
2466
+ attempt: number;
2467
+ at: string;
2468
+ }): Promise<void>;
2469
+ /** Delete a recipe row (body file removed separately). */
2470
+ remove(id: string): Promise<void>;
2471
+ /** True if `fileBase` is taken by a different recipe in this project. */
2472
+ fileBaseTaken(fileBase: string, excludeId: string, projectId?: string): Promise<boolean>;
1257
2473
  }
1258
- interface Tool {
1259
- name: string;
1260
- description: string;
1261
- input_schema: {
2474
+ /** Pull the injected store off the collections bag (or null if not wired). */
2475
+ declare function resolveScriptRecipeStore(collections: any): ScriptRecipeStore | null;
2476
+
2477
+ /**
2478
+ * ScriptStore — Postgres metadata + on-disk body for script recipes.
2479
+ *
2480
+ * Split of responsibilities:
2481
+ * - METADATA → injected `ScriptRecipeStore` (Postgres FTS + atomic counters),
2482
+ * resolved from `collections['script-recipes']`.
2483
+ * - BODY → scripts-store/<fileBase>.ts, editable in your IDE. Written
2484
+ * atomically (temp + rename); `bodyHash` (sha256) detects edits.
2485
+ *
2486
+ * The old "read every file every turn + send the whole catalog to the LLM"
2487
+ * matcher is gone — matching is `store.search(prompt)` (FTS shortlist). The
2488
+ * draft/verified filename dance is gone too: `status` is a DB column and the
2489
+ * file keeps a stable `<fileBase>.ts` name across promotion.
2490
+ *
2491
+ * When no metadata store is injected, the store degrades to a safe no-op
2492
+ * (count 0 → script flow disabled) instead of crashing.
2493
+ *
2494
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md.
2495
+ */
2496
+
2497
+ interface SaveDraftInput {
2498
+ /** Reuse an existing draft (retry); omit to mint a new one. */
2499
+ recipeId?: string;
2500
+ /** Per-turn unique suffix, stable across retries within the turn. */
2501
+ turnId: string;
2502
+ name: string;
2503
+ intentDescription: string;
2504
+ tags: string[];
2505
+ parameters: ScriptParameter[];
2506
+ scriptBody: string;
2507
+ createdFrom: string;
2508
+ /**
2509
+ * Set when this draft is a SHADOW of an existing recipe being edited. The
2510
+ * draft is verified independently and merged back onto the parent via
2511
+ * `commitEdit`, so the working script is never clobbered by an edit that
2512
+ * turns out not to run. See backend/docs/SCRIPT-EDIT-DESIGN.md § D5.
2513
+ */
2514
+ parentId?: string;
2515
+ }
2516
+ interface PromoteToVerifiedInput {
2517
+ sourceIds: string[];
2518
+ tables: string[];
2519
+ parentId?: string;
2520
+ forkDepth?: number;
2521
+ forkReason?: string;
2522
+ components?: ScriptComponentSpec[];
2523
+ }
2524
+ interface ScriptStoreOptions {
2525
+ /** Explicit metadata store, or resolved from `collections['script-recipes']`. */
2526
+ store?: ScriptRecipeStore | null;
2527
+ collections?: any;
2528
+ /** Body directory (defaults to <cwd>/scripts-store). */
2529
+ baseDir?: string;
2530
+ /** Project scope stamped on every row. */
2531
+ projectId?: string;
2532
+ }
2533
+ declare function normalizeScriptBody(scriptBody: string): string;
2534
+ declare class ScriptStore {
2535
+ private store;
2536
+ private storeDir;
2537
+ private projectId?;
2538
+ constructor(opts?: ScriptStoreOptions);
2539
+ /** Whether a metadata store is wired (matcher / authoring are gated on this). */
2540
+ hasStore(): boolean;
2541
+ /** Number of healthy verified recipes (gates the script-matching path). */
2542
+ count(): Promise<number>;
2543
+ /**
2544
+ * FTS shortlist for the matcher (metadata only — bodies are loaded lazily by
2545
+ * `get()` once the LLM picks one). Returns verified, healthy recipes ranked
2546
+ * by relevance.
2547
+ */
2548
+ search(prompt: string, limit?: number): Promise<ScriptRecipe[]>;
2549
+ /** Fetch one recipe by id with its body loaded from disk. */
2550
+ get(id: string): Promise<ScriptRecipe | null>;
2551
+ /** Create or update a recipe (metadata upsert + body write when changed). */
2552
+ save(recipe: ScriptRecipe): Promise<void>;
2553
+ /**
2554
+ * Persist (or update) a draft. Within a turn, retries that pass the same
2555
+ * `recipeId` overwrite the same row + file; a fresh `recipeId` mints a new
2556
+ * draft. The body is visible at scripts-store/<fileBase>.ts immediately.
2557
+ */
2558
+ saveDraft(input: SaveDraftInput): Promise<ScriptRecipe>;
2559
+ /** Stamp a draft's last execution error (metadata only). */
2560
+ recordDraftError(recipeId: string, err: {
2561
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2562
+ message: string;
2563
+ attempt: number;
2564
+ }): Promise<void>;
2565
+ /**
2566
+ * Promote a successfully-executed draft into a verified script.
2567
+ * The on-disk body already exists at <fileBase>.ts (written at write_script
2568
+ * time) and keeps its name — only the DB row flips status + provenance.
2569
+ */
2570
+ promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): Promise<ScriptRecipe | null>;
2571
+ /**
2572
+ * Commit a user-directed edit: merge a VERIFIED shadow draft back onto the
2573
+ * recipe it was editing, as version N+1 under the SAME recipe id.
2574
+ *
2575
+ * Keeping the id stable is the point of the whole feature — every cached
2576
+ * conversation, `script_dataset` regeneration descriptor and persisted
2577
+ * component spec already points at it, so the correction applies retroactively
2578
+ * to replays instead of stranding them on the old body.
2579
+ *
2580
+ * Steps (see backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5):
2581
+ * 1. archive the current body as `<fileBase>.v<version>.ts`
2582
+ * 2. write the edited body to the original fileBase (atomic)
2583
+ * 3. version++, copy name/description/params, append a history record
2584
+ * 4. reset health counters — the pre-edit failure history is stale
2585
+ * 5. clear component specs — they were validated against the OLD shape
2586
+ * 6. delete the shadow draft (row + file)
2587
+ *
2588
+ * Returns the updated recipe, or null when the commit could not be applied
2589
+ * (caller should then fall back to treating the draft as a new script).
2590
+ */
2591
+ commitEdit(targetId: string, draft: {
2592
+ recipeId: string;
2593
+ name?: string;
2594
+ intentDescription?: string;
2595
+ tags?: string[];
2596
+ parameters?: ScriptParameter[];
2597
+ scriptBody: string;
2598
+ sourceIds?: string[];
2599
+ tables?: string[];
2600
+ }, meta: {
2601
+ instruction?: string;
2602
+ changeSummary?: string;
2603
+ editedBy?: string;
2604
+ }): Promise<ScriptRecipe | null>;
2605
+ /**
2606
+ * Drop a draft (row + body file). MainAgent calls this at end-of-turn when a
2607
+ * draft was authored but never verified — failed drafts are never matched, so
2608
+ * deleting them immediately avoids unbounded accumulation (#5). No-op if the
2609
+ * recipe isn't a draft (so a promoted/verified script is never removed here).
2610
+ */
2611
+ discardDraft(recipeId: string): Promise<void>;
2612
+ /** Delete a recipe (row + body file). */
2613
+ delete(id: string): Promise<void>;
2614
+ /** Record a successful execution (atomic counter bump). */
2615
+ recordSuccess(id: string): Promise<void>;
2616
+ /** Record a failed execution (atomic counter bump). */
2617
+ recordFailure(id: string): Promise<void>;
2618
+ /** Absolute path to the .ts body for a recipe (used by the runner/MainAgent). */
2619
+ getScriptPath(recipe: ScriptRecipe): string;
2620
+ private removeById;
2621
+ private rowToRecipe;
2622
+ private recipeToRow;
2623
+ /** slug of name, with a short id suffix when the bare slug is already taken. */
2624
+ private computeFileBase;
2625
+ private toSlug;
2626
+ private hash;
2627
+ /**
2628
+ * Attach getComponents to the recipe body. The stored `components` column is
2629
+ * cleared at promotion (see promoteToVerified): once the body computes its own
2630
+ * specs, a stale spec array beside a live program is how the wrong one gets
2631
+ * read later. See backend/docs/COMPONENTS-AS-PROGRAM-DESIGN.md § 4.4.
2632
+ */
2633
+ attachComponents(recipeId: string, componentsBody: string): Promise<boolean>;
2634
+ /**
2635
+ * Append (or replace) the `getAnalysis` export on an existing draft body.
2636
+ *
2637
+ * The narrative is authored AFTER execution, so it lands on a file that
2638
+ * already holds a working getData — rewriting the whole body would risk
2639
+ * losing the query that just succeeded. Replaces any earlier getAnalysis so
2640
+ * a retry does not stack duplicate exports.
2641
+ */
2642
+ attachAnalysis(recipeId: string, analysisBody: string): Promise<boolean>;
2643
+ private bodyPath;
2644
+ private readBody;
2645
+ /** Directory holding superseded bodies. Dot-prefixed so IDEs/`ls` hide it. */
2646
+ private get archiveDir();
2647
+ /**
2648
+ * Archive a superseded body as `.versions/<fileBase>.v<n>.ts`.
2649
+ *
2650
+ * Kept out of the main store directory on purpose — see commitEdit step 1.
2651
+ * To roll back: copy the file back over `scripts-store/<fileBase>.ts`.
2652
+ */
2653
+ private writeArchive;
2654
+ /**
2655
+ * Move a recipe's archived versions to a new prefix when its fileBase changes,
2656
+ * so all versions of one recipe stay grouped. Without this, two renames would
2657
+ * scatter a single recipe's history across three prefixes in `.versions/` with
2658
+ * nothing linking them back to the live script.
2659
+ */
2660
+ private renameArchives;
2661
+ /** Atomic body write (temp + rename) so concurrent reads never see a partial file. */
2662
+ private writeBody;
2663
+ private unlinkBody;
2664
+ }
2665
+
2666
+ /**
2667
+ * Main Agent (Orchestrator)
2668
+ *
2669
+ * A single LLM.streamWithTools() call that handles everything:
2670
+ * - Routing: decides which source(s) to query based on summaries
2671
+ * - Querying: calls source tools (each wraps an independent SourceAgent)
2672
+ * - Direct tools: calls pre-built function tools directly with LLM-provided params
2673
+ * - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
2674
+ * - Analysis: generates final text response from the data
2675
+ *
2676
+ * Two tool types:
2677
+ * - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
2678
+ * - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
2679
+ */
2680
+
2681
+ declare class MainAgent {
2682
+ private externalTools;
2683
+ private workflows;
2684
+ private config;
2685
+ private streamBuffer;
2686
+ /**
2687
+ * Optional: when provided, MainAgent exposes the `write_script` /
2688
+ * `execute_script` tools to the LLM and persists drafts to disk via the
2689
+ * store. Headless callers (alert analyzer, metric resolver) omit these to
2690
+ * suppress script authoring entirely — drafts would otherwise leak onto
2691
+ * disk with no caller to promote or clean them up.
2692
+ */
2693
+ private scriptStore;
2694
+ private turnId;
2695
+ private createdFromPrompt;
2696
+ private scriptState;
2697
+ /** Answer-flow component catalog (filtered + projected by the caller). */
2698
+ private componentCatalog;
2699
+ /** Specs accepted by `write_components` this turn; empty until it succeeds. */
2700
+ /**
2701
+ * Entities resolved this turn, appended verbatim to every source dispatch.
2702
+ *
2703
+ * Not left to the model to copy into its intent prose: observed live, the
2704
+ * MainAgent wrote names instead of ids on the first dispatch AND re-spelled
2705
+ * 'F D C LIMITED' as 'FDC Limited', so the source agent fell back to
2706
+ * `PartyName LIKE '%FDC%'` and found 2 of 3 customers. Carrying the ids
2707
+ * structurally makes that impossible rather than instruction-dependent.
2708
+ */
2709
+ private resolvedEntities;
2710
+ /**
2711
+ * Concept bodies resolved this turn (via resolve_entities' embedded concept
2712
+ * lookup or a standalone resolve_concepts call) — retained the same way as
2713
+ * resolvedEntities above, so they can be attached to the SourceAgent dispatch.
2714
+ *
2715
+ * Without this, a concept resolved HERE (MainAgent's own tool loop) never
2716
+ * reaches SourceAgent at all: SourceAgent only gets the natural-language
2717
+ * `intent` MainAgent writes, which is a paraphrase, not the concept's
2718
+ * verbatim, authoritative body. Deduped on name so a mid-turn re-resolve
2719
+ * doesn't repeat an already-attached concept.
2720
+ */
2721
+ private resolvedConcepts;
2722
+ private componentSpecs;
2723
+ private componentLayout;
2724
+ private renderComponentAttempts;
2725
+ /** Same repeated-violation tracking as ScriptState.lastAnalysisViolationTexts, for write_components. */
2726
+ private lastComponentsViolationTexts;
2727
+ /**
2728
+ * Fork mode — set when this turn is adapting a near-matching parent script.
2729
+ * In fork mode there is no legitimate "answer with bare text" outcome: the
2730
+ * only correct first move is a tool call (write_script, or a source tool for
2731
+ * schema discovery). We therefore force tool use on the first LLM iteration
2732
+ * so the model can't end its turn with a bare "I'll adapt…" preamble and zero
2733
+ * tool calls. Never set on the fresh-authoring / general-question path.
2734
+ */
2735
+ private forkMode;
2736
+ /**
2737
+ * Edit mode — set when this turn applies a user-directed change to an
2738
+ * existing script. Swaps the system prompt to `agent-main-edit` and stamps
2739
+ * the shadow draft's parentId. Like fork mode there is no legitimate
2740
+ * "answer with bare text" outcome, so tool use is forced on iteration 1.
2741
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 4.
2742
+ */
2743
+ private editContext;
2744
+ /** The recipe's durable rendering choice — see the constructor. */
2745
+ private displayPreference;
2746
+ /**
2747
+ * Per-turn cancellation signal (user hit "Stop"). Set at the top of
2748
+ * handleQuestion and read by the tool handler, the SourceAgent dispatch, and
2749
+ * the script subprocess so an abort tears down every layer of the turn.
2750
+ */
2751
+ private abortSignal?;
2752
+ constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[], forkMode?: boolean, editContext?: EditContext, componentCatalog?: Component[],
2753
+ /**
2754
+ * The recipe's durable rendering choice, when it has one. A DATA edit
2755
+ * re-authors getComponents from scratch, so without this the user's chart
2756
+ * type is silently dropped whenever anyone changes the SQL.
2757
+ */
2758
+ displayPreference?: {
2759
+ componentTypes: string[];
2760
+ instruction: string;
2761
+ });
2762
+ /** True when the turn is applying a user-directed script edit. */
2763
+ private get editMode();
2764
+ private get scriptingEnabled();
2765
+ /**
2766
+ * Handle a user question using the multi-agent system.
2767
+ *
2768
+ * This is ONE LLM.streamWithTools() call. The LLM:
2769
+ * 1. Sees source summaries + direct tool descriptions in system prompt
2770
+ * 2. Decides which tool(s) to call (routing)
2771
+ * 3. Source tools → SourceAgent runs independently → returns data
2772
+ * 4. Direct tools → fn() called directly with LLM params → returns data
2773
+ * 5. Generates final analysis text
2774
+ */
2775
+ handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, signal?: AbortSignal): Promise<AgentResponse>;
2776
+ /**
2777
+ * Tool definition, with the catalog rendered from the registered `Metadata`
2778
+ * the caller passed in. Generated rather than hand-written so it cannot drift
2779
+ * from what the frontend actually ships.
2780
+ */
2781
+ private buildWriteComponentsToolDef;
2782
+ /**
2783
+ * Validate the agent's component picks against the REAL columns of each bound
2784
+ * dataset. All-or-nothing: any error rejects the whole call and returns the
2785
+ * findings, because a partially-accepted dashboard makes the retry ambiguous.
2786
+ */
2787
+ private validateSpecs;
2788
+ /**
2789
+ * Author the dashboard as a program. Attaches getComponents to the draft, runs
2790
+ * it over the verified rows, then validates the specs it RETURNED — the program
2791
+ * is never trusted because it is a program, exactly as an authored spec is not.
2792
+ */
2793
+ private handleWriteComponents;
2794
+ /**
2795
+ * Author the answer as a program. Runs after execute_script, so the body is
2796
+ * written with the result already known and can react to what it found.
2797
+ *
2798
+ * Rejects a body that types numbers rather than computing them — see
2799
+ * analysis-lint. A hardcoded figure is worse than prose: it freezes into the
2800
+ * recipe and replays unchanged while the data moves underneath it.
2801
+ */
2802
+ private handleWriteAnalysis;
2803
+ private handleWriteScript;
2804
+ private handleExecuteScript;
2805
+ /**
2806
+ * Build the AgentWrittenScript payload the caller will hand to
2807
+ * `ScriptStore.promoteToVerified()`. Only returned when a verified
2808
+ * successful execution is on record.
2809
+ */
2810
+ private buildSavedScript;
2811
+ private normalizeParameterList;
2812
+ /**
2813
+ * Which declared parameter NAMES never actually appear wired into the
2814
+ * script body — checked as plain text, not a real parser, so it only
2815
+ * catches the worst case (completely unreferenced) rather than every
2816
+ * subtler variant (e.g. used for display text while the SQL itself still
2817
+ * hardcodes the value). That worst case is exactly what's been observed:
2818
+ * a parameter declared purely for show, with the actual filter hardcoded.
2819
+ * Accepts `params.name`, `params['name']`/`params["name"]`, and a
2820
+ * destructuring binding (`const { name } = params`) as valid wiring.
2821
+ */
2822
+ private findUnwiredParams;
2823
+ /**
2824
+ * Use the schema embedding collection to pre-select relevant tables for
2825
+ * this source + intent. Returns a formatted schema block if confidence is
2826
+ * high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
2827
+ *
2828
+ * When this returns a block, we can skip the SourceAgent's `search_schema`
2829
+ * loop and reduce iteration budget. When it returns null, the SourceAgent
2830
+ * falls back to the existing LLM-driven keyword search (same as today).
2831
+ */
2832
+ /**
2833
+ * Ids + verbatim names for everything resolved this turn, appended by CODE to
2834
+ * each source dispatch so neither omission nor re-spelling by the model can
2835
+ * lose them. Empty string when nothing was resolved, so intents are untouched
2836
+ * for questions that name no entities.
2837
+ *
2838
+ * Also appends `attrs.scopeSql` when the resolved instance carries one —
2839
+ * same "guaranteed by code" reasoning as the ids/names above, extended to
2840
+ * the one attrs field with a documented, cross-entity-type meaning: a
2841
+ * ready-made SQL predicate an entity's index precomputed (see
2842
+ * ENTITY-SEARCH-DESIGN.md's hierarchy-broadening pattern — branch/region/
2843
+ * state entity types attach it so a lane/route question never needs its
2844
+ * own city-matching join). Confirmed real cost of not doing this: a
2845
+ * branch/state resolved with scopeSql sat unused while the source agent
2846
+ * spent 4 failed exploratory queries rediscovering the exact same
2847
+ * branch-id list by hand (Invalid column name 'StateName'/'CityId'/
2848
+ * 'OrganizationLocationId', in that order, ~144s, before landing on ids
2849
+ * that were sitting in scopeSql from the very first resolve_entities
2850
+ * call). Other attrs (code, counts, etc.) are not dumped here — they are
2851
+ * descriptive, not actionable the way a precomputed predicate is, and
2852
+ * bloating every dispatch with all of them for no clear gain isn't worth
2853
+ * it; scopeSql is the one thing worth this guarantee today.
2854
+ */
2855
+ private buildResolvedEntitiesBlock;
2856
+ /** Dedupe-and-retain helper shared by resolveConceptsForTurn and handleResolveConcepts. */
2857
+ private retainResolvedConcepts;
2858
+ /**
2859
+ * Same purpose as buildResolvedEntitiesBlock, for concept bodies instead of
2860
+ * entity ids — appended to the dispatch intent so SourceAgent's own,
2861
+ * independent LLM call receives the resolved definitions verbatim rather
2862
+ * than only MainAgent's paraphrased intent text.
2863
+ */
2864
+ private buildResolvedConceptsBlock;
2865
+ /** True when the backend registered the entity-search collection. */
2866
+ private get entitySearchEnabled();
2867
+ /** True when the backend registered the concepts collection. */
2868
+ private get conceptsEnabled();
2869
+ /**
2870
+ * Concept names for the system prompt. Names ONLY — the body comes back from
2871
+ * resolve_concepts once the LLM has named one, exactly as with the entity
2872
+ * catalog. Putting bodies here would rebuild the always-on context problem
2873
+ * concepts exist to solve.
2874
+ *
2875
+ * Not cached, for the same reason loadEntityCatalog isn't: unchanged rows
2876
+ * render byte-identical text so the prompt-cache prefix still hits, and a
2877
+ * process cache would only buy a window where a new concept is invisible.
2878
+ */
2879
+ private loadConceptCatalog;
2880
+ /**
2881
+ * The ALWAYS-INJECTED tier: preconditions no question is semantically close
2882
+ * to — date encodings, valid-row filters. These cannot be retrieval-gated.
2883
+ * "What was revenue last quarter?" has no similarity to "dates are DD/MM/YYYY
2884
+ * text", so leaving them to be requested means they are silently dropped and
2885
+ * the answer is confidently wrong rather than visibly missing.
2886
+ *
2887
+ * Bodies ARE included here — unlike the catalog — because there is nothing to
2888
+ * request: being unrequestable is what makes them invariants.
2889
+ *
2890
+ * Also retained into resolvedConcepts (same as an explicit resolve_concepts
2891
+ * call) so these bodies reach SourceAgent's dispatch too — an invariant is
2892
+ * meant to apply everywhere, not just wherever the model happens to ask for
2893
+ * something whose `requires` chain reaches it.
2894
+ */
2895
+ private loadConceptInvariants;
2896
+ /**
2897
+ * Resolve the concepts for a turn, with a SERVER-SIDE FLOOR.
2898
+ *
2899
+ * Pinning a tool guarantees it is called; it does not guarantee the model
2900
+ * fills in the arguments. Observed: a question containing the exact words
2901
+ * "revenue forecast" produced a call with no concepts at all, and the agent
2902
+ * then used an incomplete copy of the formula from the knowledge base — the
2903
+ * resulting query filtered a customer id against a project column and
2904
+ * returned zero rows on every attempt.
2905
+ *
2906
+ * So when the model names nothing, scan the question itself for catalog names
2907
+ * and aliases on word boundaries. Precise (a literal name is evidence, not a
2908
+ * guess) and asymmetric in the safe direction: an unneeded definition costs a
2909
+ * few hundred ignorable tokens, a missing one costs a wrong answer.
2910
+ */
2911
+ /**
2912
+ * Returns the tool-facing fields to spread into the resolve_entities JSON
2913
+ * response, PLUS a `_trace` field with everything the trace needs that the
2914
+ * model does not (asked/viaFloor/unmatched). Callers must pull `_trace` out
2915
+ * before spreading the rest into what the model sees — see handleResolveEntities.
2916
+ */
2917
+ private resolveConceptsForTurn;
2918
+ /**
2919
+ * Never throws: a concept-store outage must degrade to "no definition found"
2920
+ * and leave the agent deriving the formula as it does today, not take the
2921
+ * whole answer down.
2922
+ */
2923
+ private handleResolveConcepts;
2924
+ /**
2925
+ * Compact catalog (type + gloss) for the system prompt. This is what lets the
2926
+ * LLM NAME a concept instead of guessing at our vocabulary — it can infer
2927
+ * that a question is about unpaid money, but not that we call that
2928
+ * `outstanding-balance`. Full `resolution` detail is fetched by the tool.
2929
+ *
2930
+ * Deliberately NOT cached in-process. The token cost is already handled by
2931
+ * prompt caching (the system prompt carries a cache_control breakpoint), and
2932
+ * re-reading a tiny PK-ordered table costs ~nothing. Fetching fresh does not
2933
+ * weaken the prompt cache either: unchanged data renders byte-identical text,
2934
+ * so the prefix still hits. A process cache would only buy a staleness window
2935
+ * in which a newly indexed entity is invisible to the agent.
2936
+ */
2937
+ private loadEntityCatalog;
2938
+ /**
2939
+ * Never throws: a resolver outage must degrade to "nothing resolved" and
2940
+ * leave the agent exactly as it was, not take the whole answer down.
2941
+ */
2942
+ private handleResolveEntities;
2943
+ private preResolveSchema;
2944
+ /**
2945
+ * Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
2946
+ */
2947
+ private handleDirectTool;
2948
+ /**
2949
+ * Build the main agent's system prompt with source summaries, direct tool descriptions,
2950
+ * and workflow component descriptions.
2951
+ */
2952
+ private buildSystemPrompt;
2953
+ /**
2954
+ * Build tool definitions for source tools — summary-only descriptions.
2955
+ * The full schema is inside the SourceAgent which runs independently.
2956
+ */
2957
+ private buildSourceToolDefinitions;
2958
+ /**
2959
+ * Build tool definitions for direct tools — expose their actual params.
2960
+ * These are called directly by the main agent LLM, no SourceAgent.
2961
+ */
2962
+ private buildDirectToolDefinitions;
2963
+ /**
2964
+ * Capture a workflow selection. We do NOT execute anything — the LLM has
2965
+ * already extracted the props it wants the workflow rendered with. We
2966
+ * record the selection (via the capture callback) and return a short
2967
+ * acknowledgement so the LLM ends its turn cleanly without writing
2968
+ * analysis text or calling more tools.
2969
+ */
2970
+ private handleWorkflow;
2971
+ /**
2972
+ * Build LLM tool definitions for workflow components. The workflow's
2973
+ * propsSchema becomes the tool's input_schema so the LLM extracts props
2974
+ * directly from the prompt — same mechanic as direct tools.
2975
+ */
2976
+ private buildWorkflowToolDefinitions;
2977
+ /**
2978
+ * Format a source agent's result as a clean string for the main agent LLM.
2979
+ */
2980
+ private formatResultForMainAgent;
2981
+ /**
2982
+ * Get source summaries (for external inspection/debugging).
2983
+ */
2984
+ getSourceSummaries(): SourceSummary[];
2985
+ }
2986
+
2987
+ /**
2988
+ * Represents an action that can be performed on a UIBlock
2989
+ */
2990
+ interface Action {
2991
+ id: string;
2992
+ name: string;
2993
+ type: string;
2994
+ [key: string]: any;
2995
+ }
2996
+
2997
+ type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
2998
+ interface LLMMessages {
2999
+ sys: SystemPrompt;
3000
+ user: string;
3001
+ prefill?: string;
3002
+ }
3003
+ interface LLMOptions {
3004
+ model?: string;
3005
+ maxTokens?: number;
3006
+ temperature?: number;
3007
+ topP?: number;
3008
+ apiKey?: string;
3009
+ baseURL?: string;
3010
+ partial?: (chunk: string) => void;
3011
+ /**
3012
+ * Per-request cancellation. When the caller aborts this signal (user hit
3013
+ * "Stop"), the underlying provider request is cancelled and the call throws
3014
+ * a RequestAbortedError. Threaded into the provider `messages.create` request
3015
+ * options and checked between tool-loop iterations. Currently honored on the
3016
+ * Anthropic path (the agent flow's default provider).
3017
+ */
3018
+ signal?: AbortSignal;
3019
+ /**
3020
+ * Forces a tool call on the FIRST iteration of streamWithTools only
3021
+ * (subsequent iterations revert to auto). Used by fork mode to stop the
3022
+ * model from ending its turn with a bare "I'll adapt the script…" preamble
3023
+ * and zero tool calls. `{ type: 'any' }` lets the model pick which tool
3024
+ * (write_script in the common case, a source tool for schema discovery);
3025
+ * `{ type: 'tool', name }` pins a specific tool. Honored on both the
3026
+ * Anthropic path and the OpenAI/OpenRouter path (mapped to OpenAI's
3027
+ * tool_choice: 'required' / a named function).
3028
+ */
3029
+ firstIterationToolChoice?: {
3030
+ type: 'any';
3031
+ } | {
3032
+ type: 'tool';
3033
+ name: string;
3034
+ };
3035
+ /**
3036
+ * Internal — set only by the OpenRouter wrappers when the target is a Claude
3037
+ * model. Tells the OpenAI-wire path to emit Anthropic `cache_control`
3038
+ * breakpoints (OpenRouter forwards them to Anthropic for prompt caching).
3039
+ * Never set for direct OpenAI/Groq calls, so their requests are unchanged.
3040
+ */
3041
+ _openrouterClaudeCaching?: boolean;
3042
+ /**
3043
+ * Internal — OpenRouter provider-routing preferences (forwarded as the
3044
+ * `provider` body field). Set by the OpenRouter wrappers to steer routing to
3045
+ * a fast backend (e.g. {sort:'throughput'}). Never set for direct OpenAI/Groq.
3046
+ */
3047
+ _openrouterProvider?: Record<string, unknown>;
3048
+ }
3049
+ interface Tool {
3050
+ name: string;
3051
+ description: string;
3052
+ input_schema: {
1262
3053
  type: string;
1263
3054
  properties: Record<string, any>;
1264
3055
  required?: string[];
@@ -1275,6 +3066,16 @@ declare class LLM {
1275
3066
  * @returns Normalized system prompt for Anthropic API
1276
3067
  */
1277
3068
  private static _normalizeSystemPrompt;
3069
+ /**
3070
+ * Strip unpaired UTF-16 surrogates from every text field of a message set.
3071
+ *
3072
+ * A lone surrogate (from mid-pair string slicing or corrupt source data)
3073
+ * serializes to a bare `\udXXX` escape that strict JSON parsers — including
3074
+ * the one on Anthropic's API — reject with "no low surrogate in string",
3075
+ * failing the whole request. Sanitizing here, at the single boundary every
3076
+ * provider call flows through, guarantees no request can carry one.
3077
+ */
3078
+ private static _sanitizeMessages;
1278
3079
  /**
1279
3080
  * Log cache usage metrics from Anthropic API response
1280
3081
  * Shows cache hits, costs, and savings
@@ -1291,16 +3092,76 @@ declare class LLM {
1291
3092
  * "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
1292
3093
  */
1293
3094
  private static _parseModel;
3095
+ /**
3096
+ * Map an Anthropic model id (e.g. "claude-sonnet-4-5-20250929") to the OpenRouter slug
3097
+ * (e.g. "claude-sonnet-4.5"). OpenRouter slugs drop the date suffix and use dotted versions.
3098
+ */
3099
+ private static _toOpenRouterSlug;
3100
+ /**
3101
+ * Per-provider proxy base URL. Returns `${SUPERATOM_LLM_PROXY_URL}/<provider>`
3102
+ * when our Cloudflare LLM proxy is configured, else undefined (→ talk to the
3103
+ * provider directly, legacy behaviour). An explicit options.baseURL (e.g.
3104
+ * OpenRouter) always wins and is never overridden. See backend/docs/llm-proxy.md.
3105
+ */
3106
+ private static _proxyBaseURL;
3107
+ private static _openrouterOptions;
3108
+ private static _isRetryableProviderError;
3109
+ private static _withOpenrouterRetry;
3110
+ private static _openrouterText;
3111
+ private static _openrouterStream;
3112
+ private static _openrouterStreamWithTools;
3113
+ /**
3114
+ * Build an Anthropic client. Routes through our Cloudflare LLM proxy when
3115
+ * SUPERATOM_LLM_PROXY_URL is set (each client ships a per-client proxy key as
3116
+ * ANTHROPIC_API_KEY and never holds the real key); otherwise talks to
3117
+ * api.anthropic.com directly. See backend/docs/llm-proxy.md.
3118
+ */
3119
+ private static _anthropicClient;
3120
+ /** True when OpenRouter is configured as a fail-open fallback for Claude. */
3121
+ private static _openrouterAvailable;
3122
+ /** Remap an Anthropic model id to the OpenRouter model path for fail-open. */
3123
+ private static _anthropicFallbackModel;
1294
3124
  private static _anthropicText;
1295
3125
  private static _anthropicStream;
1296
3126
  private static _anthropicStreamWithTools;
1297
3127
  private static _groqText;
1298
3128
  private static _groqStream;
3129
+ /**
3130
+ * Gemini request options carrying the proxy base URL, or undefined → talk to
3131
+ * generativelanguage.googleapis.com directly. The Google SDK takes baseUrl as a
3132
+ * per-model request option, not a constructor arg. See backend/docs/llm-proxy.md.
3133
+ */
3134
+ private static _geminiRequestOptions;
1299
3135
  private static _geminiText;
1300
3136
  private static _geminiStream;
3137
+ /**
3138
+ * Recursively strip unsupported JSON Schema properties for Gemini
3139
+ * Gemini doesn't support: additionalProperties, $schema, etc.
3140
+ */
3141
+ private static _cleanSchemaForGemini;
1301
3142
  private static _geminiStreamWithTools;
3143
+ /** True for Anthropic/Claude model ids — gates OpenRouter prompt caching. */
3144
+ private static _isClaudeModel;
3145
+ /**
3146
+ * Build the OpenAI-wire system message. For OpenRouter + Claude
3147
+ * (cacheClaude=true) it emits content parts carrying Anthropic
3148
+ * `cache_control` breakpoints (preserving any the caller set, else marking
3149
+ * the last block), so OpenRouter forwards them to Anthropic for prompt
3150
+ * caching. Otherwise it returns a plain flattened string — unchanged for
3151
+ * direct OpenAI/Groq.
3152
+ */
3153
+ private static _openaiSystemMessage;
3154
+ /**
3155
+ * Split an OpenAI-wire usage object. `prompt_tokens` INCLUDES cached tokens,
3156
+ * so we subtract them out (Anthropic-style: input excludes cache reads) and
3157
+ * report cached separately — this makes calculateCost price cache reads at
3158
+ * the discounted rate and reflects OpenRouter prompt-cache savings in logs.
3159
+ */
3160
+ private static _openaiUsage;
1302
3161
  private static _openaiText;
1303
3162
  private static _openaiStream;
3163
+ /** Map the Anthropic-style firstIterationToolChoice to OpenAI's tool_choice. */
3164
+ private static _openaiToolChoice;
1304
3165
  private static _openaiStreamWithTools;
1305
3166
  /**
1306
3167
  * Parse JSON string, handling markdown code blocks and surrounding text
@@ -1390,16 +3251,6 @@ declare class UILogCollector {
1390
3251
  setUIBlockId(uiBlockId: string): void;
1391
3252
  }
1392
3253
 
1393
- /**
1394
- * Represents an action that can be performed on a UIBlock
1395
- */
1396
- interface Action {
1397
- id: string;
1398
- name: string;
1399
- type: string;
1400
- [key: string]: any;
1401
- }
1402
-
1403
3254
  /**
1404
3255
  * UIBlock represents a single user and assistant message block in a thread
1405
3256
  * Contains user question, component metadata, component data, text response, and available actions
@@ -1412,6 +3263,13 @@ declare class UIBlock {
1412
3263
  private textResponse;
1413
3264
  private actions;
1414
3265
  private createdAt;
3266
+ /**
3267
+ * Which script recipe produced this answer, when a script did. Read on the
3268
+ * NEXT turn so the user can say "use mode instead" and have the matcher
3269
+ * resolve it to a concrete script (the `edit` tier is unreachable without it).
3270
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3271
+ */
3272
+ private scriptBinding;
1415
3273
  /**
1416
3274
  * Creates a new UIBlock instance
1417
3275
  * @param userQuestion - The user's question or input
@@ -1503,9 +3361,22 @@ declare class UIBlock {
1503
3361
  * Clear all actions
1504
3362
  */
1505
3363
  clearActions(): void;
3364
+ /** The program-generated half of the answer — see setProgramAnswer. */
3365
+ programAnswer?: string | null;
1506
3366
  /**
1507
- * Get creation timestamp
3367
+ * Bind this block to the script recipe that produced its answer.
3368
+ */
3369
+ setScriptBinding(binding: Record<string, any> | null): void;
3370
+ /**
3371
+ * The program-generated half of the answer, kept verbatim so a reload can
3372
+ * replace exactly that text without disturbing the streamed narration.
1508
3373
  */
3374
+ setProgramAnswer(text: string | null): void;
3375
+ getProgramAnswer(): string | null;
3376
+ /**
3377
+ * The script recipe bound to this block, if any.
3378
+ */
3379
+ getScriptBinding(): Record<string, any> | null;
1509
3380
  getCreatedAt(): Date;
1510
3381
  /**
1511
3382
  * Convert UIBlock to JSON-serializable object
@@ -1573,6 +3444,32 @@ declare class Thread {
1573
3444
  * @param currentUIBlockId - ID of current UIBlock to exclude from context (optional)
1574
3445
  * @returns Formatted conversation history string
1575
3446
  */
3447
+ /**
3448
+ * The script recipe bound to the most recent completed UIBlock — i.e. the
3449
+ * script behind the answer the user is currently looking at. Drives the
3450
+ * matcher's `edit` tier: without it, "use mode instead" has no target and
3451
+ * falls through to regeneration.
3452
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3453
+ */
3454
+ getActiveScriptBinding(currentUIBlockId?: string): Record<string, any> | null;
3455
+ /**
3456
+ * The recent script-backed answers in this thread, newest first — the
3457
+ * candidate set a user-directed edit can target.
3458
+ *
3459
+ * Returning several rather than only the newest is what lets an instruction
3460
+ * name its own target ("use the mode for the WSP one"). With a single
3461
+ * candidate every edit lands on the most recent script, which silently edits
3462
+ * the wrong recipe whenever the user meant an earlier one.
3463
+ *
3464
+ * Deduped by recipeId (newest occurrence wins) so a long editing session on
3465
+ * one script doesn't crowd out the others. Each entry carries the question
3466
+ * that produced it — without that the candidates are indistinguishable.
3467
+ *
3468
+ * In-memory only: dies with the process. The caller falls back to the
3469
+ * persisted bindings when this comes back empty.
3470
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3471
+ */
3472
+ getScriptBindings(limit?: number, currentUIBlockId?: string): Record<string, any>[];
1576
3473
  getConversationContext(limit?: number, currentUIBlockId?: string): string;
1577
3474
  /**
1578
3475
  * Convert Thread to JSON-serializable object
@@ -1582,12 +3479,20 @@ declare class Thread {
1582
3479
 
1583
3480
  /**
1584
3481
  * ThreadManager manages all threads globally
1585
- * Provides methods to create, retrieve, and delete threads
3482
+ * Provides methods to create, retrieve, and delete threads.
3483
+ * Includes automatic cleanup to prevent unbounded memory growth.
1586
3484
  */
1587
3485
  declare class ThreadManager {
1588
3486
  private static instance;
1589
3487
  private threads;
3488
+ private cleanupInterval;
3489
+ private readonly threadTtlMs;
1590
3490
  private constructor();
3491
+ /**
3492
+ * Periodically remove threads older than 7 days.
3493
+ * Runs every hour to avoid frequent iteration over the map.
3494
+ */
3495
+ private startCleanup;
1591
3496
  /**
1592
3497
  * Get singleton instance of ThreadManager
1593
3498
  */
@@ -1986,6 +3891,92 @@ declare function rerankConversationResults<T extends {
1986
3891
  bm25Score: number;
1987
3892
  }>;
1988
3893
 
3894
+ /**
3895
+ * QueryExecutionService - Handles all query execution, validation, and retry logic
3896
+ * Extracted from BaseLLM for better separation of concerns
3897
+ */
3898
+
3899
+ /**
3900
+ * Context for component when requesting query fix
3901
+ */
3902
+ interface ComponentContext {
3903
+ name: string;
3904
+ type: string;
3905
+ title?: string;
3906
+ }
3907
+ /**
3908
+ * Result of query validation
3909
+ */
3910
+ interface QueryValidationResult {
3911
+ component: Component | null;
3912
+ queryKey: string;
3913
+ result: any;
3914
+ validated: boolean;
3915
+ }
3916
+ /**
3917
+ * Result of batch query validation
3918
+ */
3919
+ interface BatchValidationResult {
3920
+ components: Component[];
3921
+ queryResults: Map<string, any>;
3922
+ }
3923
+ /**
3924
+ * Configuration for QueryExecutionService
3925
+ */
3926
+ interface QueryExecutionServiceConfig {
3927
+ defaultLimit: number;
3928
+ getModelForTask: (taskType: 'simple' | 'complex') => string;
3929
+ getApiKey: (apiKey?: string) => string | undefined;
3930
+ providerName: string;
3931
+ }
3932
+ /**
3933
+ * QueryExecutionService handles all query-related operations
3934
+ */
3935
+ declare class QueryExecutionService {
3936
+ private config;
3937
+ constructor(config: QueryExecutionServiceConfig);
3938
+ /**
3939
+ * Get the cache key for a query
3940
+ * This ensures the cache key matches what the frontend will send
3941
+ */
3942
+ getQueryCacheKey(query: any): string;
3943
+ /**
3944
+ * Execute a query against the database
3945
+ * @param query - The SQL query to execute (string or object with sql/values)
3946
+ * @param collections - Collections object containing database execute function
3947
+ * @returns Object with result data and cache key
3948
+ */
3949
+ executeQuery(query: any, collections: any): Promise<{
3950
+ result: any;
3951
+ cacheKey: string;
3952
+ }>;
3953
+ /**
3954
+ * Request the LLM to fix a failed SQL query
3955
+ * @param failedQuery - The query that failed execution
3956
+ * @param errorMessage - The error message from the failed execution
3957
+ * @param componentContext - Context about the component
3958
+ * @param apiKey - Optional API key
3959
+ * @returns Fixed query string
3960
+ */
3961
+ requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
3962
+ /**
3963
+ * Validate a single component's query with retry logic
3964
+ * @param component - The component to validate
3965
+ * @param collections - Collections object containing database execute function
3966
+ * @param apiKey - Optional API key for LLM calls
3967
+ * @returns Validation result with component, query key, and result
3968
+ */
3969
+ validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
3970
+ /**
3971
+ * Validate multiple component queries in parallel
3972
+ * @param components - Array of components with potential queries
3973
+ * @param collections - Collections object containing database execute function
3974
+ * @param apiKey - Optional API key for LLM calls
3975
+ * @returns Object with validated components and query results map
3976
+ */
3977
+ validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
3978
+ }
3979
+
1989
3980
  /**
1990
3981
  * Task types for model selection
1991
3982
  * - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
@@ -2004,6 +3995,7 @@ interface BaseLLMConfig {
2004
3995
  * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
2005
3996
  */
2006
3997
  modelStrategy?: ModelStrategy;
3998
+ conversationSimilarityThreshold?: number;
2007
3999
  }
2008
4000
  /**
2009
4001
  * BaseLLM abstract class for AI-powered component generation and matching
@@ -2015,6 +4007,8 @@ declare abstract class BaseLLM {
2015
4007
  protected defaultLimit: number;
2016
4008
  protected apiKey?: string;
2017
4009
  protected modelStrategy: ModelStrategy;
4010
+ protected conversationSimilarityThreshold: number;
4011
+ protected queryService: QueryExecutionService;
2018
4012
  constructor(config?: BaseLLMConfig);
2019
4013
  /**
2020
4014
  * Get the appropriate model based on task type and model strategy
@@ -2032,6 +4026,16 @@ declare abstract class BaseLLM {
2032
4026
  * @returns The current model strategy
2033
4027
  */
2034
4028
  getModelStrategy(): ModelStrategy;
4029
+ /**
4030
+ * Set the conversation similarity threshold at runtime
4031
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
4032
+ */
4033
+ setConversationSimilarityThreshold(threshold: number): void;
4034
+ /**
4035
+ * Get the current conversation similarity threshold
4036
+ * @returns The current threshold value
4037
+ */
4038
+ getConversationSimilarityThreshold(): number;
2035
4039
  /**
2036
4040
  * Get the default model for this provider (used for complex tasks like text generation)
2037
4041
  */
@@ -2067,11 +4071,10 @@ declare abstract class BaseLLM {
2067
4071
  * @param analysisContent - The text response containing component suggestions
2068
4072
  * @param components - List of available components
2069
4073
  * @param apiKey - Optional API key
2070
- * @param logCollector - Optional log collector
2071
4074
  * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
2072
4075
  * @returns Object containing matched components, layout title/description, and follow-up actions
2073
4076
  */
2074
- matchComponentsFromAnalysis(analysisContent: string, components: Component[], apiKey?: string, logCollector?: any, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[]): Promise<{
4077
+ matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
2075
4078
  components: Component[];
2076
4079
  layoutTitle: string;
2077
4080
  layoutDescription: string;
@@ -2081,7 +4084,7 @@ declare abstract class BaseLLM {
2081
4084
  * Classify user question into category and detect external tools needed
2082
4085
  * Determines if question is for data analysis, requires external tools, or needs text response
2083
4086
  */
2084
- classifyQuestionCategory(userPrompt: string, apiKey?: string, logCollector?: any, conversationHistory?: string, externalTools?: any[]): Promise<{
4087
+ classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
2085
4088
  category: 'data_analysis' | 'data_modification' | 'general';
2086
4089
  externalTools: Array<{
2087
4090
  type: string;
@@ -2098,7 +4101,7 @@ declare abstract class BaseLLM {
2098
4101
  * Takes a matched UI block from semantic search and modifies its props to answer the new question
2099
4102
  * Also adapts the cached text response to match the new question
2100
4103
  */
2101
- adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, logCollector?: any, cachedTextResponse?: string): Promise<{
4104
+ adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
2102
4105
  success: boolean;
2103
4106
  adaptedComponent?: Component;
2104
4107
  adaptedTextResponse?: string;
@@ -2113,13 +4116,8 @@ declare abstract class BaseLLM {
2113
4116
  * This provides conversational text responses instead of component generation
2114
4117
  * Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
2115
4118
  * After generating text response, if components are provided, matches suggested components
2116
- * @param streamCallback - Optional callback function to receive text chunks as they stream
2117
- * @param collections - Collection registry for executing database queries via database.execute
2118
- * @param components - Optional list of available components for matching suggestions
2119
- * @param externalTools - Optional array of external tools (email, calendar, etc.) that can be called
2120
- * @param category - Question category ('data_analysis' | 'data_modification' | 'general'). For data_modification, answer component streaming is skipped. For general, component generation is skipped entirely.
2121
4119
  */
2122
- generateTextResponse(userPrompt: string, apiKey?: string, logCollector?: any, conversationHistory?: string, streamCallback?: (chunk: string) => void, collections?: any, components?: Component[], externalTools?: any[], category?: 'data_analysis' | 'data_modification' | 'general'): Promise<T_RESPONSE>;
4120
+ generateTextResponse(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, collections?: any, components?: Component[], externalTools?: any[], category?: 'data_analysis' | 'data_modification' | 'general', userId?: string): Promise<T_RESPONSE>;
2123
4121
  /**
2124
4122
  * Main orchestration function with semantic search and multi-step classification
2125
4123
  * NEW FLOW (Recommended):
@@ -2127,19 +4125,14 @@ declare abstract class BaseLLM {
2127
4125
  * - If match found → Adapt UI block parameters and return
2128
4126
  * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
2129
4127
  * 3. Route appropriately based on category and response mode
2130
- *
2131
- * @param responseMode - 'component' for component generation (default), 'text' for text responses
2132
- * @param streamCallback - Optional callback function to receive text chunks as they stream (only for text mode)
2133
- * @param collections - Collection registry for executing database queries (required for text mode)
2134
- * @param externalTools - Optional array of external tools (email, calendar, etc.) that can be called (only for text mode)
2135
4128
  */
2136
- handleUserRequest(userPrompt: string, components: Component[], apiKey?: string, logCollector?: any, conversationHistory?: string, responseMode?: 'component' | 'text', streamCallback?: (chunk: string) => void, collections?: any, externalTools?: any[], userId?: string): Promise<T_RESPONSE>;
4129
+ handleUserRequest(userPrompt: string, components: Component[], apiKey?: string, conversationHistory?: string, responseMode?: 'component' | 'text', streamCallback?: (chunk: string) => void, collections?: any, externalTools?: any[], userId?: string): Promise<T_RESPONSE>;
2137
4130
  /**
2138
4131
  * Generate next questions that the user might ask based on the original prompt and generated component
2139
4132
  * This helps provide intelligent suggestions for follow-up queries
2140
4133
  * For general/conversational questions without components, pass textResponse instead
2141
4134
  */
2142
- generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, logCollector?: any, conversationHistory?: string, textResponse?: string): Promise<string[]>;
4135
+ generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string, signal?: AbortSignal): Promise<string[]>;
2143
4136
  }
2144
4137
 
2145
4138
  interface AnthropicLLMConfig extends BaseLLMConfig {
@@ -2198,7 +4191,345 @@ declare class OpenAILLM extends BaseLLM {
2198
4191
  }
2199
4192
  declare const openaiLLM: OpenAILLM;
2200
4193
 
2201
- declare const SDK_VERSION = "0.0.8";
4194
+ /**
4195
+ * Query Cache — Two mechanisms:
4196
+ *
4197
+ * 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
4198
+ * of recently validated queries. True LRU eviction: reads bubble entries to the back via
4199
+ * delete+re-set so the oldest *unused* entry is evicted, not the oldest *inserted*.
4200
+ *
4201
+ * 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
4202
+ * No server-side storage needed for SQL mappings. The token is decrypted on each request.
4203
+ * This eliminates the unbounded queryIdCache that previously grew forever and caused
4204
+ * memory bloat (hundreds of MBs after thousands of queries).
4205
+ *
4206
+ * Result data can still be cached temporarily via the data cache (mechanism 1).
4207
+ */
4208
+ declare class QueryCache {
4209
+ private cache;
4210
+ private ttlMs;
4211
+ private maxCacheSize;
4212
+ private cleanupInterval;
4213
+ private readonly algorithm;
4214
+ private encryptionKey;
4215
+ constructor();
4216
+ /**
4217
+ * Set the cache TTL (Time To Live)
4218
+ * @param minutes - TTL in minutes (default: 10)
4219
+ */
4220
+ setTTL(minutes: number): void;
4221
+ /**
4222
+ * Get the current TTL in minutes
4223
+ */
4224
+ getTTL(): number;
4225
+ /**
4226
+ * Store query result in data cache.
4227
+ * If the key already exists, it's removed first so the re-insert places it
4228
+ * at the back of the iteration order (LRU). Eviction only fires when adding
4229
+ * a genuinely new key past the size limit.
4230
+ */
4231
+ set(query: string, data: any): void;
4232
+ /**
4233
+ * Get cached result if exists and not expired.
4234
+ * On hit, re-inserts the entry so it moves to the back of the Map's
4235
+ * iteration order — turning FIFO eviction into true LRU.
4236
+ */
4237
+ get(query: string): any | null;
4238
+ /**
4239
+ * Check if query exists in cache (not expired)
4240
+ */
4241
+ has(query: string): boolean;
4242
+ /**
4243
+ * Remove a specific query from cache
4244
+ */
4245
+ delete(query: string): void;
4246
+ /**
4247
+ * Clear all cached entries
4248
+ */
4249
+ clear(): void;
4250
+ /**
4251
+ * Get cache statistics
4252
+ */
4253
+ getStats(): {
4254
+ size: number;
4255
+ queryIdCount: number;
4256
+ oldestEntryAge: number | null;
4257
+ };
4258
+ /**
4259
+ * Start periodic cleanup of expired data cache entries.
4260
+ */
4261
+ private startCleanup;
4262
+ /**
4263
+ * Encrypt a payload into a self-contained token.
4264
+ */
4265
+ private encrypt;
4266
+ /**
4267
+ * Decrypt a token back to the original payload.
4268
+ */
4269
+ private decrypt;
4270
+ /**
4271
+ * Store a query by generating an encrypted token as queryId.
4272
+ * The SQL is encrypted INTO the token — nothing stored in memory.
4273
+ * If data is provided, it's cached temporarily in the data cache.
4274
+ */
4275
+ storeQuery(query: any, data?: any): string;
4276
+ /**
4277
+ * Get a stored query by decrypting its token.
4278
+ * Returns the SQL + any cached result data.
4279
+ */
4280
+ getQuery(queryId: string): {
4281
+ query: any;
4282
+ data: any;
4283
+ } | null;
4284
+ /**
4285
+ * Update cached data for a queryId token
4286
+ */
4287
+ setQueryData(queryId: string, data: any): void;
4288
+ /**
4289
+ * Stop cleanup interval (for graceful shutdown)
4290
+ */
4291
+ destroy(): void;
4292
+ }
4293
+ declare const queryCache: QueryCache;
4294
+
4295
+ /**
4296
+ * Manages conversation history scoped per user + dashboard.
4297
+ * Each user-dashboard pair has its own isolated history that expires after a configurable TTL.
4298
+ */
4299
+ declare class DashboardConversationHistory {
4300
+ private histories;
4301
+ private ttlMs;
4302
+ private maxEntries;
4303
+ private cleanupInterval;
4304
+ constructor();
4305
+ /**
4306
+ * Set the TTL for dashboard histories
4307
+ * @param minutes - TTL in minutes
4308
+ */
4309
+ setTTL(minutes: number): void;
4310
+ /**
4311
+ * Set max entries per dashboard
4312
+ */
4313
+ setMaxEntries(max: number): void;
4314
+ /**
4315
+ * Add a conversation entry for a user's dashboard
4316
+ */
4317
+ addEntry(dashboardId: string, userPrompt: string, componentSummary: string, userId?: string): void;
4318
+ /**
4319
+ * Get formatted conversation history for a user's dashboard
4320
+ */
4321
+ getHistory(dashboardId: string, userId?: string): string;
4322
+ /**
4323
+ * Clear history for a specific user's dashboard
4324
+ */
4325
+ clearDashboard(dashboardId: string, userId?: string): void;
4326
+ /**
4327
+ * Clear all dashboard histories
4328
+ */
4329
+ clearAll(): void;
4330
+ /**
4331
+ * Start periodic cleanup of expired histories
4332
+ */
4333
+ private startCleanup;
4334
+ /**
4335
+ * Stop cleanup interval (for graceful shutdown)
4336
+ */
4337
+ destroy(): void;
4338
+ }
4339
+ declare const dashboardConversationHistory: DashboardConversationHistory;
4340
+
4341
+ /**
4342
+ * Whole-dashboard generation via Pi, a terminal coding agent — as opposed to
4343
+ * DASH_COMP_REQ's single-widget-at-a-time flow. Runs Pi in-process via its
4344
+ * SDK (createAgentSession), not as a subprocess: no shell, no argument
4345
+ * quoting, no stdin/stdout piping, none of the Windows-specific subprocess
4346
+ * issues that came with spawning the `pi` CLI directly.
4347
+ *
4348
+ * Called from sdk-nodejs/src/dashboardAgent/index.ts (DASHBOARD_AGENT_REQ),
4349
+ * which owns the generic streaming/abort machinery (mirrors USER_PROMPT_REQ)
4350
+ * and passes `signal`/`onProgress` alongside the normal params — this stays
4351
+ * within CollectionHandler's loose (params) => Promise<result> typing, no
4352
+ * change needed to that shared type.
4353
+ *
4354
+ * This mechanism is generic and reusable across any deployment. What's
4355
+ * genuinely project-specific — where AGENTS.md lives, which model to use —
4356
+ * is supplied via `DashboardAgentCollectionConfig`, with defaults sensible
4357
+ * enough that most callers don't need to override them (see below). The
4358
+ * data-source tool list and the dashboard's current state both come from
4359
+ * things sdk-nodejs already exposes generically: `sdk.getTools()` (whatever
4360
+ * this deployment registered via `sdk.setTools()`) and `sdk.callCollection
4361
+ * ('dashboards', 'query', ...)` (whatever this deployment already registered
4362
+ * under that name/shape) — no per-deployment callback needed for either.
4363
+ * Same convention on the way out: after a successful run, the prompt and the
4364
+ * full response text are handed to `sdk.callCollection('dashboard-agent-
4365
+ * conversations', 'create', ...)` if this deployment has registered one —
4366
+ * skipped silently otherwise, since conversation history is optional.
4367
+ *
4368
+ * Pi verifies every query against the live database itself (via whatever
4369
+ * local tool-execution bridge the deployment exposes, e.g. an HTTP bridge
4370
+ * on localhost), but does NOT persist the result itself — it writes the
4371
+ * finished DSL to an absolute path inside `runtimeDir`, told to it explicitly
4372
+ * in the prompt, and stops there. This handler reads that file after the run
4373
+ * finishes and returns its content as `dashboard` in the result. The caller
4374
+ * (frontend) is the one that actually saves it, via whatever authenticated
4375
+ * create/update path any other dashboard edit goes through — Pi has no user
4376
+ * session/auth context of its own, so persistence shouldn't happen from
4377
+ * inside it.
4378
+ *
4379
+ * Session persistence: the FIRST call for a dashboardId pays the full cost
4380
+ * (explore KB, discover schema, plan, verify, build). Every call after that
4381
+ * resumes the same session file (SessionManager.open) so Pi has everything
4382
+ * it already learned — it only needs to reason about the new, smaller ask,
4383
+ * not rediscover the whole dashboard from scratch. The session's file path
4384
+ * (AgentSession.sessionFile) is captured right after creation and persisted
4385
+ * in a small local file, keyed by dashboardId, inside `runtimeDir`.
4386
+ */
4387
+ interface DashboardAgentCollectionConfig {
4388
+ /**
4389
+ * Working directory Pi runs from — must contain AGENTS.md. This is a
4390
+ * version-controlled prompt file, so `cwd` is expected to live somewhere
4391
+ * like a `.prompts/` folder alongside the deployment's other prompts.
4392
+ * Default: `<process.cwd()>/.prompts/dashboard-agent` — the same
4393
+ * process.cwd()-based convention PromptLoader already uses for the main
4394
+ * agent's prompts, which needs no explicit override in the common case
4395
+ * (the backend process's own cwd already is its project root).
4396
+ */
4397
+ cwd?: string;
4398
+ /**
4399
+ * Where drafts/, the session-id map, and dashboard.log get written —
4400
+ * separate from `cwd` deliberately, so this deployment's runtime state
4401
+ * (regenerated per session, safe to gitignore) doesn't sit inside the
4402
+ * same folder as the version-controlled AGENTS.md prompt.
4403
+ * Default: `<process.cwd()>/.pi-dashboard-agent-runtime`.
4404
+ */
4405
+ runtimeDir?: string;
4406
+ /** Model provider (default: process.env.PI_AGENT_PROVIDER || 'openrouter'). */
4407
+ provider?: string;
4408
+ /** Model id (default: process.env.PI_AGENT_MODEL || 'anthropic/claude-sonnet-4.5'). */
4409
+ model?: string;
4410
+ /**
4411
+ * true (default): every request starts a brand-new pi session, with the 2
4412
+ * most recent prior responses (if any) injected into the prompt as
4413
+ * context — bounded cost per request, but pi re-explores schema/KB facts
4414
+ * it already verified in an earlier turn on this same dashboard.
4415
+ * false: resumes the same session file across requests on a given
4416
+ * dashboard — pi keeps everything it already learned, but context (and
4417
+ * cost) grows unbounded across turns (one observed turn: 2M+ cache-read
4418
+ * tokens after a handful of edits on the same dashboard).
4419
+ * Default: process.env.PI_AGENT_FRESH_SESSION !== 'false'.
4420
+ */
4421
+ freshSession?: boolean;
4422
+ }
4423
+ declare function registerDashboardAgentCollection(sdk: SuperatomSDK, config?: DashboardAgentCollectionConfig): void;
4424
+
4425
+ /**
4426
+ * ScriptMatcher — LLM-Based Script Matching + Parameter Extraction
4427
+ *
4428
+ * Uses ONE LLM call to:
4429
+ * 1. Pick the best matching script from the library (or "none")
4430
+ * 2. Extract parameter values from the user question
4431
+ *
4432
+ * Why LLM over embeddings:
4433
+ * - Embeddings capture topic similarity ("overstock" ≈ "inventory" ≈ "revenue")
4434
+ * but can't distinguish structurally different questions about the same domain
4435
+ * - LLM understands that "overstock by warehouse" needs a different script than
4436
+ * "revenue by warehouse" even though they're semantically close
4437
+ * - One call does both matching AND parameter extraction
4438
+ *
4439
+ * When script library grows past ~50, add an embedding pre-filter
4440
+ * (ChromaDB narrows to top 10 → LLM picks from those 10).
4441
+ */
4442
+
4443
+ declare class ScriptMatcher {
4444
+ private store;
4445
+ private collections?;
4446
+ private userId?;
4447
+ private trace?;
4448
+ constructor(store: ScriptStore, opts?: {
4449
+ collections?: any;
4450
+ userId?: string;
4451
+ trace?: RunTrace;
4452
+ });
4453
+ /**
4454
+ * Find the best matching script for a user question.
4455
+ * Uses ONE LLM call that picks the script AND extracts parameters.
4456
+ * Returns null if no script matches.
4457
+ *
4458
+ * Thin wrapper around `doMatch` whose only job is guaranteeing the trace
4459
+ * capture happens exactly once, on every exit path (short-circuit, normal
4460
+ * return, or the LLM call erroring) — see RunTrace.scriptMatcher.
4461
+ */
4462
+ match(userPrompt: string, apiKey?: string, model?: string, signal?: AbortSignal, activeBindings?: ScriptBinding[]): Promise<ScriptMatch | null>;
4463
+ private doMatch;
4464
+ /**
4465
+ * Renders a recipe's declared parameters the same way in every prompt
4466
+ * section (catalog, active-script, edit candidates) so the LLM sees one
4467
+ * consistent format regardless of which block a script came from.
4468
+ */
4469
+ private formatParamList;
4470
+ /**
4471
+ * Semantic search over THIS user's own past prompts (`conversation-history`
4472
+ * ChromaDB embeddings, already user-scoped) — not a project-wide name/tag
4473
+ * search. Groups hits by the recipe that answered them, so a script gets
4474
+ * ONE catalog entry carrying every matched past question, not one per hit.
4475
+ *
4476
+ * Scope is deliberate (see SCRIPT-MATCH-IMPROVEMENTS.md, Change 2): a
4477
+ * script only shows up here because THIS user has, before, asked something
4478
+ * similar that it answered — not because some other user's question did.
4479
+ */
4480
+ private searchPromptHistory;
4481
+ /**
4482
+ * Build the script catalog string for the LLM prompt from prompt-history
4483
+ * matches: each script's declared parameters PLUS the actual past questions
4484
+ * of this user's that it answered (real precedent, not a hand-written
4485
+ * description) and what params they ran with.
4486
+ */
4487
+ private buildPromptHistoryCatalog;
4488
+ /**
4489
+ * The recent script-backed answers in this thread — the bounded set an edit
4490
+ * may target. Rendered as its own prompt section (never merged into the
4491
+ * ranked catalog) so the `edit` rules have an unambiguous referent set, and
4492
+ * numbered newest-first so the prompt's "prefer the most recent when the
4493
+ * instruction is ambiguous" tie-break has something to point at.
4494
+ *
4495
+ * Each entry carries the QUESTION that produced it plus the columns it
4496
+ * returned — that is what lets the matcher resolve "use the mode for the WSP
4497
+ * one" instead of blindly taking the newest.
4498
+ */
4499
+ private buildActiveScriptBlock;
4500
+ }
4501
+
4502
+ /**
4503
+ * ScriptRunner — Execute scripts in an isolated tsx subprocess.
4504
+ *
4505
+ * The subprocess approach replaces the earlier `new Function()` eval and gives us:
4506
+ * - Real sandbox (separate process, SIGKILL on timeout).
4507
+ * - Real TypeScript (tsx transpiles on the fly).
4508
+ * - npm imports available to scripts (clustering, stats, geo, etc.).
4509
+ *
4510
+ * Protocol: NDJSON over the child's stdin/stdout. See script-ipc.ts + backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md.
4511
+ */
4512
+
4513
+ interface RunScriptOptions {
4514
+ /** Data sources the script is allowed to query via ctx.query */
4515
+ externalTools: ExternalTool[];
4516
+ /** Optional — for propagating per-query UI progress to the user */
4517
+ streamBuffer?: StreamBuffer;
4518
+ /** Override the wall-clock timeout (default `SCRIPT_TIMEOUT_MS`, 60s). */
4519
+ timeoutMs?: number;
4520
+ /**
4521
+ * Per-turn cancellation signal. When the user hits "Stop" mid-run, the child
4522
+ * process group is SIGKILLed and the run resolves as an aborted failure (the
4523
+ * caller is already unwinding, so the result is discarded).
4524
+ */
4525
+ signal?: AbortSignal;
4526
+ }
4527
+ /**
4528
+ * Execute a recipe by spawning a tsx child on the script's .ts file.
4529
+ * `scriptPath` is the absolute path to the saved `.ts` body.
4530
+ */
4531
+ declare function runScript(recipe: ScriptRecipe, scriptPath: string, params: Record<string, any>, options: RunScriptOptions): Promise<ScriptResult>;
4532
+
2202
4533
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
2203
4534
  declare class SuperatomSDK {
2204
4535
  private ws;
@@ -2215,6 +4546,7 @@ declare class SuperatomSDK {
2215
4546
  private collections;
2216
4547
  private components;
2217
4548
  private tools;
4549
+ private workflows;
2218
4550
  private anthropicApiKey;
2219
4551
  private groqApiKey;
2220
4552
  private geminiApiKey;
@@ -2222,6 +4554,10 @@ declare class SuperatomSDK {
2222
4554
  private llmProviders;
2223
4555
  private databaseType;
2224
4556
  private modelStrategy;
4557
+ private mainAgentModel;
4558
+ private sourceAgentModel;
4559
+ private dashCompModels?;
4560
+ private conversationSimilarityThreshold;
2225
4561
  private userManager;
2226
4562
  private dashboardManager;
2227
4563
  private reportManager;
@@ -2229,6 +4565,8 @@ declare class SuperatomSDK {
2229
4565
  private lastPong;
2230
4566
  private readonly PING_INTERVAL_MS;
2231
4567
  private readonly PONG_TIMEOUT_MS;
4568
+ private pendingOutbox;
4569
+ private readonly MAX_OUTBOX_SIZE;
2232
4570
  constructor(config: SuperatomSDKConfig);
2233
4571
  /**
2234
4572
  * Initialize PromptLoader and load prompts into memory
@@ -2268,9 +4606,25 @@ declare class SuperatomSDK {
2268
4606
  */
2269
4607
  private handleMessage;
2270
4608
  /**
2271
- * Send a message to the Superatom service
4609
+ * Send a message to the Superatom service.
4610
+ * Returns true if the message was sent, false if the WebSocket is not connected.
4611
+ * Does NOT throw on closed connections — callers can check the return value if needed.
2272
4612
  */
2273
- send(message: Message): void;
4613
+ send(message: Message): boolean;
4614
+ /**
4615
+ * Queue a message that couldn't be delivered because the socket was down,
4616
+ * to be resent once it reconnects. Drops the oldest entry once the bound is
4617
+ * hit — an outage long enough to fill this queue means the oldest queued
4618
+ * responses are for requests the caller has likely already given up on.
4619
+ */
4620
+ private queuePendingMessage;
4621
+ /**
4622
+ * Resend everything queued while the socket was down, now that it's back
4623
+ * up. Uses this.ws.send() directly (not send()) so a message that fails
4624
+ * again goes back through queuePendingMessage() rather than being silently
4625
+ * dropped a second time.
4626
+ */
4627
+ private flushPendingOutbox;
2274
4628
  /**
2275
4629
  * Register a message handler to receive all messages
2276
4630
  */
@@ -2310,6 +4664,14 @@ declare class SuperatomSDK {
2310
4664
  */
2311
4665
  private handlePong;
2312
4666
  private storeComponents;
4667
+ /**
4668
+ * The live, frontend-registered component catalog (name, type, description,
4669
+ * and full prop schema per component) — the same authoritative source
4670
+ * DASH_COMP_REQ's LLM prompt is built from. Exposed so other integrations
4671
+ * (e.g. the dashboard-agent script bridge) can read real component
4672
+ * contracts instead of maintaining a separate, driftable hand-written copy.
4673
+ */
4674
+ getComponents(): Component[];
2313
4675
  /**
2314
4676
  * Set tools for the SDK instance
2315
4677
  */
@@ -2318,6 +4680,29 @@ declare class SuperatomSDK {
2318
4680
  * Get the stored tools
2319
4681
  */
2320
4682
  getTools(): Tool$1[];
4683
+ /**
4684
+ * Call a registered collection operation in-process — no WebSocket
4685
+ * round-trip, since the caller is already running inside this same SDK
4686
+ * instance. Lets SDK-internal features (e.g. the dashboard agent) reuse
4687
+ * whatever collection a deployment has already registered (e.g.
4688
+ * 'dashboards'.'query') by name/convention, instead of requiring a
4689
+ * separate callback purely to re-expose data a collection already serves.
4690
+ * Throws if the collection or operation isn't registered.
4691
+ */
4692
+ callCollection<TResult = any>(collectionName: string, operation: string, params?: any): Promise<TResult>;
4693
+ /**
4694
+ * Register workflow components for the SDK instance.
4695
+ *
4696
+ * Workflows are pre-built multi-step UI flows the main agent can pick when
4697
+ * the user's prompt matches a workflow's `whenToUse` trigger. Picking a
4698
+ * workflow short-circuits analysis text + dashboard component generation —
4699
+ * the workflow component is returned directly, with the LLM-extracted props.
4700
+ */
4701
+ setWorkflows(workflows: WorkflowDescriptor[]): void;
4702
+ /**
4703
+ * Get the registered workflow components.
4704
+ */
4705
+ getWorkflows(): WorkflowDescriptor[];
2321
4706
  /**
2322
4707
  * Apply model strategy to all LLM provider singletons
2323
4708
  * @param strategy - 'best', 'fast', or 'balanced'
@@ -2332,6 +4717,20 @@ declare class SuperatomSDK {
2332
4717
  * Get current model strategy
2333
4718
  */
2334
4719
  getModelStrategy(): ModelStrategy;
4720
+ /**
4721
+ * Apply conversation similarity threshold to all LLM provider singletons
4722
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
4723
+ */
4724
+ private applyConversationSimilarityThreshold;
4725
+ /**
4726
+ * Set conversation similarity threshold at runtime
4727
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
4728
+ */
4729
+ setConversationSimilarityThreshold(threshold: number): void;
4730
+ /**
4731
+ * Get current conversation similarity threshold
4732
+ */
4733
+ getConversationSimilarityThreshold(): number;
2335
4734
  }
2336
4735
 
2337
- export { type Action, BM25L, type BM25LOptions, type BaseLLMConfig, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, type Message, type ModelStrategy, type OutputField, type RerankedResult, SDK_VERSION, STORAGE_CONFIG, SuperatomSDK, type SuperatomSDKConfig, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, type ToolOutputSchema, UIBlock, UILogCollector, type User, UserManager, type UsersData, anthropicLLM, geminiLLM, groqLLM, hybridRerank, llmUsageLogger, logger, openaiLLM, rerankChromaResults, rerankConversationResults, userPromptErrorLogger };
4736
+ 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 };