@superatomai/sdk-node 0.0.40 → 0.0.41-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,964 @@
1
1
  import { z } from 'zod';
2
2
  import Anthropic from '@anthropic-ai/sdk';
3
3
 
4
+ /**
5
+ * What getAnalysis returns. `analysis` is the narrative and `summary` the short
6
+ * bullets the markdown block binds to — siblings over one dataset, never a
7
+ * summary OF the narrative. See backend/docs/ANALYSIS-AS-PROGRAM-DESIGN.md § 4.3.
8
+ */
9
+ interface AnalysisOutput {
10
+ analysis?: string;
11
+ summary?: string[];
12
+ method?: string;
13
+ }
14
+
15
+ /**
16
+ * StreamBuffer - Buffered streaming utility for smoother text delivery
17
+ * Batches small chunks together and flushes at regular intervals
18
+ */
19
+ type StreamCallback = (chunk: string) => void;
20
+ /**
21
+ * StreamBuffer class for managing buffered streaming output
22
+ * Provides smooth text delivery by batching small chunks
23
+ */
24
+ declare class StreamBuffer {
25
+ private buffer;
26
+ private flushTimer;
27
+ private callback;
28
+ private fullText;
29
+ constructor(callback?: StreamCallback);
30
+ /**
31
+ * Check if the buffer has a callback configured
32
+ */
33
+ hasCallback(): boolean;
34
+ /**
35
+ * Get all text that has been written (including already flushed)
36
+ */
37
+ getFullText(): string;
38
+ /**
39
+ * Write a chunk to the buffer
40
+ * Large chunks or chunks with newlines are flushed immediately
41
+ * Small chunks are batched and flushed after a short interval
42
+ *
43
+ * @param chunk - Text chunk to write
44
+ */
45
+ write(chunk: string): void;
46
+ /**
47
+ * Flush the buffer immediately
48
+ * Call this before tool execution or other operations that need clean output
49
+ */
50
+ flush(): void;
51
+ /**
52
+ * Internal flush implementation
53
+ */
54
+ private flushNow;
55
+ /**
56
+ * Clean up resources
57
+ * Call this when done with the buffer
58
+ */
59
+ dispose(): void;
60
+ }
61
+
62
+ /**
63
+ * ToolExecutorService - Handles execution of SQL queries and external tools
64
+ * Extracted from BaseLLM.generateTextResponse for better separation of concerns
65
+ */
66
+
67
+ /**
68
+ * External tool definition
69
+ */
70
+ interface ExternalTool {
71
+ id: string;
72
+ name: string;
73
+ description?: string;
74
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
75
+ toolType?: 'source' | 'direct';
76
+ /** Full untruncated schema for source agent (all columns visible) */
77
+ fullSchema?: string;
78
+ /** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
79
+ schemaTier?: string;
80
+ /** Schema search function for very_large tier — keyword search over entities */
81
+ schemaSearchFn?: (keywords: string[]) => string;
82
+ /** `signal` fires when the user hits Stop mid-query — passed through to the backend's SourceTool.fn. */
83
+ fn: (input: any, signal?: AbortSignal) => Promise<any>;
84
+ limit?: number;
85
+ outputSchema?: any;
86
+ executionType?: 'immediate' | 'deferred';
87
+ userProvidedData?: any;
88
+ params?: Record<string, any>;
89
+ }
90
+ /**
91
+ * Executed tool tracking info
92
+ */
93
+ interface ExecutedToolInfo {
94
+ id: string;
95
+ name: string;
96
+ params: any;
97
+ result: {
98
+ _totalRecords: number;
99
+ _recordsShown: number;
100
+ _metadata?: any;
101
+ _sampleData: any[];
102
+ /** Bounded summary over the FULL fetched result (complete structure). */
103
+ _summary?: any;
104
+ /** Up to MAIN_AGENT_COMPLETE_ROWS rows — the complete result when small. */
105
+ _mainAgentRows?: any[];
106
+ };
107
+ outputSchema?: any;
108
+ sourceSchema?: string;
109
+ sourceType?: string;
110
+ }
111
+
112
+ /**
113
+ * Script Flow Types
114
+ *
115
+ * Defines interfaces for the script-based query architecture:
116
+ * - ScriptRecipe: metadata for matching, validation, and quality tracking
117
+ * - ScriptResult: output from executing a script
118
+ * - ScriptMatch: result from the LLM-based script matcher
119
+ */
120
+
121
+ /**
122
+ * Recipe metadata stored alongside each script.
123
+ * Used for matching, validation, and quality tracking.
124
+ */
125
+ interface ScriptRecipe {
126
+ /** Unique script identifier */
127
+ id: string;
128
+ /** Version number (incremented on regeneration) */
129
+ version: number;
130
+ /** Human-readable name (e.g., "Revenue by Dimension") */
131
+ name: string;
132
+ /** Natural language description of what this script does */
133
+ intentDescription: string;
134
+ /** Keyword tags for quick filtering */
135
+ tags: string[];
136
+ /** Source tool IDs this script queries (e.g., ["mssql-abc123_query"]) */
137
+ sourceIds: string[];
138
+ /** Table names used (for future schema drift detection) */
139
+ tables: string[];
140
+ /** Parameter definitions — what can vary */
141
+ parameters: ScriptParameter[];
142
+ /** The script function body as a string. Loaded from disk (scripts-store/<fileBase>.ts). */
143
+ scriptBody: string;
144
+ /**
145
+ * On-disk filename stem for the body: scripts-store/<fileBase>.ts.
146
+ * Editable in the IDE. Decided at authoring time (slug of `name`, with a
147
+ * short id suffix on collision) and stable across promotion.
148
+ */
149
+ fileBase?: string;
150
+ /** sha256 of the on-disk body — lets the runtime detect manual edits. */
151
+ bodyHash?: string;
152
+ /** Project scope (single-VM deployments may leave this undefined). */
153
+ projectId?: string;
154
+ /** Times this script was used successfully */
155
+ successCount: number;
156
+ /** Times this script failed */
157
+ failureCount: number;
158
+ /** ISO timestamp of last usage */
159
+ lastUsed: string;
160
+ /** Original user question that created this script */
161
+ createdFrom: string;
162
+ /** ISO timestamp */
163
+ createdAt: string;
164
+ /** ISO timestamp */
165
+ updatedAt: string;
166
+ /**
167
+ * `recipe.id` of the parent this script was forked from.
168
+ * Undefined for root scripts (those written from scratch by MainAgent).
169
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md.
170
+ */
171
+ parentId?: string;
172
+ /** 0 for root scripts; `parent.forkDepth + 1` for forks. Capped at 3. */
173
+ forkDepth?: number;
174
+ /**
175
+ * Brief description of what this fork changed vs its parent
176
+ * (sourced from the matcher's `modificationHint`).
177
+ */
178
+ forkReason?: string;
179
+ /**
180
+ * Validated component specs captured at authoring time. On a tier-high
181
+ * replay these are rebound to fresh queryIds deterministically — no
182
+ * component-generation LLM call, and the rendered columns can't drift from
183
+ * what was validated when the script was authored. Absent on recipes
184
+ * authored before this landed; those fall back to LLM component generation.
185
+ * See backend/docs/SCRIPT-COMPONENT-CONSISTENCY.md.
186
+ */
187
+ components?: ScriptComponentSpec[];
188
+ /**
189
+ * What the user explicitly asked the output to LOOK like, set by a display
190
+ * edit ("show that as a bar chart", "make the bars horizontal").
191
+ *
192
+ * Deliberately SEPARATE from `components`. Those are validated bindings that
193
+ * must be cleared on a data edit — after "break it down by brand" the axis
194
+ * keys are wrong, and after "use the mode" the stored title still says
195
+ * "Average…". A rendering CHOICE, by contrast, is still valid afterwards.
196
+ * Keeping them in one field meant every data edit silently discarded the
197
+ * user's chart type.
198
+ *
199
+ * Fed to the component generator as a hint whenever specs are (re)generated,
200
+ * so the chosen rendering comes back even after the SQL changes.
201
+ */
202
+ displayPreference?: ScriptDisplayPreference;
203
+ /**
204
+ * Lifecycle stage of this recipe on disk.
205
+ * - 'draft': written by MainAgent's write_script during a turn; filtered out
206
+ * of FTS results (status='verified' only) so the matcher never picks it.
207
+ * Filename is suffixed with `turnId` to keep concurrent turns
208
+ * from clobbering each other's drafts.
209
+ * - 'verified': promoted after `execute_script` succeeded; the matcher sees it.
210
+ * Filename drops the turn suffix unless a verified file with
211
+ * the same slug already exists (collision case keeps the suffix).
212
+ *
213
+ * Recipes loaded from disk without this field default to 'verified' so
214
+ * existing scripts keep working unchanged.
215
+ */
216
+ status?: 'draft' | 'verified';
217
+ /**
218
+ * Per-turn unique suffix used for draft filenames (e.g. `1714745623-x9k2`).
219
+ * Set when the draft is saved; carried until the recipe is promoted.
220
+ */
221
+ turnId?: string;
222
+ /**
223
+ * Last execution error captured by `recordDraftError` while the recipe was
224
+ * still a draft. Lets users open the draft .json file and see why it failed
225
+ * without grepping logs. Cleared on promotion to 'verified'.
226
+ */
227
+ lastError?: {
228
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
229
+ message: string;
230
+ at: string;
231
+ attempt: number;
232
+ };
233
+ /** userId who committed the most recent edit (audit trail — recipes are project-scoped). */
234
+ editedBy?: string;
235
+ /** The instruction that produced the current version. */
236
+ editedFrom?: string;
237
+ /**
238
+ * Prior versions, newest last. The body itself is archived on disk as
239
+ * `<fileBase>.v<version>.ts`; this records what changed and who did it.
240
+ */
241
+ history?: ScriptVersionRecord[];
242
+ }
243
+ /**
244
+ * A durable, user-stated rendering choice for a recipe. Survives data edits.
245
+ */
246
+ interface ScriptDisplayPreference {
247
+ /** Component types the user's chosen rendering resolved to, e.g. ["DynamicBarChart"]. */
248
+ componentTypes: string[];
249
+ /** The instruction itself — carries nuance the types can't ("horizontal", "sorted descending"). */
250
+ instruction: string;
251
+ /** ISO timestamp of the display edit that set this. */
252
+ at: string;
253
+ }
254
+ /** One superseded version of a recipe body (see ScriptStore.commitEdit). */
255
+ interface ScriptVersionRecord {
256
+ /** Version number this record superseded (i.e. the OLD version). */
257
+ version: number;
258
+ /** ISO timestamp of the edit that superseded it. */
259
+ at: string;
260
+ /** userId who made the edit, when known. */
261
+ by?: string;
262
+ /** The edit instruction that caused the supersede. */
263
+ instruction?: string;
264
+ /** One-line summary of what changed, for the version picker. */
265
+ changeSummary?: string;
266
+ /** sha256 of the superseded body — pairs with `<fileBase>.v<version>.ts`. */
267
+ bodyHash?: string;
268
+ }
269
+ interface ScriptParameter {
270
+ /** Parameter name (used in script body as params.name) */
271
+ name: string;
272
+ /** Parameter type */
273
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
274
+ /** Whether this parameter is required */
275
+ required: boolean;
276
+ /** Default value if not provided */
277
+ default?: any;
278
+ /** For enum type — maps user-facing values to internal values */
279
+ enumValues?: Record<string, string>;
280
+ /** Human-readable description (used in the matcher LLM prompt) */
281
+ description: string;
282
+ }
283
+ /**
284
+ * A reusable component binding captured when a script is authored. Stored on
285
+ * the recipe so tier-high replays rebuild components deterministically (rebind
286
+ * to fresh queryIds) instead of re-running the component-picker LLM.
287
+ */
288
+ interface ScriptComponentSpec {
289
+ /** Registered component name (e.g. "DynamicBarChart") — matched against the available component library. */
290
+ componentType: string;
291
+ /** `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). */
292
+ sourceRef: string;
293
+ /** Present only when sourceRef === 'federation' — the DuckDB SQL to re-execute on replay. */
294
+ federationSql?: string;
295
+ /** Present only when sourceRef === 'markdown' — the narrative text to render on replay (markdown has no data source, so its content must be persisted). */
296
+ content?: string;
297
+ title?: string;
298
+ description?: string;
299
+ /** Validated axis/value keys + aggregation — all referencing real columns of the bound source. */
300
+ config: Record<string, any>;
301
+ }
302
+ /**
303
+ * Result from executing a script via ScriptRunner.
304
+ */
305
+ interface ScriptResult {
306
+ /** Whether the script executed successfully */
307
+ success: boolean;
308
+ /** Combined data from all queries */
309
+ data: any[];
310
+ /** Program-generated narrative, when the script exports getAnalysis. */
311
+ analysis?: AnalysisOutput;
312
+ /**
313
+ * getAnalysis threw. `success` stays true — the data is valid, so the caller
314
+ * falls back to LLM prose rather than losing the answer.
315
+ */
316
+ analysisError?: string;
317
+ /** Individual query results tracked during execution */
318
+ executedQueries: ScriptQueryResult[];
319
+ /** Error message if failed */
320
+ error?: string;
321
+ /**
322
+ * Where in the lifecycle the error occurred. Lets MainAgent's fix-loop
323
+ * decide between "rewrite the whole draft" (compile) and "patch the
324
+ * specific line" (runtime).
325
+ */
326
+ errorPhase?: 'compile' | 'runtime' | 'timeout' | 'ipc';
327
+ /** Total execution time in milliseconds */
328
+ executionTimeMs: number;
329
+ }
330
+ /**
331
+ * A single query executed during script runtime.
332
+ * Tracked by ScriptContext for component generation and debugging.
333
+ */
334
+ interface ScriptQueryResult {
335
+ /** Source tool ID */
336
+ sourceId: string;
337
+ /** Human-readable source name */
338
+ sourceName: string;
339
+ /** The SQL that was executed */
340
+ sql: string;
341
+ /** Result data rows */
342
+ data: any[];
343
+ /** Number of rows returned */
344
+ count: number;
345
+ /** Total rows that matched before limit (if available) */
346
+ totalCount?: number;
347
+ /** Query execution time in milliseconds */
348
+ executionTimeMs: number;
349
+ /**
350
+ * True for rows that did NOT come from a real SQL execution — either a
351
+ * ctx.emit() dataset or the synthesized "computed:_final" entry that
352
+ * carries the script's post-JS returned data. The component generator
353
+ * uses this to route the resulting component through the script_dataset
354
+ * sentinel toolId so the frontend resolves it via the queryCache short-circuit.
355
+ */
356
+ virtual?: boolean;
357
+ }
358
+ /**
359
+ * Match tier returned by the LLM script matcher.
360
+ *
361
+ * - 'high': the script answers the question directly; only parameter values
362
+ * may differ. The runtime replays it with extracted params (cheapest path).
363
+ * - 'near': the script answers a STRUCTURALLY similar question but needs
364
+ * body modification (different metric, dimension, table, filter shape).
365
+ * The runtime forks the parent and adapts the body via MainAgent's normal
366
+ * write_script + execute_script loop — no SourceAgent dispatch needed.
367
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md for the full design.
368
+ * - 'edit': the user is INSTRUCTING a change to the script that produced the
369
+ * previous answer (not asking a new question). Only reachable when the turn
370
+ * carries a ScriptBinding — without one the matcher coerces it to 'none', so
371
+ * a prompt regression can't turn this into a loose similarity path. The
372
+ * runtime runs MainAgent in edit mode and commits the result in place.
373
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md.
374
+ * - 'none': no script is relevant; full agent flow runs.
375
+ */
376
+ type MatchTier = 'high' | 'near' | 'edit' | 'none';
377
+ /**
378
+ * Which recipe produced the answer the user is currently looking at.
379
+ *
380
+ * Set whenever a turn's answer came from a script (replay, fresh authoring, or
381
+ * a committed edit) and carried on the UIBlock + saved conversation row. Two
382
+ * consumers:
383
+ * 1. The matcher — the 'edit' tier is ONLY reachable when a binding exists, so
384
+ * "use mode instead of mean" resolves to a concrete script instead of being
385
+ * matched on keywords it shares with no script name.
386
+ * 2. Cache invalidation — after an edit commits, conversations bound to that
387
+ * recipeId must be dropped, or the exact-match cache replays the pre-edit
388
+ * answer and the edit looks like a no-op.
389
+ *
390
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
391
+ */
392
+ interface ScriptBinding {
393
+ recipeId: string;
394
+ /** Params the script ran with — the edit's starting point. */
395
+ params: Record<string, any>;
396
+ /** Recipe name at bind time (matcher catalog + user-facing confirmation). */
397
+ name: string;
398
+ /** Columns the last run returned — grounds the editor without a re-query. */
399
+ columns?: string[];
400
+ /**
401
+ * The question that produced this answer. Required for disambiguation when a
402
+ * thread ran several scripts — without it the candidates are just names and
403
+ * the matcher cannot resolve "use the mode for the WSP one".
404
+ */
405
+ userPrompt?: string;
406
+ }
407
+ /**
408
+ * Result from the LLM-based script matcher.
409
+ *
410
+ * For `tier: 'high'`, `extractedParams` carries the values to pass to the
411
+ * existing script. For `tier: 'near'`, `gaps` and `modificationHint` describe
412
+ * what the fork-author needs to change in the parent body.
413
+ */
414
+ interface ScriptMatch {
415
+ /** The matched script recipe */
416
+ recipe: ScriptRecipe;
417
+ /** Match tier — see MatchTier docs */
418
+ tier: MatchTier;
419
+ /** Similarity score (0-1, derived from LLM tier) */
420
+ similarity: number;
421
+ /**
422
+ * Legacy confidence level. Mirrors `tier === 'high'`/`'near'` for now;
423
+ * kept so existing callers compile while we migrate to tier-based logic.
424
+ */
425
+ confidence: 'high' | 'medium';
426
+ /** Parameters extracted from the user question by the LLM (tier='high') */
427
+ extractedParams?: Record<string, any>;
428
+ /**
429
+ * Proper nouns the question named, VERBATIM, with the parameter each fills.
430
+ *
431
+ * The matcher must NOT resolve these itself. Observed live: it substituted the
432
+ * customer name "PREMER ENRGES PHOTOOTAIC" into an id parameter believing that
433
+ * "the runtime will resolve the customer name to its PartyId(s)" — nothing on
434
+ * the replay path does, and `WHERE BillingPartyId IN (PREMER ENRGES
435
+ * PHOTOOTAIC)` reached SQL. Reported here, the runtime resolves them before
436
+ * replay and rejects the match when one cannot be resolved.
437
+ */
438
+ mentions?: Array<{
439
+ text: string;
440
+ param?: string;
441
+ }>;
442
+ /** Business concepts the question relies on (e.g. "outstanding balance"). */
443
+ entityTypes?: string[];
444
+ /** What the user question needs that the parent doesn't cover (tier='near') */
445
+ gaps?: string[];
446
+ /** One-sentence description of the change the fork-author should make (tier='near') */
447
+ modificationHint?: string;
448
+ /**
449
+ * Which HALF of the recipe the edit targets (tier='edit'). A recipe has two
450
+ * independently editable halves:
451
+ * - 'data' — the scriptBody: how the rows are produced (aggregation,
452
+ * filters, joins, grouping). Runs MainAgent in edit mode.
453
+ * - 'display' — the component specs: how those SAME rows are shown (chart
454
+ * type, orientation, columns, labels). Replays the proven SQL
455
+ * and regenerates the specs — never authors a script.
456
+ * Defaults to 'data' when the matcher omits it.
457
+ */
458
+ editTarget?: 'data' | 'display';
459
+ /**
460
+ * Self-contained restatement of the change the user asked for (tier='edit').
461
+ * MUST have pronouns/deixis resolved ("this", "it", "that column") — the edit
462
+ * prompt never sees the conversation history, so an unresolved instruction is
463
+ * unusable downstream.
464
+ */
465
+ editInstruction?: string;
466
+ /** Why the matcher made this choice (for logs and telemetry) */
467
+ reasoning?: string;
468
+ }
469
+
470
+ /**
471
+ * Multi-Agent Architecture Types
472
+ *
473
+ * Defines interfaces for the hierarchical agent system:
474
+ * - Main Agent: ONE LLM.streamWithTools() call with source agent tools
475
+ * - Source Agents: independent agents that query individual data sources
476
+ *
477
+ * The main agent sees only source summaries. When it calls a source tool,
478
+ * the SourceAgent runs independently (own LLM, own retries) and returns clean data.
479
+ */
480
+
481
+ /**
482
+ * Per-entity detail: name, row count, and column names.
483
+ * Gives the main agent enough context to route to the right source.
484
+ */
485
+ interface EntityDetail {
486
+ /** Entity name (table, sheet, endpoint) */
487
+ name: string;
488
+ /** Approximate row count */
489
+ rowCount?: number;
490
+ /** Column/field names */
491
+ columns: string[];
492
+ /** Entity-level semantic summary (what the table means) — for main-agent routing. */
493
+ summary?: string;
494
+ }
495
+ /**
496
+ * Representation of a data source for the main agent.
497
+ * Contains entity names WITH column names so the LLM can route accurately.
498
+ */
499
+ interface SourceSummary {
500
+ /** Source ID (matches tool ID prefix) */
501
+ id: string;
502
+ /** Human-readable source name */
503
+ name: string;
504
+ /** Source type: postgres, excel, rest_api, etc. */
505
+ type: string;
506
+ /** Brief description of what data this source contains */
507
+ description: string;
508
+ /** Detailed entity info with column names for routing */
509
+ entityDetails: EntityDetail[];
510
+ /** The tool ID associated with this source */
511
+ toolId: string;
512
+ }
513
+ /**
514
+ * What a source agent returns after querying its data source.
515
+ * The main agent uses this to analyze and compose the final response.
516
+ */
517
+ interface SourceAgentResult {
518
+ /** Source ID */
519
+ sourceId: string;
520
+ /** Source name */
521
+ sourceName: string;
522
+ /** Whether the query succeeded */
523
+ success: boolean;
524
+ /** Result data rows */
525
+ data: any[];
526
+ /** Metadata about the query execution */
527
+ metadata: SourceAgentMetadata;
528
+ /** Tool execution info for the last successful query (backward compat) */
529
+ executedTool: ExecutedToolInfo;
530
+ /** All successful tool executions (primary + follow-up queries) */
531
+ allExecutedTools?: ExecutedToolInfo[];
532
+ /** Error message if failed */
533
+ error?: string;
534
+ }
535
+ interface SourceAgentMetadata {
536
+ /** Total rows that matched the query (before limit) */
537
+ totalRowsMatched: number;
538
+ /** Rows actually returned (after limit) */
539
+ rowsReturned: number;
540
+ /** Whether the result was truncated by the row limit */
541
+ isLimited: boolean;
542
+ /** The query/params that were executed */
543
+ queryExecuted?: string;
544
+ /** Execution time in milliseconds */
545
+ executionTimeMs: number;
546
+ }
547
+ /**
548
+ * A pre-built, multi-step UI flow registered with the SDK.
549
+ *
550
+ * When the main agent decides a user's question matches a workflow's whenToUse
551
+ * trigger, it picks the workflow instead of running source agents / generating
552
+ * dashboard components. The LLM extracts the workflow's required props from the
553
+ * prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
554
+ * workflow component directly — no analysis text, no chart generation. The
555
+ * frontend renders the registered workflow component with the LLM-extracted
556
+ * props.
557
+ */
558
+ interface WorkflowDescriptor {
559
+ /** Unique workflow id (used as the LLM tool name) */
560
+ id: string;
561
+ /** Component name on the frontend (matches the registered React component) */
562
+ name: string;
563
+ /** Short human-readable description of what this workflow does */
564
+ description: string;
565
+ /**
566
+ * 1–2 sentence trigger condition. The LLM uses this to decide if the
567
+ * user's prompt matches this workflow. Be specific — e.g.
568
+ * "User wants to *initiate* an inventory transfer (review + submit POs),
569
+ * not just see analysis or charts."
570
+ */
571
+ whenToUse: string;
572
+ /**
573
+ * JSON-schema-style description of the props the workflow needs. Becomes
574
+ * the LLM tool's input_schema, so the model fills these from the prompt.
575
+ * Use the same shape as `params` on direct tools — string descriptors with
576
+ * an optional "(optional)" suffix.
577
+ *
578
+ * Example:
579
+ * ```
580
+ * {
581
+ * selectedStore: 'object — { id, name } of the source branch',
582
+ * minROI: 'number (optional) — only show transfers with ROI ≥ this',
583
+ * }
584
+ * ```
585
+ */
586
+ propsSchema: Record<string, string>;
587
+ /**
588
+ * Optional: static prop defaults merged with LLM-extracted props before
589
+ * the component is returned. Useful for things like the embedded
590
+ * `externalTool` config that the workflow uses to fetch its own data.
591
+ */
592
+ defaultProps?: Record<string, any>;
593
+ }
594
+ /**
595
+ * The workflow selection captured during a routing call.
596
+ * Set on AgentResponse when the LLM picks a workflow tool.
597
+ */
598
+ interface SelectedWorkflow {
599
+ /** Component name (matches WorkflowDescriptor.name) */
600
+ name: string;
601
+ /** Props extracted from the prompt + merged with workflow.defaultProps */
602
+ props: Record<string, any>;
603
+ }
604
+ /**
605
+ * Set when this turn applies a user-directed edit to an existing script instead
606
+ * of authoring a new one. MainAgent keeps the SAME harness (tools, loop,
607
+ * write_script/execute_script verification) and swaps only the system prompt —
608
+ * `agent-main-edit` instead of `agent-main`.
609
+ *
610
+ * The two framings contradict each other on whether to query a source first, so
611
+ * they must never be resident in one rendered prompt.
612
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § D3.
613
+ */
614
+ interface EditContext {
615
+ /** Recipe being edited — the shadow draft records it as parentId. */
616
+ recipeId: string;
617
+ parentName: string;
618
+ parentBody: string;
619
+ /** Self-contained restatement of the change (from the matcher). */
620
+ instruction: string;
621
+ /** Columns the last run returned — grounds the edit without a re-query. */
622
+ lastResultColumns?: string[];
623
+ /** Rendered parameter list of the parent, for the prompt. */
624
+ parentParams?: string;
625
+ }
626
+ /**
627
+ * The complete response from the multi-agent system.
628
+ * Contains everything needed for text display + component generation.
629
+ */
630
+ interface AgentResponse {
631
+ /** Generated text response (analysis of the data) */
632
+ text: string;
633
+ /**
634
+ * Program-generated narrative when the script exported getAnalysis. `text`
635
+ * already carries `analysis.analysis`; this also exposes `summary`, which
636
+ * the markdown block binds to instead of being an LLM summary of the prose.
637
+ */
638
+ analysis?: AnalysisOutput;
639
+ /** All executed tools across all source agents (for component generation) */
640
+ executedTools: ExecutedToolInfo[];
641
+ /** Individual results from each source agent */
642
+ sourceResults: SourceAgentResult[];
643
+ /**
644
+ * Populated when MainAgent wrote AND successfully executed a script during its turn.
645
+ * Caller (agent-user-response.ts) persists it via ScriptStore.save().
646
+ * Absent when MainAgent didn't write one (trivial question / all attempts failed).
647
+ */
648
+ savedScript?: AgentWrittenScript;
649
+ /** Failed execute_script tool_result texts this turn, in order — see RunTrace.script.failedAttempts. */
650
+ failedScriptAttempts?: string[];
651
+ /**
652
+ * Set when the LLM routed the question to a registered workflow component.
653
+ * When present, the upstream caller should skip component generation and
654
+ * return this workflow as the response.
655
+ */
656
+ workflow?: SelectedWorkflow;
657
+ /**
658
+ * Validated component specs the agent authored via `render_components`.
659
+ * When present the caller assembles the dashboard from these instead of
660
+ * running the component-generation LLM. Absent when the agent didn't call
661
+ * the tool — the caller then falls back to `generateScriptComponents`.
662
+ * See backend/docs/COMPONENT-GENERATION-V2.md §2.2.
663
+ */
664
+ componentSpecs?: ScriptComponentSpec[];
665
+ /** Layout title/description from the same `render_components` call. */
666
+ componentLayout?: {
667
+ title: string;
668
+ description?: string;
669
+ };
670
+ }
671
+ /**
672
+ * A script MainAgent authored + verified during its turn. Shape aligns with
673
+ * what ScriptStore.save() needs — minus store-assigned fields (id, timestamps, counts).
674
+ */
675
+ interface AgentWrittenScript {
676
+ /**
677
+ * `ScriptRecipe.id` of the draft that was authored + verified during this turn.
678
+ * The caller passes this to `ScriptStore.promoteToVerified(recipeId, …)` to
679
+ * flip the draft to verified status and (when possible) drop the turn-suffix
680
+ * from its filename.
681
+ */
682
+ recipeId: string;
683
+ name: string;
684
+ intentDescription: string;
685
+ tags: string[];
686
+ parameters: Array<{
687
+ name: string;
688
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
689
+ required: boolean;
690
+ default?: any;
691
+ enumValues?: Record<string, string>;
692
+ description: string;
693
+ }>;
694
+ scriptBody: string;
695
+ /** Source IDs referenced by the script (extracted from ctx.query calls) */
696
+ sourceIds: string[];
697
+ /** Tables referenced in the script's SQL (regex-extracted) */
698
+ tables: string[];
699
+ /** Executed queries from the verified run — fed to component generation */
700
+ executedQueries: Array<{
701
+ sourceId: string;
702
+ sourceName: string;
703
+ sql: string;
704
+ data: any[];
705
+ count: number;
706
+ totalCount?: number;
707
+ executionTimeMs: number;
708
+ /**
709
+ * True for synthetic entries (ctx.emit datasets, the computed:_final
710
+ * post-JS data). The component generator routes virtual sources through
711
+ * the script_dataset sentinel toolId so the frontend resolves them via
712
+ * queryCache instead of attempting to re-execute SQL.
713
+ */
714
+ virtual?: boolean;
715
+ }>;
716
+ /** The tool_result JSON MainAgent's LLM got back from execute_script — see RunTrace.script.executionResult. */
717
+ executionResult?: string;
718
+ }
719
+ /**
720
+ * Debug trace for a single chat_agent turn — which KB/schema nodes were
721
+ * retrieved and considered, and which script (if any) produced the answer.
722
+ * Persisted separately from the answer itself (fusion-5's
723
+ * `conversation_traces` table, written via `saveTrace`), never sent through
724
+ * `analyticsClient` (data-residency — see design doc §5).
725
+ */
726
+ interface RunTrace {
727
+ version: 1;
728
+ kbNodes: {
729
+ /**
730
+ * Always-on nodes included regardless of the question (getGlobalKnowledgeBase).
731
+ * `content` is the node's full text AS IT WAS at retrieval time — captured so a
732
+ * later edit/delete of the KB node doesn't erase what the LLM actually saw.
733
+ */
734
+ global: Array<{
735
+ kbId: string;
736
+ title: string;
737
+ content?: string;
738
+ }>;
739
+ /** Semantically matched for this specific question (getKnowledgeBase). Same `content` reasoning as above. */
740
+ query: Array<{
741
+ kbId: string;
742
+ title: string;
743
+ similarity?: number;
744
+ content?: string;
745
+ }>;
746
+ };
747
+ schemaNodes: {
748
+ /** MainAgent's cross-source prefilter — which sources were even considered. */
749
+ routing: Array<{
750
+ sourceId: string;
751
+ sourceName?: string;
752
+ similarity: number;
753
+ }>;
754
+ /** SourceAgent-scope per-source table resolution (MainAgent.preResolveSchema). */
755
+ preResolve: Array<{
756
+ sourceId: string;
757
+ table?: string;
758
+ description?: string;
759
+ similarity: number;
760
+ }>;
761
+ /**
762
+ * The exact {{SOURCE_SUMMARIES}} text injected into MainAgent's system prompt
763
+ * (agent-prompt-builder.ts's formatSummariesForPrompt output) — every
764
+ * registered source's catalog entry, not retrieval-specific, captured once per
765
+ * turn. This is what the main agent actually saw when deciding which source(s)
766
+ * to call.
767
+ */
768
+ mainAgentCatalog?: string;
769
+ /**
770
+ * One entry per SourceAgent dispatch (a source called twice in one turn gets
771
+ * two entries) — the exact {{FULL_SCHEMA}} text injected into that
772
+ * SourceAgent's own system prompt, however it was sourced, plus any
773
+ * search_schema follow-up lookups it made mid-conversation when the schema
774
+ * shown wasn't enough.
775
+ */
776
+ sourceAgentSchemas: Array<{
777
+ sourceId: string;
778
+ sourceName?: string;
779
+ /**
780
+ * The exact intent text MainAgent wrote for this dispatch (before the
781
+ * resolved-entities block gets appended by code — see
782
+ * buildResolvedEntitiesBlock) — what MainAgent actually asked this
783
+ * source agent to go find.
784
+ */
785
+ intent: string;
786
+ /** How `schemaText` was sourced — see SourceAgent.buildPrompt's fullSchema fallback chain. */
787
+ method: 'preresolved-embedding' | 'tool-full-schema' | 'tool-description' | 'none';
788
+ schemaText: string;
789
+ /** In call order — each search_schema tool call this SourceAgent made, and the exact result text handed back to its own LLM. */
790
+ searchSchemaLookups: Array<{
791
+ keywords: string[];
792
+ result: string;
793
+ }>;
794
+ /** The tool_result text MainAgent's LLM read back for this dispatch (formatResultForMainAgent output). */
795
+ result?: string;
796
+ }>;
797
+ };
798
+ /** The script that produced this answer, if any. Null for a general (no-tool) answer. */
799
+ script: {
800
+ /** True when an existing recipe was replayed unchanged (ScriptMatcher tier='high'). */
801
+ reused: boolean;
802
+ recipeId?: string | null;
803
+ body?: string | null;
804
+ /** Set when reused — the matcher's reasoning for picking this recipe. */
805
+ reasoning?: string | null;
806
+ /** The winning execute_script tool_result text. Only set when reused=false — a replay never re-runs execute_script. Failed attempts aren't kept. */
807
+ executionResult?: string | null;
808
+ /** Failed execute_script tool_result texts this turn, in order (before the winning one, if any). */
809
+ failedAttempts?: string[];
810
+ } | null;
811
+ /**
812
+ * `resolve_entities` tool activity this turn (see main-agent.ts's
813
+ * RESOLVE_ENTITIES_TOOL_DEF / handleResolveEntities) — names/identifiers the
814
+ * user mentioned, resolved to database ids before any SQL was written.
815
+ * Absent/empty entirely for a project with no entity-search collection
816
+ * registered, or a turn that named nothing.
817
+ */
818
+ entityResolution: {
819
+ /**
820
+ * The entity-type catalog text injected into MainAgent's system prompt
821
+ * (loadEntityCatalog's output) — what let the LLM name a concept instead
822
+ * of guessing the project's vocabulary. Captured once per turn.
823
+ */
824
+ catalogText?: string;
825
+ /**
826
+ * One entry per `resolve_entities` tool call this turn (a turn can call it
827
+ * more than once) — the FULL raw response from the entity-search
828
+ * collection, not just the trimmed {mention,entityType,instanceId,
829
+ * displayName} MainAgent keeps for itself to build the dispatch block.
830
+ * `score`/`ambiguous`/`alternatives` only exist here, nowhere else.
831
+ */
832
+ calls: Array<{
833
+ mentions: Array<{
834
+ text: string;
835
+ entityType?: string;
836
+ }>;
837
+ entityTypes: string[];
838
+ resolved: Array<{
839
+ mention: string;
840
+ entityType: string;
841
+ instanceId: string;
842
+ displayName: string;
843
+ attrs?: Record<string, any>;
844
+ score?: number;
845
+ ambiguous?: boolean;
846
+ alternatives?: Array<{
847
+ instanceId: string;
848
+ displayName: string;
849
+ score: number;
850
+ }>;
851
+ }>;
852
+ unresolved: string[];
853
+ entityMap: Record<string, any>;
854
+ unmatchedEntityTypes?: Array<{
855
+ requested: string;
856
+ candidates?: string[];
857
+ }>;
858
+ /** Set when the collection call itself failed (fails open — see handleResolveEntities). */
859
+ error?: string;
860
+ }>;
861
+ };
862
+ /**
863
+ * The prior-turn conversation context injected into this turn's prompt as
864
+ * CONVERSATION_HISTORY — exactly what each flow already builds for itself
865
+ * (chat: thread.getConversationContext(); report/dashboard: their own
866
+ * equivalents), captured as-is. Every call site sets this unconditionally
867
+ * (empty string '' when there's no prior context — new thread, or history
868
+ * trimmed to nothing), so an empty turn is visibly "no history" in the
869
+ * saved trace rather than a silently missing key. Optional only because
870
+ * traces saved before this field existed won't have it at all.
871
+ */
872
+ conversationHistory?: string;
873
+ /**
874
+ * The exact {{USER_ACCESS_CONTEXT}} text injected into MainAgent's system
875
+ * prompt — the per-user authorization config (sa-api users.config)
876
+ * rendered by buildUserAccessContext, as-is. Captured once (MainAgent's
877
+ * prompt is what SourceAgent's identical value is derived from — no need
878
+ * to duplicate it per source dispatch). Set unconditionally (empty string
879
+ * '' when there's no config for this user), so "no restrictions" is
880
+ * visible in the saved trace rather than a silently missing key. Optional
881
+ * only because traces saved before this field existed won't have it.
882
+ */
883
+ userAccessContext?: string;
884
+ }
885
+ /**
886
+ * Configuration for the multi-agent system.
887
+ * Controls limits, models, and behavior.
888
+ */
889
+ interface AgentConfig {
890
+ /** Max rows shown to the UI preview / inlined per source (default: 10) */
891
+ maxRowsPerSource: number;
892
+ /**
893
+ * Max rows a source query may FETCH from the DB server-side (default: 2000).
894
+ * Decoupled from what the main agent is shown: the full result is fetched and
895
+ * summarized (bounded), but only a small/complete slice enters LLM context.
896
+ * This lets small lookups (benchmark maps) arrive COMPLETE without letting
897
+ * large results blow up context.
898
+ */
899
+ maxRowsFetched: number;
900
+ /** Model for the main agent (routing + analysis in one LLM call) */
901
+ mainAgentModel: string;
902
+ /** Model for source agent query generation */
903
+ sourceAgentModel: string;
904
+ /** API key for LLM calls */
905
+ apiKey?: string;
906
+ /** Max retry attempts per source agent */
907
+ maxRetries: number;
908
+ /** Max tool calling iterations for the main agent loop */
909
+ maxIterations: number;
910
+ /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
911
+ globalKnowledgeBase?: string;
912
+ /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
913
+ knowledgeBaseContext?: string;
914
+ /** Per-user authorization config (sa-api users.config), rendered to text — see buildUserAccessContext */
915
+ userAccessContext?: string;
916
+ /** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
917
+ collections?: any;
918
+ /** Optional project ID for scoping embedding searches */
919
+ projectId?: string;
920
+ /**
921
+ * Optional debug-trace accumulator for this turn (Phase 1, chat_agent only).
922
+ * When present, MainAgent-scope retrieval call sites (e.g. preResolveSchema)
923
+ * push their structured results into it. Absent for callers that don't care
924
+ * about trace capture (e.g. headless flows) — every push site must treat
925
+ * this as optional and never let a capture failure affect the real answer.
926
+ */
927
+ trace?: RunTrace;
928
+ }
929
+ /**
930
+ * Default agent configuration
931
+ */
932
+ declare const DEFAULT_AGENT_CONFIG: AgentConfig;
933
+
4
934
  /**
5
935
  * Unified UIBlock structure for database storage
6
- * Used in both bookmarks and user-conversations tables
936
+ * Used in both bookmarks and user-conversations tables.
937
+ *
938
+ * `analysis` always holds whatever real narration exists — the full answer on
939
+ * success, or whatever was actually streamed before a failure (may be empty).
940
+ * `error` is a dedicated field, null on success — it can be a plain string OR
941
+ * a structured object/array (e.g. the agent's raw `errors` list), whatever
942
+ * shape the failure naturally has; it's never coerced into `analysis`.
7
943
  */
