@superatomai/sdk-node 0.0.39 → 0.0.40-dsp

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