@superatomai/sdk-node 0.0.37 → 0.0.38-dsp

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