8
944
  interface DBUIBlock {
9
945
  id: string;
10
946
  component: Record<string, any> | null;
11
947
  analysis: string | null;
12
948
  user_prompt: string;
949
+ error?: unknown | null;
950
+ /**
951
+ * The script recipe that produced this answer, when one did. Read back via
952
+ * `conversation-history.exactMatch` so an edit follow-up still has a target
953
+ * after a reload (the in-memory thread is gone by then), and indexed so
954
+ * committing an edit can purge every cached answer bound to the recipe.
955
+ */
956
+ scriptBinding?: {
957
+ recipeId: string;
958
+ params?: Record<string, any>;
959
+ name?: string;
960
+ columns?: string[];
961
+ };
13
962
  }
14
963
 
15
964
  /**
@@ -59,7 +1008,18 @@ declare class Logger {
59
1008
  * Log debug message (only shown for verbose level)
60
1009
  */
61
1010
  debug(...args: any[]): void;
1011
+ /**
1012
+ * Write to log file
1013
+ */
62
1014
  file(...args: any[]): void;
1015
+ /**
1016
+ * Clear the log file (call at start of new user request)
1017
+ */
1018
+ clearFile(): void;
1019
+ /**
1020
+ * Log LLM method prompts with clear labeling
1021
+ */
1022
+ logLLMPrompt(methodName: string, promptType: 'system' | 'user', content: string | object | any[]): void;
63
1023
  }
64
1024
  declare const logger: Logger;
65
1025
 
@@ -149,6 +1109,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
149
1109
  dependencies?: string[] | undefined;
150
1110
  } | undefined;
151
1111
  props?: Record<string, any> | undefined;
1112
+ data?: Record<string, any> | undefined;
152
1113
  render?: any;
153
1114
  states?: Record<string, any> | undefined;
154
1115
  methods?: Record<string, {
@@ -159,7 +1120,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
159
1120
  fn: string;
160
1121
  deps?: string[] | undefined;
161
1122
  }[] | undefined;
162
- data?: Record<string, any> | undefined;
163
1123
  pages?: {
164
1124
  id: string;
165
1125
  name: string;
@@ -181,6 +1141,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
181
1141
  dependencies?: string[] | undefined;
182
1142
  } | undefined;
183
1143
  props?: Record<string, any> | undefined;
1144
+ data?: Record<string, any> | undefined;
184
1145
  render?: any;
185
1146
  states?: Record<string, any> | undefined;
186
1147
  methods?: Record<string, {
@@ -191,7 +1152,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
191
1152
  fn: string;
192
1153
  deps?: string[] | undefined;
193
1154
  }[] | undefined;
194
- data?: Record<string, any> | undefined;
195
1155
  pages?: {
196
1156
  id: string;
197
1157
  name: string;
@@ -217,6 +1177,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
217
1177
  dependencies?: string[] | undefined;
218
1178
  } | undefined;
219
1179
  props?: Record<string, any> | undefined;
1180
+ data?: Record<string, any> | undefined;
220
1181
  render?: any;
221
1182
  states?: Record<string, any> | undefined;
222
1183
  methods?: Record<string, {
@@ -227,7 +1188,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
227
1188
  fn: string;
228
1189
  deps?: string[] | undefined;
229
1190
  }[] | undefined;
230
- data?: Record<string, any> | undefined;
231
1191
  pages?: {
232
1192
  id: string;
233
1193
  name: string;
@@ -253,6 +1213,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
253
1213
  dependencies?: string[] | undefined;
254
1214
  } | undefined;
255
1215
  props?: Record<string, any> | undefined;
1216
+ data?: Record<string, any> | undefined;
256
1217
  render?: any;
257
1218
  states?: Record<string, any> | undefined;
258
1219
  methods?: Record<string, {
@@ -263,7 +1224,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
263
1224
  fn: string;
264
1225
  deps?: string[] | undefined;
265
1226
  }[] | undefined;
266
- data?: Record<string, any> | undefined;
267
1227
  pages?: {
268
1228
  id: string;
269
1229
  name: string;
@@ -344,6 +1304,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
344
1304
  dependencies?: string[] | undefined;
345
1305
  } | undefined;
346
1306
  props?: Record<string, any> | undefined;
1307
+ data?: Record<string, any> | undefined;
347
1308
  render?: any;
348
1309
  states?: Record<string, any> | undefined;
349
1310
  methods?: Record<string, {
@@ -354,7 +1315,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
354
1315
  fn: string;
355
1316
  deps?: string[] | undefined;
356
1317
  }[] | undefined;
357
- data?: Record<string, any> | undefined;
358
1318
  }, {
359
1319
  id: string;
360
1320
  name?: string | undefined;
@@ -368,6 +1328,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
368
1328
  dependencies?: string[] | undefined;
369
1329
  } | undefined;
370
1330
  props?: Record<string, any> | undefined;
1331
+ data?: Record<string, any> | undefined;
371
1332
  render?: any;
372
1333
  states?: Record<string, any> | undefined;
373
1334
  methods?: Record<string, {
@@ -378,7 +1339,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
378
1339
  fn: string;
379
1340
  deps?: string[] | undefined;
380
1341
  }[] | undefined;
381
- data?: Record<string, any> | undefined;
382
1342
  }>;
383
1343
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
384
1344
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -396,6 +1356,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
396
1356
  dependencies?: string[] | undefined;
397
1357
  } | undefined;
398
1358
  props?: Record<string, any> | undefined;
1359
+ data?: Record<string, any> | undefined;
399
1360
  render?: any;
400
1361
  states?: Record<string, any> | undefined;
401
1362
  methods?: Record<string, {
@@ -406,7 +1367,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
406
1367
  fn: string;
407
1368
  deps?: string[] | undefined;
408
1369
  }[] | undefined;
409
- data?: Record<string, any> | undefined;
410
1370
  };
411
1371
  data?: Record<string, any> | undefined;
412
1372
  context?: Record<string, any> | undefined;
@@ -424,6 +1384,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
424
1384
  dependencies?: string[] | undefined;
425
1385
  } | undefined;
426
1386
  props?: Record<string, any> | undefined;
1387
+ data?: Record<string, any> | undefined;
427
1388
  render?: any;
428
1389
  states?: Record<string, any> | undefined;
429
1390
  methods?: Record<string, {
@@ -434,7 +1395,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
434
1395
  fn: string;
435
1396
  deps?: string[] | undefined;
436
1397
  }[] | undefined;
437
- data?: Record<string, any> | undefined;
438
1398
  };
439
1399
  data?: Record<string, any> | undefined;
440
1400
  context?: Record<string, any> | undefined;
@@ -615,24 +1575,203 @@ declare const IncomingMessageSchema: z.ZodObject<{
615
1575
  payload?: unknown;
616
1576
  }>;
617
1577
  type IncomingMessage = z.infer<typeof IncomingMessageSchema>;
1578
+ declare const ComponentSchema: z.ZodObject<{
1579
+ id: z.ZodString;
1580
+ name: z.ZodString;
1581
+ displayName: z.ZodOptional<z.ZodString>;
1582
+ isDisplayComp: z.ZodOptional<z.ZodBoolean>;
1583
+ type: z.ZodString;
1584
+ description: z.ZodString;
1585
+ props: z.ZodObject<{
1586
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
1587
+ title: z.ZodOptional<z.ZodString>;
1588
+ description: z.ZodOptional<z.ZodString>;
1589
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1590
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
1591
+ }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
1592
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
1593
+ title: z.ZodOptional<z.ZodString>;
1594
+ description: z.ZodOptional<z.ZodString>;
1595
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1596
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
1597
+ }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
1598
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
1599
+ title: z.ZodOptional<z.ZodString>;
1600
+ description: z.ZodOptional<z.ZodString>;
1601
+ config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1602
+ actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
1603
+ }, z.ZodTypeAny, "passthrough">>;
1604
+ category: z.ZodOptional<z.ZodString>;
1605
+ keywords: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
1606
+ }, "strip", z.ZodTypeAny, {
1607
+ id: string;
1608
+ type: string;
1609
+ name: string;
1610
+ description: string;
1611
+ props: {
1612
+ description?: string | undefined;
1613
+ query?: string | {} | null | undefined;
1614
+ title?: string | undefined;
1615
+ config?: Record<string, unknown> | undefined;
1616
+ actions?: any[] | undefined;
1617
+ } & {
1618
+ [k: string]: unknown;
1619
+ };
1620
+ displayName?: string | undefined;
1621
+ isDisplayComp?: boolean | undefined;
1622
+ category?: string | undefined;
1623
+ keywords?: string[] | undefined;
1624
+ }, {
1625
+ id: string;
1626
+ type: string;
1627
+ name: string;
1628
+ description: string;
1629
+ props: {
1630
+ description?: string | undefined;
1631
+ query?: string | {} | null | undefined;
1632
+ title?: string | undefined;
1633
+ config?: Record<string, unknown> | undefined;
1634
+ actions?: any[] | undefined;
1635
+ } & {
1636
+ [k: string]: unknown;
1637
+ };
1638
+ displayName?: string | undefined;
1639
+ isDisplayComp?: boolean | undefined;
1640
+ category?: string | undefined;
1641
+ keywords?: string[] | undefined;
1642
+ }>;
1643
+ type Component = z.infer<typeof ComponentSchema>;
1644
+ declare const OutputFieldSchema: z.ZodObject<{
1645
+ name: z.ZodString;
1646
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
1647
+ description: z.ZodString;
1648
+ }, "strip", z.ZodTypeAny, {
1649
+ type: "string" | "number" | "boolean" | "date";
1650
+ name: string;
1651
+ description: string;
1652
+ }, {
1653
+ type: "string" | "number" | "boolean" | "date";
1654
+ name: string;
1655
+ description: string;
1656
+ }>;
1657
+ type OutputField = z.infer<typeof OutputFieldSchema>;
1658
+ declare const OutputSchema: z.ZodObject<{
1659
+ description: z.ZodString;
1660
+ fields: z.ZodArray<z.ZodObject<{
1661
+ name: z.ZodString;
1662
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
1663
+ description: z.ZodString;
1664
+ }, "strip", z.ZodTypeAny, {
1665
+ type: "string" | "number" | "boolean" | "date";
1666
+ name: string;
1667
+ description: string;
1668
+ }, {
1669
+ type: "string" | "number" | "boolean" | "date";
1670
+ name: string;
1671
+ description: string;
1672
+ }>, "many">;
1673
+ }, "strip", z.ZodTypeAny, {
1674
+ description: string;
1675
+ fields: {
1676
+ type: "string" | "number" | "boolean" | "date";
1677
+ name: string;
1678
+ description: string;
1679
+ }[];
1680
+ }, {
1681
+ description: string;
1682
+ fields: {
1683
+ type: "string" | "number" | "boolean" | "date";
1684
+ name: string;
1685
+ description: string;
1686
+ }[];
1687
+ }>;
1688
+ type ToolOutputSchema = z.infer<typeof OutputSchema>;
618
1689
  declare const ToolSchema: z.ZodObject<{
619
1690
  id: z.ZodString;
620
1691
  name: z.ZodString;
621
1692
  description: z.ZodString;
1693
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
1694
+ toolType: z.ZodOptional<z.ZodEnum<["source", "direct"]>>;
1695
+ /** Full untruncated schema for source agent (all columns visible) */
1696
+ fullSchema: z.ZodOptional<z.ZodString>;
622
1697
  params: z.ZodRecord<z.ZodString, z.ZodString>;
623
1698
  fn: z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodAny>;
1699
+ outputSchema: z.ZodOptional<z.ZodObject<{
1700
+ description: z.ZodString;
1701
+ fields: z.ZodArray<z.ZodObject<{
1702
+ name: z.ZodString;
1703
+ type: z.ZodEnum<["string", "number", "boolean", "date"]>;
1704
+ description: z.ZodString;
1705
+ }, "strip", z.ZodTypeAny, {
1706
+ type: "string" | "number" | "boolean" | "date";
1707
+ name: string;
1708
+ description: string;
1709
+ }, {
1710
+ type: "string" | "number" | "boolean" | "date";
1711
+ name: string;
1712
+ description: string;
1713
+ }>, "many">;
1714
+ }, "strip", z.ZodTypeAny, {
1715
+ description: string;
1716
+ fields: {
1717
+ type: "string" | "number" | "boolean" | "date";
1718
+ name: string;
1719
+ description: string;
1720
+ }[];
1721
+ }, {
1722
+ description: string;
1723
+ fields: {
1724
+ type: "string" | "number" | "boolean" | "date";
1725
+ name: string;
1726
+ description: string;
1727
+ }[];
1728
+ }>>;
1729
+ /** Cache policy. `false` = never cache (live data, write ops). Mirrors HTTP `Cache-Control: no-store`. */
1730
+ cache: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<false>, z.ZodObject<{
1731
+ ttlMs: z.ZodOptional<z.ZodNumber>;
1732
+ }, "strip", z.ZodTypeAny, {
1733
+ ttlMs?: number | undefined;
1734
+ }, {
1735
+ ttlMs?: number | undefined;
1736
+ }>]>>;
624
1737
  }, "strip", z.ZodTypeAny, {
625
1738
  id: string;
626
1739
  params: Record<string, string>;
627
1740
  name: string;
628
1741
  description: string;
629
1742
  fn: (args_0: any, ...args: unknown[]) => any;
1743
+ toolType?: "source" | "direct" | undefined;
1744
+ fullSchema?: string | undefined;
1745
+ outputSchema?: {
1746
+ description: string;
1747
+ fields: {
1748
+ type: "string" | "number" | "boolean" | "date";
1749
+ name: string;
1750
+ description: string;
1751
+ }[];
1752
+ } | undefined;
1753
+ cache?: false | {
1754
+ ttlMs?: number | undefined;
1755
+ } | undefined;
630
1756
  }, {
631
1757
  id: string;
632
1758
  params: Record<string, string>;
633
1759
  name: string;
634
1760
  description: string;
635
1761
  fn: (args_0: any, ...args: unknown[]) => any;
1762
+ toolType?: "source" | "direct" | undefined;
1763
+ fullSchema?: string | undefined;
1764
+ outputSchema?: {
1765
+ description: string;
1766
+ fields: {
1767
+ type: "string" | "number" | "boolean" | "date";
1768
+ name: string;
1769
+ description: string;
1770
+ }[];
1771
+ } | undefined;
1772
+ cache?: false | {
1773
+ ttlMs?: number | undefined;
1774
+ } | undefined;
636
1775
  }>;
637
1776
  type Tool$1 = z.infer<typeof ToolSchema>;
638
1777
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
@@ -640,11 +1779,33 @@ type CollectionHandler<TParams = any, TResult = any> = (params: TParams) => Prom
640
1779
  type LLMProvider = 'anthropic' | 'groq' | 'gemini' | 'openai';
641
1780
 
642
1781
  type DatabaseType = 'postgresql' | 'mssql' | 'snowflake' | 'mysql';
1782
+ /**
1783
+ * Model strategy for controlling which models are used for different tasks
1784
+ * - 'best': Use the best model (e.g., Sonnet) for all tasks - highest quality, higher cost
1785
+ * - 'fast': Use the fast model (e.g., Haiku) for all tasks - lower quality, lower cost
1786
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
1787
+ */
1788
+ type ModelStrategy = 'best' | 'fast' | 'balanced';
1789
+ /**
1790
+ * Model configuration for DASH_COMP flow (dashboard component picking)
1791
+ * Allows separate control of models used for component selection
1792
+ */
1793
+ interface DashCompModelConfig {
1794
+ /**
1795
+ * Primary model for DASH_COMP requests
1796
+ * Format: "provider/model-name" (e.g., "anthropic/claude-sonnet-4-5-20250929")
1797
+ */
1798
+ model?: string;
1799
+ /**
1800
+ * Fast model for simpler DASH_COMP tasks (optional)
1801
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
1802
+ */
1803
+ fastModel?: string;
1804
+ }
643
1805
  interface SuperatomSDKConfig {
644
1806
  url?: string;
645
1807
  apiKey?: string;
646
1808
  projectId: string;
647
- userId?: string;
648
1809
  type?: string;
649
1810
  bundleDir?: string;
650
1811
  promptsDir?: string;
@@ -655,22 +1816,68 @@ interface SuperatomSDKConfig {
655
1816
  OPENAI_API_KEY?: string;
656
1817
  LLM_PROVIDERS?: LLMProvider[];
657
1818
  logLevel?: LogLevel;
1819
+ /**
1820
+ * Model selection strategy for LLM API calls:
1821
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
1822
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
1823
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
1824
+ */
1825
+ modelStrategy?: ModelStrategy;
1826
+ /**
1827
+ * Model for the main agent (routing + analysis).
1828
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
1829
+ * If not set, uses the provider's default model.
1830
+ */
1831
+ mainAgentModel?: string;
1832
+ /**
1833
+ * Model for source agents (per-source query generation).
1834
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
1835
+ * If not set, uses the provider's default model.
1836
+ */
1837
+ sourceAgentModel?: string;
1838
+ /**
1839
+ * Separate model configuration for DASH_COMP flow (dashboard component picking)
1840
+ * If not provided, falls back to provider-based model selection
1841
+ */
1842
+ dashCompModels?: DashCompModelConfig;
1843
+ /**
1844
+ * Similarity threshold for conversation search (semantic matching)
1845
+ * Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
1846
+ * Higher values require closer matches, lower values allow more distant matches
1847
+ * Default: 0.8
1848
+ */
1849
+ conversationSimilarityThreshold?: number;
1850
+ /**
1851
+ * Query cache TTL (Time To Live) in minutes
1852
+ * Cached query results expire after this duration
1853
+ * Default: 5 minutes
1854
+ */
1855
+ queryCacheTTL?: number;
1856
+ /**
1857
+ * Dashboard conversation history TTL (Time To Live) in minutes
1858
+ * Per-dashboard conversation histories expire after this duration
1859
+ * Default: 30 minutes
1860
+ */
1861
+ dashboardHistoryTTL?: number;
658
1862
  }
659
1863
 
660
1864
  declare const KbNodesQueryFiltersSchema: z.ZodObject<{
661
1865
  query: z.ZodOptional<z.ZodString>;
662
1866
  category: z.ZodOptional<z.ZodString>;
663
1867
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
664
- createdBy: z.ZodOptional<z.ZodNumber>;
1868
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
1869
+ createdBy: z.ZodOptional<z.ZodString>;
665
1870
  }, "strip", z.ZodTypeAny, {
1871
+ type?: "query" | "user" | "global" | undefined;
666
1872
  query?: string | undefined;
667
1873
  category?: string | undefined;
668
- createdBy?: number | undefined;
1874
+ createdBy?: string | undefined;
669
1875
  tags?: string[] | undefined;
670
1876
  }, {
1877
+ type?: "query" | "user" | "global" | undefined;
671
1878
  query?: string | undefined;
672
1879
  category?: string | undefined;
673
- createdBy?: number | undefined;
1880
+ createdBy?: string | undefined;
674
1881
  tags?: string[] | undefined;
675
1882
  }>;
676
1883
  type KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
@@ -682,109 +1889,126 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
682
1889
  content: z.ZodOptional<z.ZodString>;
683
1890
  category: z.ZodOptional<z.ZodString>;
684
1891
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
685
- createdBy: z.ZodOptional<z.ZodNumber>;
686
- updatedBy: z.ZodOptional<z.ZodNumber>;
687
- userId: z.ZodOptional<z.ZodNumber>;
1892
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
1893
+ createdBy: z.ZodOptional<z.ZodString>;
1894
+ updatedBy: z.ZodOptional<z.ZodString>;
1895
+ userId: z.ZodOptional<z.ZodString>;
688
1896
  query: z.ZodOptional<z.ZodString>;
689
1897
  filters: z.ZodOptional<z.ZodObject<{
690
1898
  query: z.ZodOptional<z.ZodString>;
691
1899
  category: z.ZodOptional<z.ZodString>;
692
1900
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
693
- createdBy: z.ZodOptional<z.ZodNumber>;
1901
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
1902
+ createdBy: z.ZodOptional<z.ZodString>;
694
1903
  }, "strip", z.ZodTypeAny, {
1904
+ type?: "query" | "user" | "global" | undefined;
695
1905
  query?: string | undefined;
696
1906
  category?: string | undefined;
697
- createdBy?: number | undefined;
1907
+ createdBy?: string | undefined;
698
1908
  tags?: string[] | undefined;
699
1909
  }, {
1910
+ type?: "query" | "user" | "global" | undefined;
700
1911
  query?: string | undefined;
701
1912
  category?: string | undefined;
702
- createdBy?: number | undefined;
1913
+ createdBy?: string | undefined;
703
1914
  tags?: string[] | undefined;
704
1915
  }>>;
705
1916
  limit: z.ZodOptional<z.ZodNumber>;
706
1917
  offset: z.ZodOptional<z.ZodNumber>;
707
1918
  }, "strip", z.ZodTypeAny, {
708
1919
  id?: number | undefined;
1920
+ type?: "query" | "user" | "global" | undefined;
709
1921
  query?: string | undefined;
710
1922
  title?: string | undefined;
711
1923
  category?: string | undefined;
712
- userId?: number | undefined;
1924
+ userId?: string | undefined;
713
1925
  limit?: number | undefined;
714
1926
  filters?: {
1927
+ type?: "query" | "user" | "global" | undefined;
715
1928
  query?: string | undefined;
716
1929
  category?: string | undefined;
717
- createdBy?: number | undefined;
1930
+ createdBy?: string | undefined;
718
1931
  tags?: string[] | undefined;
719
1932
  } | undefined;
720
- createdBy?: number | undefined;
721
- updatedBy?: number | undefined;
1933
+ createdBy?: string | undefined;
1934
+ updatedBy?: string | undefined;
1935
+ offset?: number | undefined;
722
1936
  tags?: string[] | undefined;
723
1937
  content?: string | undefined;
724
- offset?: number | undefined;
725
1938
  }, {
726
1939
  id?: number | undefined;
1940
+ type?: "query" | "user" | "global" | undefined;
727
1941
  query?: string | undefined;
728
1942
  title?: string | undefined;
729
1943
  category?: string | undefined;
730
- userId?: number | undefined;
1944
+ userId?: string | undefined;
731
1945
  limit?: number | undefined;
732
1946
  filters?: {
1947
+ type?: "query" | "user" | "global" | undefined;
733
1948
  query?: string | undefined;
734
1949
  category?: string | undefined;
735
- createdBy?: number | undefined;
1950
+ createdBy?: string | undefined;
736
1951
  tags?: string[] | undefined;
737
1952
  } | undefined;
738
- createdBy?: number | undefined;
739
- updatedBy?: number | undefined;
1953
+ createdBy?: string | undefined;
1954
+ updatedBy?: string | undefined;
1955
+ offset?: number | undefined;
740
1956
  tags?: string[] | undefined;
741
1957
  content?: string | undefined;
742
- offset?: number | undefined;
743
1958
  }>>;
744
1959
  }, "strip", z.ZodTypeAny, {
745
- operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
1960
+ operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
746
1961
  data?: {
747
1962
  id?: number | undefined;
1963
+ type?: "query" | "user" | "global" | undefined;
748
1964
  query?: string | undefined;
749
1965
  title?: string | undefined;
750
1966
  category?: string | undefined;
751
- userId?: number | undefined;
1967
+ userId?: string | undefined;
752
1968
  limit?: number | undefined;
753
1969
  filters?: {
1970
+ type?: "query" | "user" | "global" | undefined;
754
1971
  query?: string | undefined;
755
1972
  category?: string | undefined;
756
- createdBy?: number | undefined;
1973
+ createdBy?: string | undefined;
757
1974
  tags?: string[] | undefined;
758
1975
  } | undefined;
759
- createdBy?: number | undefined;
760
- updatedBy?: number | undefined;
1976
+ createdBy?: string | undefined;
1977
+ updatedBy?: string | undefined;
1978
+ offset?: number | undefined;
761
1979
  tags?: string[] | undefined;
762
1980
  content?: string | undefined;
763
- offset?: number | undefined;
764
1981
  } | undefined;
765
1982
  }, {
766
- operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
1983
+ operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
767
1984
  data?: {
768
1985
  id?: number | undefined;
1986
+ type?: "query" | "user" | "global" | undefined;
769
1987
  query?: string | undefined;
770
1988
  title?: string | undefined;
771
1989
  category?: string | undefined;
772
- userId?: number | undefined;
1990
+ userId?: string | undefined;
773
1991
  limit?: number | undefined;
774
1992
  filters?: {
1993
+ type?: "query" | "user" | "global" | undefined;
775
1994
  query?: string | undefined;
776
1995
  category?: string | undefined;
777
- createdBy?: number | undefined;
1996
+ createdBy?: string | undefined;
778
1997
  tags?: string[] | undefined;
779
1998
  } | undefined;
780
- createdBy?: number | undefined;
781
- updatedBy?: number | undefined;
1999
+ createdBy?: string | undefined;
2000
+ updatedBy?: string | undefined;
2001
+ offset?: number | undefined;
782
2002
  tags?: string[] | undefined;
783
2003
  content?: string | undefined;
784
- offset?: number | undefined;
785
2004
  } | undefined;
786
2005
  }>;
787
2006
  type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
2007
+ interface T_RESPONSE {
2008
+ success: boolean;
2009
+ data?: any;
2010
+ errors: string[];
2011
+ }
788
2012
 
789
2013
  /**
790
2014
  * UserManager class to handle CRUD operations on users with file persistence
@@ -1045,6 +2269,534 @@ declare class ReportManager {
1045
2269
  getReportCount(): number;
1046
2270
  }
1047
2271
 
2272
+ /**
2273
+ * ScriptRecipeStore — injected metadata backend for the script flow.
2274
+ *
2275
+ * The SDK is standalone (no DB dependency). The backend implements this
2276
+ * interface over Postgres (full-text search + atomic counters) and injects it
2277
+ * via `collections['script-recipes']`, exactly like `collections['source-embeddings']`.
2278
+ * `ScriptStore` consumes it for all METADATA operations while keeping the
2279
+ * executable body on disk as scripts-store/<fileBase>.ts.
2280
+ *
2281
+ * All metadata rows are plain JSON (no scriptBody — that lives on disk).
2282
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md (#1, #3, #7).
2283
+ */
2284
+
2285
+ /** One recipe's metadata as stored in Postgres (mirrors the script_recipes table). */
2286
+ interface ScriptRecipeMetaRow {
2287
+ id: string;
2288
+ projectId?: string | null;
2289
+ version: number;
2290
+ name: string;
2291
+ intentDescription: string;
2292
+ tags: string[] | null;
2293
+ createdFrom: string | null;
2294
+ sourceIds: string[] | null;
2295
+ tables: string[] | null;
2296
+ parameters: ScriptParameter[] | null;
2297
+ components?: ScriptComponentSpec[] | null;
2298
+ displayPreference?: ScriptDisplayPreference | null;
2299
+ fileBase: string;
2300
+ bodyHash?: string | null;
2301
+ successCount: number;
2302
+ failureCount: number;
2303
+ lastUsed: string | null;
2304
+ parentId?: string | null;
2305
+ forkDepth?: number | null;
2306
+ forkReason?: string | null;
2307
+ status: 'draft' | 'verified' | string;
2308
+ turnId?: string | null;
2309
+ editedBy?: string | null;
2310
+ editedFrom?: string | null;
2311
+ history?: ScriptVersionRecord[] | null;
2312
+ lastError?: {
2313
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2314
+ message: string;
2315
+ at: string;
2316
+ attempt: number;
2317
+ } | null;
2318
+ createdAt?: string | null;
2319
+ updatedAt?: string | null;
2320
+ }
2321
+ interface ScriptRecipeStore {
2322
+ /** FTS shortlist of healthy verified recipes for the matcher (metadata only). */
2323
+ search(params: {
2324
+ prompt: string;
2325
+ projectId?: string;
2326
+ limit?: number;
2327
+ }): Promise<ScriptRecipeMetaRow[]>;
2328
+ /** Fetch one recipe by id (any status). */
2329
+ getById(id: string): Promise<ScriptRecipeMetaRow | null>;
2330
+ /** Count healthy verified recipes (drives the "any scripts?" gate). */
2331
+ count(params?: {
2332
+ projectId?: string;
2333
+ }): Promise<number>;
2334
+ /** Insert or update a recipe row (keyed by id). */
2335
+ upsert(row: ScriptRecipeMetaRow): Promise<void>;
2336
+ /** Atomically bump counters / last-used. */
2337
+ updateStats(id: string, patch: {
2338
+ successDelta?: number;
2339
+ failureDelta?: number;
2340
+ lastUsed?: string;
2341
+ }): Promise<void>;
2342
+ /** Flip a draft to verified, applying provenance + optional fork lineage. */
2343
+ promote(id: string, patch: {
2344
+ sourceIds: string[];
2345
+ tables: string[];
2346
+ fileBase?: string;
2347
+ parentId?: string;
2348
+ forkDepth?: number;
2349
+ forkReason?: string;
2350
+ components?: ScriptComponentSpec[];
2351
+ }): Promise<ScriptRecipeMetaRow | null>;
2352
+ /**
2353
+ * Commit a verified edit onto an EXISTING recipe: bump `version`, replace the
2354
+ * body-bearing metadata, append a history record, reset health counters, and
2355
+ * clear the component specs (they were validated against the old shape).
2356
+ * Returns the updated row, or null when the target is gone.
2357
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5.
2358
+ */
2359
+ commitEdit?(id: string, patch: {
2360
+ name?: string;
2361
+ intentDescription?: string;
2362
+ tags?: string[];
2363
+ parameters?: ScriptParameter[];
2364
+ bodyHash: string;
2365
+ /** New on-disk stem when the edit renamed the script; omitted otherwise. */
2366
+ fileBase?: string;
2367
+ sourceIds?: string[];
2368
+ tables?: string[];
2369
+ editedBy?: string;
2370
+ editedFrom?: string;
2371
+ historyEntry: {
2372
+ version: number;
2373
+ at: string;
2374
+ by?: string;
2375
+ instruction?: string;
2376
+ changeSummary?: string;
2377
+ bodyHash?: string;
2378
+ };
2379
+ }): Promise<ScriptRecipeMetaRow | null>;
2380
+ /** Stamp a draft's last execution error. */
2381
+ recordDraftError(id: string, err: {
2382
+ phase: string;
2383
+ message: string;
2384
+ attempt: number;
2385
+ at: string;
2386
+ }): Promise<void>;
2387
+ /** Delete a recipe row (body file removed separately). */
2388
+ remove(id: string): Promise<void>;
2389
+ /** True if `fileBase` is taken by a different recipe in this project. */
2390
+ fileBaseTaken(fileBase: string, excludeId: string, projectId?: string): Promise<boolean>;
2391
+ }
2392
+ /** Pull the injected store off the collections bag (or null if not wired). */
2393
+ declare function resolveScriptRecipeStore(collections: any): ScriptRecipeStore | null;
2394
+
2395
+ /**
2396
+ * ScriptStore — Postgres metadata + on-disk body for script recipes.
2397
+ *
2398
+ * Split of responsibilities:
2399
+ * - METADATA → injected `ScriptRecipeStore` (Postgres FTS + atomic counters),
2400
+ * resolved from `collections['script-recipes']`.
2401
+ * - BODY → scripts-store/<fileBase>.ts, editable in your IDE. Written
2402
+ * atomically (temp + rename); `bodyHash` (sha256) detects edits.
2403
+ *
2404
+ * The old "read every file every turn + send the whole catalog to the LLM"
2405
+ * matcher is gone — matching is `store.search(prompt)` (FTS shortlist). The
2406
+ * draft/verified filename dance is gone too: `status` is a DB column and the
2407
+ * file keeps a stable `<fileBase>.ts` name across promotion.
2408
+ *
2409
+ * When no metadata store is injected, the store degrades to a safe no-op
2410
+ * (count 0 → script flow disabled) instead of crashing.
2411
+ *
2412
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md.
2413
+ */
2414
+
2415
+ interface SaveDraftInput {
2416
+ /** Reuse an existing draft (retry); omit to mint a new one. */
2417
+ recipeId?: string;
2418
+ /** Per-turn unique suffix, stable across retries within the turn. */
2419
+ turnId: string;
2420
+ name: string;
2421
+ intentDescription: string;
2422
+ tags: string[];
2423
+ parameters: ScriptParameter[];
2424
+ scriptBody: string;
2425
+ createdFrom: string;
2426
+ /**
2427
+ * Set when this draft is a SHADOW of an existing recipe being edited. The
2428
+ * draft is verified independently and merged back onto the parent via
2429
+ * `commitEdit`, so the working script is never clobbered by an edit that
2430
+ * turns out not to run. See backend/docs/SCRIPT-EDIT-DESIGN.md § D5.
2431
+ */
2432
+ parentId?: string;
2433
+ }
2434
+ interface PromoteToVerifiedInput {
2435
+ sourceIds: string[];
2436
+ tables: string[];
2437
+ parentId?: string;
2438
+ forkDepth?: number;
2439
+ forkReason?: string;
2440
+ components?: ScriptComponentSpec[];
2441
+ }
2442
+ interface ScriptStoreOptions {
2443
+ /** Explicit metadata store, or resolved from `collections['script-recipes']`. */
2444
+ store?: ScriptRecipeStore | null;
2445
+ collections?: any;
2446
+ /** Body directory (defaults to <cwd>/scripts-store). */
2447
+ baseDir?: string;
2448
+ /** Project scope stamped on every row. */
2449
+ projectId?: string;
2450
+ }
2451
+ declare function normalizeScriptBody(scriptBody: string): string;
2452
+ declare class ScriptStore {
2453
+ private store;
2454
+ private storeDir;
2455
+ private projectId?;
2456
+ constructor(opts?: ScriptStoreOptions);
2457
+ /** Whether a metadata store is wired (matcher / authoring are gated on this). */
2458
+ hasStore(): boolean;
2459
+ /** Number of healthy verified recipes (gates the script-matching path). */
2460
+ count(): Promise<number>;
2461
+ /**
2462
+ * FTS shortlist for the matcher (metadata only — bodies are loaded lazily by
2463
+ * `get()` once the LLM picks one). Returns verified, healthy recipes ranked
2464
+ * by relevance.
2465
+ */
2466
+ search(prompt: string, limit?: number): Promise<ScriptRecipe[]>;
2467
+ /** Fetch one recipe by id with its body loaded from disk. */
2468
+ get(id: string): Promise<ScriptRecipe | null>;
2469
+ /** Create or update a recipe (metadata upsert + body write when changed). */
2470
+ save(recipe: ScriptRecipe): Promise<void>;
2471
+ /**
2472
+ * Persist (or update) a draft. Within a turn, retries that pass the same
2473
+ * `recipeId` overwrite the same row + file; a fresh `recipeId` mints a new
2474
+ * draft. The body is visible at scripts-store/<fileBase>.ts immediately.
2475
+ */
2476
+ saveDraft(input: SaveDraftInput): Promise<ScriptRecipe>;
2477
+ /** Stamp a draft's last execution error (metadata only). */
2478
+ recordDraftError(recipeId: string, err: {
2479
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2480
+ message: string;
2481
+ attempt: number;
2482
+ }): Promise<void>;
2483
+ /**
2484
+ * Promote a successfully-executed draft into a verified script.
2485
+ * The on-disk body already exists at <fileBase>.ts (written at write_script
2486
+ * time) and keeps its name — only the DB row flips status + provenance.
2487
+ */
2488
+ promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): Promise<ScriptRecipe | null>;
2489
+ /**
2490
+ * Commit a user-directed edit: merge a VERIFIED shadow draft back onto the
2491
+ * recipe it was editing, as version N+1 under the SAME recipe id.
2492
+ *
2493
+ * Keeping the id stable is the point of the whole feature — every cached
2494
+ * conversation, `script_dataset` regeneration descriptor and persisted
2495
+ * component spec already points at it, so the correction applies retroactively
2496
+ * to replays instead of stranding them on the old body.
2497
+ *
2498
+ * Steps (see backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5):
2499
+ * 1. archive the current body as `<fileBase>.v<version>.ts`
2500
+ * 2. write the edited body to the original fileBase (atomic)
2501
+ * 3. version++, copy name/description/params, append a history record
2502
+ * 4. reset health counters — the pre-edit failure history is stale
2503
+ * 5. clear component specs — they were validated against the OLD shape
2504
+ * 6. delete the shadow draft (row + file)
2505
+ *
2506
+ * Returns the updated recipe, or null when the commit could not be applied
2507
+ * (caller should then fall back to treating the draft as a new script).
2508
+ */
2509
+ commitEdit(targetId: string, draft: {
2510
+ recipeId: string;
2511
+ name?: string;
2512
+ intentDescription?: string;
2513
+ tags?: string[];
2514
+ parameters?: ScriptParameter[];
2515
+ scriptBody: string;
2516
+ sourceIds?: string[];
2517
+ tables?: string[];
2518
+ }, meta: {
2519
+ instruction?: string;
2520
+ changeSummary?: string;
2521
+ editedBy?: string;
2522
+ }): Promise<ScriptRecipe | null>;
2523
+ /**
2524
+ * Drop a draft (row + body file). MainAgent calls this at end-of-turn when a
2525
+ * draft was authored but never verified — failed drafts are never matched, so
2526
+ * deleting them immediately avoids unbounded accumulation (#5). No-op if the
2527
+ * recipe isn't a draft (so a promoted/verified script is never removed here).
2528
+ */
2529
+ discardDraft(recipeId: string): Promise<void>;
2530
+ /** Delete a recipe (row + body file). */
2531
+ delete(id: string): Promise<void>;
2532
+ /** Record a successful execution (atomic counter bump). */
2533
+ recordSuccess(id: string): Promise<void>;
2534
+ /** Record a failed execution (atomic counter bump). */
2535
+ recordFailure(id: string): Promise<void>;
2536
+ /** Absolute path to the .ts body for a recipe (used by the runner/MainAgent). */
2537
+ getScriptPath(recipe: ScriptRecipe): string;
2538
+ private removeById;
2539
+ private rowToRecipe;
2540
+ private recipeToRow;
2541
+ /** slug of name, with a short id suffix when the bare slug is already taken. */
2542
+ private computeFileBase;
2543
+ private toSlug;
2544
+ private hash;
2545
+ /**
2546
+ * Append (or replace) the `getAnalysis` export on an existing draft body.
2547
+ *
2548
+ * The narrative is authored AFTER execution, so it lands on a file that
2549
+ * already holds a working getData — rewriting the whole body would risk
2550
+ * losing the query that just succeeded. Replaces any earlier getAnalysis so
2551
+ * a retry does not stack duplicate exports.
2552
+ */
2553
+ attachAnalysis(recipeId: string, analysisBody: string): Promise<boolean>;
2554
+ private bodyPath;
2555
+ private readBody;
2556
+ /** Directory holding superseded bodies. Dot-prefixed so IDEs/`ls` hide it. */
2557
+ private get archiveDir();
2558
+ /**
2559
+ * Archive a superseded body as `.versions/<fileBase>.v<n>.ts`.
2560
+ *
2561
+ * Kept out of the main store directory on purpose — see commitEdit step 1.
2562
+ * To roll back: copy the file back over `scripts-store/<fileBase>.ts`.
2563
+ */
2564
+ private writeArchive;
2565
+ /**
2566
+ * Move a recipe's archived versions to a new prefix when its fileBase changes,
2567
+ * so all versions of one recipe stay grouped. Without this, two renames would
2568
+ * scatter a single recipe's history across three prefixes in `.versions/` with
2569
+ * nothing linking them back to the live script.
2570
+ */
2571
+ private renameArchives;
2572
+ /** Atomic body write (temp + rename) so concurrent reads never see a partial file. */
2573
+ private writeBody;
2574
+ private unlinkBody;
2575
+ }
2576
+
2577
+ /**
2578
+ * Main Agent (Orchestrator)
2579
+ *
2580
+ * A single LLM.streamWithTools() call that handles everything:
2581
+ * - Routing: decides which source(s) to query based on summaries
2582
+ * - Querying: calls source tools (each wraps an independent SourceAgent)
2583
+ * - Direct tools: calls pre-built function tools directly with LLM-provided params
2584
+ * - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
2585
+ * - Analysis: generates final text response from the data
2586
+ *
2587
+ * Two tool types:
2588
+ * - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
2589
+ * - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
2590
+ */
2591
+
2592
+ declare class MainAgent {
2593
+ private externalTools;
2594
+ private workflows;
2595
+ private config;
2596
+ private streamBuffer;
2597
+ /**
2598
+ * Optional: when provided, MainAgent exposes the `write_script` /
2599
+ * `execute_script` tools to the LLM and persists drafts to disk via the
2600
+ * store. Headless callers (alert analyzer, metric resolver) omit these to
2601
+ * suppress script authoring entirely — drafts would otherwise leak onto
2602
+ * disk with no caller to promote or clean them up.
2603
+ */
2604
+ private scriptStore;
2605
+ private turnId;
2606
+ private createdFromPrompt;
2607
+ private scriptState;
2608
+ /** Answer-flow component catalog (filtered + projected by the caller). */
2609
+ private componentCatalog;
2610
+ /** Specs accepted by `render_components` this turn; empty until it succeeds. */
2611
+ /**
2612
+ * Entities resolved this turn, appended verbatim to every source dispatch.
2613
+ *
2614
+ * Not left to the model to copy into its intent prose: observed live, the
2615
+ * MainAgent wrote names instead of ids on the first dispatch AND re-spelled
2616
+ * 'F D C LIMITED' as 'FDC Limited', so the source agent fell back to
2617
+ * `PartyName LIKE '%FDC%'` and found 2 of 3 customers. Carrying the ids
2618
+ * structurally makes that impossible rather than instruction-dependent.
2619
+ */
2620
+ private resolvedEntities;
2621
+ private componentSpecs;
2622
+ private componentLayout;
2623
+ private renderComponentAttempts;
2624
+ /**
2625
+ * Fork mode — set when this turn is adapting a near-matching parent script.
2626
+ * In fork mode there is no legitimate "answer with bare text" outcome: the
2627
+ * only correct first move is a tool call (write_script, or a source tool for
2628
+ * schema discovery). We therefore force tool use on the first LLM iteration
2629
+ * so the model can't end its turn with a bare "I'll adapt…" preamble and zero
2630
+ * tool calls. Never set on the fresh-authoring / general-question path.
2631
+ */
2632
+ private forkMode;
2633
+ /**
2634
+ * Edit mode — set when this turn applies a user-directed change to an
2635
+ * existing script. Swaps the system prompt to `agent-main-edit` and stamps
2636
+ * the shadow draft's parentId. Like fork mode there is no legitimate
2637
+ * "answer with bare text" outcome, so tool use is forced on iteration 1.
2638
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 4.
2639
+ */
2640
+ private editContext;
2641
+ /**
2642
+ * Per-turn cancellation signal (user hit "Stop"). Set at the top of
2643
+ * handleQuestion and read by the tool handler, the SourceAgent dispatch, and
2644
+ * the script subprocess so an abort tears down every layer of the turn.
2645
+ */
2646
+ private abortSignal?;
2647
+ constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[], forkMode?: boolean, editContext?: EditContext, componentCatalog?: Component[]);
2648
+ /** True when the turn is applying a user-directed script edit. */
2649
+ private get editMode();
2650
+ private get scriptingEnabled();
2651
+ /**
2652
+ * Handle a user question using the multi-agent system.
2653
+ *
2654
+ * This is ONE LLM.streamWithTools() call. The LLM:
2655
+ * 1. Sees source summaries + direct tool descriptions in system prompt
2656
+ * 2. Decides which tool(s) to call (routing)
2657
+ * 3. Source tools → SourceAgent runs independently → returns data
2658
+ * 4. Direct tools → fn() called directly with LLM params → returns data
2659
+ * 5. Generates final analysis text
2660
+ */
2661
+ handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, signal?: AbortSignal): Promise<AgentResponse>;
2662
+ /**
2663
+ * Tool definition, with the catalog rendered from the registered `Metadata`
2664
+ * the caller passed in. Generated rather than hand-written so it cannot drift
2665
+ * from what the frontend actually ships.
2666
+ */
2667
+ private buildRenderComponentsToolDef;
2668
+ /**
2669
+ * Validate the agent's component picks against the REAL columns of each bound
2670
+ * dataset. All-or-nothing: any error rejects the whole call and returns the
2671
+ * findings, because a partially-accepted dashboard makes the retry ambiguous.
2672
+ */
2673
+ private handleRenderComponents;
2674
+ /**
2675
+ * Author the answer as a program. Runs after execute_script, so the body is
2676
+ * written with the result already known and can react to what it found.
2677
+ *
2678
+ * Rejects a body that types numbers rather than computing them — see
2679
+ * analysis-lint. A hardcoded figure is worse than prose: it freezes into the
2680
+ * recipe and replays unchanged while the data moves underneath it.
2681
+ */
2682
+ private handleWriteAnalysis;
2683
+ private handleWriteScript;
2684
+ private handleExecuteScript;
2685
+ /**
2686
+ * Build the AgentWrittenScript payload the caller will hand to
2687
+ * `ScriptStore.promoteToVerified()`. Only returned when a verified
2688
+ * successful execution is on record.
2689
+ */
2690
+ private buildSavedScript;
2691
+ private normalizeParameterList;
2692
+ /**
2693
+ * Use the schema embedding collection to pre-select relevant tables for
2694
+ * this source + intent. Returns a formatted schema block if confidence is
2695
+ * high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
2696
+ *
2697
+ * When this returns a block, we can skip the SourceAgent's `search_schema`
2698
+ * loop and reduce iteration budget. When it returns null, the SourceAgent
2699
+ * falls back to the existing LLM-driven keyword search (same as today).
2700
+ */
2701
+ /**
2702
+ * Ids + verbatim names for everything resolved this turn, appended by CODE to
2703
+ * each source dispatch so neither omission nor re-spelling by the model can
2704
+ * lose them. Empty string when nothing was resolved, so intents are untouched
2705
+ * for questions that name no entities.
2706
+ *
2707
+ * Also appends `attrs.scopeSql` when the resolved instance carries one —
2708
+ * same "guaranteed by code" reasoning as the ids/names above, extended to
2709
+ * the one attrs field with a documented, cross-entity-type meaning: a
2710
+ * ready-made SQL predicate an entity's index precomputed (see
2711
+ * ENTITY-SEARCH-DESIGN.md's hierarchy-broadening pattern — branch/region/
2712
+ * state entity types attach it so a lane/route question never needs its
2713
+ * own city-matching join). Confirmed real cost of not doing this: a
2714
+ * branch/state resolved with scopeSql sat unused while the source agent
2715
+ * spent 4 failed exploratory queries rediscovering the exact same
2716
+ * branch-id list by hand (Invalid column name 'StateName'/'CityId'/
2717
+ * 'OrganizationLocationId', in that order, ~144s, before landing on ids
2718
+ * that were sitting in scopeSql from the very first resolve_entities
2719
+ * call). Other attrs (code, counts, etc.) are not dumped here — they are
2720
+ * descriptive, not actionable the way a precomputed predicate is, and
2721
+ * bloating every dispatch with all of them for no clear gain isn't worth
2722
+ * it; scopeSql is the one thing worth this guarantee today.
2723
+ */
2724
+ private buildResolvedEntitiesBlock;
2725
+ /** True when the backend registered the entity-search collection. */
2726
+ private get entitySearchEnabled();
2727
+ /**
2728
+ * Compact catalog (type + gloss) for the system prompt. This is what lets the
2729
+ * LLM NAME a concept instead of guessing at our vocabulary — it can infer
2730
+ * that a question is about unpaid money, but not that we call that
2731
+ * `outstanding-balance`. Full `resolution` detail is fetched by the tool.
2732
+ *
2733
+ * Deliberately NOT cached in-process. The token cost is already handled by
2734
+ * prompt caching (the system prompt carries a cache_control breakpoint), and
2735
+ * re-reading a tiny PK-ordered table costs ~nothing. Fetching fresh does not
2736
+ * weaken the prompt cache either: unchanged data renders byte-identical text,
2737
+ * so the prefix still hits. A process cache would only buy a staleness window
2738
+ * in which a newly indexed entity is invisible to the agent.
2739
+ */
2740
+ private loadEntityCatalog;
2741
+ /**
2742
+ * Never throws: a resolver outage must degrade to "nothing resolved" and
2743
+ * leave the agent exactly as it was, not take the whole answer down.
2744
+ */
2745
+ private handleResolveEntities;
2746
+ private preResolveSchema;
2747
+ /**
2748
+ * Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
2749
+ */
2750
+ private handleDirectTool;
2751
+ /**
2752
+ * Build the main agent's system prompt with source summaries, direct tool descriptions,
2753
+ * and workflow component descriptions.
2754
+ */
2755
+ private buildSystemPrompt;
2756
+ /**
2757
+ * Build tool definitions for source tools — summary-only descriptions.
2758
+ * The full schema is inside the SourceAgent which runs independently.
2759
+ */
2760
+ private buildSourceToolDefinitions;
2761
+ /**
2762
+ * Build tool definitions for direct tools — expose their actual params.
2763
+ * These are called directly by the main agent LLM, no SourceAgent.
2764
+ */
2765
+ private buildDirectToolDefinitions;
2766
+ /**
2767
+ * Capture a workflow selection. We do NOT execute anything — the LLM has
2768
+ * already extracted the props it wants the workflow rendered with. We
2769
+ * record the selection (via the capture callback) and return a short
2770
+ * acknowledgement so the LLM ends its turn cleanly without writing
2771
+ * analysis text or calling more tools.
2772
+ */
2773
+ private handleWorkflow;
2774
+ /**
2775
+ * Build LLM tool definitions for workflow components. The workflow's
2776
+ * propsSchema becomes the tool's input_schema so the LLM extracts props
2777
+ * directly from the prompt — same mechanic as direct tools.
2778
+ */
2779
+ private buildWorkflowToolDefinitions;
2780
+ /**
2781
+ * Format a source agent's result as a clean string for the main agent LLM.
2782
+ */
2783
+ private formatResultForMainAgent;
2784
+ /**
2785
+ * Get source summaries (for external inspection/debugging).
2786
+ */
2787
+ getSourceSummaries(): SourceSummary[];
2788
+ }
2789
+
2790
+ /**
2791
+ * Represents an action that can be performed on a UIBlock
2792
+ */
2793
+ interface Action {
2794
+ id: string;
2795
+ name: string;
2796
+ type: string;
2797
+ [key: string]: any;
2798
+ }
2799
+
1048
2800
  type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
1049
2801
  interface LLMMessages {
1050
2802
  sys: SystemPrompt;
@@ -1057,7 +2809,45 @@ interface LLMOptions {
1057
2809
  temperature?: number;
1058
2810
  topP?: number;
1059
2811
  apiKey?: string;
2812
+ baseURL?: string;
1060
2813
  partial?: (chunk: string) => void;
2814
+ /**
2815
+ * Per-request cancellation. When the caller aborts this signal (user hit
2816
+ * "Stop"), the underlying provider request is cancelled and the call throws
2817
+ * a RequestAbortedError. Threaded into the provider `messages.create` request
2818
+ * options and checked between tool-loop iterations. Currently honored on the
2819
+ * Anthropic path (the agent flow's default provider).
2820
+ */
2821
+ signal?: AbortSignal;
2822
+ /**
2823
+ * Forces a tool call on the FIRST iteration of streamWithTools only
2824
+ * (subsequent iterations revert to auto). Used by fork mode to stop the
2825
+ * model from ending its turn with a bare "I'll adapt the script…" preamble
2826
+ * and zero tool calls. `{ type: 'any' }` lets the model pick which tool
2827
+ * (write_script in the common case, a source tool for schema discovery);
2828
+ * `{ type: 'tool', name }` pins a specific tool. Honored on both the
2829
+ * Anthropic path and the OpenAI/OpenRouter path (mapped to OpenAI's
2830
+ * tool_choice: 'required' / a named function).
2831
+ */
2832
+ firstIterationToolChoice?: {
2833
+ type: 'any';
2834
+ } | {
2835
+ type: 'tool';
2836
+ name: string;
2837
+ };
2838
+ /**
2839
+ * Internal — set only by the OpenRouter wrappers when the target is a Claude
2840
+ * model. Tells the OpenAI-wire path to emit Anthropic `cache_control`
2841
+ * breakpoints (OpenRouter forwards them to Anthropic for prompt caching).
2842
+ * Never set for direct OpenAI/Groq calls, so their requests are unchanged.
2843
+ */
2844
+ _openrouterClaudeCaching?: boolean;
2845
+ /**
2846
+ * Internal — OpenRouter provider-routing preferences (forwarded as the
2847
+ * `provider` body field). Set by the OpenRouter wrappers to steer routing to
2848
+ * a fast backend (e.g. {sort:'throughput'}). Never set for direct OpenAI/Groq.
2849
+ */
2850
+ _openrouterProvider?: Record<string, unknown>;
1061
2851
  }
1062
2852
  interface Tool {
1063
2853
  name: string;
@@ -1079,6 +2869,16 @@ declare class LLM {
1079
2869
  * @returns Normalized system prompt for Anthropic API
1080
2870
  */
1081
2871
  private static _normalizeSystemPrompt;
2872
+ /**
2873
+ * Strip unpaired UTF-16 surrogates from every text field of a message set.
2874
+ *
2875
+ * A lone surrogate (from mid-pair string slicing or corrupt source data)
2876
+ * serializes to a bare `\udXXX` escape that strict JSON parsers — including
2877
+ * the one on Anthropic's API — reject with "no low surrogate in string",
2878
+ * failing the whole request. Sanitizing here, at the single boundary every
2879
+ * provider call flows through, guarantees no request can carry one.
2880
+ */
2881
+ private static _sanitizeMessages;
1082
2882
  /**
1083
2883
  * Log cache usage metrics from Anthropic API response
1084
2884
  * Shows cache hits, costs, and savings
@@ -1095,16 +2895,76 @@ declare class LLM {
1095
2895
  * "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
1096
2896
  */
1097
2897
  private static _parseModel;
2898
+ /**
2899
+ * Map an Anthropic model id (e.g. "claude-sonnet-4-5-20250929") to the OpenRouter slug
2900
+ * (e.g. "claude-sonnet-4.5"). OpenRouter slugs drop the date suffix and use dotted versions.
2901
+ */
2902
+ private static _toOpenRouterSlug;
2903
+ /**
2904
+ * Per-provider proxy base URL. Returns `${SUPERATOM_LLM_PROXY_URL}/<provider>`
2905
+ * when our Cloudflare LLM proxy is configured, else undefined (→ talk to the
2906
+ * provider directly, legacy behaviour). An explicit options.baseURL (e.g.
2907
+ * OpenRouter) always wins and is never overridden. See backend/docs/llm-proxy.md.
2908
+ */
2909
+ private static _proxyBaseURL;
2910
+ private static _openrouterOptions;
2911
+ private static _isRetryableProviderError;
2912
+ private static _withOpenrouterRetry;
2913
+ private static _openrouterText;
2914
+ private static _openrouterStream;
2915
+ private static _openrouterStreamWithTools;
2916
+ /**
2917
+ * Build an Anthropic client. Routes through our Cloudflare LLM proxy when
2918
+ * SUPERATOM_LLM_PROXY_URL is set (each client ships a per-client proxy key as
2919
+ * ANTHROPIC_API_KEY and never holds the real key); otherwise talks to
2920
+ * api.anthropic.com directly. See backend/docs/llm-proxy.md.
2921
+ */
2922
+ private static _anthropicClient;
2923
+ /** True when OpenRouter is configured as a fail-open fallback for Claude. */
2924
+ private static _openrouterAvailable;
2925
+ /** Remap an Anthropic model id to the OpenRouter model path for fail-open. */
2926
+ private static _anthropicFallbackModel;
1098
2927
  private static _anthropicText;
1099
2928
  private static _anthropicStream;
1100
2929
  private static _anthropicStreamWithTools;
1101
2930
  private static _groqText;
1102
2931
  private static _groqStream;
2932
+ /**
2933
+ * Gemini request options carrying the proxy base URL, or undefined → talk to
2934
+ * generativelanguage.googleapis.com directly. The Google SDK takes baseUrl as a
2935
+ * per-model request option, not a constructor arg. See backend/docs/llm-proxy.md.
2936
+ */
2937
+ private static _geminiRequestOptions;
1103
2938
  private static _geminiText;
1104
2939
  private static _geminiStream;
2940
+ /**
2941
+ * Recursively strip unsupported JSON Schema properties for Gemini
2942
+ * Gemini doesn't support: additionalProperties, $schema, etc.
2943
+ */
2944
+ private static _cleanSchemaForGemini;
1105
2945
  private static _geminiStreamWithTools;
2946
+ /** True for Anthropic/Claude model ids — gates OpenRouter prompt caching. */
2947
+ private static _isClaudeModel;
2948
+ /**
2949
+ * Build the OpenAI-wire system message. For OpenRouter + Claude
2950
+ * (cacheClaude=true) it emits content parts carrying Anthropic
2951
+ * `cache_control` breakpoints (preserving any the caller set, else marking
2952
+ * the last block), so OpenRouter forwards them to Anthropic for prompt
2953
+ * caching. Otherwise it returns a plain flattened string — unchanged for
2954
+ * direct OpenAI/Groq.
2955
+ */
2956
+ private static _openaiSystemMessage;
2957
+ /**
2958
+ * Split an OpenAI-wire usage object. `prompt_tokens` INCLUDES cached tokens,
2959
+ * so we subtract them out (Anthropic-style: input excludes cache reads) and
2960
+ * report cached separately — this makes calculateCost price cache reads at
2961
+ * the discounted rate and reflects OpenRouter prompt-cache savings in logs.
2962
+ */
2963
+ private static _openaiUsage;
1106
2964
  private static _openaiText;
1107
2965
  private static _openaiStream;
2966
+ /** Map the Anthropic-style firstIterationToolChoice to OpenAI's tool_choice. */
2967
+ private static _openaiToolChoice;
1108
2968
  private static _openaiStreamWithTools;
1109
2969
  /**
1110
2970
  * Parse JSON string, handling markdown code blocks and surrounding text
@@ -1194,16 +3054,6 @@ declare class UILogCollector {
1194
3054
  setUIBlockId(uiBlockId: string): void;
1195
3055
  }
1196
3056
 
1197
- /**
1198
- * Represents an action that can be performed on a UIBlock
1199
- */
1200
- interface Action {
1201
- id: string;
1202
- name: string;
1203
- type: string;
1204
- [key: string]: any;
1205
- }
1206
-
1207
3057
  /**
1208
3058
  * UIBlock represents a single user and assistant message block in a thread
1209
3059
  * Contains user question, component metadata, component data, text response, and available actions
@@ -1216,6 +3066,13 @@ declare class UIBlock {
1216
3066
  private textResponse;
1217
3067
  private actions;
1218
3068
  private createdAt;
3069
+ /**
3070
+ * Which script recipe produced this answer, when a script did. Read on the
3071
+ * NEXT turn so the user can say "use mode instead" and have the matcher
3072
+ * resolve it to a concrete script (the `edit` tier is unreachable without it).
3073
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3074
+ */
3075
+ private scriptBinding;
1219
3076
  /**
1220
3077
  * Creates a new UIBlock instance
1221
3078
  * @param userQuestion - The user's question or input
@@ -1310,6 +3167,14 @@ declare class UIBlock {
1310
3167
  /**
1311
3168
  * Get creation timestamp
1312
3169
  */
3170
+ /**
3171
+ * Bind this block to the script recipe that produced its answer.
3172
+ */
3173
+ setScriptBinding(binding: Record<string, any> | null): void;
3174
+ /**
3175
+ * The script recipe bound to this block, if any.
3176
+ */
3177
+ getScriptBinding(): Record<string, any> | null;
1313
3178
  getCreatedAt(): Date;
1314
3179
  /**
1315
3180
  * Convert UIBlock to JSON-serializable object
@@ -1377,6 +3242,32 @@ declare class Thread {
1377
3242
  * @param currentUIBlockId - ID of current UIBlock to exclude from context (optional)
1378
3243
  * @returns Formatted conversation history string
1379
3244
  */
3245
+ /**
3246
+ * The script recipe bound to the most recent completed UIBlock — i.e. the
3247
+ * script behind the answer the user is currently looking at. Drives the
3248
+ * matcher's `edit` tier: without it, "use mode instead" has no target and
3249
+ * falls through to regeneration.
3250
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3251
+ */
3252
+ getActiveScriptBinding(currentUIBlockId?: string): Record<string, any> | null;
3253
+ /**
3254
+ * The recent script-backed answers in this thread, newest first — the
3255
+ * candidate set a user-directed edit can target.
3256
+ *
3257
+ * Returning several rather than only the newest is what lets an instruction
3258
+ * name its own target ("use the mode for the WSP one"). With a single
3259
+ * candidate every edit lands on the most recent script, which silently edits
3260
+ * the wrong recipe whenever the user meant an earlier one.
3261
+ *
3262
+ * Deduped by recipeId (newest occurrence wins) so a long editing session on
3263
+ * one script doesn't crowd out the others. Each entry carries the question
3264
+ * that produced it — without that the candidates are indistinguishable.
3265
+ *
3266
+ * In-memory only: dies with the process. The caller falls back to the
3267
+ * persisted bindings when this comes back empty.
3268
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3269
+ */
3270
+ getScriptBindings(limit?: number, currentUIBlockId?: string): Record<string, any>[];
1380
3271
  getConversationContext(limit?: number, currentUIBlockId?: string): string;
1381
3272
  /**
1382
3273
  * Convert Thread to JSON-serializable object
@@ -1386,12 +3277,20 @@ declare class Thread {
1386
3277
 
1387
3278
  /**
1388
3279
  * ThreadManager manages all threads globally
1389
- * Provides methods to create, retrieve, and delete threads
3280
+ * Provides methods to create, retrieve, and delete threads.
3281
+ * Includes automatic cleanup to prevent unbounded memory growth.
1390
3282
  */
1391
3283
  declare class ThreadManager {
1392
3284
  private static instance;
1393
3285
  private threads;
3286
+ private cleanupInterval;
3287
+ private readonly threadTtlMs;
1394
3288
  private constructor();
3289
+ /**
3290
+ * Periodically remove threads older than 7 days.
3291
+ * Runs every hour to avoid frequent iteration over the map.
3292
+ */
3293
+ private startCleanup;
1395
3294
  /**
1396
3295
  * Get singleton instance of ThreadManager
1397
3296
  */
@@ -1790,14 +3689,640 @@ declare function rerankConversationResults<T extends {
1790
3689
  bm25Score: number;
1791
3690
  }>;
1792
3691
 
1793
- declare const SDK_VERSION = "0.0.8";
3692
+ /**
3693
+ * QueryExecutionService - Handles all query execution, validation, and retry logic
3694
+ * Extracted from BaseLLM for better separation of concerns
3695
+ */
3696
+
3697
+ /**
3698
+ * Context for component when requesting query fix
3699
+ */
3700
+ interface ComponentContext {
3701
+ name: string;
3702
+ type: string;
3703
+ title?: string;
3704
+ }
3705
+ /**
3706
+ * Result of query validation
3707
+ */
3708
+ interface QueryValidationResult {
3709
+ component: Component | null;
3710
+ queryKey: string;
3711
+ result: any;
3712
+ validated: boolean;
3713
+ }
3714
+ /**
3715
+ * Result of batch query validation
3716
+ */
3717
+ interface BatchValidationResult {
3718
+ components: Component[];
3719
+ queryResults: Map<string, any>;
3720
+ }
3721
+ /**
3722
+ * Configuration for QueryExecutionService
3723
+ */
3724
+ interface QueryExecutionServiceConfig {
3725
+ defaultLimit: number;
3726
+ getModelForTask: (taskType: 'simple' | 'complex') => string;
3727
+ getApiKey: (apiKey?: string) => string | undefined;
3728
+ providerName: string;
3729
+ }
3730
+ /**
3731
+ * QueryExecutionService handles all query-related operations
3732
+ */
3733
+ declare class QueryExecutionService {
3734
+ private config;
3735
+ constructor(config: QueryExecutionServiceConfig);
3736
+ /**
3737
+ * Get the cache key for a query
3738
+ * This ensures the cache key matches what the frontend will send
3739
+ */
3740
+ getQueryCacheKey(query: any): string;
3741
+ /**
3742
+ * Execute a query against the database
3743
+ * @param query - The SQL query to execute (string or object with sql/values)
3744
+ * @param collections - Collections object containing database execute function
3745
+ * @returns Object with result data and cache key
3746
+ */
3747
+ executeQuery(query: any, collections: any): Promise<{
3748
+ result: any;
3749
+ cacheKey: string;
3750
+ }>;
3751
+ /**
3752
+ * Request the LLM to fix a failed SQL query
3753
+ * @param failedQuery - The query that failed execution
3754
+ * @param errorMessage - The error message from the failed execution
3755
+ * @param componentContext - Context about the component
3756
+ * @param apiKey - Optional API key
3757
+ * @returns Fixed query string
3758
+ */
3759
+ requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
3760
+ /**
3761
+ * Validate a single component's query with retry logic
3762
+ * @param component - The component to validate
3763
+ * @param collections - Collections object containing database execute function
3764
+ * @param apiKey - Optional API key for LLM calls
3765
+ * @returns Validation result with component, query key, and result
3766
+ */
3767
+ validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
3768
+ /**
3769
+ * Validate multiple component queries in parallel
3770
+ * @param components - Array of components with potential queries
3771
+ * @param collections - Collections object containing database execute function
3772
+ * @param apiKey - Optional API key for LLM calls
3773
+ * @returns Object with validated components and query results map
3774
+ */
3775
+ validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
3776
+ }
3777
+
3778
+ /**
3779
+ * Task types for model selection
3780
+ * - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
3781
+ * - 'simple': Classification, action generation (uses fast model in balanced mode)
3782
+ */
3783
+ type TaskType = 'complex' | 'simple';
3784
+ interface BaseLLMConfig {
3785
+ model?: string;
3786
+ fastModel?: string;
3787
+ defaultLimit?: number;
3788
+ apiKey?: string;
3789
+ /**
3790
+ * Model selection strategy:
3791
+ * - 'best': Use best model for all tasks (highest quality, higher cost)
3792
+ * - 'fast': Use fast model for all tasks (lower quality, lower cost)
3793
+ * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
3794
+ */
3795
+ modelStrategy?: ModelStrategy;
3796
+ conversationSimilarityThreshold?: number;
3797
+ }
3798
+ /**
3799
+ * BaseLLM abstract class for AI-powered component generation and matching
3800
+ * Provides common functionality for all LLM providers
3801
+ */
3802
+ declare abstract class BaseLLM {
3803
+ protected model: string;
3804
+ protected fastModel: string;
3805
+ protected defaultLimit: number;
3806
+ protected apiKey?: string;
3807
+ protected modelStrategy: ModelStrategy;
3808
+ protected conversationSimilarityThreshold: number;
3809
+ protected queryService: QueryExecutionService;
3810
+ constructor(config?: BaseLLMConfig);
3811
+ /**
3812
+ * Get the appropriate model based on task type and model strategy
3813
+ * @param taskType - 'complex' for text generation/matching, 'simple' for classification/actions
3814
+ * @returns The model string to use for this task
3815
+ */
3816
+ protected getModelForTask(taskType: TaskType): string;
3817
+ /**
3818
+ * Set the model strategy at runtime
3819
+ * @param strategy - 'best', 'fast', or 'balanced'
3820
+ */
3821
+ setModelStrategy(strategy: ModelStrategy): void;
3822
+ /**
3823
+ * Get the current model strategy
3824
+ * @returns The current model strategy
3825
+ */
3826
+ getModelStrategy(): ModelStrategy;
3827
+ /**
3828
+ * Set the conversation similarity threshold at runtime
3829
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
3830
+ */
3831
+ setConversationSimilarityThreshold(threshold: number): void;
3832
+ /**
3833
+ * Get the current conversation similarity threshold
3834
+ * @returns The current threshold value
3835
+ */
3836
+ getConversationSimilarityThreshold(): number;
3837
+ /**
3838
+ * Get the default model for this provider (used for complex tasks like text generation)
3839
+ */
3840
+ protected abstract getDefaultModel(): string;
3841
+ /**
3842
+ * Get the default fast model for this provider (used for simple tasks: classification, matching, actions)
3843
+ * Should return a cheaper/faster model like Haiku for Anthropic
3844
+ */
3845
+ protected abstract getDefaultFastModel(): string;
3846
+ /**
3847
+ * Get the default API key from environment
3848
+ */
3849
+ protected abstract getDefaultApiKey(): string | undefined;
3850
+ /**
3851
+ * Get the provider name (for logging)
3852
+ */
3853
+ protected abstract getProviderName(): string;
3854
+ /**
3855
+ * Get the API key (from instance, parameter, or environment)
3856
+ */
3857
+ protected getApiKey(apiKey?: string): string | undefined;
3858
+ /**
3859
+ * Check if a component contains a Form (data_modification component)
3860
+ * Forms have hardcoded defaultValues that become stale when cached
3861
+ * This checks both single Form components and Forms inside MultiComponentContainer
3862
+ */
3863
+ protected containsFormComponent(component: any): boolean;
3864
+ /**
3865
+ * Match components from text response suggestions and generate follow-up questions
3866
+ * Takes a text response with component suggestions (c1:type format) and matches with available components
3867
+ * Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
3868
+ * All components are placed in a default MultiComponentContainer layout
3869
+ * @param analysisContent - The text response containing component suggestions
3870
+ * @param components - List of available components
3871
+ * @param apiKey - Optional API key
3872
+ * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
3873
+ * @returns Object containing matched components, layout title/description, and follow-up actions
3874
+ */
3875
+ matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
3876
+ components: Component[];
3877
+ layoutTitle: string;
3878
+ layoutDescription: string;
3879
+ actions: Action[];
3880
+ }>;
3881
+ /**
3882
+ * Classify user question into category and detect external tools needed
3883
+ * Determines if question is for data analysis, requires external tools, or needs text response
3884
+ */
3885
+ classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
3886
+ category: 'data_analysis' | 'data_modification' | 'general';
3887
+ externalTools: Array<{
3888
+ type: string;
3889
+ name: string;
3890
+ description: string;
3891
+ parameters: Record<string, any>;
3892
+ }>;
3893
+ dataAnalysisType?: 'visualization' | 'calculation' | 'comparison' | 'trend';
3894
+ reasoning: string;
3895
+ confidence: number;
3896
+ }>;
3897
+ /**
3898
+ * Adapt UI block parameters based on current user question
3899
+ * Takes a matched UI block from semantic search and modifies its props to answer the new question
3900
+ * Also adapts the cached text response to match the new question
3901
+ */
3902
+ adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
3903
+ success: boolean;
3904
+ adaptedComponent?: Component;
3905
+ adaptedTextResponse?: string;
3906
+ parametersChanged?: Array<{
3907
+ field: string;
3908
+ reason: string;
3909
+ }>;
3910
+ explanation: string;
3911
+ }>;
3912
+ /**
3913
+ * Generate text-based response for user question
3914
+ * This provides conversational text responses instead of component generation
3915
+ * Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
3916
+ * After generating text response, if components are provided, matches suggested components
3917
+ */
3918
+ 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>;
3919
+ /**
3920
+ * Main orchestration function with semantic search and multi-step classification
3921
+ * NEW FLOW (Recommended):
3922
+ * 1. Semantic search: Check previous conversations (>60% match)
3923
+ * - If match found → Adapt UI block parameters and return
3924
+ * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
3925
+ * 3. Route appropriately based on category and response mode
3926
+ */
3927
+ 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>;
3928
+ /**
3929
+ * Generate next questions that the user might ask based on the original prompt and generated component
3930
+ * This helps provide intelligent suggestions for follow-up queries
3931
+ * For general/conversational questions without components, pass textResponse instead
3932
+ */
3933
+ generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string, signal?: AbortSignal): Promise<string[]>;
3934
+ }
3935
+
3936
+ interface AnthropicLLMConfig extends BaseLLMConfig {
3937
+ }
3938
+ /**
3939
+ * AnthropicLLM class for handling AI-powered component generation and matching using Anthropic Claude
3940
+ */
3941
+ declare class AnthropicLLM extends BaseLLM {
3942
+ constructor(config?: AnthropicLLMConfig);
3943
+ protected getDefaultModel(): string;
3944
+ protected getDefaultFastModel(): string;
3945
+ protected getDefaultApiKey(): string | undefined;
3946
+ protected getProviderName(): string;
3947
+ }
3948
+ declare const anthropicLLM: AnthropicLLM;
3949
+
3950
+ interface GroqLLMConfig extends BaseLLMConfig {
3951
+ }
3952
+ /**
3953
+ * GroqLLM class for handling AI-powered component generation and matching using Groq
3954
+ */
3955
+ declare class GroqLLM extends BaseLLM {
3956
+ constructor(config?: GroqLLMConfig);
3957
+ protected getDefaultModel(): string;
3958
+ protected getDefaultFastModel(): string;
3959
+ protected getDefaultApiKey(): string | undefined;
3960
+ protected getProviderName(): string;
3961
+ }
3962
+ declare const groqLLM: GroqLLM;
3963
+
3964
+ interface GeminiLLMConfig extends BaseLLMConfig {
3965
+ }
3966
+ /**
3967
+ * GeminiLLM class for handling AI-powered component generation and matching using Google Gemini
3968
+ */
3969
+ declare class GeminiLLM extends BaseLLM {
3970
+ constructor(config?: GeminiLLMConfig);
3971
+ protected getDefaultModel(): string;
3972
+ protected getDefaultFastModel(): string;
3973
+ protected getDefaultApiKey(): string | undefined;
3974
+ protected getProviderName(): string;
3975
+ }
3976
+ declare const geminiLLM: GeminiLLM;
3977
+
3978
+ interface OpenAILLMConfig extends BaseLLMConfig {
3979
+ }
3980
+ /**
3981
+ * OpenAILLM class for handling AI-powered component generation and matching using OpenAI GPT models
3982
+ */
3983
+ declare class OpenAILLM extends BaseLLM {
3984
+ constructor(config?: OpenAILLMConfig);
3985
+ protected getDefaultModel(): string;
3986
+ protected getDefaultFastModel(): string;
3987
+ protected getDefaultApiKey(): string | undefined;
3988
+ protected getProviderName(): string;
3989
+ }
3990
+ declare const openaiLLM: OpenAILLM;
3991
+
3992
+ /**
3993
+ * Query Cache — Two mechanisms:
3994
+ *
3995
+ * 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
3996
+ * of recently validated queries. True LRU eviction: reads bubble entries to the back via
3997
+ * delete+re-set so the oldest *unused* entry is evicted, not the oldest *inserted*.
3998
+ *
3999
+ * 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
4000
+ * No server-side storage needed for SQL mappings. The token is decrypted on each request.
4001
+ * This eliminates the unbounded queryIdCache that previously grew forever and caused
4002
+ * memory bloat (hundreds of MBs after thousands of queries).
4003
+ *
4004
+ * Result data can still be cached temporarily via the data cache (mechanism 1).
4005
+ */
4006
+ declare class QueryCache {
4007
+ private cache;
4008
+ private ttlMs;
4009
+ private maxCacheSize;
4010
+ private cleanupInterval;
4011
+ private readonly algorithm;
4012
+ private encryptionKey;
4013
+ constructor();
4014
+ /**
4015
+ * Set the cache TTL (Time To Live)
4016
+ * @param minutes - TTL in minutes (default: 10)
4017
+ */
4018
+ setTTL(minutes: number): void;
4019
+ /**
4020
+ * Get the current TTL in minutes
4021
+ */
4022
+ getTTL(): number;
4023
+ /**
4024
+ * Store query result in data cache.
4025
+ * If the key already exists, it's removed first so the re-insert places it
4026
+ * at the back of the iteration order (LRU). Eviction only fires when adding
4027
+ * a genuinely new key past the size limit.
4028
+ */
4029
+ set(query: string, data: any): void;
4030
+ /**
4031
+ * Get cached result if exists and not expired.
4032
+ * On hit, re-inserts the entry so it moves to the back of the Map's
4033
+ * iteration order — turning FIFO eviction into true LRU.
4034
+ */
4035
+ get(query: string): any | null;
4036
+ /**
4037
+ * Check if query exists in cache (not expired)
4038
+ */
4039
+ has(query: string): boolean;
4040
+ /**
4041
+ * Remove a specific query from cache
4042
+ */
4043
+ delete(query: string): void;
4044
+ /**
4045
+ * Clear all cached entries
4046
+ */
4047
+ clear(): void;
4048
+ /**
4049
+ * Get cache statistics
4050
+ */
4051
+ getStats(): {
4052
+ size: number;
4053
+ queryIdCount: number;
4054
+ oldestEntryAge: number | null;
4055
+ };
4056
+ /**
4057
+ * Start periodic cleanup of expired data cache entries.
4058
+ */
4059
+ private startCleanup;
4060
+ /**
4061
+ * Encrypt a payload into a self-contained token.
4062
+ */
4063
+ private encrypt;
4064
+ /**
4065
+ * Decrypt a token back to the original payload.
4066
+ */
4067
+ private decrypt;
4068
+ /**
4069
+ * Store a query by generating an encrypted token as queryId.
4070
+ * The SQL is encrypted INTO the token — nothing stored in memory.
4071
+ * If data is provided, it's cached temporarily in the data cache.
4072
+ */
4073
+ storeQuery(query: any, data?: any): string;
4074
+ /**
4075
+ * Get a stored query by decrypting its token.
4076
+ * Returns the SQL + any cached result data.
4077
+ */
4078
+ getQuery(queryId: string): {
4079
+ query: any;
4080
+ data: any;
4081
+ } | null;
4082
+ /**
4083
+ * Update cached data for a queryId token
4084
+ */
4085
+ setQueryData(queryId: string, data: any): void;
4086
+ /**
4087
+ * Stop cleanup interval (for graceful shutdown)
4088
+ */
4089
+ destroy(): void;
4090
+ }
4091
+ declare const queryCache: QueryCache;
4092
+
4093
+ /**
4094
+ * Manages conversation history scoped per user + dashboard.
4095
+ * Each user-dashboard pair has its own isolated history that expires after a configurable TTL.
4096
+ */
4097
+ declare class DashboardConversationHistory {
4098
+ private histories;
4099
+ private ttlMs;
4100
+ private maxEntries;
4101
+ private cleanupInterval;
4102
+ constructor();
4103
+ /**
4104
+ * Set the TTL for dashboard histories
4105
+ * @param minutes - TTL in minutes
4106
+ */
4107
+ setTTL(minutes: number): void;
4108
+ /**
4109
+ * Set max entries per dashboard
4110
+ */
4111
+ setMaxEntries(max: number): void;
4112
+ /**
4113
+ * Add a conversation entry for a user's dashboard
4114
+ */
4115
+ addEntry(dashboardId: string, userPrompt: string, componentSummary: string, userId?: string): void;
4116
+ /**
4117
+ * Get formatted conversation history for a user's dashboard
4118
+ */
4119
+ getHistory(dashboardId: string, userId?: string): string;
4120
+ /**
4121
+ * Clear history for a specific user's dashboard
4122
+ */
4123
+ clearDashboard(dashboardId: string, userId?: string): void;
4124
+ /**
4125
+ * Clear all dashboard histories
4126
+ */
4127
+ clearAll(): void;
4128
+ /**
4129
+ * Start periodic cleanup of expired histories
4130
+ */
4131
+ private startCleanup;
4132
+ /**
4133
+ * Stop cleanup interval (for graceful shutdown)
4134
+ */
4135
+ destroy(): void;
4136
+ }
4137
+ declare const dashboardConversationHistory: DashboardConversationHistory;
4138
+
4139
+ /**
4140
+ * Whole-dashboard generation via Pi, a terminal coding agent — as opposed to
4141
+ * DASH_COMP_REQ's single-widget-at-a-time flow. Runs Pi in-process via its
4142
+ * SDK (createAgentSession), not as a subprocess: no shell, no argument
4143
+ * quoting, no stdin/stdout piping, none of the Windows-specific subprocess
4144
+ * issues that came with spawning the `pi` CLI directly.
4145
+ *
4146
+ * Called from sdk-nodejs/src/dashboardAgent/index.ts (DASHBOARD_AGENT_REQ),
4147
+ * which owns the generic streaming/abort machinery (mirrors USER_PROMPT_REQ)
4148
+ * and passes `signal`/`onProgress` alongside the normal params — this stays
4149
+ * within CollectionHandler's loose (params) => Promise<result> typing, no
4150
+ * change needed to that shared type.
4151
+ *
4152
+ * This mechanism is generic and reusable across any deployment. What's
4153
+ * genuinely project-specific — where AGENTS.md lives, which model to use —
4154
+ * is supplied via `DashboardAgentCollectionConfig`, with defaults sensible
4155
+ * enough that most callers don't need to override them (see below). The
4156
+ * data-source tool list and the dashboard's current state both come from
4157
+ * things sdk-nodejs already exposes generically: `sdk.getTools()` (whatever
4158
+ * this deployment registered via `sdk.setTools()`) and `sdk.callCollection
4159
+ * ('dashboards', 'query', ...)` (whatever this deployment already registered
4160
+ * under that name/shape) — no per-deployment callback needed for either.
4161
+ * Same convention on the way out: after a successful run, the prompt and the
4162
+ * full response text are handed to `sdk.callCollection('dashboard-agent-
4163
+ * conversations', 'create', ...)` if this deployment has registered one —
4164
+ * skipped silently otherwise, since conversation history is optional.
4165
+ *
4166
+ * Pi verifies every query against the live database itself (via whatever
4167
+ * local tool-execution bridge the deployment exposes, e.g. an HTTP bridge
4168
+ * on localhost), but does NOT persist the result itself — it writes the
4169
+ * finished DSL to an absolute path inside `runtimeDir`, told to it explicitly
4170
+ * in the prompt, and stops there. This handler reads that file after the run
4171
+ * finishes and returns its content as `dashboard` in the result. The caller
4172
+ * (frontend) is the one that actually saves it, via whatever authenticated
4173
+ * create/update path any other dashboard edit goes through — Pi has no user
4174
+ * session/auth context of its own, so persistence shouldn't happen from
4175
+ * inside it.
4176
+ *
4177
+ * Session persistence: the FIRST call for a dashboardId pays the full cost
4178
+ * (explore KB, discover schema, plan, verify, build). Every call after that
4179
+ * resumes the same session file (SessionManager.open) so Pi has everything
4180
+ * it already learned — it only needs to reason about the new, smaller ask,
4181
+ * not rediscover the whole dashboard from scratch. The session's file path
4182
+ * (AgentSession.sessionFile) is captured right after creation and persisted
4183
+ * in a small local file, keyed by dashboardId, inside `runtimeDir`.
4184
+ */
4185
+ interface DashboardAgentCollectionConfig {
4186
+ /**
4187
+ * Working directory Pi runs from — must contain AGENTS.md. This is a
4188
+ * version-controlled prompt file, so `cwd` is expected to live somewhere
4189
+ * like a `.prompts/` folder alongside the deployment's other prompts.
4190
+ * Default: `<process.cwd()>/.prompts/dashboard-agent` — the same
4191
+ * process.cwd()-based convention PromptLoader already uses for the main
4192
+ * agent's prompts, which needs no explicit override in the common case
4193
+ * (the backend process's own cwd already is its project root).
4194
+ */
4195
+ cwd?: string;
4196
+ /**
4197
+ * Where drafts/, the session-id map, and dashboard.log get written —
4198
+ * separate from `cwd` deliberately, so this deployment's runtime state
4199
+ * (regenerated per session, safe to gitignore) doesn't sit inside the
4200
+ * same folder as the version-controlled AGENTS.md prompt.
4201
+ * Default: `<process.cwd()>/.pi-dashboard-agent-runtime`.
4202
+ */
4203
+ runtimeDir?: string;
4204
+ /** Model provider (default: process.env.PI_AGENT_PROVIDER || 'openrouter'). */
4205
+ provider?: string;
4206
+ /** Model id (default: process.env.PI_AGENT_MODEL || 'anthropic/claude-sonnet-4.5'). */
4207
+ model?: string;
4208
+ /**
4209
+ * true (default): every request starts a brand-new pi session, with the 2
4210
+ * most recent prior responses (if any) injected into the prompt as
4211
+ * context — bounded cost per request, but pi re-explores schema/KB facts
4212
+ * it already verified in an earlier turn on this same dashboard.
4213
+ * false: resumes the same session file across requests on a given
4214
+ * dashboard — pi keeps everything it already learned, but context (and
4215
+ * cost) grows unbounded across turns (one observed turn: 2M+ cache-read
4216
+ * tokens after a handful of edits on the same dashboard).
4217
+ * Default: process.env.PI_AGENT_FRESH_SESSION !== 'false'.
4218
+ */
4219
+ freshSession?: boolean;
4220
+ }
4221
+ declare function registerDashboardAgentCollection(sdk: SuperatomSDK, config?: DashboardAgentCollectionConfig): void;
4222
+
4223
+ /**
4224
+ * ScriptMatcher — LLM-Based Script Matching + Parameter Extraction
4225
+ *
4226
+ * Uses ONE LLM call to:
4227
+ * 1. Pick the best matching script from the library (or "none")
4228
+ * 2. Extract parameter values from the user question
4229
+ *
4230
+ * Why LLM over embeddings:
4231
+ * - Embeddings capture topic similarity ("overstock" ≈ "inventory" ≈ "revenue")
4232
+ * but can't distinguish structurally different questions about the same domain
4233
+ * - LLM understands that "overstock by warehouse" needs a different script than
4234
+ * "revenue by warehouse" even though they're semantically close
4235
+ * - One call does both matching AND parameter extraction
4236
+ *
4237
+ * When script library grows past ~50, add an embedding pre-filter
4238
+ * (ChromaDB narrows to top 10 → LLM picks from those 10).
4239
+ */
4240
+
4241
+ declare class ScriptMatcher {
4242
+ private store;
4243
+ constructor(store: ScriptStore);
4244
+ /**
4245
+ * Find the best matching script for a user question.
4246
+ * Uses ONE LLM call that picks the script AND extracts parameters.
4247
+ * Returns null if no script matches.
4248
+ */
4249
+ match(userPrompt: string, apiKey?: string, model?: string, signal?: AbortSignal,
4250
+ /**
4251
+ * Recent script-backed answers in this thread, newest first. Presence of at
4252
+ * least one is what makes the `edit` tier reachable at all (see the guards
4253
+ * below), and handing over SEVERAL is what lets an instruction name its own
4254
+ * target instead of always hitting the most recent script.
4255
+ */
4256
+ activeBindings?: ScriptBinding[],
4257
+ /**
4258
+ * Recent conversation turns, most recent last. The gate needs this to tell
4259
+ * "this reply is an edit instruction for the active script" apart from
4260
+ * "this reply is answering a clarifying question about a DIFFERENT,
4261
+ * unresolved topic that never became a script" — a bare parameter-shaped
4262
+ * reply ("April 2025 to March 2026") is textually indistinguishable
4263
+ * between those two cases without seeing what the assistant just asked.
4264
+ * Once this tier is decided, nothing downstream re-checks it — the edit
4265
+ * path hands MainAgent a system prompt that explicitly instructs it to
4266
+ * trust the premise and not treat the turn as a new question — so this
4267
+ * gate is the only place that can catch a mismatch.
4268
+ */
4269
+ conversationHistory?: string): Promise<ScriptMatch | null>;
4270
+ /**
4271
+ * Build the script catalog string for the LLM prompt.
4272
+ * Each script gets: index, ID, name, description, and parameter definitions.
4273
+ */
4274
+ private buildScriptCatalog;
4275
+ /**
4276
+ * The recent script-backed answers in this thread — the bounded set an edit
4277
+ * may target. Rendered as its own prompt section (never merged into the
4278
+ * ranked catalog) so the `edit` rules have an unambiguous referent set, and
4279
+ * numbered newest-first so the prompt's "prefer the most recent when the
4280
+ * instruction is ambiguous" tie-break has something to point at.
4281
+ *
4282
+ * Each entry carries the QUESTION that produced it plus the columns it
4283
+ * returned — that is what lets the matcher resolve "use the mode for the WSP
4284
+ * one" instead of blindly taking the newest.
4285
+ */
4286
+ private buildActiveScriptBlock;
4287
+ }
4288
+
4289
+ /**
4290
+ * ScriptRunner — Execute scripts in an isolated tsx subprocess.
4291
+ *
4292
+ * The subprocess approach replaces the earlier `new Function()` eval and gives us:
4293
+ * - Real sandbox (separate process, SIGKILL on timeout).
4294
+ * - Real TypeScript (tsx transpiles on the fly).
4295
+ * - npm imports available to scripts (clustering, stats, geo, etc.).
4296
+ *
4297
+ * Protocol: NDJSON over the child's stdin/stdout. See script-ipc.ts + backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md.
4298
+ */
4299
+
4300
+ interface RunScriptOptions {
4301
+ /** Data sources the script is allowed to query via ctx.query */
4302
+ externalTools: ExternalTool[];
4303
+ /** Optional — for propagating per-query UI progress to the user */
4304
+ streamBuffer?: StreamBuffer;
4305
+ /** Override the wall-clock timeout (default `SCRIPT_TIMEOUT_MS`, 60s). */
4306
+ timeoutMs?: number;
4307
+ /**
4308
+ * Per-turn cancellation signal. When the user hits "Stop" mid-run, the child
4309
+ * process group is SIGKILLed and the run resolves as an aborted failure (the
4310
+ * caller is already unwinding, so the result is discarded).
4311
+ */
4312
+ signal?: AbortSignal;
4313
+ }
4314
+ /**
4315
+ * Execute a recipe by spawning a tsx child on the script's .ts file.
4316
+ * `scriptPath` is the absolute path to the saved `.ts` body.
4317
+ */
4318
+ declare function runScript(recipe: ScriptRecipe, scriptPath: string, params: Record<string, any>, options: RunScriptOptions): Promise<ScriptResult>;
4319
+
1794
4320
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
1795
4321
  declare class SuperatomSDK {
1796
4322
  private ws;
1797
4323
  private url;
1798
4324
  private apiKey?;
1799
4325
  private projectId;
1800
- private userId;
1801
4326
  private type;
1802
4327
  private bundleDir;
1803
4328
  private messageHandlers;
@@ -1808,12 +4333,18 @@ declare class SuperatomSDK {
1808
4333
  private collections;
1809
4334
  private components;
1810
4335
  private tools;
4336
+ private workflows;
1811
4337
  private anthropicApiKey;
1812
4338
  private groqApiKey;
1813
4339
  private geminiApiKey;
1814
4340
  private openaiApiKey;
1815
4341
  private llmProviders;
1816
4342
  private databaseType;
4343
+ private modelStrategy;
4344
+ private mainAgentModel;
4345
+ private sourceAgentModel;
4346
+ private dashCompModels?;
4347
+ private conversationSimilarityThreshold;
1817
4348
  private userManager;
1818
4349
  private dashboardManager;
1819
4350
  private reportManager;
@@ -1821,6 +4352,8 @@ declare class SuperatomSDK {
1821
4352
  private lastPong;
1822
4353
  private readonly PING_INTERVAL_MS;
1823
4354
  private readonly PONG_TIMEOUT_MS;
4355
+ private pendingOutbox;
4356
+ private readonly MAX_OUTBOX_SIZE;
1824
4357
  constructor(config: SuperatomSDKConfig);
1825
4358
  /**
1826
4359
  * Initialize PromptLoader and load prompts into memory
@@ -1860,9 +4393,25 @@ declare class SuperatomSDK {
1860
4393
  */
1861
4394
  private handleMessage;
1862
4395
  /**
1863
- * Send a message to the Superatom service
4396
+ * Send a message to the Superatom service.
4397
+ * Returns true if the message was sent, false if the WebSocket is not connected.
4398
+ * Does NOT throw on closed connections — callers can check the return value if needed.
4399
+ */
4400
+ send(message: Message): boolean;
4401
+ /**
4402
+ * Queue a message that couldn't be delivered because the socket was down,
4403
+ * to be resent once it reconnects. Drops the oldest entry once the bound is
4404
+ * hit — an outage long enough to fill this queue means the oldest queued
4405
+ * responses are for requests the caller has likely already given up on.
4406
+ */
4407
+ private queuePendingMessage;
4408
+ /**
4409
+ * Resend everything queued while the socket was down, now that it's back
4410
+ * up. Uses this.ws.send() directly (not send()) so a message that fails
4411
+ * again goes back through queuePendingMessage() rather than being silently
4412
+ * dropped a second time.
1864
4413
  */
1865
- send(message: Message): void;
4414
+ private flushPendingOutbox;
1866
4415
  /**
1867
4416
  * Register a message handler to receive all messages
1868
4417
  */
@@ -1902,6 +4451,14 @@ declare class SuperatomSDK {
1902
4451
  */
1903
4452
  private handlePong;
1904
4453
  private storeComponents;
4454
+ /**
4455
+ * The live, frontend-registered component catalog (name, type, description,
4456
+ * and full prop schema per component) — the same authoritative source
4457
+ * DASH_COMP_REQ's LLM prompt is built from. Exposed so other integrations
4458
+ * (e.g. the dashboard-agent script bridge) can read real component
4459
+ * contracts instead of maintaining a separate, driftable hand-written copy.
4460
+ */
4461
+ getComponents(): Component[];
1905
4462
  /**
1906
4463
  * Set tools for the SDK instance
1907
4464
  */
@@ -1910,6 +4467,57 @@ declare class SuperatomSDK {
1910
4467
  * Get the stored tools
1911
4468
  */
1912
4469
  getTools(): Tool$1[];
4470
+ /**
4471
+ * Call a registered collection operation in-process — no WebSocket
4472
+ * round-trip, since the caller is already running inside this same SDK
4473
+ * instance. Lets SDK-internal features (e.g. the dashboard agent) reuse
4474
+ * whatever collection a deployment has already registered (e.g.
4475
+ * 'dashboards'.'query') by name/convention, instead of requiring a
4476
+ * separate callback purely to re-expose data a collection already serves.
4477
+ * Throws if the collection or operation isn't registered.
4478
+ */
4479
+ callCollection<TResult = any>(collectionName: string, operation: string, params?: any): Promise<TResult>;
4480
+ /**
4481
+ * Register workflow components for the SDK instance.
4482
+ *
4483
+ * Workflows are pre-built multi-step UI flows the main agent can pick when
4484
+ * the user's prompt matches a workflow's `whenToUse` trigger. Picking a
4485
+ * workflow short-circuits analysis text + dashboard component generation —
4486
+ * the workflow component is returned directly, with the LLM-extracted props.
4487
+ */
4488
+ setWorkflows(workflows: WorkflowDescriptor[]): void;
4489
+ /**
4490
+ * Get the registered workflow components.
4491
+ */
4492
+ getWorkflows(): WorkflowDescriptor[];
4493
+ /**
4494
+ * Apply model strategy to all LLM provider singletons
4495
+ * @param strategy - 'best', 'fast', or 'balanced'
4496
+ */
4497
+ private applyModelStrategy;
4498
+ /**
4499
+ * Set model strategy at runtime
4500
+ * @param strategy - 'best', 'fast', or 'balanced'
4501
+ */
4502
+ setModelStrategy(strategy: ModelStrategy): void;
4503
+ /**
4504
+ * Get current model strategy
4505
+ */
4506
+ getModelStrategy(): ModelStrategy;
4507
+ /**
4508
+ * Apply conversation similarity threshold to all LLM provider singletons
4509
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
4510
+ */
4511
+ private applyConversationSimilarityThreshold;
4512
+ /**
4513
+ * Set conversation similarity threshold at runtime
4514
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
4515
+ */
4516
+ setConversationSimilarityThreshold(threshold: number): void;
4517
+ /**
4518
+ * Get current conversation similarity threshold
4519
+ */
4520
+ getConversationSimilarityThreshold(): number;
1913
4521
  }
1914
4522
 
1915
- export { type Action, BM25L, type BM25LOptions, 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 RerankedResult, SDK_VERSION, STORAGE_CONFIG, SuperatomSDK, type SuperatomSDKConfig, Thread, ThreadManager, type Tool$1 as Tool, UIBlock, UILogCollector, type User, UserManager, type UsersData, hybridRerank, llmUsageLogger, logger, rerankChromaResults, rerankConversationResults, userPromptErrorLogger };
4523
+ 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 };