@superatomai/sdk-node 0.0.55 → 0.0.56-dsp

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,15 +1,1249 @@
1
1
  import { z } from 'zod';
2
2
  import Anthropic from '@anthropic-ai/sdk';
3
3
 
4
+ /**
5
+ * Script Flow Types
6
+ *
7
+ * Defines interfaces for the script-based query architecture:
8
+ * - ScriptRecipe: metadata for matching, validation, and quality tracking
9
+ * - ScriptResult: output from executing a script
10
+ * - ScriptMatch: result from the LLM-based script matcher
11
+ */
12
+
13
+ /**
14
+ * Recipe metadata stored alongside each script.
15
+ * Used for matching, validation, and quality tracking.
16
+ */
17
+ interface ScriptRecipe {
18
+ /** Unique script identifier */
19
+ id: string;
20
+ /** Version number (incremented on regeneration) */
21
+ version: number;
22
+ /** Human-readable name (e.g., "Revenue by Dimension") */
23
+ name: string;
24
+ /** Natural language description of what this script does */
25
+ intentDescription: string;
26
+ /** Keyword tags for quick filtering */
27
+ tags: string[];
28
+ /** Source tool IDs this script queries (e.g., ["mssql-abc123_query"]) */
29
+ sourceIds: string[];
30
+ /** Table names used (for future schema drift detection) */
31
+ tables: string[];
32
+ /** Parameter definitions — what can vary */
33
+ parameters: ScriptParameter[];
34
+ /** The script function body as a string. Loaded from disk (scripts-store/<fileBase>.ts). */
35
+ scriptBody: string;
36
+ /**
37
+ * On-disk filename stem for the body: scripts-store/<fileBase>.ts.
38
+ * Editable in the IDE. Decided at authoring time (slug of `name`, with a
39
+ * short id suffix on collision) and stable across promotion.
40
+ */
41
+ fileBase?: string;
42
+ /** sha256 of the on-disk body — lets the runtime detect manual edits. */
43
+ bodyHash?: string;
44
+ /** Project scope (single-VM deployments may leave this undefined). */
45
+ projectId?: string;
46
+ /** Times this script was used successfully */
47
+ successCount: number;
48
+ /** Times this script failed */
49
+ failureCount: number;
50
+ /** ISO timestamp of last usage */
51
+ lastUsed: string;
52
+ /** Original user question that created this script */
53
+ createdFrom: string;
54
+ /** ISO timestamp */
55
+ createdAt: string;
56
+ /** ISO timestamp */
57
+ updatedAt: string;
58
+ /**
59
+ * `recipe.id` of the parent this script was forked from.
60
+ * Undefined for root scripts (those written from scratch by MainAgent).
61
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md.
62
+ */
63
+ parentId?: string;
64
+ /** 0 for root scripts; `parent.forkDepth + 1` for forks. Capped at 3. */
65
+ forkDepth?: number;
66
+ /**
67
+ * Brief description of what this fork changed vs its parent
68
+ * (sourced from the matcher's `modificationHint`).
69
+ */
70
+ forkReason?: string;
71
+ /**
72
+ * Validated component specs captured at authoring time. On a tier-high
73
+ * replay these are rebound to fresh queryIds deterministically — no
74
+ * component-generation LLM call, and the rendered columns can't drift from
75
+ * what was validated when the script was authored. Absent on recipes
76
+ * authored before this landed; those fall back to LLM component generation.
77
+ * See backend/docs/SCRIPT-COMPONENT-CONSISTENCY.md.
78
+ */
79
+ components?: ScriptComponentSpec[];
80
+ /**
81
+ * What the user explicitly asked the output to LOOK like, set by a display
82
+ * edit ("show that as a bar chart", "make the bars horizontal").
83
+ *
84
+ * Deliberately SEPARATE from `components`. Those are validated bindings that
85
+ * must be cleared on a data edit — after "break it down by brand" the axis
86
+ * keys are wrong, and after "use the mode" the stored title still says
87
+ * "Average…". A rendering CHOICE, by contrast, is still valid afterwards.
88
+ * Keeping them in one field meant every data edit silently discarded the
89
+ * user's chart type.
90
+ *
91
+ * Fed to the component generator as a hint whenever specs are (re)generated,
92
+ * so the chosen rendering comes back even after the SQL changes.
93
+ */
94
+ displayPreference?: ScriptDisplayPreference;
95
+ /**
96
+ * Lifecycle stage of this recipe on disk.
97
+ * - 'draft': written by MainAgent's write_script during a turn; filtered out
98
+ * of FTS results (status='verified' only) so the matcher never picks it.
99
+ * Filename is suffixed with `turnId` to keep concurrent turns
100
+ * from clobbering each other's drafts.
101
+ * - 'verified': promoted after `execute_script` succeeded; the matcher sees it.
102
+ * Filename drops the turn suffix unless a verified file with
103
+ * the same slug already exists (collision case keeps the suffix).
104
+ *
105
+ * Recipes loaded from disk without this field default to 'verified' so
106
+ * existing scripts keep working unchanged.
107
+ */
108
+ status?: 'draft' | 'verified';
109
+ /**
110
+ * Per-turn unique suffix used for draft filenames (e.g. `1714745623-x9k2`).
111
+ * Set when the draft is saved; carried until the recipe is promoted.
112
+ */
113
+ turnId?: string;
114
+ /**
115
+ * Last execution error captured by `recordDraftError` while the recipe was
116
+ * still a draft. Lets users open the draft .json file and see why it failed
117
+ * without grepping logs. Cleared on promotion to 'verified'.
118
+ */
119
+ lastError?: {
120
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
121
+ message: string;
122
+ at: string;
123
+ attempt: number;
124
+ };
125
+ /** userId who committed the most recent edit (audit trail — recipes are project-scoped). */
126
+ editedBy?: string;
127
+ /** The instruction that produced the current version. */
128
+ editedFrom?: string;
129
+ /**
130
+ * Prior versions, newest last. The body itself is archived on disk as
131
+ * `<fileBase>.v<version>.ts`; this records what changed and who did it.
132
+ */
133
+ history?: ScriptVersionRecord[];
134
+ }
135
+ /**
136
+ * A durable, user-stated rendering choice for a recipe. Survives data edits.
137
+ */
138
+ interface ScriptDisplayPreference {
139
+ /** Component types the user's chosen rendering resolved to, e.g. ["DynamicBarChart"]. */
140
+ componentTypes: string[];
141
+ /** The instruction itself — carries nuance the types can't ("horizontal", "sorted descending"). */
142
+ instruction: string;
143
+ /** ISO timestamp of the display edit that set this. */
144
+ at: string;
145
+ }
146
+ /** One superseded version of a recipe body (see ScriptStore.commitEdit). */
147
+ interface ScriptVersionRecord {
148
+ /** Version number this record superseded (i.e. the OLD version). */
149
+ version: number;
150
+ /** ISO timestamp of the edit that superseded it. */
151
+ at: string;
152
+ /** userId who made the edit, when known. */
153
+ by?: string;
154
+ /** The edit instruction that caused the supersede. */
155
+ instruction?: string;
156
+ /** One-line summary of what changed, for the version picker. */
157
+ changeSummary?: string;
158
+ /** sha256 of the superseded body — pairs with `<fileBase>.v<version>.ts`. */
159
+ bodyHash?: string;
160
+ }
161
+ interface ScriptParameter {
162
+ /** Parameter name (used in script body as params.name) */
163
+ name: string;
164
+ /** Parameter type */
165
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
166
+ /** Whether this parameter is required */
167
+ required: boolean;
168
+ /** Default value if not provided */
169
+ default?: any;
170
+ /** For enum type — maps user-facing values to internal values */
171
+ enumValues?: Record<string, string>;
172
+ /** Human-readable description (used in the matcher LLM prompt) */
173
+ description: string;
174
+ }
175
+ /**
176
+ * A reusable component binding captured when a script is authored. Stored on
177
+ * the recipe so tier-high replays rebuild components deterministically (rebind
178
+ * to fresh queryIds) instead of re-running the component-picker LLM.
179
+ */
180
+ interface ScriptComponentSpec {
181
+ /** Registered component name (e.g. "DynamicBarChart") — matched against the available component library. */
182
+ componentType: string;
183
+ /** `executedQuery.sourceId` to bind to (e.g. a tool id or 'computed:_final'), 'federation' for a cross-source component, or 'markdown' for a content-only narrative block (no data source). */
184
+ sourceRef: string;
185
+ /** Present only when sourceRef === 'federation' — the DuckDB SQL to re-execute on replay. */
186
+ federationSql?: string;
187
+ /** Present only when sourceRef === 'markdown' — the narrative text to render on replay (markdown has no data source, so its content must be persisted). */
188
+ content?: string;
189
+ title?: string;
190
+ description?: string;
191
+ /** Validated axis/value keys + aggregation — all referencing real columns of the bound source. */
192
+ config: Record<string, any>;
193
+ }
194
+ /**
195
+ * Result from executing a script via ScriptRunner.
196
+ */
197
+ interface ScriptResult {
198
+ /** Whether the script executed successfully */
199
+ success: boolean;
200
+ /** Combined data from all queries */
201
+ data: any[];
202
+ /** Program-generated narrative, when the script exports getAnalysis. */
203
+ analysis?: AnalysisOutput;
204
+ /**
205
+ * getAnalysis threw. `success` stays true — the data is valid, so the caller
206
+ * falls back to LLM prose rather than losing the answer.
207
+ */
208
+ analysisError?: string;
209
+ /** Program-generated component specs, when the script exports getComponents. */
210
+ components?: ScriptComponentSpec[];
211
+ /**
212
+ * getComponents threw or returned a non-array. `success` stays true — the data
213
+ * is valid, so the caller falls back to the recipe's stored specs and then to
214
+ * LLM generation rather than losing the dashboard.
215
+ */
216
+ componentsError?: string;
217
+ /** Individual query results tracked during execution */
218
+ executedQueries: ScriptQueryResult[];
219
+ /** Error message if failed */
220
+ error?: string;
221
+ /**
222
+ * Where in the lifecycle the error occurred. Lets MainAgent's fix-loop
223
+ * decide between "rewrite the whole draft" (compile) and "patch the
224
+ * specific line" (runtime).
225
+ */
226
+ errorPhase?: 'compile' | 'runtime' | 'timeout' | 'ipc';
227
+ /** Total execution time in milliseconds */
228
+ executionTimeMs: number;
229
+ }
230
+ /**
231
+ * A single query executed during script runtime.
232
+ * Tracked by ScriptContext for component generation and debugging.
233
+ */
234
+ interface ScriptQueryResult {
235
+ /** Source tool ID */
236
+ sourceId: string;
237
+ /** Human-readable source name */
238
+ sourceName: string;
239
+ /** The SQL that was executed */
240
+ sql: string;
241
+ /** Result data rows */
242
+ data: any[];
243
+ /** Number of rows returned */
244
+ count: number;
245
+ /** Total rows that matched before limit (if available) */
246
+ totalCount?: number;
247
+ /** Query execution time in milliseconds */
248
+ executionTimeMs: number;
249
+ /**
250
+ * True for rows that did NOT come from a real SQL execution — either a
251
+ * ctx.emit() dataset or the synthesized "computed:_final" entry that
252
+ * carries the script's post-JS returned data. The component generator
253
+ * uses this to route the resulting component through the script_dataset
254
+ * sentinel toolId so the frontend resolves it via the queryCache short-circuit.
255
+ */
256
+ virtual?: boolean;
257
+ }
258
+ /**
259
+ * Match tier returned by the LLM script matcher.
260
+ *
261
+ * - 'high': the script answers the question directly; only parameter values
262
+ * may differ. The runtime replays it with extracted params (cheapest path).
263
+ * - 'near': the script answers a STRUCTURALLY similar question but needs
264
+ * body modification (different metric, dimension, table, filter shape).
265
+ * The runtime forks the parent and adapts the body via MainAgent's normal
266
+ * write_script + execute_script loop — no SourceAgent dispatch needed.
267
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md for the full design.
268
+ * - 'edit': the user is INSTRUCTING a change to the script that produced the
269
+ * previous answer (not asking a new question). Only reachable when the turn
270
+ * carries a ScriptBinding — without one the matcher coerces it to 'none', so
271
+ * a prompt regression can't turn this into a loose similarity path. The
272
+ * runtime runs MainAgent in edit mode and commits the result in place.
273
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md.
274
+ * - 'none': no script is relevant; full agent flow runs.
275
+ */
276
+ type MatchTier = 'high' | 'near' | 'edit' | 'none';
277
+ /**
278
+ * Which recipe produced the answer the user is currently looking at.
279
+ *
280
+ * Set whenever a turn's answer came from a script (replay, fresh authoring, or
281
+ * a committed edit) and carried on the UIBlock + saved conversation row. Two
282
+ * consumers:
283
+ * 1. The matcher — the 'edit' tier is ONLY reachable when a binding exists, so
284
+ * "use mode instead of mean" resolves to a concrete script instead of being
285
+ * matched on keywords it shares with no script name.
286
+ * 2. Cache invalidation — after an edit commits, conversations bound to that
287
+ * recipeId must be dropped, or the exact-match cache replays the pre-edit
288
+ * answer and the edit looks like a no-op.
289
+ *
290
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
291
+ */
292
+ interface ScriptBinding {
293
+ recipeId: string;
294
+ /**
295
+ * The recipe's own version number at the moment THIS turn ran — not
296
+ * necessarily the recipe's current version. A later edit bumps the live
297
+ * version, so without this a past turn's binding would silently point at
298
+ * whatever the recipe looks like today instead of what actually produced
299
+ * that answer. Absent on bindings created before this field existed.
300
+ */
301
+ version?: number;
302
+ /** Params the script ran with — the edit's starting point. */
303
+ params: Record<string, any>;
304
+ /** Recipe name at bind time (matcher catalog + user-facing confirmation). */
305
+ name: string;
306
+ /** Columns the last run returned — grounds the editor without a re-query. */
307
+ columns?: string[];
308
+ /**
309
+ * The question that produced this answer. Required for disambiguation when a
310
+ * thread ran several scripts — without it the candidates are just names and
311
+ * the matcher cannot resolve "use the mode for the WSP one".
312
+ */
313
+ userPrompt?: string;
314
+ /**
315
+ * The polished analysis text this script actually produced last time it ran
316
+ * (the same programAnswer Thread.getConversationContext() shows elsewhere).
317
+ * Carried alongside the script's own shape (columns, params) so the matcher
318
+ * sees "what did this script actually say" right next to "what can I ask it
319
+ * to change", instead of needing a separate conversation-history transcript
320
+ * that would otherwise just repeat the same question this block already
321
+ * states. This is why ScriptMatcher's own prompt no longer receives a raw
322
+ * conversation-history transcript at all — this field is what replaced it.
323
+ */
324
+ answerSummary?: string;
325
+ }
326
+ /**
327
+ * Result from the LLM-based script matcher.
328
+ *
329
+ * For `tier: 'high'`, `extractedParams` carries the values to pass to the
330
+ * existing script. For `tier: 'near'`, `gaps` and `modificationHint` describe
331
+ * what the fork-author needs to change in the parent body.
332
+ */
333
+ interface ScriptMatch {
334
+ /** The matched script recipe */
335
+ recipe: ScriptRecipe;
336
+ /** Match tier — see MatchTier docs */
337
+ tier: MatchTier;
338
+ /** Similarity score (0-1, derived from LLM tier) */
339
+ similarity: number;
340
+ /**
341
+ * Legacy confidence level. Mirrors `tier === 'high'`/`'near'` for now;
342
+ * kept so existing callers compile while we migrate to tier-based logic.
343
+ */
344
+ confidence: 'high' | 'medium';
345
+ /** Parameters extracted from the user question by the LLM (tier='high') */
346
+ extractedParams?: Record<string, any>;
347
+ /**
348
+ * Proper nouns the question named, VERBATIM, with the parameter each fills.
349
+ *
350
+ * The matcher must NOT resolve these itself. Observed live: it substituted the
351
+ * customer name "PREMER ENRGES PHOTOOTAIC" into an id parameter believing that
352
+ * "the runtime will resolve the customer name to its PartyId(s)" — nothing on
353
+ * the replay path does, and `WHERE BillingPartyId IN (PREMER ENRGES
354
+ * PHOTOOTAIC)` reached SQL. Reported here, the runtime resolves them before
355
+ * replay and rejects the match when one cannot be resolved.
356
+ */
357
+ mentions?: Array<{
358
+ text: string;
359
+ param?: string;
360
+ }>;
361
+ /** Business concepts the question relies on (e.g. "outstanding balance"). */
362
+ entityTypes?: string[];
363
+ /** What the user question needs that the parent doesn't cover (tier='near') */
364
+ gaps?: string[];
365
+ /** One-sentence description of the change the fork-author should make (tier='near') */
366
+ modificationHint?: string;
367
+ /**
368
+ * Which HALF of the recipe the edit targets (tier='edit'). A recipe has two
369
+ * independently editable halves:
370
+ * - 'data' — the scriptBody: how the rows are produced (aggregation,
371
+ * filters, joins, grouping). Runs MainAgent in edit mode.
372
+ * - 'display' — the component specs: how those SAME rows are shown (chart
373
+ * type, orientation, columns, labels). Replays the proven SQL
374
+ * and regenerates the specs — never authors a script.
375
+ * Defaults to 'data' when the matcher omits it.
376
+ */
377
+ editTarget?: 'data' | 'display';
378
+ /**
379
+ * Self-contained restatement of the change the user asked for (tier='edit').
380
+ * MUST have pronouns/deixis resolved ("this", "it", "that column") — the edit
381
+ * prompt never sees the conversation history, so an unresolved instruction is
382
+ * unusable downstream.
383
+ */
384
+ editInstruction?: string;
385
+ /** Why the matcher made this choice (for logs and telemetry) */
386
+ reasoning?: string;
387
+ }
388
+
389
+ /**
390
+ * script-ipc.ts — Protocol definitions for parent/child IPC.
391
+ *
392
+ * Transport: newline-delimited JSON over the child's stdin/stdout.
393
+ * stderr is passed through for uncaught exceptions and compile errors.
394
+ *
395
+ * See backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md § IPC Bridge.
396
+ */
397
+
398
+ /**
399
+ * A name the user said, and what it resolved to.
400
+ *
401
+ * Handed to getAnalysis/getComponents so a narrative can NAME the thing the
402
+ * question was about without typing the name in. Before this, the runtime knew
403
+ * "Fusion5 Pty Ltd" and used that knowledge only to REJECT scripts that typed
404
+ * it — with no sanctioned way to obtain it, the only legal escape was to add a
405
+ * column to getData and re-run the query, spending an execute attempt to learn
406
+ * something the runtime already knew.
407
+ */
408
+ interface ResolvedEntityRef {
409
+ /** The text the user actually wrote. */
410
+ mention: string;
411
+ entityType: string;
412
+ instanceId: string;
413
+ displayName: string;
414
+ }
415
+ /**
416
+ * What getAnalysis returns. `analysis` is the narrative and `summary` the short
417
+ * bullets the markdown block binds to — siblings over one dataset, never a
418
+ * summary OF the narrative. See backend/docs/ANALYSIS-AS-PROGRAM-DESIGN.md § 4.3.
419
+ */
420
+ interface AnalysisOutput {
421
+ analysis?: string;
422
+ summary?: string[];
423
+ method?: string;
424
+ }
425
+
426
+ /**
427
+ * StreamBuffer - Buffered streaming utility for smoother text delivery
428
+ * Batches small chunks together and flushes at regular intervals
429
+ */
430
+ type StreamCallback = (chunk: string) => void;
431
+ /**
432
+ * StreamBuffer class for managing buffered streaming output
433
+ * Provides smooth text delivery by batching small chunks
434
+ */
435
+ declare class StreamBuffer {
436
+ private buffer;
437
+ private flushTimer;
438
+ private callback;
439
+ private fullText;
440
+ constructor(callback?: StreamCallback);
441
+ /**
442
+ * Check if the buffer has a callback configured
443
+ */
444
+ hasCallback(): boolean;
445
+ /**
446
+ * Get all text that has been written (including already flushed)
447
+ */
448
+ getFullText(): string;
449
+ /**
450
+ * Write a chunk to the buffer
451
+ * Large chunks or chunks with newlines are flushed immediately
452
+ * Small chunks are batched and flushed after a short interval
453
+ *
454
+ * @param chunk - Text chunk to write
455
+ */
456
+ write(chunk: string): void;
457
+ /**
458
+ * Flush the buffer immediately
459
+ * Call this before tool execution or other operations that need clean output
460
+ */
461
+ flush(): void;
462
+ /**
463
+ * Internal flush implementation
464
+ */
465
+ private flushNow;
466
+ /**
467
+ * Clean up resources
468
+ * Call this when done with the buffer
469
+ */
470
+ dispose(): void;
471
+ }
472
+
473
+ /**
474
+ * ToolExecutorService - Handles execution of SQL queries and external tools
475
+ * Extracted from BaseLLM.generateTextResponse for better separation of concerns
476
+ */
477
+
478
+ /**
479
+ * External tool definition
480
+ */
481
+ interface ExternalTool {
482
+ id: string;
483
+ name: string;
484
+ description?: string;
485
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
486
+ toolType?: 'source' | 'direct';
487
+ /** Full untruncated schema for source agent (all columns visible) */
488
+ fullSchema?: string;
489
+ /** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
490
+ schemaTier?: string;
491
+ /** Schema search function for very_large tier — keyword search over entities */
492
+ schemaSearchFn?: (keywords: string[]) => string;
493
+ /** `signal` fires when the user hits Stop mid-query — passed through to the backend's SourceTool.fn. */
494
+ fn: (input: any, signal?: AbortSignal) => Promise<any>;
495
+ limit?: number;
496
+ outputSchema?: any;
497
+ executionType?: 'immediate' | 'deferred';
498
+ userProvidedData?: any;
499
+ params?: Record<string, any>;
500
+ }
501
+ /**
502
+ * Executed tool tracking info
503
+ */
504
+ interface ExecutedToolInfo {
505
+ id: string;
506
+ name: string;
507
+ params: any;
508
+ result: {
509
+ _totalRecords: number;
510
+ _recordsShown: number;
511
+ _metadata?: any;
512
+ _sampleData: any[];
513
+ /** Bounded summary over the FULL fetched result (complete structure). */
514
+ _summary?: any;
515
+ /** Up to MAIN_AGENT_COMPLETE_ROWS rows — the complete result when small. */
516
+ _mainAgentRows?: any[];
517
+ };
518
+ /**
519
+ * THIS call's rows, at render size — deliberately a sibling of `result`, not a
520
+ * field inside it, because `result` is the object that gets picked apart for
521
+ * prompts (`_sampleData`, `_mainAgentRows`, `_summary`). Never put these in a
522
+ * prompt.
523
+ *
524
+ * Exists because a SourceAgentResult keeps only the LAST query's rows for a
525
+ * whole dispatch (see main-agent's "a follow-up query overwrites result.data"
526
+ * note). A component bound to an EARLIER query therefore rendered the later
527
+ * query's data — confirmed live: a revenue chart and a budget chart both drew
528
+ * budget, because both queries ran through one tool.
529
+ */
530
+ renderRows?: any[];
531
+ outputSchema?: any;
532
+ sourceSchema?: string;
533
+ sourceType?: string;
534
+ }
535
+
536
+ /**
537
+ * Multi-Agent Architecture Types
538
+ *
539
+ * Defines interfaces for the hierarchical agent system:
540
+ * - Main Agent: ONE LLM.streamWithTools() call with source agent tools
541
+ * - Source Agents: independent agents that query individual data sources
542
+ *
543
+ * The main agent sees only source summaries. When it calls a source tool,
544
+ * the SourceAgent runs independently (own LLM, own retries) and returns clean data.
545
+ */
546
+
547
+ /**
548
+ * Per-entity detail: name, row count, and column names.
549
+ * Gives the main agent enough context to route to the right source.
550
+ */
551
+ interface EntityDetail {
552
+ /** Entity name (table, sheet, endpoint) */
553
+ name: string;
554
+ /** Approximate row count */
555
+ rowCount?: number;
556
+ /** Column/field names */
557
+ columns: string[];
558
+ /** Entity-level semantic summary (what the table means) — for main-agent routing. */
559
+ summary?: string;
560
+ }
561
+ /**
562
+ * Representation of a data source for the main agent.
563
+ * Contains entity names WITH column names so the LLM can route accurately.
564
+ */
565
+ interface SourceSummary {
566
+ /** Source ID (matches tool ID prefix) */
567
+ id: string;
568
+ /** Human-readable source name */
569
+ name: string;
570
+ /** Source type: postgres, excel, rest_api, etc. */
571
+ type: string;
572
+ /** Brief description of what data this source contains */
573
+ description: string;
574
+ /** Detailed entity info with column names for routing */
575
+ entityDetails: EntityDetail[];
576
+ /** The tool ID associated with this source */
577
+ toolId: string;
578
+ }
579
+ /**
580
+ * What a source agent returns after querying its data source.
581
+ * The main agent uses this to analyze and compose the final response.
582
+ */
583
+ interface SourceAgentResult {
584
+ /** Source ID */
585
+ sourceId: string;
586
+ /** Source name */
587
+ sourceName: string;
588
+ /** Whether the query succeeded */
589
+ success: boolean;
590
+ /** Result data rows — bounded to MAIN_AGENT_COMPLETE_ROWS (Stage 2: what the LLM
591
+ * sees verbatim in its own prompt). NOT render-sized — do not bind a UI
592
+ * component's dataset to this field; use renderData instead. */
593
+ data: any[];
594
+ /** Result data rows bounded to MAX_ROWS_RENDERED (Stage 3: render-appropriate).
595
+ * This is what already-fetched (Stage 1, <=MAX_ROWS_FETCHED) rows look like
596
+ * before Stage 2 further truncates `data` down for the LLM's own context —
597
+ * use this, not `data`, whenever binding a UI component's dataset. */
598
+ renderData: any[];
599
+ /** Metadata about the query execution */
600
+ metadata: SourceAgentMetadata;
601
+ /** Tool execution info for the last successful query (backward compat) */
602
+ executedTool: ExecutedToolInfo;
603
+ /** All successful tool executions (primary + follow-up queries) */
604
+ allExecutedTools?: ExecutedToolInfo[];
605
+ /** Error message if failed */
606
+ error?: string;
607
+ }
608
+ interface SourceAgentMetadata {
609
+ /** Total rows that matched the query (before limit) */
610
+ totalRowsMatched: number;
611
+ /** Rows actually returned (after limit) */
612
+ rowsReturned: number;
613
+ /** Whether the result was truncated by the row limit */
614
+ isLimited: boolean;
615
+ /** The query/params that were executed */
616
+ queryExecuted?: string;
617
+ /** Execution time in milliseconds */
618
+ executionTimeMs: number;
619
+ }
620
+ /**
621
+ * A pre-built, multi-step UI flow registered with the SDK.
622
+ *
623
+ * When the main agent decides a user's question matches a workflow's whenToUse
624
+ * trigger, it picks the workflow instead of running source agents / generating
625
+ * dashboard components. The LLM extracts the workflow's required props from the
626
+ * prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
627
+ * workflow component directly — no analysis text, no chart generation. The
628
+ * frontend renders the registered workflow component with the LLM-extracted
629
+ * props.
630
+ */
631
+ interface WorkflowDescriptor {
632
+ /** Unique workflow id (used as the LLM tool name) */
633
+ id: string;
634
+ /** Component name on the frontend (matches the registered React component) */
635
+ name: string;
636
+ /** Short human-readable description of what this workflow does */
637
+ description: string;
638
+ /**
639
+ * 1–2 sentence trigger condition. The LLM uses this to decide if the
640
+ * user's prompt matches this workflow. Be specific — e.g.
641
+ * "User wants to *initiate* an inventory transfer (review + submit POs),
642
+ * not just see analysis or charts."
643
+ */
644
+ whenToUse: string;
645
+ /**
646
+ * JSON-schema-style description of the props the workflow needs. Becomes
647
+ * the LLM tool's input_schema, so the model fills these from the prompt.
648
+ * Use the same shape as `params` on direct tools — string descriptors with
649
+ * an optional "(optional)" suffix.
650
+ *
651
+ * Example:
652
+ * ```
653
+ * {
654
+ * selectedStore: 'object — { id, name } of the source branch',
655
+ * minROI: 'number (optional) — only show transfers with ROI ≥ this',
656
+ * }
657
+ * ```
658
+ */
659
+ propsSchema: Record<string, string>;
660
+ /**
661
+ * Optional: static prop defaults merged with LLM-extracted props before
662
+ * the component is returned. Useful for things like the embedded
663
+ * `externalTool` config that the workflow uses to fetch its own data.
664
+ */
665
+ defaultProps?: Record<string, any>;
666
+ }
667
+ /**
668
+ * The workflow selection captured during a routing call.
669
+ * Set on AgentResponse when the LLM picks a workflow tool.
670
+ */
671
+ interface SelectedWorkflow {
672
+ /** Component name (matches WorkflowDescriptor.name) */
673
+ name: string;
674
+ /** Props extracted from the prompt + merged with workflow.defaultProps */
675
+ props: Record<string, any>;
676
+ }
677
+ /**
678
+ * Set when this turn applies a user-directed edit to an existing script instead
679
+ * of authoring a new one. MainAgent keeps the SAME harness (tools, loop,
680
+ * write_script/execute_script verification) and swaps only the system prompt —
681
+ * `agent-main-edit` instead of `agent-main`.
682
+ *
683
+ * The two framings contradict each other on whether to query a source first, so
684
+ * they must never be resident in one rendered prompt.
685
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § D3.
686
+ */
687
+ interface EditContext {
688
+ /** Recipe being edited — the shadow draft records it as parentId. */
689
+ recipeId: string;
690
+ parentName: string;
691
+ parentBody: string;
692
+ /** Self-contained restatement of the change (from the matcher). */
693
+ instruction: string;
694
+ /** Columns the last run returned — grounds the edit without a re-query. */
695
+ lastResultColumns?: string[];
696
+ /** Rendered parameter list of the parent, for the prompt. */
697
+ parentParams?: string;
698
+ }
699
+ /**
700
+ * The complete response from the multi-agent system.
701
+ * Contains everything needed for text display + component generation.
702
+ */
703
+ interface AgentResponse {
704
+ /** Generated text response (analysis of the data) */
705
+ text: string;
706
+ /**
707
+ * Program-generated narrative when the script exported getAnalysis. `text`
708
+ * already carries `analysis.analysis`; this also exposes `summary`, which
709
+ * the markdown block binds to instead of being an LLM summary of the prose.
710
+ */
711
+ analysis?: AnalysisOutput;
712
+ /** All executed tools across all source agents (for component generation) */
713
+ executedTools: ExecutedToolInfo[];
714
+ /** Individual results from each source agent */
715
+ sourceResults: SourceAgentResult[];
716
+ /**
717
+ * Populated when MainAgent wrote AND successfully executed a script during its turn.
718
+ * Caller (agent-user-response.ts) persists it via ScriptStore.save().
719
+ * Absent when MainAgent didn't write one (trivial question / all attempts failed).
720
+ */
721
+ savedScript?: AgentWrittenScript;
722
+ /** Failed execute_script tool_result texts this turn, in order — see RunTrace.script.failedAttempts. */
723
+ failedScriptAttempts?: string[];
724
+ /**
725
+ * Set when the LLM routed the question to a registered workflow component.
726
+ * When present, the upstream caller should skip component generation and
727
+ * return this workflow as the response.
728
+ */
729
+ workflow?: SelectedWorkflow;
730
+ /**
731
+ * Validated component specs the agent authored via `write_components`.
732
+ * When present the caller assembles the dashboard from these instead of
733
+ * running the component-generation LLM. Absent when the agent didn't call
734
+ * the tool — the caller then falls back to `generateScriptComponents`.
735
+ * See backend/docs/COMPONENT-GENERATION-V2.md §2.2.
736
+ */
737
+ componentSpecs?: ScriptComponentSpec[];
738
+ /** Layout title/description from the same `write_components` call. */
739
+ componentLayout?: {
740
+ title: string;
741
+ description?: string;
742
+ };
743
+ }
744
+ /**
745
+ * A script MainAgent authored + verified during its turn. Shape aligns with
746
+ * what ScriptStore.save() needs — minus store-assigned fields (id, timestamps, counts).
747
+ */
748
+ interface AgentWrittenScript {
749
+ /**
750
+ * `ScriptRecipe.id` of the draft that was authored + verified during this turn.
751
+ * The caller passes this to `ScriptStore.promoteToVerified(recipeId, …)` to
752
+ * flip the draft to verified status and (when possible) drop the turn-suffix
753
+ * from its filename.
754
+ */
755
+ recipeId: string;
756
+ name: string;
757
+ intentDescription: string;
758
+ tags: string[];
759
+ parameters: Array<{
760
+ name: string;
761
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
762
+ required: boolean;
763
+ default?: any;
764
+ enumValues?: Record<string, string>;
765
+ description: string;
766
+ }>;
767
+ scriptBody: string;
768
+ /** Source IDs referenced by the script (extracted from ctx.query calls) */
769
+ sourceIds: string[];
770
+ /** Tables referenced in the script's SQL (regex-extracted) */
771
+ tables: string[];
772
+ /** Executed queries from the verified run — fed to component generation */
773
+ executedQueries: Array<{
774
+ sourceId: string;
775
+ sourceName: string;
776
+ sql: string;
777
+ data: any[];
778
+ count: number;
779
+ totalCount?: number;
780
+ executionTimeMs: number;
781
+ /**
782
+ * True for synthetic entries (ctx.emit datasets, the computed:_final
783
+ * post-JS data). The component generator routes virtual sources through
784
+ * the script_dataset sentinel toolId so the frontend resolves them via
785
+ * queryCache instead of attempting to re-execute SQL.
786
+ */
787
+ virtual?: boolean;
788
+ }>;
789
+ /** The tool_result JSON MainAgent's LLM got back from execute_script — see RunTrace.script.executionResult. */
790
+ executionResult?: string;
791
+ }
792
+ /**
793
+ * Debug trace for a single chat_agent turn — which KB/schema nodes were
794
+ * retrieved and considered, and which script (if any) produced the answer.
795
+ * Persisted separately from the answer itself (fusion-5's
796
+ * `conversation_traces` table, written via `saveTrace`), never sent through
797
+ * `analyticsClient` (data-residency — see design doc §5).
798
+ */
799
+ interface RunTrace {
800
+ version: 1;
801
+ kbNodes: {
802
+ /**
803
+ * Always-on nodes included regardless of the question (getGlobalKnowledgeBase).
804
+ * `content` is the node's full text AS IT WAS at retrieval time — captured so a
805
+ * later edit/delete of the KB node doesn't erase what the LLM actually saw.
806
+ */
807
+ global: Array<{
808
+ kbId: string;
809
+ title: string;
810
+ content?: string;
811
+ }>;
812
+ /** Semantically matched for this specific question (getKnowledgeBase). Same `content` reasoning as above. */
813
+ query: Array<{
814
+ kbId: string;
815
+ title: string;
816
+ similarity?: number;
817
+ content?: string;
818
+ }>;
819
+ };
820
+ schemaNodes: {
821
+ /** MainAgent's cross-source prefilter — which sources were even considered. */
822
+ routing: Array<{
823
+ sourceId: string;
824
+ sourceName?: string;
825
+ similarity: number;
826
+ }>;
827
+ /** SourceAgent-scope per-source table resolution (MainAgent.preResolveSchema). */
828
+ preResolve: Array<{
829
+ sourceId: string;
830
+ table?: string;
831
+ description?: string;
832
+ similarity: number;
833
+ }>;
834
+ /**
835
+ * The exact {{SOURCE_SUMMARIES}} text injected into MainAgent's system prompt
836
+ * (agent-prompt-builder.ts's formatSummariesForPrompt output) — every
837
+ * registered source's catalog entry, not retrieval-specific, captured once per
838
+ * turn. This is what the main agent actually saw when deciding which source(s)
839
+ * to call.
840
+ */
841
+ mainAgentCatalog?: string;
842
+ /**
843
+ * One entry per SourceAgent dispatch (a source called twice in one turn gets
844
+ * two entries) — the exact {{FULL_SCHEMA}} text injected into that
845
+ * SourceAgent's own system prompt, however it was sourced, plus any
846
+ * search_schema follow-up lookups it made mid-conversation when the schema
847
+ * shown wasn't enough.
848
+ */
849
+ sourceAgentSchemas: Array<{
850
+ sourceId: string;
851
+ sourceName?: string;
852
+ /**
853
+ * The exact intent text this dispatch's own prompt was built from —
854
+ * captured in SourceAgent.buildPrompt, so it ALREADY includes the
855
+ * resolved-entities and resolved-concepts blocks MainAgent appends by
856
+ * code before calling execute() (see buildResolvedEntitiesBlock /
857
+ * buildResolvedConceptsBlock) — not just what the LLM itself wrote.
858
+ */
859
+ intent: string;
860
+ /** How `schemaText` was sourced — see SourceAgent.buildPrompt's fullSchema fallback chain. */
861
+ method: 'preresolved-embedding' | 'tool-full-schema' | 'tool-description' | 'none';
862
+ schemaText: string;
863
+ /** In call order — each search_schema tool call this SourceAgent made, and the exact result text handed back to its own LLM. */
864
+ searchSchemaLookups: Array<{
865
+ keywords: string[];
866
+ result: string;
867
+ }>;
868
+ /** The tool_result text MainAgent's LLM read back for this dispatch (formatResultForMainAgent output). */
869
+ result?: string;
870
+ /**
871
+ * The full resolved-concept bodies this dispatch's intent was built
872
+ * with (the same content already baked into `intent` via
873
+ * buildResolvedConceptsBlock, surfaced here structured/separately so a
874
+ * trace reader doesn't have to parse it back out of the raw text).
875
+ * Stamped AFTER execute() resolves — same timing as `result` above —
876
+ * specifically so its presence here is proof the concepts were part
877
+ * of the prompt actually sent, not just of what MainAgent intended to
878
+ * send before the call happened.
879
+ */
880
+ resolvedConcepts?: Array<{
881
+ name: string;
882
+ kind: string;
883
+ body: string;
884
+ }>;
885
+ /** This dispatch's `SourceToolInput.aggregation` ('raw' | 'pre-aggregate' | 'summary') — decides which AGGREGATION_MODE text this SourceAgent's own prompt got. */
886
+ aggregation?: string;
887
+ /** The exact DATABASE_RULES text this SourceAgent's own prompt got (promptLoader.loadDatabaseRulesForType). */
888
+ databaseRulesText?: string;
889
+ /** The exact ROW_LIMIT_SYNTAX text this SourceAgent's own prompt got. */
890
+ rowLimitSyntaxText?: string;
891
+ /** The exact SCHEMA_SEARCH_INSTRUCTIONS text this SourceAgent's own prompt got — the guidance, not the runtime searchSchemaLookups results above. */
892
+ schemaSearchInstructionsText?: string;
893
+ /** The literal tool definitions (query tool + search_schema tool, when offered) handed to this SourceAgent's own LLM.streamWithTools call. */
894
+ toolsSent?: any[];
895
+ /** This SourceAgent's own LLM.streamWithTools call config. */
896
+ callConfig?: {
897
+ model?: string;
898
+ maxTokens?: number;
899
+ temperature?: number;
900
+ maxIterations?: number;
901
+ };
902
+ /** The exact USER_ACCESS_CONTEXT text this SourceAgent's own prompt got — its own copy of the same value captured once at the turn level in userAccessContext. */
903
+ userAccessContextText?: string;
904
+ }>;
905
+ };
906
+ /**
907
+ * Concept-catalog activity this turn (see main-agent.ts's loadConceptCatalog /
908
+ * loadConceptInvariants / RESOLVE_CONCEPTS_TOOL_DEF). Parallel to
909
+ * `entityResolution` above. Absent/empty for a project with no concepts
910
+ * collection registered.
911
+ */
912
+ concepts: {
913
+ /** The exact {{CONCEPT_CATALOG}} text injected into MainAgent's system prompt (names + aliases only — bodies come back via resolve_concepts). */
914
+ catalogText?: string;
915
+ /** The exact {{CONCEPT_INVARIANTS}} text injected into MainAgent's system prompt — always-on, never requested by the LLM. Distinct from the resolved-concept bodies below, which mix invariants and explicitly-resolved concepts together. */
916
+ invariantsText?: string;
917
+ /** One entry per resolve_concepts-driven resolution this turn — explicit tool calls, resolve_entities-triggered concept lookups, and (for the dashboard flow) its own concept tool. */
918
+ calls: Array<{
919
+ via: 'resolve_concepts' | 'resolve_entities' | 'dashboard-agent';
920
+ asked?: string[];
921
+ implied?: string[];
922
+ returned?: Array<{
923
+ kind: string;
924
+ name: string;
925
+ returns?: any;
926
+ definition: string;
927
+ viaRequires?: boolean;
928
+ }>;
929
+ viaFloor?: string[];
930
+ corrected?: Array<{
931
+ asked: string;
932
+ matched: string;
933
+ }>;
934
+ unmatched?: string[];
935
+ suggestions?: string[];
936
+ error?: string;
937
+ note?: string;
938
+ }>;
939
+ };
940
+ /** The script that produced this answer, if any. Null for a general (no-tool) answer. */
941
+ script: {
942
+ /** True when an existing recipe was replayed unchanged (ScriptMatcher tier='high'). */
943
+ reused: boolean;
944
+ recipeId?: string | null;
945
+ body?: string | null;
946
+ /** Set when reused — the matcher's reasoning for picking this recipe. */
947
+ reasoning?: string | null;
948
+ /** The winning execute_script tool_result text. Only set when reused=false — a replay never re-runs execute_script. Failed attempts aren't kept. */
949
+ executionResult?: string | null;
950
+ /** Failed execute_script tool_result texts this turn, in order (before the winning one, if any). */
951
+ failedAttempts?: string[];
952
+ } | null;
953
+ /**
954
+ * Everything ScriptMatcher.match() built and sent to its one LLM call this
955
+ * turn — Step 2 of the request flow, immediately after Step 1's exact-match
956
+ * check misses. Captured even when short-circuited before any LLM call, or
957
+ * when the call itself errored, so "why didn't this reuse a script" can
958
+ * always be answered from the trace alone, not just the outcome in `script`.
959
+ * See backend/docs/user-prompt-req-flow/SCRIPT-MATCH-IMPROVEMENTS.md.
960
+ */
961
+ scriptMatcher: {
962
+ /**
963
+ * Exactly what went INTO the one LLM call — every placeholder value
964
+ * substituted into `.prompts/script-match/system.md`, plus the routing
965
+ * facts (isExplicitEdit, the two counts) that aren't literal prompt text
966
+ * but explain WHY the catalog/active-script blocks look the way they do.
967
+ */
968
+ sent: {
969
+ /** Whether the raw prompt carried the explicit "edit :" prefix (see parseEditPrefix). */
970
+ isExplicitEdit: boolean;
971
+ /** The prefix-stripped question actually shown to the LLM (the USER_PROMPT placeholder). */
972
+ userPrompt: string;
973
+ /** The Edit Signal text handed to the LLM this turn (CONFIRMED/NOT CONFIRMED wording). */
974
+ editSignal: string;
975
+ /** The rendered "Scripts From Your Past Questions" catalog text (SCRIPT_CATALOG placeholder). */
976
+ scriptCatalog: string;
977
+ /** Distinct scripts actually in scriptCatalog, after health-filtering and the MAX_CATALOG_RECIPES cap. */
978
+ catalogRecipeCount: number;
979
+ /** The rendered "EDITABLE SCRIPTS" block text (ACTIVE_SCRIPT placeholder) — '' when the thread has no active bindings. */
980
+ activeScript: string;
981
+ /** Active bindings offered as edit candidates this turn. */
982
+ activeBindingCount: number;
983
+ /** This call's LLM.stream config. */
984
+ model?: string;
985
+ maxTokens?: number;
986
+ temperature?: number;
987
+ };
988
+ /**
989
+ * Everything that came back OUT — the LLM's raw answer plus what the
990
+ * runtime decided to do with it. `tier` here is the FINAL tier after
991
+ * every coercion (near→none, the edit-prefix gate, candidate checks) —
992
+ * it can legitimately differ from `rawResponse.tier`.
993
+ */
994
+ received: {
995
+ /** False when short-circuited before any LLM call (no catalog match AND no active bindings) — `rawResponse`/`tier` below don't apply. */
996
+ calledLLM: boolean;
997
+ /** The raw JSON the LLM returned, when calledLLM is true and the call didn't throw. */
998
+ rawResponse?: any;
999
+ /** Set when calledLLM is true and the call threw, or the response named an unknown script id. */
1000
+ error?: string;
1001
+ /** Final tier after ALL coercions. Null when short-circuited, errored, or the call/coercions landed on no match. */
1002
+ tier: MatchTier | null;
1003
+ };
1004
+ } | null;
1005
+ /**
1006
+ * `resolve_entities` tool activity this turn (see main-agent.ts's
1007
+ * RESOLVE_ENTITIES_TOOL_DEF / handleResolveEntities) — names/identifiers the
1008
+ * user mentioned, resolved to database ids before any SQL was written.
1009
+ * Absent/empty entirely for a project with no entity-search collection
1010
+ * registered, or a turn that named nothing.
1011
+ */
1012
+ entityResolution: {
1013
+ /**
1014
+ * The entity-type catalog text injected into MainAgent's system prompt
1015
+ * (loadEntityCatalog's output) — what let the LLM name a concept instead
1016
+ * of guessing the project's vocabulary. Captured once per turn.
1017
+ */
1018
+ catalogText?: string;
1019
+ /**
1020
+ * One entry per `resolve_entities` tool call this turn (a turn can call it
1021
+ * more than once) — the FULL raw response from the entity-search
1022
+ * collection, not just the trimmed {mention,entityType,instanceId,
1023
+ * displayName} MainAgent keeps for itself to build the dispatch block.
1024
+ * `score`/`ambiguous`/`alternatives` only exist here, nowhere else.
1025
+ */
1026
+ calls: Array<{
1027
+ mentions: Array<{
1028
+ text: string;
1029
+ entityType?: string;
1030
+ }>;
1031
+ entityTypes: string[];
1032
+ resolved: Array<{
1033
+ mention: string;
1034
+ entityType: string;
1035
+ instanceId: string;
1036
+ displayName: string;
1037
+ attrs?: Record<string, any>;
1038
+ score?: number;
1039
+ ambiguous?: boolean;
1040
+ alternatives?: Array<{
1041
+ instanceId: string;
1042
+ displayName: string;
1043
+ score: number;
1044
+ }>;
1045
+ }>;
1046
+ unresolved: string[];
1047
+ entityMap: Record<string, any>;
1048
+ unmatchedEntityTypes?: Array<{
1049
+ requested: string;
1050
+ candidates?: string[];
1051
+ }>;
1052
+ /** Set when the collection call itself failed (fails open — see handleResolveEntities). */
1053
+ error?: string;
1054
+ /** Set on an early return (unavailable / nothing named) so the call is still visible in the trace, not indistinguishable from never having run. */
1055
+ note?: string;
1056
+ }>;
1057
+ };
1058
+ /**
1059
+ * The prior-turn conversation context injected into this turn's prompt as
1060
+ * CONVERSATION_HISTORY — exactly what each flow already builds for itself
1061
+ * (chat: thread.getConversationContext(); report/dashboard: their own
1062
+ * equivalents), captured as-is. Every call site sets this unconditionally
1063
+ * (empty string '' when there's no prior context — new thread, or history
1064
+ * trimmed to nothing), so an empty turn is visibly "no history" in the
1065
+ * saved trace rather than a silently missing key. Optional only because
1066
+ * traces saved before this field existed won't have it at all.
1067
+ */
1068
+ conversationHistory?: string;
1069
+ /**
1070
+ * The exact {{USER_ACCESS_CONTEXT}} text injected into MainAgent's system
1071
+ * prompt — the per-user authorization config (sa-api users.config)
1072
+ * rendered by buildUserAccessContext, as-is. Captured once (MainAgent's
1073
+ * prompt is what SourceAgent's identical value is derived from — no need
1074
+ * to duplicate it per source dispatch). Set unconditionally (empty string
1075
+ * '' when there's no config for this user), so "no restrictions" is
1076
+ * visible in the saved trace rather than a silently missing key. Optional
1077
+ * only because traces saved before this field existed won't have it.
1078
+ */
1079
+ userAccessContext?: string;
1080
+ /**
1081
+ * The exact per-user knowledge-base text injected into MainAgent's system
1082
+ * prompt (getUserKnowledgeBase's output, folded into KNOWLEDGE_BASE_CONTEXT
1083
+ * alongside the query-matched half already captured in kbNodes.query).
1084
+ * Captured separately because it's a distinct fetch with no node-level
1085
+ * structure to list, unlike kbNodes.
1086
+ */
1087
+ userKbContext?: string;
1088
+ /** The literal tool definitions (source, direct, workflow, resolve_entities, resolve_concepts, write_script, execute_script, write_analysis, write_components — whichever were actually offered this turn) handed to MainAgent's LLM.streamWithTools call. */
1089
+ toolsSent?: any[];
1090
+ /** The exact {{DIRECT_TOOLS}} text injected into MainAgent's system prompt. */
1091
+ directToolsText?: string;
1092
+ /** The exact {{WORKFLOW_COMPONENTS}} text injected into MainAgent's system prompt. */
1093
+ workflowsText?: string;
1094
+ /** The exact {{SCRIPT_BODY_CONTRACT}} text injected into MainAgent's system prompt (promptLoader.loadScriptBodyContract). */
1095
+ scriptBodyContractText?: string;
1096
+ /**
1097
+ * Full edit-mode context as sent to MainAgent this turn — every EditContext
1098
+ * field, not just the instruction already folded into `script.reasoning`.
1099
+ * Null for a non-edit turn.
1100
+ */
1101
+ editContext?: {
1102
+ recipeId?: string;
1103
+ parentName?: string;
1104
+ parentBody?: string;
1105
+ instruction?: string;
1106
+ lastResultColumns?: string[];
1107
+ parentParams?: string;
1108
+ } | null;
1109
+ /**
1110
+ * The fork-mode preamble as actually assembled and prepended to the user
1111
+ * prompt (agent-user-response.ts) — parentBody/gaps/modificationHint as
1112
+ * sent, plus the lineage fields also written to the script store separately
1113
+ * (parentRecipeId/forkDepth/forkReason). Null for a non-fork turn.
1114
+ */
1115
+ forkContext?: {
1116
+ parentBody?: string;
1117
+ gaps?: string;
1118
+ modificationHint?: string;
1119
+ parentRecipeId?: string;
1120
+ forkDepth?: number;
1121
+ forkReason?: string;
1122
+ } | null;
1123
+ /** The write_analysis tool call's analysisBody argument this turn, when called. */
1124
+ writeAnalysisBody?: string;
1125
+ /** The write_components tool call's componentsBody argument this turn, when called. */
1126
+ writeComponentsBody?: string;
1127
+ /**
1128
+ * Component-generation/re-authoring activity this turn — one entry per call
1129
+ * to `authorComponentsProgram` (script-component-generator.ts — the
1130
+ * display-edit path, reauthoring getComponents as a program),
1131
+ * `generateScriptComponents` (the script-replay fallback, spec/analysis-based
1132
+ * generation), or `summarizeToMarkdown` (its own small analysis-summary LLM
1133
+ * call, reached via `assembleComponentsFromSpecs`). A turn can hit more than
1134
+ * one of these across its fallback chain, so this is an array, not a
1135
+ * singleton — same pattern as `concepts.calls`/`entityResolution.calls`.
1136
+ */
1137
+ componentGen: Array<{
1138
+ via: 'authorComponentsProgram' | 'generateScriptComponents' | 'summarizeToMarkdown';
1139
+ /** authorComponentsProgram only: the edit instruction driving the re-author. */
1140
+ instruction?: string;
1141
+ /** authorComponentsProgram only: the component body being revised, before this attempt. */
1142
+ currentBody?: string;
1143
+ /** Dataset shapes/schemas the LLM was shown (both generation paths, different derivation). */
1144
+ datasetShapes?: string;
1145
+ /** The component catalog text/list handed to the LLM. */
1146
+ componentCatalog?: string;
1147
+ /** generateScriptComponents only: source name(s) shown (SOURCE_NAME). */
1148
+ sourceName?: string;
1149
+ /** generateScriptComponents only: row count(s) shown (ROW_COUNT). */
1150
+ rowCount?: string;
1151
+ /** generateScriptComponents only: column descriptions text shown. */
1152
+ columnDescriptions?: string;
1153
+ /** generateScriptComponents/summarizeToMarkdown: the analysis text handed to the LLM. */
1154
+ analysisText?: string;
1155
+ /** This call's LLM config. */
1156
+ callConfig?: {
1157
+ model?: string;
1158
+ maxTokens?: number;
1159
+ temperature?: number;
1160
+ };
1161
+ /** authorComponentsProgram only: one entry per retry attempt — the feedback fed back in and the raw response for that attempt, in order. */
1162
+ attempts?: Array<{
1163
+ feedback?: string;
1164
+ rawResponse?: string;
1165
+ }>;
1166
+ /** The final raw LLM response text for this call (last attempt, for authorComponentsProgram's retry loop; the single response otherwise). */
1167
+ rawResponse?: string;
1168
+ }>;
1169
+ }
1170
+ /**
1171
+ * Configuration for the multi-agent system.
1172
+ * Controls limits, models, and behavior.
1173
+ */
1174
+ interface AgentConfig {
1175
+ /** Max rows shown to the UI preview / inlined per source (default: 10) */
1176
+ maxRowsPerSource: number;
1177
+ /**
1178
+ * Max rows a source query may FETCH from the DB server-side (default: 2000).
1179
+ * Decoupled from what the main agent is shown: the full result is fetched and
1180
+ * summarized (bounded), but only a small/complete slice enters LLM context.
1181
+ * This lets small lookups (benchmark maps) arrive COMPLETE without letting
1182
+ * large results blow up context.
1183
+ */
1184
+ maxRowsFetched: number;
1185
+ /** Model for the main agent (routing + analysis in one LLM call) */
1186
+ mainAgentModel: string;
1187
+ /** Model for source agent query generation */
1188
+ sourceAgentModel: string;
1189
+ /** API key for LLM calls */
1190
+ apiKey?: string;
1191
+ /** Max retry attempts per source agent */
1192
+ maxRetries: number;
1193
+ /** Max tool calling iterations for the main agent loop */
1194
+ maxIterations: number;
1195
+ /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
1196
+ globalKnowledgeBase?: string;
1197
+ /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
1198
+ knowledgeBaseContext?: string;
1199
+ /** Per-user authorization config (sa-api users.config), rendered to text — see buildUserAccessContext */
1200
+ userAccessContext?: string;
1201
+ /** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
1202
+ collections?: any;
1203
+ /** Optional project ID for scoping embedding searches */
1204
+ projectId?: string;
1205
+ /**
1206
+ * Optional debug-trace accumulator for this turn (Phase 1, chat_agent only).
1207
+ * When present, MainAgent-scope retrieval call sites (e.g. preResolveSchema)
1208
+ * push their structured results into it. Absent for callers that don't care
1209
+ * about trace capture (e.g. headless flows) — every push site must treat
1210
+ * this as optional and never let a capture failure affect the real answer.
1211
+ */
1212
+ trace?: RunTrace;
1213
+ }
1214
+ /**
1215
+ * Default agent configuration
1216
+ */
1217
+ declare const DEFAULT_AGENT_CONFIG: AgentConfig;
1218
+
4
1219
  /**
5
1220
  * Unified UIBlock structure for database storage
6
- * Used in both bookmarks and user-conversations tables
1221
+ * Used in both bookmarks and user-conversations tables.
1222
+ *
1223
+ * `analysis` always holds whatever real narration exists — the full answer on
1224
+ * success, or whatever was actually streamed before a failure (may be empty).
1225
+ * `error` is a dedicated field, null on success — it can be a plain string OR
1226
+ * a structured object/array (e.g. the agent's raw `errors` list), whatever
1227
+ * shape the failure naturally has; it's never coerced into `analysis`.
7
1228
  */
8
1229
  interface DBUIBlock {
9
1230
  id: string;
10
1231
  component: Record<string, any> | null;
11
1232
  analysis: string | null;
12
1233
  user_prompt: string;
1234
+ error?: unknown | null;
1235
+ /**
1236
+ * The script recipe that produced this answer, when one did. Read back via
1237
+ * `conversation-history.exactMatch` so an edit follow-up still has a target
1238
+ * after a reload (the in-memory thread is gone by then), and indexed so
1239
+ * committing an edit can purge every cached answer bound to the recipe.
1240
+ */
1241
+ scriptBinding?: {
1242
+ recipeId: string;
1243
+ params?: Record<string, any>;
1244
+ name?: string;
1245
+ columns?: string[];
1246
+ };
13
1247
  }
14
1248
 
15
1249
  /**
@@ -160,6 +1394,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
160
1394
  dependencies?: string[] | undefined;
161
1395
  } | undefined;
162
1396
  props?: Record<string, any> | undefined;
1397
+ data?: Record<string, any> | undefined;
163
1398
  render?: any;
164
1399
  states?: Record<string, any> | undefined;
165
1400
  methods?: Record<string, {
@@ -170,7 +1405,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
170
1405
  fn: string;
171
1406
  deps?: string[] | undefined;
172
1407
  }[] | undefined;
173
- data?: Record<string, any> | undefined;
174
1408
  pages?: {
175
1409
  id: string;
176
1410
  name: string;
@@ -192,6 +1426,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
192
1426
  dependencies?: string[] | undefined;
193
1427
  } | undefined;
194
1428
  props?: Record<string, any> | undefined;
1429
+ data?: Record<string, any> | undefined;
195
1430
  render?: any;
196
1431
  states?: Record<string, any> | undefined;
197
1432
  methods?: Record<string, {
@@ -202,7 +1437,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
202
1437
  fn: string;
203
1438
  deps?: string[] | undefined;
204
1439
  }[] | undefined;
205
- data?: Record<string, any> | undefined;
206
1440
  pages?: {
207
1441
  id: string;
208
1442
  name: string;
@@ -228,6 +1462,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
228
1462
  dependencies?: string[] | undefined;
229
1463
  } | undefined;
230
1464
  props?: Record<string, any> | undefined;
1465
+ data?: Record<string, any> | undefined;
231
1466
  render?: any;
232
1467
  states?: Record<string, any> | undefined;
233
1468
  methods?: Record<string, {
@@ -238,7 +1473,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
238
1473
  fn: string;
239
1474
  deps?: string[] | undefined;
240
1475
  }[] | undefined;
241
- data?: Record<string, any> | undefined;
242
1476
  pages?: {
243
1477
  id: string;
244
1478
  name: string;
@@ -264,6 +1498,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
264
1498
  dependencies?: string[] | undefined;
265
1499
  } | undefined;
266
1500
  props?: Record<string, any> | undefined;
1501
+ data?: Record<string, any> | undefined;
267
1502
  render?: any;
268
1503
  states?: Record<string, any> | undefined;
269
1504
  methods?: Record<string, {
@@ -274,7 +1509,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
274
1509
  fn: string;
275
1510
  deps?: string[] | undefined;
276
1511
  }[] | undefined;
277
- data?: Record<string, any> | undefined;
278
1512
  pages?: {
279
1513
  id: string;
280
1514
  name: string;
@@ -355,6 +1589,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
355
1589
  dependencies?: string[] | undefined;
356
1590
  } | undefined;
357
1591
  props?: Record<string, any> | undefined;
1592
+ data?: Record<string, any> | undefined;
358
1593
  render?: any;
359
1594
  states?: Record<string, any> | undefined;
360
1595
  methods?: Record<string, {
@@ -365,7 +1600,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
365
1600
  fn: string;
366
1601
  deps?: string[] | undefined;
367
1602
  }[] | undefined;
368
- data?: Record<string, any> | undefined;
369
1603
  }, {
370
1604
  id: string;
371
1605
  name?: string | undefined;
@@ -379,6 +1613,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
379
1613
  dependencies?: string[] | undefined;
380
1614
  } | undefined;
381
1615
  props?: Record<string, any> | undefined;
1616
+ data?: Record<string, any> | undefined;
382
1617
  render?: any;
383
1618
  states?: Record<string, any> | undefined;
384
1619
  methods?: Record<string, {
@@ -389,7 +1624,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
389
1624
  fn: string;
390
1625
  deps?: string[] | undefined;
391
1626
  }[] | undefined;
392
- data?: Record<string, any> | undefined;
393
1627
  }>;
394
1628
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
395
1629
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -407,6 +1641,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
407
1641
  dependencies?: string[] | undefined;
408
1642
  } | undefined;
409
1643
  props?: Record<string, any> | undefined;
1644
+ data?: Record<string, any> | undefined;
410
1645
  render?: any;
411
1646
  states?: Record<string, any> | undefined;
412
1647
  methods?: Record<string, {
@@ -417,7 +1652,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
417
1652
  fn: string;
418
1653
  deps?: string[] | undefined;
419
1654
  }[] | undefined;
420
- data?: Record<string, any> | undefined;
421
1655
  };
422
1656
  data?: Record<string, any> | undefined;
423
1657
  context?: Record<string, any> | undefined;
@@ -435,6 +1669,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
435
1669
  dependencies?: string[] | undefined;
436
1670
  } | undefined;
437
1671
  props?: Record<string, any> | undefined;
1672
+ data?: Record<string, any> | undefined;
438
1673
  render?: any;
439
1674
  states?: Record<string, any> | undefined;
440
1675
  methods?: Record<string, {
@@ -445,7 +1680,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
445
1680
  fn: string;
446
1681
  deps?: string[] | undefined;
447
1682
  }[] | undefined;
448
- data?: Record<string, any> | undefined;
449
1683
  };
450
1684
  data?: Record<string, any> | undefined;
451
1685
  context?: Record<string, any> | undefined;
@@ -634,23 +1868,20 @@ declare const ComponentSchema: z.ZodObject<{
634
1868
  type: z.ZodString;
635
1869
  description: z.ZodString;
636
1870
  props: z.ZodObject<{
637
- query: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>;
1871
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
638
1872
  title: z.ZodOptional<z.ZodString>;
639
1873
  description: z.ZodOptional<z.ZodString>;
640
1874
  config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
641
- actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
642
1875
  }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
643
- query: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>;
1876
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
644
1877
  title: z.ZodOptional<z.ZodString>;
645
1878
  description: z.ZodOptional<z.ZodString>;
646
1879
  config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
647
- actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
648
1880
  }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
649
- query: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>;
1881
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
650
1882
  title: z.ZodOptional<z.ZodString>;
651
1883
  description: z.ZodOptional<z.ZodString>;
652
1884
  config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
653
- actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
654
1885
  }, z.ZodTypeAny, "passthrough">>;
655
1886
  category: z.ZodOptional<z.ZodString>;
656
1887
  keywords: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
@@ -661,10 +1892,9 @@ declare const ComponentSchema: z.ZodObject<{
661
1892
  description: string;
662
1893
  props: {
663
1894
  description?: string | undefined;
664
- query?: string | {} | undefined;
1895
+ query?: string | {} | null | undefined;
665
1896
  title?: string | undefined;
666
1897
  config?: Record<string, unknown> | undefined;
667
- actions?: any[] | undefined;
668
1898
  } & {
669
1899
  [k: string]: unknown;
670
1900
  };
@@ -679,10 +1909,9 @@ declare const ComponentSchema: z.ZodObject<{
679
1909
  description: string;
680
1910
  props: {
681
1911
  description?: string | undefined;
682
- query?: string | {} | undefined;
1912
+ query?: string | {} | null | undefined;
683
1913
  title?: string | undefined;
684
1914
  config?: Record<string, unknown> | undefined;
685
- actions?: any[] | undefined;
686
1915
  } & {
687
1916
  [k: string]: unknown;
688
1917
  };
@@ -741,6 +1970,10 @@ declare const ToolSchema: z.ZodObject<{
741
1970
  id: z.ZodString;
742
1971
  name: z.ZodString;
743
1972
  description: z.ZodString;
1973
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
1974
+ toolType: z.ZodOptional<z.ZodEnum<["source", "direct"]>>;
1975
+ /** Full untruncated schema for source agent (all columns visible) */
1976
+ fullSchema: z.ZodOptional<z.ZodString>;
744
1977
  params: z.ZodRecord<z.ZodString, z.ZodString>;
745
1978
  fn: z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodAny>;
746
1979
  outputSchema: z.ZodOptional<z.ZodObject<{
@@ -773,12 +2006,22 @@ declare const ToolSchema: z.ZodObject<{
773
2006
  description: string;
774
2007
  }[];
775
2008
  }>>;
2009
+ /** Cache policy. `false` = never cache (live data, write ops). Mirrors HTTP `Cache-Control: no-store`. */
2010
+ cache: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<false>, z.ZodObject<{
2011
+ ttlMs: z.ZodOptional<z.ZodNumber>;
2012
+ }, "strip", z.ZodTypeAny, {
2013
+ ttlMs?: number | undefined;
2014
+ }, {
2015
+ ttlMs?: number | undefined;
2016
+ }>]>>;
776
2017
  }, "strip", z.ZodTypeAny, {
777
2018
  id: string;
778
2019
  params: Record<string, string>;
779
2020
  name: string;
780
2021
  description: string;
781
2022
  fn: (args_0: any, ...args: unknown[]) => any;
2023
+ toolType?: "source" | "direct" | undefined;
2024
+ fullSchema?: string | undefined;
782
2025
  outputSchema?: {
783
2026
  description: string;
784
2027
  fields: {
@@ -787,12 +2030,17 @@ declare const ToolSchema: z.ZodObject<{
787
2030
  description: string;
788
2031
  }[];
789
2032
  } | undefined;
2033
+ cache?: false | {
2034
+ ttlMs?: number | undefined;
2035
+ } | undefined;
790
2036
  }, {
791
2037
  id: string;
792
2038
  params: Record<string, string>;
793
2039
  name: string;
794
2040
  description: string;
795
2041
  fn: (args_0: any, ...args: unknown[]) => any;
2042
+ toolType?: "source" | "direct" | undefined;
2043
+ fullSchema?: string | undefined;
796
2044
  outputSchema?: {
797
2045
  description: string;
798
2046
  fields: {
@@ -801,6 +2049,9 @@ declare const ToolSchema: z.ZodObject<{
801
2049
  description: string;
802
2050
  }[];
803
2051
  } | undefined;
2052
+ cache?: false | {
2053
+ ttlMs?: number | undefined;
2054
+ } | undefined;
804
2055
  }>;
805
2056
  type Tool$1 = z.infer<typeof ToolSchema>;
806
2057
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
@@ -839,6 +2090,10 @@ interface SuperatomSDKConfig {
839
2090
  bundleDir?: string;
840
2091
  promptsDir?: string;
841
2092
  databaseType?: DatabaseType;
2093
+ /** BCP-47 locale for `fmt` in generated analyses, e.g. 'en-IN', 'en-US'. Defaults to 'en-IN'. */
2094
+ locale?: string;
2095
+ /** ISO-4217 currency for `fmt`, e.g. 'INR', 'USD'. Defaults to 'INR'. */
2096
+ currency?: string;
842
2097
  ANTHROPIC_API_KEY?: string;
843
2098
  GROQ_API_KEY?: string;
844
2099
  GEMINI_API_KEY?: string;
@@ -852,27 +2107,61 @@ interface SuperatomSDKConfig {
852
2107
  * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
853
2108
  */
854
2109
  modelStrategy?: ModelStrategy;
2110
+ /**
2111
+ * Model for the main agent (routing + analysis).
2112
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
2113
+ * If not set, uses the provider's default model.
2114
+ */
2115
+ mainAgentModel?: string;
2116
+ /**
2117
+ * Model for source agents (per-source query generation).
2118
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
2119
+ * If not set, uses the provider's default model.
2120
+ */
2121
+ sourceAgentModel?: string;
855
2122
  /**
856
2123
  * Separate model configuration for DASH_COMP flow (dashboard component picking)
857
2124
  * If not provided, falls back to provider-based model selection
858
2125
  */
859
2126
  dashCompModels?: DashCompModelConfig;
2127
+ /**
2128
+ * Similarity threshold for conversation search (semantic matching)
2129
+ * Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
2130
+ * Higher values require closer matches, lower values allow more distant matches
2131
+ * Default: 0.8
2132
+ */
2133
+ conversationSimilarityThreshold?: number;
2134
+ /**
2135
+ * Query cache TTL (Time To Live) in minutes
2136
+ * Cached query results expire after this duration
2137
+ * Default: 5 minutes
2138
+ */
2139
+ queryCacheTTL?: number;
2140
+ /**
2141
+ * Dashboard conversation history TTL (Time To Live) in minutes
2142
+ * Per-dashboard conversation histories expire after this duration
2143
+ * Default: 30 minutes
2144
+ */
2145
+ dashboardHistoryTTL?: number;
860
2146
  }
861
2147
 
862
2148
  declare const KbNodesQueryFiltersSchema: z.ZodObject<{
863
2149
  query: z.ZodOptional<z.ZodString>;
864
2150
  category: z.ZodOptional<z.ZodString>;
865
2151
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
866
- createdBy: z.ZodOptional<z.ZodNumber>;
2152
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
2153
+ createdBy: z.ZodOptional<z.ZodString>;
867
2154
  }, "strip", z.ZodTypeAny, {
2155
+ type?: "query" | "user" | "global" | undefined;
868
2156
  query?: string | undefined;
869
2157
  category?: string | undefined;
870
- createdBy?: number | undefined;
2158
+ createdBy?: string | undefined;
871
2159
  tags?: string[] | undefined;
872
2160
  }, {
2161
+ type?: "query" | "user" | "global" | undefined;
873
2162
  query?: string | undefined;
874
2163
  category?: string | undefined;
875
- createdBy?: number | undefined;
2164
+ createdBy?: string | undefined;
876
2165
  tags?: string[] | undefined;
877
2166
  }>;
878
2167
  type KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
@@ -884,106 +2173,118 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
884
2173
  content: z.ZodOptional<z.ZodString>;
885
2174
  category: z.ZodOptional<z.ZodString>;
886
2175
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
887
- createdBy: z.ZodOptional<z.ZodNumber>;
888
- updatedBy: z.ZodOptional<z.ZodNumber>;
889
- userId: z.ZodOptional<z.ZodNumber>;
2176
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
2177
+ createdBy: z.ZodOptional<z.ZodString>;
2178
+ updatedBy: z.ZodOptional<z.ZodString>;
2179
+ userId: z.ZodOptional<z.ZodString>;
890
2180
  query: z.ZodOptional<z.ZodString>;
891
2181
  filters: z.ZodOptional<z.ZodObject<{
892
2182
  query: z.ZodOptional<z.ZodString>;
893
2183
  category: z.ZodOptional<z.ZodString>;
894
2184
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
895
- createdBy: z.ZodOptional<z.ZodNumber>;
2185
+ type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
2186
+ createdBy: z.ZodOptional<z.ZodString>;
896
2187
  }, "strip", z.ZodTypeAny, {
2188
+ type?: "query" | "user" | "global" | undefined;
897
2189
  query?: string | undefined;
898
2190
  category?: string | undefined;
899
- createdBy?: number | undefined;
2191
+ createdBy?: string | undefined;
900
2192
  tags?: string[] | undefined;
901
2193
  }, {
2194
+ type?: "query" | "user" | "global" | undefined;
902
2195
  query?: string | undefined;
903
2196
  category?: string | undefined;
904
- createdBy?: number | undefined;
2197
+ createdBy?: string | undefined;
905
2198
  tags?: string[] | undefined;
906
2199
  }>>;
907
2200
  limit: z.ZodOptional<z.ZodNumber>;
908
2201
  offset: z.ZodOptional<z.ZodNumber>;
909
2202
  }, "strip", z.ZodTypeAny, {
910
2203
  id?: number | undefined;
2204
+ type?: "query" | "user" | "global" | undefined;
911
2205
  query?: string | undefined;
912
2206
  title?: string | undefined;
913
2207
  category?: string | undefined;
914
- userId?: number | undefined;
2208
+ userId?: string | undefined;
915
2209
  limit?: number | undefined;
916
2210
  filters?: {
2211
+ type?: "query" | "user" | "global" | undefined;
917
2212
  query?: string | undefined;
918
2213
  category?: string | undefined;
919
- createdBy?: number | undefined;
2214
+ createdBy?: string | undefined;
920
2215
  tags?: string[] | undefined;
921
2216
  } | undefined;
922
- createdBy?: number | undefined;
923
- updatedBy?: number | undefined;
2217
+ createdBy?: string | undefined;
2218
+ updatedBy?: string | undefined;
2219
+ offset?: number | undefined;
924
2220
  tags?: string[] | undefined;
925
2221
  content?: string | undefined;
926
- offset?: number | undefined;
927
2222
  }, {
928
2223
  id?: number | undefined;
2224
+ type?: "query" | "user" | "global" | undefined;
929
2225
  query?: string | undefined;
930
2226
  title?: string | undefined;
931
2227
  category?: string | undefined;
932
- userId?: number | undefined;
2228
+ userId?: string | undefined;
933
2229
  limit?: number | undefined;
934
2230
  filters?: {
2231
+ type?: "query" | "user" | "global" | undefined;
935
2232
  query?: string | undefined;
936
2233
  category?: string | undefined;
937
- createdBy?: number | undefined;
2234
+ createdBy?: string | undefined;
938
2235
  tags?: string[] | undefined;
939
2236
  } | undefined;
940
- createdBy?: number | undefined;
941
- updatedBy?: number | undefined;
2237
+ createdBy?: string | undefined;
2238
+ updatedBy?: string | undefined;
2239
+ offset?: number | undefined;
942
2240
  tags?: string[] | undefined;
943
2241
  content?: string | undefined;
944
- offset?: number | undefined;
945
2242
  }>>;
946
2243
  }, "strip", z.ZodTypeAny, {
947
- operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
2244
+ operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
948
2245
  data?: {
949
2246
  id?: number | undefined;
2247
+ type?: "query" | "user" | "global" | undefined;
950
2248
  query?: string | undefined;
951
2249
  title?: string | undefined;
952
2250
  category?: string | undefined;
953
- userId?: number | undefined;
2251
+ userId?: string | undefined;
954
2252
  limit?: number | undefined;
955
2253
  filters?: {
2254
+ type?: "query" | "user" | "global" | undefined;
956
2255
  query?: string | undefined;
957
2256
  category?: string | undefined;
958
- createdBy?: number | undefined;
2257
+ createdBy?: string | undefined;
959
2258
  tags?: string[] | undefined;
960
2259
  } | undefined;
961
- createdBy?: number | undefined;
962
- updatedBy?: number | undefined;
2260
+ createdBy?: string | undefined;
2261
+ updatedBy?: string | undefined;
2262
+ offset?: number | undefined;
963
2263
  tags?: string[] | undefined;
964
2264
  content?: string | undefined;
965
- offset?: number | undefined;
966
2265
  } | undefined;
967
2266
  }, {
968
- operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
2267
+ operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
969
2268
  data?: {
970
2269
  id?: number | undefined;
2270
+ type?: "query" | "user" | "global" | undefined;
971
2271
  query?: string | undefined;
972
2272
  title?: string | undefined;
973
2273
  category?: string | undefined;
974
- userId?: number | undefined;
2274
+ userId?: string | undefined;
975
2275
  limit?: number | undefined;
976
2276
  filters?: {
2277
+ type?: "query" | "user" | "global" | undefined;
977
2278
  query?: string | undefined;
978
2279
  category?: string | undefined;
979
- createdBy?: number | undefined;
2280
+ createdBy?: string | undefined;
980
2281
  tags?: string[] | undefined;
981
2282
  } | undefined;
982
- createdBy?: number | undefined;
983
- updatedBy?: number | undefined;
2283
+ createdBy?: string | undefined;
2284
+ updatedBy?: string | undefined;
2285
+ offset?: number | undefined;
984
2286
  tags?: string[] | undefined;
985
2287
  content?: string | undefined;
986
- offset?: number | undefined;
987
2288
  } | undefined;
988
2289
  }>;
989
2290
  type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
@@ -1252,19 +2553,725 @@ declare class ReportManager {
1252
2553
  getReportCount(): number;
1253
2554
  }
1254
2555
 
1255
- type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
1256
- interface LLMMessages {
1257
- sys: SystemPrompt;
1258
- user: string;
1259
- prefill?: string;
2556
+ /**
2557
+ * ScriptRecipeStore — injected metadata backend for the script flow.
2558
+ *
2559
+ * The SDK is standalone (no DB dependency). The backend implements this
2560
+ * interface over Postgres (full-text search + atomic counters) and injects it
2561
+ * via `collections['script-recipes']`, exactly like `collections['source-embeddings']`.
2562
+ * `ScriptStore` consumes it for all METADATA operations while keeping the
2563
+ * executable body on disk as scripts-store/<fileBase>.ts.
2564
+ *
2565
+ * All metadata rows are plain JSON (no scriptBody — that lives on disk).
2566
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md (#1, #3, #7).
2567
+ */
2568
+
2569
+ /** One recipe's metadata as stored in Postgres (mirrors the script_recipes table). */
2570
+ interface ScriptRecipeMetaRow {
2571
+ id: string;
2572
+ projectId?: string | null;
2573
+ version: number;
2574
+ name: string;
2575
+ intentDescription: string;
2576
+ tags: string[] | null;
2577
+ createdFrom: string | null;
2578
+ sourceIds: string[] | null;
2579
+ tables: string[] | null;
2580
+ parameters: ScriptParameter[] | null;
2581
+ components?: ScriptComponentSpec[] | null;
2582
+ displayPreference?: ScriptDisplayPreference | null;
2583
+ fileBase: string;
2584
+ bodyHash?: string | null;
2585
+ successCount: number;
2586
+ failureCount: number;
2587
+ lastUsed: string | null;
2588
+ parentId?: string | null;
2589
+ forkDepth?: number | null;
2590
+ forkReason?: string | null;
2591
+ status: 'draft' | 'verified' | string;
2592
+ turnId?: string | null;
2593
+ editedBy?: string | null;
2594
+ editedFrom?: string | null;
2595
+ history?: ScriptVersionRecord[] | null;
2596
+ lastError?: {
2597
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2598
+ message: string;
2599
+ at: string;
2600
+ attempt: number;
2601
+ } | null;
2602
+ createdAt?: string | null;
2603
+ updatedAt?: string | null;
1260
2604
  }
1261
- interface LLMOptions {
1262
- model?: string;
1263
- maxTokens?: number;
1264
- temperature?: number;
1265
- topP?: number;
1266
- apiKey?: string;
2605
+ interface ScriptRecipeStore {
2606
+ /** FTS shortlist of healthy verified recipes for the matcher (metadata only). */
2607
+ search(params: {
2608
+ prompt: string;
2609
+ projectId?: string;
2610
+ limit?: number;
2611
+ }): Promise<ScriptRecipeMetaRow[]>;
2612
+ /** Fetch one recipe by id (any status). */
2613
+ getById(id: string): Promise<ScriptRecipeMetaRow | null>;
2614
+ /** Count healthy verified recipes (drives the "any scripts?" gate). */
2615
+ count(params?: {
2616
+ projectId?: string;
2617
+ }): Promise<number>;
2618
+ /** Insert or update a recipe row (keyed by id). */
2619
+ upsert(row: ScriptRecipeMetaRow): Promise<void>;
2620
+ /** Atomically bump counters / last-used. */
2621
+ updateStats(id: string, patch: {
2622
+ successDelta?: number;
2623
+ failureDelta?: number;
2624
+ lastUsed?: string;
2625
+ }): Promise<void>;
2626
+ /** Flip a draft to verified, applying provenance + optional fork lineage. */
2627
+ promote(id: string, patch: {
2628
+ sourceIds: string[];
2629
+ tables: string[];
2630
+ fileBase?: string;
2631
+ parentId?: string;
2632
+ forkDepth?: number;
2633
+ forkReason?: string;
2634
+ components?: ScriptComponentSpec[];
2635
+ }): Promise<ScriptRecipeMetaRow | null>;
2636
+ /**
2637
+ * Commit a verified edit onto an EXISTING recipe: bump `version`, replace the
2638
+ * body-bearing metadata, append a history record, reset health counters, and
2639
+ * clear the component specs (they were validated against the old shape).
2640
+ * Returns the updated row, or null when the target is gone.
2641
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5.
2642
+ */
2643
+ commitEdit?(id: string, patch: {
2644
+ name?: string;
2645
+ intentDescription?: string;
2646
+ tags?: string[];
2647
+ parameters?: ScriptParameter[];
2648
+ bodyHash: string;
2649
+ /** New on-disk stem when the edit renamed the script; omitted otherwise. */
2650
+ fileBase?: string;
2651
+ sourceIds?: string[];
2652
+ tables?: string[];
2653
+ editedBy?: string;
2654
+ editedFrom?: string;
2655
+ historyEntry: {
2656
+ version: number;
2657
+ at: string;
2658
+ by?: string;
2659
+ instruction?: string;
2660
+ changeSummary?: string;
2661
+ bodyHash?: string;
2662
+ };
2663
+ }): Promise<ScriptRecipeMetaRow | null>;
2664
+ /** Stamp a draft's last execution error. */
2665
+ recordDraftError(id: string, err: {
2666
+ phase: string;
2667
+ message: string;
2668
+ attempt: number;
2669
+ at: string;
2670
+ }): Promise<void>;
2671
+ /** Delete a recipe row (body file removed separately). */
2672
+ remove(id: string): Promise<void>;
2673
+ /** True if `fileBase` is taken by a different recipe in this project. */
2674
+ fileBaseTaken(fileBase: string, excludeId: string, projectId?: string): Promise<boolean>;
2675
+ }
2676
+ /** Pull the injected store off the collections bag (or null if not wired). */
2677
+ declare function resolveScriptRecipeStore(collections: any): ScriptRecipeStore | null;
2678
+
2679
+ /**
2680
+ * ScriptStore — Postgres metadata + on-disk body for script recipes.
2681
+ *
2682
+ * Split of responsibilities:
2683
+ * - METADATA → injected `ScriptRecipeStore` (Postgres FTS + atomic counters),
2684
+ * resolved from `collections['script-recipes']`.
2685
+ * - BODY → scripts-store/<fileBase>.ts, editable in your IDE. Written
2686
+ * atomically (temp + rename); `bodyHash` (sha256) detects edits.
2687
+ *
2688
+ * The old "read every file every turn + send the whole catalog to the LLM"
2689
+ * matcher is gone — matching is `store.search(prompt)` (FTS shortlist). The
2690
+ * draft/verified filename dance is gone too: `status` is a DB column and the
2691
+ * file keeps a stable `<fileBase>.ts` name across promotion.
2692
+ *
2693
+ * When no metadata store is injected, the store degrades to a safe no-op
2694
+ * (count 0 → script flow disabled) instead of crashing.
2695
+ *
2696
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md.
2697
+ */
2698
+
2699
+ interface SaveDraftInput {
2700
+ /** Reuse an existing draft (retry); omit to mint a new one. */
2701
+ recipeId?: string;
2702
+ /** Per-turn unique suffix, stable across retries within the turn. */
2703
+ turnId: string;
2704
+ name: string;
2705
+ intentDescription: string;
2706
+ tags: string[];
2707
+ parameters: ScriptParameter[];
2708
+ scriptBody: string;
2709
+ createdFrom: string;
2710
+ /**
2711
+ * Set when this draft is a SHADOW of an existing recipe being edited. The
2712
+ * draft is verified independently and merged back onto the parent via
2713
+ * `commitEdit`, so the working script is never clobbered by an edit that
2714
+ * turns out not to run. See backend/docs/SCRIPT-EDIT-DESIGN.md § D5.
2715
+ */
2716
+ parentId?: string;
2717
+ }
2718
+ interface PromoteToVerifiedInput {
2719
+ sourceIds: string[];
2720
+ tables: string[];
2721
+ parentId?: string;
2722
+ forkDepth?: number;
2723
+ forkReason?: string;
2724
+ components?: ScriptComponentSpec[];
2725
+ }
2726
+ interface ScriptStoreOptions {
2727
+ /** Explicit metadata store, or resolved from `collections['script-recipes']`. */
2728
+ store?: ScriptRecipeStore | null;
2729
+ collections?: any;
2730
+ /** Body directory (defaults to <cwd>/scripts-store). */
2731
+ baseDir?: string;
2732
+ /** Project scope stamped on every row. */
2733
+ projectId?: string;
2734
+ }
2735
+ /**
2736
+ * Fingerprint of everything that decides what `getData` PRODUCES.
2737
+ *
2738
+ * A recipe holds three programs in one file — getData, getAnalysis,
2739
+ * getComponents — but only getData costs a source query, and only getData's
2740
+ * output can invalidate a verified run. Editing the narrative or a chart title
2741
+ * cannot change a single row, yet a whole-body comparison says it did, because
2742
+ * `write_script` resubmits the entire file. That is what made a cosmetic edit
2743
+ * indistinguishable from a SQL change and cost a scarce execute attempt.
2744
+ *
2745
+ * Parameters are part of the fingerprint, not an afterthought: `execute_script`
2746
+ * runs with `{}`, so the DEFAULTS are the values getData actually sees. Same
2747
+ * getData text with a changed default is a genuinely different result, and
2748
+ * hashing the body alone would have called it unchanged.
2749
+ *
2750
+ * Deliberately conservative — trimmed, not whitespace-collapsed. The two ways
2751
+ * to be wrong are NOT symmetric: a false "unchanged" reuses a stale result and
2752
+ * reports wrong numbers, while a false "changed" merely costs an attempt. So it
2753
+ * biases toward detecting change, and a reformat is allowed to look like an edit.
2754
+ */
2755
+ declare function dataFingerprint(scriptBody: string, parameters?: ScriptParameter[]): string;
2756
+ /** Inverse of `stripNamedExport` — pulls the named export block OUT instead of removing it. Null when absent. */
2757
+ declare function extractNamedExport(body: string, fnName: string): string | null;
2758
+ declare function normalizeScriptBody(scriptBody: string): string;
2759
+ declare class ScriptStore {
2760
+ private store;
2761
+ private storeDir;
2762
+ private projectId?;
2763
+ constructor(opts?: ScriptStoreOptions);
2764
+ /** Whether a metadata store is wired (matcher / authoring are gated on this). */
2765
+ hasStore(): boolean;
2766
+ /** Number of healthy verified recipes (gates the script-matching path). */
2767
+ count(): Promise<number>;
2768
+ /**
2769
+ * FTS shortlist for the matcher (metadata only — bodies are loaded lazily by
2770
+ * `get()` once the LLM picks one). Returns verified, healthy recipes ranked
2771
+ * by relevance.
2772
+ */
2773
+ search(prompt: string, limit?: number): Promise<ScriptRecipe[]>;
2774
+ /** Fetch one recipe by id with its body loaded from disk. */
2775
+ get(id: string): Promise<ScriptRecipe | null>;
2776
+ /**
2777
+ * Fetch one recipe by id, pinned to a SPECIFIC past version rather than
2778
+ * whatever is live today. Needed to render a past turn's conversation
2779
+ * history accurately after the script has since been edited — get() alone
2780
+ * always returns the CURRENT body, which may no longer be what that turn
2781
+ * actually ran.
2782
+ *
2783
+ * Returns null (never a silently-wrong version) when the requested version
2784
+ * isn't the current one and its archived body can't be found — e.g. the
2785
+ * archive was cleaned up after the whole recipe was later deleted.
2786
+ */
2787
+ getVersion(id: string, version: number): Promise<ScriptRecipe | null>;
2788
+ /** Create or update a recipe (metadata upsert + body write when changed). */
2789
+ save(recipe: ScriptRecipe): Promise<void>;
2790
+ /**
2791
+ * Persist (or update) a draft. Within a turn, retries that pass the same
2792
+ * `recipeId` overwrite the same row + file; a fresh `recipeId` mints a new
2793
+ * draft. The body is visible at scripts-store/<fileBase>.ts immediately.
2794
+ */
2795
+ saveDraft(input: SaveDraftInput): Promise<ScriptRecipe>;
2796
+ /** Stamp a draft's last execution error (metadata only). */
2797
+ recordDraftError(recipeId: string, err: {
2798
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2799
+ message: string;
2800
+ attempt: number;
2801
+ }): Promise<void>;
2802
+ /**
2803
+ * Promote a successfully-executed draft into a verified script.
2804
+ * The on-disk body already exists at <fileBase>.ts (written at write_script
2805
+ * time) and keeps its name — only the DB row flips status + provenance.
2806
+ */
2807
+ promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): Promise<ScriptRecipe | null>;
2808
+ /**
2809
+ * Commit a user-directed edit: merge a VERIFIED shadow draft back onto the
2810
+ * recipe it was editing, as version N+1 under the SAME recipe id.
2811
+ *
2812
+ * Keeping the id stable is the point of the whole feature — every cached
2813
+ * conversation, `script_dataset` regeneration descriptor and persisted
2814
+ * component spec already points at it, so the correction applies retroactively
2815
+ * to replays instead of stranding them on the old body.
2816
+ *
2817
+ * Steps (see backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5):
2818
+ * 1. archive the current body as `<fileBase>.v<version>.ts`
2819
+ * 2. write the edited body to the original fileBase (atomic)
2820
+ * 3. version++, copy name/description/params, append a history record
2821
+ * 4. reset health counters — the pre-edit failure history is stale
2822
+ * 5. clear component specs — they were validated against the OLD shape
2823
+ * 6. delete the shadow draft (row + file)
2824
+ *
2825
+ * Returns the updated recipe, or null when the commit could not be applied
2826
+ * (caller should then fall back to treating the draft as a new script).
2827
+ */
2828
+ commitEdit(targetId: string, draft: {
2829
+ recipeId: string;
2830
+ name?: string;
2831
+ intentDescription?: string;
2832
+ tags?: string[];
2833
+ parameters?: ScriptParameter[];
2834
+ scriptBody: string;
2835
+ sourceIds?: string[];
2836
+ tables?: string[];
2837
+ }, meta: {
2838
+ instruction?: string;
2839
+ changeSummary?: string;
2840
+ editedBy?: string;
2841
+ }): Promise<ScriptRecipe | null>;
2842
+ /**
2843
+ * Drop a draft (row + body file). MainAgent calls this at end-of-turn when a
2844
+ * draft was authored but never verified — failed drafts are never matched, so
2845
+ * deleting them immediately avoids unbounded accumulation (#5). No-op if the
2846
+ * recipe isn't a draft (so a promoted/verified script is never removed here).
2847
+ */
2848
+ discardDraft(recipeId: string): Promise<void>;
2849
+ /** Delete a recipe (row + body file). */
2850
+ delete(id: string): Promise<void>;
2851
+ /** Record a successful execution (atomic counter bump). */
2852
+ recordSuccess(id: string): Promise<void>;
2853
+ /** Record a failed execution (atomic counter bump). */
2854
+ recordFailure(id: string): Promise<void>;
2855
+ /** Absolute path to the .ts body for a recipe (used by the runner/MainAgent). */
2856
+ getScriptPath(recipe: ScriptRecipe): string;
2857
+ private removeById;
2858
+ private rowToRecipe;
2859
+ private recipeToRow;
2860
+ /** slug of name, with a short id suffix when the bare slug is already taken. */
2861
+ private computeFileBase;
2862
+ private toSlug;
2863
+ private hash;
2864
+ /**
2865
+ * Attach getComponents to the recipe body. The stored `components` column is
2866
+ * cleared at promotion (see promoteToVerified): once the body computes its own
2867
+ * specs, a stale spec array beside a live program is how the wrong one gets
2868
+ * read later. See backend/docs/COMPONENTS-AS-PROGRAM-DESIGN.md § 4.4.
2869
+ */
2870
+ attachComponents(recipeId: string, componentsBody: string): Promise<boolean>;
2871
+ /**
2872
+ * Append (or replace) the `getAnalysis` export on an existing draft body.
2873
+ *
2874
+ * The narrative is authored AFTER execution, so it lands on a file that
2875
+ * already holds a working getData — rewriting the whole body would risk
2876
+ * losing the query that just succeeded. Replaces any earlier getAnalysis so
2877
+ * a retry does not stack duplicate exports.
2878
+ */
2879
+ attachAnalysis(recipeId: string, analysisBody: string): Promise<boolean>;
2880
+ private bodyPath;
2881
+ private readBody;
2882
+ /** Directory holding superseded bodies. Dot-prefixed so IDEs/`ls` hide it. */
2883
+ private get archiveDir();
2884
+ /**
2885
+ * Archive a superseded body as `.versions/<fileBase>.v<n>.ts`.
2886
+ *
2887
+ * Kept out of the main store directory on purpose — see commitEdit step 1.
2888
+ * To roll back: copy the file back over `scripts-store/<fileBase>.ts`.
2889
+ */
2890
+ private writeArchive;
2891
+ /**
2892
+ * Move a recipe's archived versions to a new prefix when its fileBase changes,
2893
+ * so all versions of one recipe stay grouped. Without this, two renames would
2894
+ * scatter a single recipe's history across three prefixes in `.versions/` with
2895
+ * nothing linking them back to the live script.
2896
+ */
2897
+ private renameArchives;
2898
+ /** Atomic body write (temp + rename) so concurrent reads never see a partial file. */
2899
+ private writeBody;
2900
+ private unlinkBody;
2901
+ }
2902
+
2903
+ /**
2904
+ * Main Agent (Orchestrator)
2905
+ *
2906
+ * A single LLM.streamWithTools() call that handles everything:
2907
+ * - Routing: decides which source(s) to query based on summaries
2908
+ * - Querying: calls source tools (each wraps an independent SourceAgent)
2909
+ * - Direct tools: calls pre-built function tools directly with LLM-provided params
2910
+ * - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
2911
+ * - Analysis: generates final text response from the data
2912
+ *
2913
+ * Two tool types:
2914
+ * - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
2915
+ * - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
2916
+ */
2917
+
2918
+ declare class MainAgent {
2919
+ private externalTools;
2920
+ private workflows;
2921
+ private config;
2922
+ private streamBuffer;
2923
+ /**
2924
+ * Optional: when provided, MainAgent exposes the `write_script` /
2925
+ * `execute_script` tools to the LLM and persists drafts to disk via the
2926
+ * store. Headless callers (alert analyzer, metric resolver) omit these to
2927
+ * suppress script authoring entirely — drafts would otherwise leak onto
2928
+ * disk with no caller to promote or clean them up.
2929
+ */
2930
+ private scriptStore;
2931
+ private turnId;
2932
+ private createdFromPrompt;
2933
+ private scriptState;
2934
+ /** Answer-flow component catalog (filtered + projected by the caller). */
2935
+ private componentCatalog;
2936
+ /** Specs accepted by `write_components` this turn; empty until it succeeds. */
2937
+ /**
2938
+ * Entities resolved this turn, appended verbatim to every source dispatch.
2939
+ *
2940
+ * Not left to the model to copy into its intent prose: observed live, the
2941
+ * MainAgent wrote names instead of ids on the first dispatch AND re-spelled
2942
+ * 'F D C LIMITED' as 'FDC Limited', so the source agent fell back to
2943
+ * `PartyName LIKE '%FDC%'` and found 2 of 3 customers. Carrying the ids
2944
+ * structurally makes that impossible rather than instruction-dependent.
2945
+ */
2946
+ private resolvedEntities;
2947
+ /**
2948
+ * Concept bodies resolved this turn (via resolve_entities' embedded concept
2949
+ * lookup or a standalone resolve_concepts call) — retained the same way as
2950
+ * resolvedEntities above, so they can be attached to the SourceAgent dispatch.
2951
+ *
2952
+ * Without this, a concept resolved HERE (MainAgent's own tool loop) never
2953
+ * reaches SourceAgent at all: SourceAgent only gets the natural-language
2954
+ * `intent` MainAgent writes, which is a paraphrase, not the concept's
2955
+ * verbatim, authoritative body. Deduped on name so a mid-turn re-resolve
2956
+ * doesn't repeat an already-attached concept.
2957
+ */
2958
+ private resolvedConcepts;
2959
+ private componentSpecs;
2960
+ private componentLayout;
2961
+ private renderComponentAttempts;
2962
+ /** Same repeated-violation tracking as ScriptState.lastAnalysisViolationTexts, for write_components. */
2963
+ private lastComponentsViolationTexts;
2964
+ /**
2965
+ * Fork mode — set when this turn is adapting a near-matching parent script.
2966
+ * In fork mode there is no legitimate "answer with bare text" outcome: the
2967
+ * only correct first move is a tool call (write_script, or a source tool for
2968
+ * schema discovery). We therefore force tool use on the first LLM iteration
2969
+ * so the model can't end its turn with a bare "I'll adapt…" preamble and zero
2970
+ * tool calls. Never set on the fresh-authoring / general-question path.
2971
+ */
2972
+ private forkMode;
2973
+ /**
2974
+ * Edit mode — set when this turn applies a user-directed change to an
2975
+ * existing script. Swaps the system prompt to `agent-main-edit` and stamps
2976
+ * the shadow draft's parentId. Like fork mode there is no legitimate
2977
+ * "answer with bare text" outcome, so tool use is forced on iteration 1.
2978
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 4.
2979
+ */
2980
+ private editContext;
2981
+ /** The recipe's durable rendering choice — see the constructor. */
2982
+ private displayPreference;
2983
+ /**
2984
+ * Per-turn cancellation signal (user hit "Stop"). Set at the top of
2985
+ * handleQuestion and read by the tool handler, the SourceAgent dispatch, and
2986
+ * the script subprocess so an abort tears down every layer of the turn.
2987
+ */
2988
+ private abortSignal?;
2989
+ constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[], forkMode?: boolean, editContext?: EditContext, componentCatalog?: Component[],
2990
+ /**
2991
+ * The recipe's durable rendering choice, when it has one. A DATA edit
2992
+ * re-authors getComponents from scratch, so without this the user's chart
2993
+ * type is silently dropped whenever anyone changes the SQL.
2994
+ */
2995
+ displayPreference?: {
2996
+ componentTypes: string[];
2997
+ instruction: string;
2998
+ });
2999
+ /** True when the turn is applying a user-directed script edit. */
3000
+ private get editMode();
3001
+ private get scriptingEnabled();
3002
+ /**
3003
+ * Handle a user question using the multi-agent system.
3004
+ *
3005
+ * This is ONE LLM.streamWithTools() call. The LLM:
3006
+ * 1. Sees source summaries + direct tool descriptions in system prompt
3007
+ * 2. Decides which tool(s) to call (routing)
3008
+ * 3. Source tools → SourceAgent runs independently → returns data
3009
+ * 4. Direct tools → fn() called directly with LLM params → returns data
3010
+ * 5. Generates final analysis text
3011
+ */
3012
+ handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, signal?: AbortSignal): Promise<AgentResponse>;
3013
+ /**
3014
+ * Tool definition, with the catalog rendered from the registered `Metadata`
3015
+ * the caller passed in. Generated rather than hand-written so it cannot drift
3016
+ * from what the frontend actually ships.
3017
+ */
3018
+ private buildWriteComponentsToolDef;
3019
+ /**
3020
+ * Validate the agent's component picks against the REAL columns of each bound
3021
+ * dataset. All-or-nothing: any error rejects the whole call and returns the
3022
+ * findings, because a partially-accepted dashboard makes the retry ambiguous.
3023
+ */
3024
+ private validateSpecs;
3025
+ /**
3026
+ * Author the dashboard as a program. Attaches getComponents to the draft, runs
3027
+ * it over the verified rows, then validates the specs it RETURNED — the program
3028
+ * is never trusted because it is a program, exactly as an authored spec is not.
3029
+ */
3030
+ private handleWriteComponents;
3031
+ /**
3032
+ * Author the answer as a program. Runs after execute_script, so the body is
3033
+ * written with the result already known and can react to what it found.
3034
+ *
3035
+ * Rejects a body that types numbers rather than computing them — see
3036
+ * analysis-lint. A hardcoded figure is worse than prose: it freezes into the
3037
+ * recipe and replays unchanged while the data moves underneath it.
3038
+ */
3039
+ private handleWriteAnalysis;
3040
+ private handleWriteScript;
3041
+ private handleExecuteScript;
3042
+ /**
3043
+ * Build the AgentWrittenScript payload the caller will hand to
3044
+ * `ScriptStore.promoteToVerified()`. Only returned when a verified
3045
+ * successful execution is on record.
3046
+ */
3047
+ private buildSavedScript;
3048
+ private normalizeParameterList;
3049
+ /**
3050
+ * Which declared parameter NAMES never actually appear wired into the
3051
+ * script body — checked as plain text, not a real parser, so it only
3052
+ * catches the worst case (completely unreferenced) rather than every
3053
+ * subtler variant (e.g. used for display text while the SQL itself still
3054
+ * hardcodes the value). That worst case is exactly what's been observed:
3055
+ * a parameter declared purely for show, with the actual filter hardcoded.
3056
+ * Accepts `params.name`, `params['name']`/`params["name"]`, and a
3057
+ * destructuring binding (`const { name } = params`) as valid wiring.
3058
+ */
3059
+ private findUnwiredParams;
3060
+ /**
3061
+ * Use the schema embedding collection to pre-select relevant tables for
3062
+ * this source + intent. Returns a formatted schema block if confidence is
3063
+ * high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
3064
+ *
3065
+ * When this returns a block, we can skip the SourceAgent's `search_schema`
3066
+ * loop and reduce iteration budget. When it returns null, the SourceAgent
3067
+ * falls back to the existing LLM-driven keyword search (same as today).
3068
+ */
3069
+ /**
3070
+ * Ids + verbatim names for everything resolved this turn, appended by CODE to
3071
+ * each source dispatch so neither omission nor re-spelling by the model can
3072
+ * lose them. Empty string when nothing was resolved, so intents are untouched
3073
+ * for questions that name no entities.
3074
+ *
3075
+ * Also appends `attrs.scopeSql` when the resolved instance carries one —
3076
+ * same "guaranteed by code" reasoning as the ids/names above, extended to
3077
+ * the one attrs field with a documented, cross-entity-type meaning: a
3078
+ * ready-made SQL predicate an entity's index precomputed (see
3079
+ * ENTITY-SEARCH-DESIGN.md's hierarchy-broadening pattern — branch/region/
3080
+ * state entity types attach it so a lane/route question never needs its
3081
+ * own city-matching join). Confirmed real cost of not doing this: a
3082
+ * branch/state resolved with scopeSql sat unused while the source agent
3083
+ * spent 4 failed exploratory queries rediscovering the exact same
3084
+ * branch-id list by hand (Invalid column name 'StateName'/'CityId'/
3085
+ * 'OrganizationLocationId', in that order, ~144s, before landing on ids
3086
+ * that were sitting in scopeSql from the very first resolve_entities
3087
+ * call). Other attrs (code, counts, etc.) are not dumped here — they are
3088
+ * descriptive, not actionable the way a precomputed predicate is, and
3089
+ * bloating every dispatch with all of them for no clear gain isn't worth
3090
+ * it; scopeSql is the one thing worth this guarantee today.
3091
+ */
3092
+ private buildResolvedEntitiesBlock;
3093
+ /** Dedupe-and-retain helper shared by resolveConceptsForTurn and handleResolveConcepts. */
3094
+ private retainResolvedConcepts;
3095
+ /**
3096
+ * Same purpose as buildResolvedEntitiesBlock, for concept bodies instead of
3097
+ * entity ids — appended to the dispatch intent so SourceAgent's own,
3098
+ * independent LLM call receives the resolved definitions verbatim rather
3099
+ * than only MainAgent's paraphrased intent text.
3100
+ */
3101
+ private buildResolvedConceptsBlock;
3102
+ /** True when the backend registered the entity-search collection. */
3103
+ private get entitySearchEnabled();
3104
+ /** True when the backend registered the concepts collection. */
3105
+ private get conceptsEnabled();
3106
+ /**
3107
+ * Concept names for the system prompt. Names ONLY — the body comes back from
3108
+ * resolve_concepts once the LLM has named one, exactly as with the entity
3109
+ * catalog. Putting bodies here would rebuild the always-on context problem
3110
+ * concepts exist to solve.
3111
+ *
3112
+ * Not cached, for the same reason loadEntityCatalog isn't: unchanged rows
3113
+ * render byte-identical text so the prompt-cache prefix still hits, and a
3114
+ * process cache would only buy a window where a new concept is invisible.
3115
+ */
3116
+ private loadConceptCatalog;
3117
+ /**
3118
+ * The ALWAYS-INJECTED tier: preconditions no question is semantically close
3119
+ * to — date encodings, valid-row filters. These cannot be retrieval-gated.
3120
+ * "What was revenue last quarter?" has no similarity to "dates are DD/MM/YYYY
3121
+ * text", so leaving them to be requested means they are silently dropped and
3122
+ * the answer is confidently wrong rather than visibly missing.
3123
+ *
3124
+ * Bodies ARE included here — unlike the catalog — because there is nothing to
3125
+ * request: being unrequestable is what makes them invariants.
3126
+ *
3127
+ * Also retained into resolvedConcepts (same as an explicit resolve_concepts
3128
+ * call) so these bodies reach SourceAgent's dispatch too — an invariant is
3129
+ * meant to apply everywhere, not just wherever the model happens to ask for
3130
+ * something whose `requires` chain reaches it.
3131
+ */
3132
+ private loadConceptInvariants;
3133
+ /**
3134
+ * Resolve the concepts for a turn, with a SERVER-SIDE FLOOR.
3135
+ *
3136
+ * Pinning a tool guarantees it is called; it does not guarantee the model
3137
+ * fills in the arguments. Observed: a question containing the exact words
3138
+ * "revenue forecast" produced a call with no concepts at all, and the agent
3139
+ * then used an incomplete copy of the formula from the knowledge base — the
3140
+ * resulting query filtered a customer id against a project column and
3141
+ * returned zero rows on every attempt.
3142
+ *
3143
+ * So when the model names nothing, scan the question itself for catalog names
3144
+ * and aliases on word boundaries. Precise (a literal name is evidence, not a
3145
+ * guess) and asymmetric in the safe direction: an unneeded definition costs a
3146
+ * few hundred ignorable tokens, a missing one costs a wrong answer.
3147
+ */
3148
+ /**
3149
+ * Returns the tool-facing fields to spread into the resolve_entities JSON
3150
+ * response, PLUS a `_trace` field with everything the trace needs that the
3151
+ * model does not (asked/viaFloor/unmatched). Callers must pull `_trace` out
3152
+ * before spreading the rest into what the model sees — see handleResolveEntities.
3153
+ */
3154
+ private resolveConceptsForTurn;
3155
+ /**
3156
+ * Never throws: a concept-store outage must degrade to "no definition found"
3157
+ * and leave the agent deriving the formula as it does today, not take the
3158
+ * whole answer down.
3159
+ */
3160
+ private handleResolveConcepts;
3161
+ /**
3162
+ * Compact catalog (type + gloss) for the system prompt. This is what lets the
3163
+ * LLM NAME a concept instead of guessing at our vocabulary — it can infer
3164
+ * that a question is about unpaid money, but not that we call that
3165
+ * `outstanding-balance`. Full `resolution` detail is fetched by the tool.
3166
+ *
3167
+ * Deliberately NOT cached in-process. The token cost is already handled by
3168
+ * prompt caching (the system prompt carries a cache_control breakpoint), and
3169
+ * re-reading a tiny PK-ordered table costs ~nothing. Fetching fresh does not
3170
+ * weaken the prompt cache either: unchanged data renders byte-identical text,
3171
+ * so the prefix still hits. A process cache would only buy a staleness window
3172
+ * in which a newly indexed entity is invisible to the agent.
3173
+ */
3174
+ private loadEntityCatalog;
3175
+ /**
3176
+ * Never throws: a resolver outage must degrade to "nothing resolved" and
3177
+ * leave the agent exactly as it was, not take the whole answer down.
3178
+ */
3179
+ private handleResolveEntities;
3180
+ private preResolveSchema;
3181
+ /**
3182
+ * Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
3183
+ */
3184
+ private handleDirectTool;
3185
+ /**
3186
+ * Build the main agent's system prompt with source summaries, direct tool descriptions,
3187
+ * and workflow component descriptions.
3188
+ */
3189
+ private buildSystemPrompt;
3190
+ /**
3191
+ * Build tool definitions for source tools — summary-only descriptions.
3192
+ * The full schema is inside the SourceAgent which runs independently.
3193
+ */
3194
+ private buildSourceToolDefinitions;
3195
+ /**
3196
+ * Build tool definitions for direct tools — expose their actual params.
3197
+ * These are called directly by the main agent LLM, no SourceAgent.
3198
+ */
3199
+ private buildDirectToolDefinitions;
3200
+ /**
3201
+ * Capture a workflow selection. We do NOT execute anything — the LLM has
3202
+ * already extracted the props it wants the workflow rendered with. We
3203
+ * record the selection (via the capture callback) and return a short
3204
+ * acknowledgement so the LLM ends its turn cleanly without writing
3205
+ * analysis text or calling more tools.
3206
+ */
3207
+ private handleWorkflow;
3208
+ /**
3209
+ * Build LLM tool definitions for workflow components. The workflow's
3210
+ * propsSchema becomes the tool's input_schema so the LLM extracts props
3211
+ * directly from the prompt — same mechanic as direct tools.
3212
+ */
3213
+ private buildWorkflowToolDefinitions;
3214
+ /**
3215
+ * Format a source agent's result as a clean string for the main agent LLM.
3216
+ */
3217
+ private formatResultForMainAgent;
3218
+ /**
3219
+ * Get source summaries (for external inspection/debugging).
3220
+ */
3221
+ getSourceSummaries(): SourceSummary[];
3222
+ }
3223
+
3224
+ type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
3225
+ interface LLMMessages {
3226
+ sys: SystemPrompt;
3227
+ user: string;
3228
+ prefill?: string;
3229
+ }
3230
+ interface LLMOptions {
3231
+ model?: string;
3232
+ maxTokens?: number;
3233
+ temperature?: number;
3234
+ topP?: number;
3235
+ apiKey?: string;
3236
+ baseURL?: string;
1267
3237
  partial?: (chunk: string) => void;
3238
+ /**
3239
+ * Per-request cancellation. When the caller aborts this signal (user hit
3240
+ * "Stop"), the underlying provider request is cancelled and the call throws
3241
+ * a RequestAbortedError. Threaded into the provider `messages.create` request
3242
+ * options and checked between tool-loop iterations. Currently honored on the
3243
+ * Anthropic path (the agent flow's default provider).
3244
+ */
3245
+ signal?: AbortSignal;
3246
+ /**
3247
+ * Forces a tool call on the FIRST iteration of streamWithTools only
3248
+ * (subsequent iterations revert to auto). Used by fork mode to stop the
3249
+ * model from ending its turn with a bare "I'll adapt the script…" preamble
3250
+ * and zero tool calls. `{ type: 'any' }` lets the model pick which tool
3251
+ * (write_script in the common case, a source tool for schema discovery);
3252
+ * `{ type: 'tool', name }` pins a specific tool. Honored on both the
3253
+ * Anthropic path and the OpenAI/OpenRouter path (mapped to OpenAI's
3254
+ * tool_choice: 'required' / a named function).
3255
+ */
3256
+ firstIterationToolChoice?: {
3257
+ type: 'any';
3258
+ } | {
3259
+ type: 'tool';
3260
+ name: string;
3261
+ };
3262
+ /**
3263
+ * Internal — set only by the OpenRouter wrappers when the target is a Claude
3264
+ * model. Tells the OpenAI-wire path to emit Anthropic `cache_control`
3265
+ * breakpoints (OpenRouter forwards them to Anthropic for prompt caching).
3266
+ * Never set for direct OpenAI/Groq calls, so their requests are unchanged.
3267
+ */
3268
+ _openrouterClaudeCaching?: boolean;
3269
+ /**
3270
+ * Internal — OpenRouter provider-routing preferences (forwarded as the
3271
+ * `provider` body field). Set by the OpenRouter wrappers to steer routing to
3272
+ * a fast backend (e.g. {sort:'throughput'}). Never set for direct OpenAI/Groq.
3273
+ */
3274
+ _openrouterProvider?: Record<string, unknown>;
1268
3275
  }
1269
3276
  interface Tool {
1270
3277
  name: string;
@@ -1286,6 +3293,16 @@ declare class LLM {
1286
3293
  * @returns Normalized system prompt for Anthropic API
1287
3294
  */
1288
3295
  private static _normalizeSystemPrompt;
3296
+ /**
3297
+ * Strip unpaired UTF-16 surrogates from every text field of a message set.
3298
+ *
3299
+ * A lone surrogate (from mid-pair string slicing or corrupt source data)
3300
+ * serializes to a bare `\udXXX` escape that strict JSON parsers — including
3301
+ * the one on Anthropic's API — reject with "no low surrogate in string",
3302
+ * failing the whole request. Sanitizing here, at the single boundary every
3303
+ * provider call flows through, guarantees no request can carry one.
3304
+ */
3305
+ private static _sanitizeMessages;
1289
3306
  /**
1290
3307
  * Log cache usage metrics from Anthropic API response
1291
3308
  * Shows cache hits, costs, and savings
@@ -1302,16 +3319,76 @@ declare class LLM {
1302
3319
  * "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
1303
3320
  */
1304
3321
  private static _parseModel;
3322
+ /**
3323
+ * Map an Anthropic model id (e.g. "claude-sonnet-4-5-20250929") to the OpenRouter slug
3324
+ * (e.g. "claude-sonnet-4.5"). OpenRouter slugs drop the date suffix and use dotted versions.
3325
+ */
3326
+ private static _toOpenRouterSlug;
3327
+ /**
3328
+ * Per-provider proxy base URL. Returns `${SUPERATOM_LLM_PROXY_URL}/<provider>`
3329
+ * when our Cloudflare LLM proxy is configured, else undefined (→ talk to the
3330
+ * provider directly, legacy behaviour). An explicit options.baseURL (e.g.
3331
+ * OpenRouter) always wins and is never overridden. See backend/docs/llm-proxy.md.
3332
+ */
3333
+ private static _proxyBaseURL;
3334
+ private static _openrouterOptions;
3335
+ private static _isRetryableProviderError;
3336
+ private static _withOpenrouterRetry;
3337
+ private static _openrouterText;
3338
+ private static _openrouterStream;
3339
+ private static _openrouterStreamWithTools;
3340
+ /**
3341
+ * Build an Anthropic client. Routes through our Cloudflare LLM proxy when
3342
+ * SUPERATOM_LLM_PROXY_URL is set (each client ships a per-client proxy key as
3343
+ * ANTHROPIC_API_KEY and never holds the real key); otherwise talks to
3344
+ * api.anthropic.com directly. See backend/docs/llm-proxy.md.
3345
+ */
3346
+ private static _anthropicClient;
3347
+ /** True when OpenRouter is configured as a fail-open fallback for Claude. */
3348
+ private static _openrouterAvailable;
3349
+ /** Remap an Anthropic model id to the OpenRouter model path for fail-open. */
3350
+ private static _anthropicFallbackModel;
1305
3351
  private static _anthropicText;
1306
3352
  private static _anthropicStream;
1307
3353
  private static _anthropicStreamWithTools;
1308
3354
  private static _groqText;
1309
3355
  private static _groqStream;
3356
+ /**
3357
+ * Gemini request options carrying the proxy base URL, or undefined → talk to
3358
+ * generativelanguage.googleapis.com directly. The Google SDK takes baseUrl as a
3359
+ * per-model request option, not a constructor arg. See backend/docs/llm-proxy.md.
3360
+ */
3361
+ private static _geminiRequestOptions;
1310
3362
  private static _geminiText;
1311
3363
  private static _geminiStream;
3364
+ /**
3365
+ * Recursively strip unsupported JSON Schema properties for Gemini
3366
+ * Gemini doesn't support: additionalProperties, $schema, etc.
3367
+ */
3368
+ private static _cleanSchemaForGemini;
1312
3369
  private static _geminiStreamWithTools;
3370
+ /** True for Anthropic/Claude model ids — gates OpenRouter prompt caching. */
3371
+ private static _isClaudeModel;
3372
+ /**
3373
+ * Build the OpenAI-wire system message. For OpenRouter + Claude
3374
+ * (cacheClaude=true) it emits content parts carrying Anthropic
3375
+ * `cache_control` breakpoints (preserving any the caller set, else marking
3376
+ * the last block), so OpenRouter forwards them to Anthropic for prompt
3377
+ * caching. Otherwise it returns a plain flattened string — unchanged for
3378
+ * direct OpenAI/Groq.
3379
+ */
3380
+ private static _openaiSystemMessage;
3381
+ /**
3382
+ * Split an OpenAI-wire usage object. `prompt_tokens` INCLUDES cached tokens,
3383
+ * so we subtract them out (Anthropic-style: input excludes cache reads) and
3384
+ * report cached separately — this makes calculateCost price cache reads at
3385
+ * the discounted rate and reflects OpenRouter prompt-cache savings in logs.
3386
+ */
3387
+ private static _openaiUsage;
1313
3388
  private static _openaiText;
1314
3389
  private static _openaiStream;
3390
+ /** Map the Anthropic-style firstIterationToolChoice to OpenAI's tool_choice. */
3391
+ private static _openaiToolChoice;
1315
3392
  private static _openaiStreamWithTools;
1316
3393
  /**
1317
3394
  * Parse JSON string, handling markdown code blocks and surrounding text
@@ -1401,19 +3478,9 @@ declare class UILogCollector {
1401
3478
  setUIBlockId(uiBlockId: string): void;
1402
3479
  }
1403
3480
 
1404
- /**
1405
- * Represents an action that can be performed on a UIBlock
1406
- */
1407
- interface Action {
1408
- id: string;
1409
- name: string;
1410
- type: string;
1411
- [key: string]: any;
1412
- }
1413
-
1414
3481
  /**
1415
3482
  * UIBlock represents a single user and assistant message block in a thread
1416
- * Contains user question, component metadata, component data, text response, and available actions
3483
+ * Contains user question, component metadata, component data, and text response
1417
3484
  */
1418
3485
  declare class UIBlock {
1419
3486
  private id;
@@ -1421,18 +3488,23 @@ declare class UIBlock {
1421
3488
  private generatedComponentMetadata;
1422
3489
  private componentData;
1423
3490
  private textResponse;
1424
- private actions;
1425
3491
  private createdAt;
3492
+ /**
3493
+ * Which script recipe produced this answer, when a script did. Read on the
3494
+ * NEXT turn so the user can say "use mode instead" and have the matcher
3495
+ * resolve it to a concrete script (the `edit` tier is unreachable without it).
3496
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3497
+ */
3498
+ private scriptBinding;
1426
3499
  /**
1427
3500
  * Creates a new UIBlock instance
1428
3501
  * @param userQuestion - The user's question or input
1429
3502
  * @param componentData - The component data object
1430
3503
  * @param generatedComponentMetadata - Optional metadata about the generated component
1431
- * @param actions - Optional array of available actions
1432
3504
  * @param id - Optional custom ID, generates UUID if not provided
1433
3505
  * @param textResponse - Optional text response from LLM
1434
3506
  */
1435
- constructor(userQuestion: string, componentData?: Record<string, any>, generatedComponentMetadata?: Record<string, any>, actions?: Action[], id?: string, textResponse?: string | null);
3507
+ constructor(userQuestion: string, componentData?: Record<string, any>, generatedComponentMetadata?: Record<string, any>, id?: string, textResponse?: string | null);
1436
3508
  /**
1437
3509
  * Get the UIBlock ID
1438
3510
  */
@@ -1482,41 +3554,22 @@ declare class UIBlock {
1482
3554
  * Set or update text response
1483
3555
  */
1484
3556
  setTextResponse(textResponse: string | null): void;
3557
+ /** The program-generated half of the answer — see setProgramAnswer. */
3558
+ programAnswer?: string | null;
1485
3559
  /**
1486
- * Get all actions (only if they are resolved, not if fetching)
3560
+ * Bind this block to the script recipe that produced its answer.
1487
3561
  */
1488
- getActions(): Action[] | null | Promise<Action[]>;
3562
+ setScriptBinding(binding: Record<string, any> | null): void;
1489
3563
  /**
1490
- * Get or fetch actions
1491
- * If actions don't exist or are a Promise, calls the generateFn and stores the promise
1492
- * If actions already exist, returns them
1493
- * @param generateFn - Async function to generate actions
1494
- * @returns Promise resolving to Action[]
3564
+ * The program-generated half of the answer, kept verbatim so a reload can
3565
+ * replace exactly that text without disturbing the streamed narration.
1495
3566
  */
1496
- getOrFetchActions(generateFn: () => Promise<Action[]>): Promise<Action[]>;
3567
+ setProgramAnswer(text: string | null): void;
3568
+ getProgramAnswer(): string | null;
1497
3569
  /**
1498
- * Set or replace all actions
1499
- */
1500
- setActions(actions: Action[]): void;
1501
- /**
1502
- * Add a single action (only if actions are resolved)
1503
- */
1504
- addAction(action: Action): void;
1505
- /**
1506
- * Add multiple actions (only if actions are resolved)
1507
- */
1508
- addActions(actions: Action[]): void;
1509
- /**
1510
- * Remove an action by ID (only if actions are resolved)
1511
- */
1512
- removeAction(actionId: string): boolean;
1513
- /**
1514
- * Clear all actions
1515
- */
1516
- clearActions(): void;
1517
- /**
1518
- * Get creation timestamp
3570
+ * The script recipe bound to this block, if any.
1519
3571
  */
3572
+ getScriptBinding(): Record<string, any> | null;
1520
3573
  getCreatedAt(): Date;
1521
3574
  /**
1522
3575
  * Convert UIBlock to JSON-serializable object
@@ -1584,7 +3637,55 @@ declare class Thread {
1584
3637
  * @param currentUIBlockId - ID of current UIBlock to exclude from context (optional)
1585
3638
  * @returns Formatted conversation history string
1586
3639
  */
1587
- getConversationContext(limit?: number, currentUIBlockId?: string): string;
3640
+ /**
3641
+ * The script recipe bound to the most recent completed UIBlock — i.e. the
3642
+ * script behind the answer the user is currently looking at. Drives the
3643
+ * matcher's `edit` tier: without it, "use mode instead" has no target and
3644
+ * falls through to regeneration.
3645
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3646
+ */
3647
+ getActiveScriptBinding(currentUIBlockId?: string): Record<string, any> | null;
3648
+ /**
3649
+ * The recent script-backed answers in this thread, newest first — the
3650
+ * candidate set a user-directed edit can target.
3651
+ *
3652
+ * Returning several rather than only the newest is what lets an instruction
3653
+ * name its own target ("use the mode for the WSP one"). With a single
3654
+ * candidate every edit lands on the most recent script, which silently edits
3655
+ * the wrong recipe whenever the user meant an earlier one.
3656
+ *
3657
+ * Deduped by recipeId (newest occurrence wins) so a long editing session on
3658
+ * one script doesn't crowd out the others. Each entry carries the question
3659
+ * that produced it — without that the candidates are indistinguishable.
3660
+ *
3661
+ * In-memory only: dies with the process. The caller falls back to the
3662
+ * persisted bindings when this comes back empty.
3663
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3664
+ */
3665
+ getScriptBindings(limit?: number, currentUIBlockId?: string): Record<string, any>[];
3666
+ /**
3667
+ * @param getScriptBody Resolves a script-backed turn's EXACT script, pinned
3668
+ * to the version that turn actually ran — never today's (possibly
3669
+ * since-edited) live body. Owned by the caller (needs a ScriptStore, which
3670
+ * Thread doesn't hold) — omit it and every turn falls back to the
3671
+ * no-script summary below.
3672
+ * @param fetchRecentFromDb When provided, this is now the SOURCE OF TRUTH
3673
+ * for history instead of this process's in-memory `uiblocks` map — reads
3674
+ * the persisted `user_conversations` rows (DB `response` jsonb shape, see
3675
+ * transformUIBlockForDB in conversation-saver.ts) via the caller's own
3676
+ * `user-conversations.getRecentForContext` collection. Rows come back
3677
+ * newest-first (already excluding status='aborted' — the query itself
3678
+ * filters that, matching what the in-memory path achieved via
3679
+ * thread.removeUIBlock() on abort). Fixes the standing gap where a backend
3680
+ * restart lost every thread's history (ThreadManager has no DB-backed
3681
+ * rehydration) — DB-backed history survives that, and is correct even if
3682
+ * a different process instance saved the row. Omit it and this falls back
3683
+ * to the in-memory map, for any caller not yet updated.
3684
+ */
3685
+ getConversationContext(limit?: number, currentUIBlockId?: string, getScriptBody?: (recipeId: string, version: number) => Promise<string | null>, fetchRecentFromDb?: (limit: number) => Promise<Array<{
3686
+ userprompt?: string;
3687
+ response?: Record<string, any>;
3688
+ }>>): Promise<string>;
1588
3689
  /**
1589
3690
  * Convert Thread to JSON-serializable object
1590
3691
  */
@@ -1593,12 +3694,20 @@ declare class Thread {
1593
3694
 
1594
3695
  /**
1595
3696
  * ThreadManager manages all threads globally
1596
- * Provides methods to create, retrieve, and delete threads
3697
+ * Provides methods to create, retrieve, and delete threads.
3698
+ * Includes automatic cleanup to prevent unbounded memory growth.
1597
3699
  */
1598
3700
  declare class ThreadManager {
1599
3701
  private static instance;
1600
3702
  private threads;
3703
+ private cleanupInterval;
3704
+ private readonly threadTtlMs;
1601
3705
  private constructor();
3706
+ /**
3707
+ * Periodically remove threads older than 7 days.
3708
+ * Runs every hour to avoid frequent iteration over the map.
3709
+ */
3710
+ private startCleanup;
1602
3711
  /**
1603
3712
  * Get singleton instance of ThreadManager
1604
3713
  */
@@ -1997,6 +4106,92 @@ declare function rerankConversationResults<T extends {
1997
4106
  bm25Score: number;
1998
4107
  }>;
1999
4108
 
4109
+ /**
4110
+ * QueryExecutionService - Handles all query execution, validation, and retry logic
4111
+ * Extracted from BaseLLM for better separation of concerns
4112
+ */
4113
+
4114
+ /**
4115
+ * Context for component when requesting query fix
4116
+ */
4117
+ interface ComponentContext {
4118
+ name: string;
4119
+ type: string;
4120
+ title?: string;
4121
+ }
4122
+ /**
4123
+ * Result of query validation
4124
+ */
4125
+ interface QueryValidationResult {
4126
+ component: Component | null;
4127
+ queryKey: string;
4128
+ result: any;
4129
+ validated: boolean;
4130
+ }
4131
+ /**
4132
+ * Result of batch query validation
4133
+ */
4134
+ interface BatchValidationResult {
4135
+ components: Component[];
4136
+ queryResults: Map<string, any>;
4137
+ }
4138
+ /**
4139
+ * Configuration for QueryExecutionService
4140
+ */
4141
+ interface QueryExecutionServiceConfig {
4142
+ defaultLimit: number;
4143
+ getModelForTask: (taskType: 'simple' | 'complex') => string;
4144
+ getApiKey: (apiKey?: string) => string | undefined;
4145
+ providerName: string;
4146
+ }
4147
+ /**
4148
+ * QueryExecutionService handles all query-related operations
4149
+ */
4150
+ declare class QueryExecutionService {
4151
+ private config;
4152
+ constructor(config: QueryExecutionServiceConfig);
4153
+ /**
4154
+ * Get the cache key for a query
4155
+ * This ensures the cache key matches what the frontend will send
4156
+ */
4157
+ getQueryCacheKey(query: any): string;
4158
+ /**
4159
+ * Execute a query against the database
4160
+ * @param query - The SQL query to execute (string or object with sql/values)
4161
+ * @param collections - Collections object containing database execute function
4162
+ * @returns Object with result data and cache key
4163
+ */
4164
+ executeQuery(query: any, collections: any): Promise<{
4165
+ result: any;
4166
+ cacheKey: string;
4167
+ }>;
4168
+ /**
4169
+ * Request the LLM to fix a failed SQL query
4170
+ * @param failedQuery - The query that failed execution
4171
+ * @param errorMessage - The error message from the failed execution
4172
+ * @param componentContext - Context about the component
4173
+ * @param apiKey - Optional API key
4174
+ * @returns Fixed query string
4175
+ */
4176
+ requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
4177
+ /**
4178
+ * Validate a single component's query with retry logic
4179
+ * @param component - The component to validate
4180
+ * @param collections - Collections object containing database execute function
4181
+ * @param apiKey - Optional API key for LLM calls
4182
+ * @returns Validation result with component, query key, and result
4183
+ */
4184
+ validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
4185
+ /**
4186
+ * Validate multiple component queries in parallel
4187
+ * @param components - Array of components with potential queries
4188
+ * @param collections - Collections object containing database execute function
4189
+ * @param apiKey - Optional API key for LLM calls
4190
+ * @returns Object with validated components and query results map
4191
+ */
4192
+ validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
4193
+ }
4194
+
2000
4195
  /**
2001
4196
  * Task types for model selection
2002
4197
  * - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
@@ -2015,6 +4210,7 @@ interface BaseLLMConfig {
2015
4210
  * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
2016
4211
  */
2017
4212
  modelStrategy?: ModelStrategy;
4213
+ conversationSimilarityThreshold?: number;
2018
4214
  }
2019
4215
  /**
2020
4216
  * BaseLLM abstract class for AI-powered component generation and matching
@@ -2026,6 +4222,8 @@ declare abstract class BaseLLM {
2026
4222
  protected defaultLimit: number;
2027
4223
  protected apiKey?: string;
2028
4224
  protected modelStrategy: ModelStrategy;
4225
+ protected conversationSimilarityThreshold: number;
4226
+ protected queryService: QueryExecutionService;
2029
4227
  constructor(config?: BaseLLMConfig);
2030
4228
  /**
2031
4229
  * Get the appropriate model based on task type and model strategy
@@ -2043,6 +4241,16 @@ declare abstract class BaseLLM {
2043
4241
  * @returns The current model strategy
2044
4242
  */
2045
4243
  getModelStrategy(): ModelStrategy;
4244
+ /**
4245
+ * Set the conversation similarity threshold at runtime
4246
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
4247
+ */
4248
+ setConversationSimilarityThreshold(threshold: number): void;
4249
+ /**
4250
+ * Get the current conversation similarity threshold
4251
+ * @returns The current threshold value
4252
+ */
4253
+ getConversationSimilarityThreshold(): number;
2046
4254
  /**
2047
4255
  * Get the default model for this provider (used for complex tasks like text generation)
2048
4256
  */
@@ -2071,28 +4279,26 @@ declare abstract class BaseLLM {
2071
4279
  */
2072
4280
  protected containsFormComponent(component: any): boolean;
2073
4281
  /**
2074
- * Match components from text response suggestions and generate follow-up questions
4282
+ * Match components from text response suggestions
2075
4283
  * Takes a text response with component suggestions (c1:type format) and matches with available components
2076
- * Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
4284
+ * Also generates title and description based on the analysis
2077
4285
  * All components are placed in a default MultiComponentContainer layout
2078
4286
  * @param analysisContent - The text response containing component suggestions
2079
4287
  * @param components - List of available components
2080
4288
  * @param apiKey - Optional API key
2081
- * @param logCollector - Optional log collector
2082
4289
  * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
2083
- * @returns Object containing matched components, layout title/description, and follow-up actions
4290
+ * @returns Object containing matched components and layout title/description
2084
4291
  */
2085
- matchComponentsFromAnalysis(analysisContent: string, components: Component[], apiKey?: string, logCollector?: any, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[]): Promise<{
4292
+ matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
2086
4293
  components: Component[];
2087
4294
  layoutTitle: string;
2088
4295
  layoutDescription: string;
2089
- actions: Action[];
2090
4296
  }>;
2091
4297
  /**
2092
4298
  * Classify user question into category and detect external tools needed
2093
4299
  * Determines if question is for data analysis, requires external tools, or needs text response
2094
4300
  */
2095
- classifyQuestionCategory(userPrompt: string, apiKey?: string, logCollector?: any, conversationHistory?: string, externalTools?: any[]): Promise<{
4301
+ classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
2096
4302
  category: 'data_analysis' | 'data_modification' | 'general';
2097
4303
  externalTools: Array<{
2098
4304
  type: string;
@@ -2109,7 +4315,7 @@ declare abstract class BaseLLM {
2109
4315
  * Takes a matched UI block from semantic search and modifies its props to answer the new question
2110
4316
  * Also adapts the cached text response to match the new question
2111
4317
  */
2112
- adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, logCollector?: any, cachedTextResponse?: string): Promise<{
4318
+ adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
2113
4319
  success: boolean;
2114
4320
  adaptedComponent?: Component;
2115
4321
  adaptedTextResponse?: string;
@@ -2124,13 +4330,8 @@ declare abstract class BaseLLM {
2124
4330
  * This provides conversational text responses instead of component generation
2125
4331
  * Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
2126
4332
  * After generating text response, if components are provided, matches suggested components
2127
- * @param streamCallback - Optional callback function to receive text chunks as they stream
2128
- * @param collections - Collection registry for executing database queries via database.execute
2129
- * @param components - Optional list of available components for matching suggestions
2130
- * @param externalTools - Optional array of external tools (email, calendar, etc.) that can be called
2131
- * @param category - Question category ('data_analysis' | 'data_modification' | 'general'). For data_modification, answer component streaming is skipped. For general, component generation is skipped entirely.
2132
4333
  */
2133
- generateTextResponse(userPrompt: string, apiKey?: string, logCollector?: any, conversationHistory?: string, streamCallback?: (chunk: string) => void, collections?: any, components?: Component[], externalTools?: any[], category?: 'data_analysis' | 'data_modification' | 'general'): Promise<T_RESPONSE>;
4334
+ 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>;
2134
4335
  /**
2135
4336
  * Main orchestration function with semantic search and multi-step classification
2136
4337
  * NEW FLOW (Recommended):
@@ -2138,19 +4339,8 @@ declare abstract class BaseLLM {
2138
4339
  * - If match found → Adapt UI block parameters and return
2139
4340
  * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
2140
4341
  * 3. Route appropriately based on category and response mode
2141
- *
2142
- * @param responseMode - 'component' for component generation (default), 'text' for text responses
2143
- * @param streamCallback - Optional callback function to receive text chunks as they stream (only for text mode)
2144
- * @param collections - Collection registry for executing database queries (required for text mode)
2145
- * @param externalTools - Optional array of external tools (email, calendar, etc.) that can be called (only for text mode)
2146
4342
  */
2147
- handleUserRequest(userPrompt: string, components: Component[], apiKey?: string, logCollector?: any, conversationHistory?: string, responseMode?: 'component' | 'text', streamCallback?: (chunk: string) => void, collections?: any, externalTools?: any[], userId?: string): Promise<T_RESPONSE>;
2148
- /**
2149
- * Generate next questions that the user might ask based on the original prompt and generated component
2150
- * This helps provide intelligent suggestions for follow-up queries
2151
- * For general/conversational questions without components, pass textResponse instead
2152
- */
2153
- generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, logCollector?: any, conversationHistory?: string, textResponse?: string): Promise<string[]>;
4343
+ 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>;
2154
4344
  }
2155
4345
 
2156
4346
  interface AnthropicLLMConfig extends BaseLLMConfig {
@@ -2209,7 +4399,989 @@ declare class OpenAILLM extends BaseLLM {
2209
4399
  }
2210
4400
  declare const openaiLLM: OpenAILLM;
2211
4401
 
2212
- declare const SDK_VERSION = "0.0.8";
4402
+ /**
4403
+ * Query Cache — Two mechanisms:
4404
+ *
4405
+ * 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
4406
+ * of recently validated queries. True LRU eviction: reads bubble entries to the back via
4407
+ * delete+re-set so the oldest *unused* entry is evicted, not the oldest *inserted*.
4408
+ *
4409
+ * 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
4410
+ * No server-side storage needed for SQL mappings. The token is decrypted on each request.
4411
+ * This eliminates the unbounded queryIdCache that previously grew forever and caused
4412
+ * memory bloat (hundreds of MBs after thousands of queries).
4413
+ *
4414
+ * Result data can still be cached temporarily via the data cache (mechanism 1).
4415
+ */
4416
+ declare class QueryCache {
4417
+ private cache;
4418
+ private ttlMs;
4419
+ private maxCacheSize;
4420
+ private cleanupInterval;
4421
+ private readonly algorithm;
4422
+ private encryptionKey;
4423
+ constructor();
4424
+ /**
4425
+ * Set the cache TTL (Time To Live)
4426
+ * @param minutes - TTL in minutes (default: 10)
4427
+ */
4428
+ setTTL(minutes: number): void;
4429
+ /**
4430
+ * Get the current TTL in minutes
4431
+ */
4432
+ getTTL(): number;
4433
+ /**
4434
+ * Store query result in data cache.
4435
+ * If the key already exists, it's removed first so the re-insert places it
4436
+ * at the back of the iteration order (LRU). Eviction only fires when adding
4437
+ * a genuinely new key past the size limit.
4438
+ */
4439
+ set(query: string, data: any): void;
4440
+ /**
4441
+ * Get cached result if exists and not expired.
4442
+ * On hit, re-inserts the entry so it moves to the back of the Map's
4443
+ * iteration order — turning FIFO eviction into true LRU.
4444
+ */
4445
+ get(query: string): any | null;
4446
+ /**
4447
+ * Check if query exists in cache (not expired)
4448
+ */
4449
+ has(query: string): boolean;
4450
+ /**
4451
+ * Remove a specific query from cache
4452
+ */
4453
+ delete(query: string): void;
4454
+ /**
4455
+ * Clear all cached entries
4456
+ */
4457
+ clear(): void;
4458
+ /**
4459
+ * Get cache statistics
4460
+ */
4461
+ getStats(): {
4462
+ size: number;
4463
+ queryIdCount: number;
4464
+ oldestEntryAge: number | null;
4465
+ };
4466
+ /**
4467
+ * Start periodic cleanup of expired data cache entries.
4468
+ */
4469
+ private startCleanup;
4470
+ /**
4471
+ * Encrypt a payload into a self-contained token.
4472
+ */
4473
+ private encrypt;
4474
+ /**
4475
+ * Decrypt a token back to the original payload.
4476
+ */
4477
+ private decrypt;
4478
+ /**
4479
+ * Store a query by generating an encrypted token as queryId.
4480
+ * The SQL is encrypted INTO the token — nothing stored in memory.
4481
+ * If data is provided, it's cached temporarily in the data cache.
4482
+ */
4483
+ storeQuery(query: any, data?: any): string;
4484
+ /**
4485
+ * Get a stored query by decrypting its token.
4486
+ * Returns the SQL + any cached result data.
4487
+ */
4488
+ getQuery(queryId: string): {
4489
+ query: any;
4490
+ data: any;
4491
+ } | null;
4492
+ /**
4493
+ * Update cached data for a queryId token
4494
+ */
4495
+ setQueryData(queryId: string, data: any): void;
4496
+ /**
4497
+ * Stop cleanup interval (for graceful shutdown)
4498
+ */
4499
+ destroy(): void;
4500
+ }
4501
+ declare const queryCache: QueryCache;
4502
+
4503
+ /**
4504
+ * Manages conversation history scoped per user + dashboard.
4505
+ * Each user-dashboard pair has its own isolated history that expires after a configurable TTL.
4506
+ */
4507
+ declare class DashboardConversationHistory {
4508
+ private histories;
4509
+ private ttlMs;
4510
+ private maxEntries;
4511
+ private cleanupInterval;
4512
+ constructor();
4513
+ /**
4514
+ * Set the TTL for dashboard histories
4515
+ * @param minutes - TTL in minutes
4516
+ */
4517
+ setTTL(minutes: number): void;
4518
+ /**
4519
+ * Set max entries per dashboard
4520
+ */
4521
+ setMaxEntries(max: number): void;
4522
+ /**
4523
+ * Add a conversation entry for a user's dashboard
4524
+ */
4525
+ addEntry(dashboardId: string, userPrompt: string, componentSummary: string, userId?: string): void;
4526
+ /**
4527
+ * Get formatted conversation history for a user's dashboard
4528
+ */
4529
+ getHistory(dashboardId: string, userId?: string): string;
4530
+ /**
4531
+ * Clear history for a specific user's dashboard
4532
+ */
4533
+ clearDashboard(dashboardId: string, userId?: string): void;
4534
+ /**
4535
+ * Clear all dashboard histories
4536
+ */
4537
+ clearAll(): void;
4538
+ /**
4539
+ * Start periodic cleanup of expired histories
4540
+ */
4541
+ private startCleanup;
4542
+ /**
4543
+ * Stop cleanup interval (for graceful shutdown)
4544
+ */
4545
+ destroy(): void;
4546
+ }
4547
+ declare const dashboardConversationHistory: DashboardConversationHistory;
4548
+
4549
+ /**
4550
+ * Whole-dashboard generation via Pi, a terminal coding agent — as opposed to
4551
+ * DASH_COMP_REQ's single-widget-at-a-time flow. Runs Pi in-process via its
4552
+ * SDK (createAgentSession), not as a subprocess: no shell, no argument
4553
+ * quoting, no stdin/stdout piping, none of the Windows-specific subprocess
4554
+ * issues that came with spawning the `pi` CLI directly.
4555
+ *
4556
+ * Called from sdk-nodejs/src/dashboardAgent/index.ts (DASHBOARD_AGENT_REQ),
4557
+ * which owns the generic streaming/abort machinery (mirrors USER_PROMPT_REQ)
4558
+ * and passes `signal`/`onProgress` alongside the normal params — this stays
4559
+ * within CollectionHandler's loose (params) => Promise<result> typing, no
4560
+ * change needed to that shared type.
4561
+ *
4562
+ * This mechanism is generic and reusable across any deployment. What's
4563
+ * genuinely project-specific — where AGENTS.md lives, which model to use —
4564
+ * is supplied via `DashboardAgentCollectionConfig`, with defaults sensible
4565
+ * enough that most callers don't need to override them (see below). The
4566
+ * data-source tool list and the dashboard's current state both come from
4567
+ * things sdk-nodejs already exposes generically: `sdk.getTools()` (whatever
4568
+ * this deployment registered via `sdk.setTools()`) and `sdk.callCollection
4569
+ * ('dashboards', 'query', ...)` (whatever this deployment already registered
4570
+ * under that name/shape) — no per-deployment callback needed for either.
4571
+ * Same convention on the way out: after a successful run, the prompt and the
4572
+ * full response text are handed to `sdk.callCollection('dashboard-agent-
4573
+ * conversations', 'create', ...)` if this deployment has registered one —
4574
+ * skipped silently otherwise, since conversation history is optional.
4575
+ *
4576
+ * Pi verifies every query against the live database itself (via whatever
4577
+ * local tool-execution bridge the deployment exposes, e.g. an HTTP bridge
4578
+ * on localhost), but does NOT persist the result itself — it writes the
4579
+ * finished DSL to an absolute path inside `runtimeDir`, told to it explicitly
4580
+ * in the prompt, and stops there. This handler reads that file after the run
4581
+ * finishes and returns its content as `dashboard` in the result. The caller
4582
+ * (frontend) is the one that actually saves it, via whatever authenticated
4583
+ * create/update path any other dashboard edit goes through — Pi has no user
4584
+ * session/auth context of its own, so persistence shouldn't happen from
4585
+ * inside it.
4586
+ *
4587
+ * Session persistence: the FIRST call for a dashboardId pays the full cost
4588
+ * (explore KB, discover schema, plan, verify, build). Every call after that
4589
+ * resumes the same session file (SessionManager.open) so Pi has everything
4590
+ * it already learned — it only needs to reason about the new, smaller ask,
4591
+ * not rediscover the whole dashboard from scratch. The session's file path
4592
+ * (AgentSession.sessionFile) is captured right after creation and persisted
4593
+ * in a small local file, keyed by dashboardId, inside `runtimeDir`.
4594
+ */
4595
+ interface DashboardAgentCollectionConfig {
4596
+ /**
4597
+ * Working directory Pi runs from — must contain AGENTS.md. This is a
4598
+ * version-controlled prompt file, so `cwd` is expected to live somewhere
4599
+ * like a `.prompts/` folder alongside the deployment's other prompts.
4600
+ * Default: `<process.cwd()>/.prompts/dashboard-agent` — the same
4601
+ * process.cwd()-based convention PromptLoader already uses for the main
4602
+ * agent's prompts, which needs no explicit override in the common case
4603
+ * (the backend process's own cwd already is its project root).
4604
+ */
4605
+ cwd?: string;
4606
+ /**
4607
+ * Where drafts/, the session-id map, and dashboard.log get written —
4608
+ * separate from `cwd` deliberately, so this deployment's runtime state
4609
+ * (regenerated per session, safe to gitignore) doesn't sit inside the
4610
+ * same folder as the version-controlled AGENTS.md prompt.
4611
+ * Default: `<process.cwd()>/.pi-dashboard-agent-runtime`.
4612
+ */
4613
+ runtimeDir?: string;
4614
+ /** Model provider (default: process.env.PI_AGENT_PROVIDER || 'openrouter'). */
4615
+ provider?: string;
4616
+ /** Model id (default: process.env.PI_AGENT_MODEL || 'anthropic/claude-sonnet-4.5'). */
4617
+ model?: string;
4618
+ /**
4619
+ * true (default): every request starts a brand-new pi session, with the 2
4620
+ * most recent prior responses (if any) injected into the prompt as
4621
+ * context — bounded cost per request, but pi re-explores schema/KB facts
4622
+ * it already verified in an earlier turn on this same dashboard.
4623
+ * false: resumes the same session file across requests on a given
4624
+ * dashboard — pi keeps everything it already learned, but context (and
4625
+ * cost) grows unbounded across turns (one observed turn: 2M+ cache-read
4626
+ * tokens after a handful of edits on the same dashboard).
4627
+ * Default: process.env.PI_AGENT_FRESH_SESSION !== 'false'.
4628
+ */
4629
+ freshSession?: boolean;
4630
+ }
4631
+ declare function registerDashboardAgentCollection(sdk: SuperatomSDK, config?: DashboardAgentCollectionConfig): void;
4632
+
4633
+ /**
4634
+ * Coding-agent driver contract — one shape over every harness (codex today;
4635
+ * claude-code / opencode / pi next). Callers depend on this file only, never on
4636
+ * a harness SDK, so swapping the agent behind a task is a config change.
4637
+ *
4638
+ * Deliberately narrower than the harness SDKs it wraps: the three things a
4639
+ * production run needs and that harness abstractions usually omit — real abort,
4640
+ * real token accounting, and structured tool args — are part of the contract,
4641
+ * not per-driver extras.
4642
+ */
4643
+ type AgentEventKind = 'turn' | 'message' | 'reasoning' | 'command' | 'tool' | 'file' | 'todo' | 'error';
4644
+ interface AgentEvent {
4645
+ kind: AgentEventKind;
4646
+ /** Stable across started→updated→completed, so a UI updates one block in place. */
4647
+ id?: string;
4648
+ text?: string;
4649
+ command?: string;
4650
+ output?: string;
4651
+ /** Tool calls carry real parsed args — never SQL scraped back out of a shell string. */
4652
+ tool?: {
4653
+ server?: string;
4654
+ name: string;
4655
+ args?: unknown;
4656
+ };
4657
+ status?: 'in_progress' | 'completed' | 'failed';
4658
+ done?: boolean;
4659
+ }
4660
+ interface AgentUsage {
4661
+ inputTokens: number;
4662
+ outputTokens: number;
4663
+ reasoningTokens: number;
4664
+ cacheReadTokens: number;
4665
+ cacheWriteTokens: number;
4666
+ /** Tool + command invocations. With tokens, separates "silently did nothing" from a real run. */
4667
+ toolCalls: number;
4668
+ /** Only when the harness reports it — codex reports tokens but not cost. */
4669
+ costUSD?: number;
4670
+ }
4671
+ interface AgentRunHandlers {
4672
+ /** Formatted live stream: assistant text deltas plus one-line tool/command markers. */
4673
+ onOutput?: (chunk: string) => void;
4674
+ onEvent?: (event: AgentEvent) => void;
4675
+ /** Assistant prose only — safe to show a non-technical user as progress. */
4676
+ onNarration?: (text: string) => void;
4677
+ onUsage?: (usage: AgentUsage) => void;
4678
+ /**
4679
+ * Polled once the turn is live. When it returns true the run ends immediately —
4680
+ * for tasks whose deliverable is a file, the moment it exists there is nothing
4681
+ * left to wait for.
4682
+ */
4683
+ doneWhen?: () => boolean | Promise<boolean>;
4684
+ }
4685
+ type AgentRunStatus = 'completed' | 'early' | 'aborted' | 'error';
4686
+ interface AgentRunResult {
4687
+ status: AgentRunStatus;
4688
+ /** The final assistant message. */
4689
+ answer: string;
4690
+ ms: number;
4691
+ usage: AgentUsage;
4692
+ /**
4693
+ * Set when status is 'error'. Covers stream-reported failures too, which arrive
4694
+ * as events rather than thrown exceptions — a swallowed provider error is the
4695
+ * failure mode that otherwise looks like a successful empty run.
4696
+ */
4697
+ error?: string;
4698
+ sessionId?: string;
4699
+ }
4700
+ interface McpServerSpec {
4701
+ command: string;
4702
+ args?: string[];
4703
+ env?: Record<string, string>;
4704
+ }
4705
+ interface CodingAgentSessionOptions {
4706
+ /** Working directory the agent operates in. Scope it to a runtime dir, not a source checkout. */
4707
+ cwd: string;
4708
+ model?: string;
4709
+ /** Resume a prior conversation — the value a previous run returned as sessionId. */
4710
+ resumeId?: string;
4711
+ /** Tools, as MCP servers. Keyed by server name, which shows up on every tool event. */
4712
+ mcpServers?: Record<string, McpServerSpec>;
4713
+ /**
4714
+ * Extra env for the agent process. By default only a small allowlist is passed
4715
+ * through (see ENV_ALLOWLIST) so an agent with shell access can't read the
4716
+ * backend's own secrets out of its environment.
4717
+ */
4718
+ env?: Record<string, string>;
4719
+ /** Opt out of env scrubbing. Only for local debugging. */
4720
+ inheritEnv?: boolean;
4721
+ }
4722
+ interface CodingAgentSession {
4723
+ readonly harness: string;
4724
+ /** Structured event log vs. a raw terminal stream — the UI picks its renderer from this. */
4725
+ readonly kind: 'events' | 'pty';
4726
+ run(prompt: string, handlers?: AgentRunHandlers, signal?: AbortSignal): Promise<AgentRunResult>;
4727
+ /** Rolling structured events, for replay when a client reconnects mid-run. */
4728
+ events(): AgentEvent[];
4729
+ /** Rolling formatted text, same purpose as events() for text-oriented views. */
4730
+ buffer(): string;
4731
+ busy(): boolean;
4732
+ /** Persist this and pass it back as resumeId to continue the conversation. */
4733
+ sessionId(): string | undefined;
4734
+ /** Abandon the conversation; the next run starts fresh. */
4735
+ reset(): void;
4736
+ dispose(): void;
4737
+ }
4738
+
4739
+ /**
4740
+ * Harness registry. Kept separate from index.ts so collection.ts can reach the
4741
+ * factory without importing the module's own barrel (a cycle tsup would have to
4742
+ * resolve at bundle time).
4743
+ */
4744
+ type Harness = 'codex';
4745
+ declare function createCodingAgentSession(harness: Harness, opts: CodingAgentSessionOptions): CodingAgentSession;
4746
+
4747
+ /**
4748
+ * Codex driver — OpenAI Codex via @openai/codex-sdk.
4749
+ *
4750
+ * FORMAT CONTRACT: written against @openai/codex-sdk 0.149.1. Harness event
4751
+ * shapes drift; if the event log goes blank after an SDK bump, check normEvent
4752
+ * against the package's dist/index.d.ts first.
4753
+ *
4754
+ * Three things this leans on that the SDK gives natively, so we don't reinvent
4755
+ * them: TurnOptions.signal (real cancellation), TurnCompletedEvent.usage (token
4756
+ * accounting), and mcp_tool_call items (tool args arrive parsed, not scraped
4757
+ * out of a shell command string).
4758
+ *
4759
+ * The package is an optionalDependency: every deployment gets it, but an
4760
+ * install that cannot fetch the ~309MB platform binary skips it rather than
4761
+ * failing. It is therefore loaded dynamically and its types mirrored
4762
+ * structurally below, so a VM without it still builds, starts, and runs
4763
+ * everything else — only the coding agent reports itself unavailable.
4764
+ */
4765
+ type CodexSandboxMode = 'read-only' | 'workspace-write' | 'danger-full-access';
4766
+ type CodexReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra';
4767
+ interface CodexSessionOptions extends CodingAgentSessionOptions {
4768
+ reasoningEffort?: CodexReasoningEffort;
4769
+ /**
4770
+ * Filesystem reach. Default 'workspace-write' — the agent writes its
4771
+ * deliverable into cwd and nothing else. 'danger-full-access' hands a
4772
+ * shell-capable agent the whole box; don't use it on a client VM.
4773
+ */
4774
+ sandboxMode?: CodexSandboxMode;
4775
+ /** Network for commands the agent runs. Off by default; MCP tools don't need it. */
4776
+ networkAccessEnabled?: boolean;
4777
+ apiKey?: string;
4778
+ baseUrl?: string;
4779
+ /** Raw `--config` overrides merged into the codex config. */
4780
+ extraConfig?: Record<string, unknown>;
4781
+ approvalPolicy?: 'never' | 'on-request' | 'on-failure' | 'untrusted';
4782
+ }
4783
+ declare function createCodexSession(opts: CodexSessionOptions): CodingAgentSession;
4784
+
4785
+ /**
4786
+ * What makes an agent fire.
4787
+ *
4788
+ * Declared ON the definition, deliberately. If triggers lived at the call sites
4789
+ * instead — a counter in the conversation handler, a hook in the kb-nodes
4790
+ * collection — then adding an agent would mean editing unrelated files across
4791
+ * the backend, and no one file would tell you when an agent actually runs.
4792
+ * Here, an agent's folder plus its definition is the whole story.
4793
+ *
4794
+ * The deployment's only job is to announce that something happened:
4795
+ *
4796
+ * emitAgentEvent('conversation.answered', { threadId })
4797
+ * emitAgentEvent('kb-node.changed', { id, op: 'update' })
4798
+ *
4799
+ * Which agents care, and how many events it takes, is the agents' business.
4800
+ * The emitter therefore speaks the WORLD's vocabulary, never any one agent's —
4801
+ * translating an event into a particular agent's input is `buildInput` below.
4802
+ */
4803
+ /** One announced fact, as it reaches a trigger. */
4804
+ interface TriggerEvent {
4805
+ /** The event name passed to emitAgentEvent. */
4806
+ name: string;
4807
+ payload?: unknown;
4808
+ }
4809
+ /**
4810
+ * Turns the events that caused this run into the agent's `input`.
4811
+ *
4812
+ * Takes the whole list, not one payload, because every batching trigger here
4813
+ * fires for MANY events: a debounced burst, or N counted occurrences. Handing
4814
+ * over only the last one silently discarded the rest — five edited nodes became
4815
+ * one.
4816
+ *
4817
+ * Omit it and the agent receives the most recent payload unchanged, which is
4818
+ * the historical behaviour. Any agent that batches should declare one.
4819
+ */
4820
+ type BuildTriggerInput = (events: TriggerEvent[]) => unknown;
4821
+ type AgentTrigger =
4822
+ /** Only runCodingAgent(). The default. */
4823
+ {
4824
+ type: 'manual';
4825
+ }
4826
+ /** Every N milliseconds while the process is up. Fires with no events. */
4827
+ | {
4828
+ type: 'interval';
4829
+ everyMs: number;
4830
+ buildInput?: BuildTriggerInput;
4831
+ }
4832
+ /**
4833
+ * On a named event. `debounceMs` collapses a burst into one run — editing
4834
+ * five knowledge nodes in a row is one reason to rebuild, not five. The run
4835
+ * still receives all five events; only the RUNS are collapsed.
4836
+ */
4837
+ | {
4838
+ type: 'event';
4839
+ on: string | string[];
4840
+ debounceMs?: number;
4841
+ buildInput?: BuildTriggerInput;
4842
+ }
4843
+ /**
4844
+ * Every Nth occurrence of an event. The events are PERSISTED, so "after 10
4845
+ * questions" survives a restart instead of silently starting over.
4846
+ */
4847
+ | {
4848
+ type: 'count';
4849
+ on: string;
4850
+ every: number;
4851
+ buildInput?: BuildTriggerInput;
4852
+ };
4853
+ interface TriggerFireInfo {
4854
+ agentId: string;
4855
+ /** What set it off, for the log line. */
4856
+ reason: string;
4857
+ /** Everything that caused this run, in arrival order. */
4858
+ events: TriggerEvent[];
4859
+ /** What buildInput produced — exactly what the agent was handed. */
4860
+ input?: unknown;
4861
+ }
4862
+ /** Notified after every triggered run — for recording history or alerting. */
4863
+ type RunListener = (record: AgentRunRecord, info: TriggerFireInfo) => void;
4864
+ declare function onAgentRun(fn: RunListener): () => void;
4865
+ /**
4866
+ * Tell the agents something happened. Safe to call from anywhere, including a
4867
+ * request path — it never throws and never blocks: matching runs are started,
4868
+ * not awaited.
4869
+ */
4870
+ declare function emitAgentEvent(event: string, payload?: unknown): void;
4871
+ /**
4872
+ * Start interval triggers. Call once at startup, after registerCodingAgents.
4873
+ * Event and count triggers need nothing started — they wake on emitAgentEvent.
4874
+ */
4875
+ declare function startAgentTriggers(): void;
4876
+ declare function stopAgentTriggers(): void;
4877
+ /** What fires each agent — for a startup log or an admin screen. */
4878
+ declare function describeTriggers(): Array<{
4879
+ agentId: string;
4880
+ triggers: string[];
4881
+ }>;
4882
+
4883
+ /**
4884
+ * What a coding agent IS.
4885
+ *
4886
+ * An agent is a job description, not code that does the job: instructions, the
4887
+ * inputs it should be handed, the tools it may reach, the deliverable it must
4888
+ * produce, and what we do with that deliverable. The agent itself decides HOW —
4889
+ * it can read the inputs, write and run scripts over them, check its own work,
4890
+ * and iterate. That is the whole reason for using a coding agent rather than a
4891
+ * single LLM call: the job's data never has to fit in a context window.
4892
+ *
4893
+ * Adding an agent is a folder with a system.md, one file implementing this
4894
+ * interface, and one line in the registry. Nothing else changes.
4895
+ */
4896
+ /** The disposable directory one run happens in. */
4897
+ interface Workspace {
4898
+ /** Absolute path the agent runs in. Everything below is relative to it. */
4899
+ dir: string;
4900
+ /** Unique per run — also the folder name, so runs never collide. */
4901
+ runId: string;
4902
+ /** Write a file into the workspace, creating parent directories. */
4903
+ write(relPath: string, contents: string): Promise<void>;
4904
+ /** Write JSON (pretty-printed — the agent reads these by eye as often as by script). */
4905
+ writeJson(relPath: string, value: unknown): Promise<void>;
4906
+ /** Write one JSON object per line. The right shape for anything the agent will stream or grep. */
4907
+ writeJsonl(relPath: string, rows: unknown[]): Promise<void>;
4908
+ /** Read a file the agent produced. Returns null when it isn't there. */
4909
+ read(relPath: string): Promise<string | null>;
4910
+ /** Absolute path for a workspace-relative path — for telling the agent where to write. */
4911
+ pathTo(relPath: string): string;
4912
+ }
4913
+ /** Minimal validator shape, so this file needn't depend on a schema library. */
4914
+ interface OutputValidator<T> {
4915
+ /** Throw with a useful message, or return the parsed value. Zod's `.parse` satisfies this. */
4916
+ parse(value: unknown): T;
4917
+ }
4918
+ interface OutputContract<T> {
4919
+ /**
4920
+ * Workspace-relative path the agent must write, e.g. 'out/concepts.json'.
4921
+ * Nothing else counts as the deliverable: the run ends the moment this
4922
+ * appears, and a run that finishes without it is a failure, not a partial
4923
+ * success.
4924
+ */
4925
+ file: string;
4926
+ /** Validated before anything is persisted, so a malformed run fails loudly and applies nothing. */
4927
+ schema: OutputValidator<T>;
4928
+ }
4929
+ /** What apply() reports back — surfaced in the run record and to the caller. */
4930
+ interface ApplySummary {
4931
+ /** One line a human can read in a log or the UI. */
4932
+ summary: string;
4933
+ /** Whatever counts for this agent: {created, updated, skipped}, etc. */
4934
+ counts?: Record<string, number>;
4935
+ /** Anything the caller may want to inspect or show. */
4936
+ details?: unknown;
4937
+ }
4938
+ interface AgentRunContext {
4939
+ projectId?: string;
4940
+ userId?: string;
4941
+ /**
4942
+ * This run's id — also the workspace directory name. Passed so apply() can
4943
+ * stamp whatever it persists with the run that produced it, which is the
4944
+ * only link from a stored result back to the inputs and scripts behind it.
4945
+ */
4946
+ runId?: string;
4947
+ /** The run's workspace, for an apply() that needs a file the agent left. */
4948
+ workspaceDir?: string;
4949
+ /** Cancels the run; forwarded to the driver's real abort. */
4950
+ signal?: AbortSignal;
4951
+ /** Live progress. Populated for chat mode; a task run may also stream to a log. */
4952
+ onOutput?: (chunk: string) => void;
4953
+ onEvent?: (event: AgentEvent) => void;
4954
+ onUsage?: (usage: AgentUsage) => void;
4955
+ }
4956
+ /**
4957
+ * How much an agent carries between runs.
4958
+ *
4959
+ * Codex manages its own context: it tracks the window and compacts when it
4960
+ * crosses `auto_compact_token_limit`, emitting a ContextCompacted event. That
4961
+ * happens with no involvement from us, so a persistent session survives
4962
+ * indefinitely on its own. (The mechanism is in the engine but not the
4963
+ * TypeScript SDK — Thread exposes only id/run/runStreamed — which is why there
4964
+ * is nothing here to call.)
4965
+ *
4966
+ * What compaction cannot do is make the session authoritative. It summarises to
4967
+ * make room, so detail is lost by design; and ~/.codex/sessions is a directory
4968
+ * on one machine, not the database. So durable facts belong in `memory/` files
4969
+ * and in the tables the agent writes through apply(), with the session free to
4970
+ * compact itself as it likes. Memory on disk, context managed by codex.
4971
+ */
4972
+ interface SessionPolicy {
4973
+ /**
4974
+ * 'per-run' a fresh harness session each time (default).
4975
+ * 'persistent' resume the same session across runs, so the agent keeps its
4976
+ * working context. Always paired with durable files — never rely
4977
+ * on it alone.
4978
+ */
4979
+ scope?: 'per-run' | 'persistent';
4980
+ /**
4981
+ * 'per-run' a throwaway directory per run (default); pruned by keepRuns.
4982
+ * 'persistent' one directory the agent owns across runs. `memory/` survives
4983
+ * untouched; `input/` is cleared each run so a stale input can
4984
+ * never be mistaken for this run's.
4985
+ */
4986
+ workspace?: 'per-run' | 'persistent';
4987
+ /**
4988
+ * Safety valve, not the compaction mechanism — codex already compacts on its
4989
+ * own. Starts a fresh session after this many runs while keeping the
4990
+ * workspace, for when you want a hard ceiling on how much summarised history
4991
+ * an agent drags along, or a clean slate on a cadence. Omit by default.
4992
+ */
4993
+ resetAfterTurns?: number;
4994
+ }
4995
+ interface CodingAgentDefinition<TInput = unknown, TOutput = unknown> {
4996
+ /** Stable id: the folder name under .prompts/coding-agents, and the key callers use. */
4997
+ id: string;
4998
+ /** Human-readable, for the UI and logs. */
4999
+ title: string;
5000
+ /** One line: what this agent is for. */
5001
+ description?: string;
5002
+ /**
5003
+ * 'task' — headless. Runs from a cron, an event, or a command; produces the
5004
+ * deliverable and applies it. Nobody is watching.
5005
+ * 'chat' — a person is typing. Streams, keeps its session across turns, and
5006
+ * is not required to produce a deliverable at all.
5007
+ */
5008
+ mode: 'task' | 'chat';
5009
+ /**
5010
+ * Directory holding this agent's system.md. Defaults to
5011
+ * `<promptRoot>/<id>`. The runner copies system.md into the workspace as
5012
+ * AGENTS.md, which is the filename the harness actually reads from its
5013
+ * working directory — that indirection is what lets the instructions stay
5014
+ * version-controlled while the workspace stays disposable.
5015
+ */
5016
+ promptDir?: string;
5017
+ /** Override the deployment default for this agent alone. */
5018
+ harness?: Harness;
5019
+ model?: string;
5020
+ /**
5021
+ * Let this agent's shell reach the network. Off by default.
5022
+ *
5023
+ * Needed by any agent given bridge shims (writeBridgeShims), which reach the
5024
+ * backend over localhost HTTP. Note the sandbox has no host allowlist, so
5025
+ * this grants the whole internet, not just the bridge — scope it to agents
5026
+ * that genuinely need it.
5027
+ */
5028
+ networkAccessEnabled?: boolean;
5029
+ /**
5030
+ * Filesystem reach. Defaults to the driver's 'workspace-write'.
5031
+ * 'danger-full-access' removes the sandbox entirely — it is the only mode in
5032
+ * which codex permits MCP tool calls headlessly, which is exactly why the
5033
+ * shims exist instead.
5034
+ */
5035
+ sandboxMode?: 'read-only' | 'workspace-write' | 'danger-full-access';
5036
+ /**
5037
+ * Tools this agent may reach, as MCP servers. Deliberately per-agent: an
5038
+ * agent that reads the knowledge base has no business holding a database
5039
+ * connection. Omit for an agent that only needs the files it is given.
5040
+ */
5041
+ tools?: Record<string, McpServerSpec>;
5042
+ /**
5043
+ * Put the job's inputs in the workspace as FILES, not prompt text. A coding
5044
+ * agent can grep, aggregate and script over a file; it cannot do any of that
5045
+ * with text pasted into its prompt, and a large input would not fit there
5046
+ * anyway.
5047
+ */
5048
+ prepare?(ws: Workspace, input: TInput, ctx: AgentRunContext): Promise<void>;
5049
+ /**
5050
+ * The short framing sent as the turn's prompt. Keep it short — the standing
5051
+ * instructions belong in system.md and the data belongs in files. Defaults
5052
+ * to a generic instruction naming the output path.
5053
+ */
5054
+ buildPrompt?(ws: Workspace, input: TInput, ctx: AgentRunContext): string | Promise<string>;
5055
+ /** Required for 'task' mode; meaningless for 'chat'. */
5056
+ output?: OutputContract<TOutput>;
5057
+ /**
5058
+ * Persist the validated deliverable — through existing services, never raw
5059
+ * SQL from inside the agent. Keeping the write on this side is what makes a
5060
+ * run auditable and replayable: the artifact on disk is the same input
5061
+ * apply() would get again tomorrow.
5062
+ */
5063
+ apply?(result: TOutput, input: TInput, ctx: AgentRunContext): Promise<ApplySummary>;
5064
+ /**
5065
+ * What makes this agent run. Declared here so an agent's folder plus this
5066
+ * file is the complete story of when it fires. See triggers.ts.
5067
+ */
5068
+ trigger?: AgentTrigger | AgentTrigger[];
5069
+ /**
5070
+ * WHO this agent's accumulated state belongs to. Distinct from `mode`, which
5071
+ * is only how a run was triggered — the two were conflated before, so a
5072
+ * project agent someone chatted with silently got a private per-thread
5073
+ * workspace and lost its memory.
5074
+ *
5075
+ * 'project' ONE workspace and session for the whole deployment, whoever
5076
+ * invokes it. A concept builder is project-wide: everything it
5077
+ * learns should accumulate in one place, and a chat turn joins
5078
+ * that same workspace rather than forking a copy. Concurrent
5079
+ * runs serialise.
5080
+ * 'user' one per user, shared across that user's threads.
5081
+ * 'thread' one per conversation — an ordinary chat assistant.
5082
+ *
5083
+ * Default: 'thread' for mode 'chat', 'project' for mode 'task'.
5084
+ */
5085
+ scope?: 'project' | 'user' | 'thread';
5086
+ /**
5087
+ * Kill the turn the moment the deliverable file appears, instead of letting
5088
+ * the agent finish.
5089
+ *
5090
+ * Off by default, and the reason is measured: an agent typically writes its
5091
+ * output and then keeps going — verifying, re-reading, summarising — so
5092
+ * stopping at the write cuts the turn well before codex emits
5093
+ * turn.completed, which is the only event carrying token usage. Early stop
5094
+ * therefore costs you all cost tracking, and skips the agent's own
5095
+ * self-check. Turn it on for a long-tailed agent where the file really is
5096
+ * the last thing that matters.
5097
+ */
5098
+ stopOnDeliverable?: boolean;
5099
+ /** What this agent carries between runs. Default: nothing (fresh session and workspace). */
5100
+ session?: SessionPolicy;
5101
+ /** Hard cap for one run. Default 15 minutes. */
5102
+ timeoutMs?: number;
5103
+ }
5104
+ /** What a completed run reports. */
5105
+ interface AgentRunRecord<TOutput = unknown> {
5106
+ agentId: string;
5107
+ runId: string;
5108
+ /** The run's directory — instructions, inputs, scripts and output all still there. */
5109
+ workspaceDir: string;
5110
+ /**
5111
+ * 'early' the deliverable landed and we stopped the turn — a success, kept
5112
+ * distinct from 'completed' so a masked early exit is visible.
5113
+ * 'skipped' another run of this agent held the lock; nothing was done.
5114
+ */
5115
+ status: 'completed' | 'early' | 'aborted' | 'error' | 'skipped';
5116
+ /** The agent's closing message. */
5117
+ answer: string;
5118
+ ms: number;
5119
+ usage: AgentUsage;
5120
+ /** Present when the agent produced and validated its deliverable. */
5121
+ output?: TOutput;
5122
+ /** Present when apply() ran. */
5123
+ applied?: ApplySummary;
5124
+ error?: string;
5125
+ /** Harness session id, for resuming a chat. */
5126
+ sessionId?: string;
5127
+ }
5128
+
5129
+ /**
5130
+ * The agent registry — one place that knows which agents this deployment has.
5131
+ *
5132
+ * Deliberately a plain module-level map rather than something on the SDK: a
5133
+ * cron job, a CLI command and the websocket handler all need to reach the same
5134
+ * agents, and only one of those has an SDK instance in hand.
5135
+ */
5136
+ interface CodingAgentsConfig {
5137
+ /**
5138
+ * Where per-agent instruction folders live. Each agent reads
5139
+ * `<promptRoot>/<agent.id>/system.md`.
5140
+ * Default: `<cwd>/.prompts/coding-agents`, matching the .prompts convention
5141
+ * the rest of the deployment already uses.
5142
+ */
5143
+ promptRoot?: string;
5144
+ /**
5145
+ * Root for run workspaces: `<runtimeDir>/<agentId>/<runId>/`. Regenerated
5146
+ * per run and safe to gitignore — deliberately not inside promptRoot, which
5147
+ * is version-controlled.
5148
+ * Default: `<cwd>/.coding-agent-runtime`.
5149
+ */
5150
+ runtimeDir?: string;
5151
+ /** Fallback harness for agents that don't name one. */
5152
+ harness?: Harness;
5153
+ /** Fallback model. */
5154
+ model?: string;
5155
+ /** Tools every agent gets, merged under each agent's own (the agent's win on a name clash). */
5156
+ sharedTools?: Record<string, McpServerSpec>;
5157
+ /** Keep this many run directories per agent; older ones are pruned. 0 keeps everything. */
5158
+ keepRuns?: number;
5159
+ }
5160
+ /**
5161
+ * Register this deployment's agents. Call once at startup.
5162
+ *
5163
+ * Re-registering an id replaces it — that keeps hot-reload working in dev and
5164
+ * makes a double registration a no-op rather than a silent duplicate.
5165
+ */
5166
+ declare function registerCodingAgents(definitions: CodingAgentDefinition<any, any>[], options?: CodingAgentsConfig): void;
5167
+ declare function getCodingAgent(id: string): CodingAgentDefinition<any, any> | undefined;
5168
+ declare function listCodingAgents(): Array<{
5169
+ id: string;
5170
+ title: string;
5171
+ description?: string;
5172
+ mode: 'task' | 'chat';
5173
+ }>;
5174
+ declare function getCodingAgentsConfig(): Required<Pick<CodingAgentsConfig, "harness" | "promptRoot" | "runtimeDir" | "keepRuns">> & CodingAgentsConfig;
5175
+
5176
+ interface RunAgentOptions<TInput> extends AgentRunContext {
5177
+ input?: TInput;
5178
+ /** Scopes a 'thread' agent. Ignored by a project-scoped one. */
5179
+ threadId?: string;
5180
+ /**
5181
+ * Escape hatch that pins the workspace directory outright. Almost never
5182
+ * right — it defeats the agent's own scope, which is how a project agent
5183
+ * ends up with a private copy per caller. Left for tests and one-offs.
5184
+ */
5185
+ workspaceDir?: string;
5186
+ /** Resume the harness session — chat continuity across turns and restarts. */
5187
+ resumeId?: string;
5188
+ /** Overrides the definition's prompt entirely. Chat mode: this is the user's message. */
5189
+ prompt?: string;
5190
+ /**
5191
+ * A person is typing, rather than a job running.
5192
+ *
5193
+ * For an agent whose mode is 'task' this turns off the JOB — prepare(), the
5194
+ * deliverable contract and apply() are one unit that sets work up and
5195
+ * consumes it, and a conversation should do neither. The turn joins the
5196
+ * workspace as it stands and its answer is the whole result.
5197
+ *
5198
+ * Without this, chatting with a task agent could only ever fail: the user's
5199
+ * message replaces the prompt that names the output path, so the agent never
5200
+ * writes the deliverable, and the run is then reported as an error despite
5201
+ * having answered perfectly well. Worse, prepare() ran on every turn — for a
5202
+ * batching agent that means a chat turn quietly consumed a batch of work.
5203
+ *
5204
+ * An agent whose mode is 'chat' is unaffected: its prepare() is per-turn
5205
+ * context setup, not job setup, so it still runs.
5206
+ */
5207
+ chat?: boolean;
5208
+ }
5209
+ /**
5210
+ * Run one agent, end to end.
5211
+ *
5212
+ * Never throws for an agent-side failure — a bad run comes back as a record
5213
+ * with status 'error', because callers are usually crons and message handlers
5214
+ * that must keep going. Genuinely programmer errors (unknown agent id) do throw.
5215
+ */
5216
+ declare function runCodingAgent<TInput = unknown, TOutput = unknown>(agentId: string, options?: RunAgentOptions<TInput>): Promise<AgentRunRecord<TOutput>>;
5217
+
5218
+ /**
5219
+ * Write `./sources` and `./query` into an agent's workspace: read-only data
5220
+ * access as plain executables it runs with bash.
5221
+ *
5222
+ * Why not MCP: codex gates MCP tool calls on the sandbox. Under any sandboxed
5223
+ * mode they need approval, and a headless run must set approvalPolicy 'never',
5224
+ * which denies rather than grants — measured, not assumed. Only
5225
+ * danger-full-access permits them, and that removes the filesystem sandbox
5226
+ * entirely. Bash commands under workspace-write need no approval, so a shim
5227
+ * buys the same capability while the agent stays confined to its workspace.
5228
+ *
5229
+ * An MCP server for this was written and then removed: the same approval gate
5230
+ * applies to the Agents chat tab, which is equally headless from codex's point
5231
+ * of view, so it was unreachable everywhere. `mcpServers` stays plumbed through
5232
+ * the driver for third-party servers; see git history for the removed one.
5233
+ *
5234
+ * The cost is structured tool events: calls arrive as `bash → ./query ...`
5235
+ * rather than typed items with parsed arguments. That matters for a chat UI
5236
+ * with a human watching; for a headless task agent it does not.
5237
+ *
5238
+ * Requires networkAccessEnabled on the session — the shim reaches the bridge
5239
+ * over HTTP, and that is the whole point of it.
5240
+ */
5241
+ declare function writeBridgeShims(ws: Workspace, opts: {
5242
+ bridgeUrl: string;
5243
+ sources: Array<{
5244
+ id: string;
5245
+ name?: string;
5246
+ description?: string;
5247
+ }>;
5248
+ maxRows?: number;
5249
+ }): void;
5250
+
5251
+ /**
5252
+ * Read-only SQL guard for any path that hands an agent a database.
5253
+ *
5254
+ * Defence in depth, NOT a boundary. The agent has a shell and can reach the
5255
+ * bridge directly, so anything enforced only here is advisory — it stops
5256
+ * mistakes, not determination. The real boundary is a database user without
5257
+ * write permission; this exists so a confused agent gets a clear correction
5258
+ * instead of a silent partial write.
5259
+ */
5260
+ /** Throws with a message written for the agent to act on. */
5261
+ declare function assertReadOnlySql(sql: string): void;
5262
+
5263
+ /**
5264
+ * The 'coding-agent'.'run' collection — a chat turn against a coding agent.
5265
+ *
5266
+ * Generic on purpose: nothing here knows about dashboards, reports, or any
5267
+ * particular deliverable. It owns what every harness-backed chat needs — one
5268
+ * session per thread, a per-thread workspace, a run lock, and forwarding the
5269
+ * driver's callbacks to the transport. Task-specific flows (prompt assembly, a
5270
+ * draft-file contract, persistence) build on top of this rather than inside it.
5271
+ */
5272
+ interface CodingAgentCollectionConfig {
5273
+ /**
5274
+ * Root for per-thread agent workspaces. Each thread gets its own directory
5275
+ * underneath, so one chat can't read or clobber another's files, and none of
5276
+ * them sit inside the backend's own source tree.
5277
+ * Default: `<process.cwd()>/.coding-agent-runtime`.
5278
+ */
5279
+ runtimeDir?: string;
5280
+ /** Default harness when the request doesn't name one. */
5281
+ harness?: Harness;
5282
+ model?: string;
5283
+ /** Tools, as MCP servers, handed to every session. */
5284
+ mcpServers?: Record<string, McpServerSpec>;
5285
+ }
5286
+ declare function registerCodingAgentCollection(sdk: SuperatomSDK, config?: CodingAgentCollectionConfig): void;
5287
+
5288
+ declare class ScriptMatcher {
5289
+ private store;
5290
+ private collections?;
5291
+ private userId?;
5292
+ private trace?;
5293
+ constructor(store: ScriptStore, opts?: {
5294
+ collections?: any;
5295
+ userId?: string;
5296
+ trace?: RunTrace;
5297
+ });
5298
+ /**
5299
+ * Find the best matching script for a user question.
5300
+ * Uses ONE LLM call that picks the script AND extracts parameters.
5301
+ * Returns null if no script matches.
5302
+ *
5303
+ * Thin wrapper around `doMatch` whose only job is guaranteeing the trace
5304
+ * capture happens exactly once, on every exit path (short-circuit, normal
5305
+ * return, or the LLM call erroring) — see RunTrace.scriptMatcher.
5306
+ */
5307
+ match(userPrompt: string, apiKey?: string, model?: string, signal?: AbortSignal, activeBindings?: ScriptBinding[]): Promise<ScriptMatch | null>;
5308
+ private doMatch;
5309
+ /**
5310
+ * Renders a recipe's declared parameters the same way in every prompt
5311
+ * section (catalog, active-script, edit candidates) so the LLM sees one
5312
+ * consistent format regardless of which block a script came from.
5313
+ */
5314
+ private formatParamList;
5315
+ /**
5316
+ * Semantic search over THIS user's own past prompts (`conversation-history`
5317
+ * ChromaDB embeddings, already user-scoped) — not a project-wide name/tag
5318
+ * search. Groups hits by the recipe that answered them, so a script gets
5319
+ * ONE catalog entry carrying every matched past question, not one per hit.
5320
+ *
5321
+ * Scope is deliberate (see SCRIPT-MATCH-IMPROVEMENTS.md, Change 2): a
5322
+ * script only shows up here because THIS user has, before, asked something
5323
+ * similar that it answered — not because some other user's question did.
5324
+ */
5325
+ private searchPromptHistory;
5326
+ /**
5327
+ * Build the script catalog string for the LLM prompt from prompt-history
5328
+ * matches: each script's declared parameters PLUS the actual past questions
5329
+ * of this user's that it answered (real precedent, not a hand-written
5330
+ * description) and what params they ran with.
5331
+ */
5332
+ private buildPromptHistoryCatalog;
5333
+ /**
5334
+ * The most recent script-backed answer in this thread — the one an `edit`
5335
+ * targets. Rendered as its own prompt section (never merged into the ranked
5336
+ * catalog) so the `edit` rules have an unambiguous referent.
5337
+ *
5338
+ * `candidates` holds at most one entry (see doMatch) — `edit` always means
5339
+ * "the answer I just got", so there is nothing else to show here.
5340
+ *
5341
+ * Carries the QUESTION that produced it plus the columns it returned — that
5342
+ * is what lets the matcher resolve "use the mode for the WSP one" against
5343
+ * this one script's own context.
5344
+ */
5345
+ private buildActiveScriptBlock;
5346
+ }
5347
+
5348
+ /**
5349
+ * ScriptRunner — Execute scripts in an isolated tsx subprocess.
5350
+ *
5351
+ * The subprocess approach replaces the earlier `new Function()` eval and gives us:
5352
+ * - Real sandbox (separate process, SIGKILL on timeout).
5353
+ * - Real TypeScript (tsx transpiles on the fly).
5354
+ * - npm imports available to scripts (clustering, stats, geo, etc.).
5355
+ *
5356
+ * Protocol: NDJSON over the child's stdin/stdout. See script-ipc.ts + backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md.
5357
+ */
5358
+
5359
+ interface RunScriptOptions {
5360
+ /** Data sources the script is allowed to query via ctx.query */
5361
+ externalTools: ExternalTool[];
5362
+ /** Optional — for propagating per-query UI progress to the user */
5363
+ streamBuffer?: StreamBuffer;
5364
+ /** Override the wall-clock timeout (default `SCRIPT_TIMEOUT_MS`, 60s). */
5365
+ timeoutMs?: number;
5366
+ /**
5367
+ * Per-turn cancellation signal. When the user hits "Stop" mid-run, the child
5368
+ * process group is SIGKILLed and the run resolves as an aborted failure (the
5369
+ * caller is already unwinding, so the result is discarded).
5370
+ */
5371
+ signal?: AbortSignal;
5372
+ /**
5373
+ * Names resolved for this run, handed to getAnalysis/getComponents as their
5374
+ * 5th argument. Supplying these is what stops "the narrative needs the
5375
+ * subsidiary's name" from being a reason to rewrite getData and re-query.
5376
+ */
5377
+ entities?: ResolvedEntityRef[];
5378
+ }
5379
+ /**
5380
+ * Execute a recipe by spawning a tsx child on the script's .ts file.
5381
+ * `scriptPath` is the absolute path to the saved `.ts` body.
5382
+ */
5383
+ declare function runScript(recipe: ScriptRecipe, scriptPath: string, params: Record<string, any>, options: RunScriptOptions): Promise<ScriptResult>;
5384
+
2213
5385
  type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
2214
5386
  declare class SuperatomSDK {
2215
5387
  private ws;
@@ -2226,6 +5398,7 @@ declare class SuperatomSDK {
2226
5398
  private collections;
2227
5399
  private components;
2228
5400
  private tools;
5401
+ private workflows;
2229
5402
  private anthropicApiKey;
2230
5403
  private groqApiKey;
2231
5404
  private geminiApiKey;
@@ -2233,6 +5406,10 @@ declare class SuperatomSDK {
2233
5406
  private llmProviders;
2234
5407
  private databaseType;
2235
5408
  private modelStrategy;
5409
+ private mainAgentModel;
5410
+ private sourceAgentModel;
5411
+ private dashCompModels?;
5412
+ private conversationSimilarityThreshold;
2236
5413
  private userManager;
2237
5414
  private dashboardManager;
2238
5415
  private reportManager;
@@ -2240,6 +5417,8 @@ declare class SuperatomSDK {
2240
5417
  private lastPong;
2241
5418
  private readonly PING_INTERVAL_MS;
2242
5419
  private readonly PONG_TIMEOUT_MS;
5420
+ private pendingOutbox;
5421
+ private readonly MAX_OUTBOX_SIZE;
2243
5422
  constructor(config: SuperatomSDKConfig);
2244
5423
  /**
2245
5424
  * Initialize PromptLoader and load prompts into memory
@@ -2279,9 +5458,25 @@ declare class SuperatomSDK {
2279
5458
  */
2280
5459
  private handleMessage;
2281
5460
  /**
2282
- * Send a message to the Superatom service
5461
+ * Send a message to the Superatom service.
5462
+ * Returns true if the message was sent, false if the WebSocket is not connected.
5463
+ * Does NOT throw on closed connections — callers can check the return value if needed.
5464
+ */
5465
+ send(message: Message): boolean;
5466
+ /**
5467
+ * Queue a message that couldn't be delivered because the socket was down,
5468
+ * to be resent once it reconnects. Drops the oldest entry once the bound is
5469
+ * hit — an outage long enough to fill this queue means the oldest queued
5470
+ * responses are for requests the caller has likely already given up on.
2283
5471
  */
2284
- send(message: Message): void;
5472
+ private queuePendingMessage;
5473
+ /**
5474
+ * Resend everything queued while the socket was down, now that it's back
5475
+ * up. Uses this.ws.send() directly (not send()) so a message that fails
5476
+ * again goes back through queuePendingMessage() rather than being silently
5477
+ * dropped a second time.
5478
+ */
5479
+ private flushPendingOutbox;
2285
5480
  /**
2286
5481
  * Register a message handler to receive all messages
2287
5482
  */
@@ -2321,6 +5516,14 @@ declare class SuperatomSDK {
2321
5516
  */
2322
5517
  private handlePong;
2323
5518
  private storeComponents;
5519
+ /**
5520
+ * The live, frontend-registered component catalog (name, type, description,
5521
+ * and full prop schema per component) — the same authoritative source
5522
+ * DASH_COMP_REQ's LLM prompt is built from. Exposed so other integrations
5523
+ * (e.g. the dashboard-agent script bridge) can read real component
5524
+ * contracts instead of maintaining a separate, driftable hand-written copy.
5525
+ */
5526
+ getComponents(): Component[];
2324
5527
  /**
2325
5528
  * Set tools for the SDK instance
2326
5529
  */
@@ -2329,6 +5532,29 @@ declare class SuperatomSDK {
2329
5532
  * Get the stored tools
2330
5533
  */
2331
5534
  getTools(): Tool$1[];
5535
+ /**
5536
+ * Call a registered collection operation in-process — no WebSocket
5537
+ * round-trip, since the caller is already running inside this same SDK
5538
+ * instance. Lets SDK-internal features (e.g. the dashboard agent) reuse
5539
+ * whatever collection a deployment has already registered (e.g.
5540
+ * 'dashboards'.'query') by name/convention, instead of requiring a
5541
+ * separate callback purely to re-expose data a collection already serves.
5542
+ * Throws if the collection or operation isn't registered.
5543
+ */
5544
+ callCollection<TResult = any>(collectionName: string, operation: string, params?: any): Promise<TResult>;
5545
+ /**
5546
+ * Register workflow components for the SDK instance.
5547
+ *
5548
+ * Workflows are pre-built multi-step UI flows the main agent can pick when
5549
+ * the user's prompt matches a workflow's `whenToUse` trigger. Picking a
5550
+ * workflow short-circuits analysis text + dashboard component generation —
5551
+ * the workflow component is returned directly, with the LLM-extracted props.
5552
+ */
5553
+ setWorkflows(workflows: WorkflowDescriptor[]): void;
5554
+ /**
5555
+ * Get the registered workflow components.
5556
+ */
5557
+ getWorkflows(): WorkflowDescriptor[];
2332
5558
  /**
2333
5559
  * Apply model strategy to all LLM provider singletons
2334
5560
  * @param strategy - 'best', 'fast', or 'balanced'
@@ -2343,6 +5569,20 @@ declare class SuperatomSDK {
2343
5569
  * Get current model strategy
2344
5570
  */
2345
5571
  getModelStrategy(): ModelStrategy;
5572
+ /**
5573
+ * Apply conversation similarity threshold to all LLM provider singletons
5574
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
5575
+ */
5576
+ private applyConversationSimilarityThreshold;
5577
+ /**
5578
+ * Set conversation similarity threshold at runtime
5579
+ * @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
5580
+ */
5581
+ setConversationSimilarityThreshold(threshold: number): void;
5582
+ /**
5583
+ * Get current conversation similarity threshold
5584
+ */
5585
+ getConversationSimilarityThreshold(): number;
2346
5586
  }
2347
5587
 
2348
- export { type Action, BM25L, type BM25LOptions, type BaseLLMConfig, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, type Message, type ModelStrategy, type OutputField, type RerankedResult, SDK_VERSION, STORAGE_CONFIG, SuperatomSDK, type SuperatomSDKConfig, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, type ToolOutputSchema, UIBlock, UILogCollector, type User, UserManager, type UsersData, anthropicLLM, geminiLLM, groqLLM, hybridRerank, llmUsageLogger, logger, openaiLLM, rerankChromaResults, rerankConversationResults, userPromptErrorLogger };
5588
+ export { type AgentConfig, type AgentEvent, type AgentResponse, type AgentRunContext, type AgentRunHandlers, type AgentRunRecord, type AgentRunResult, type AgentTrigger, type AgentUsage, type ApplySummary, BM25L, type BM25LOptions, type BaseLLMConfig, type BuildTriggerInput, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CodexSessionOptions, type CodingAgentCollectionConfig, type CodingAgentDefinition, type CodingAgentSession, type CodingAgentSessionOptions, type CodingAgentsConfig, type CollectionHandler, type CollectionOperation, type DBUIBlock, DEFAULT_AGENT_CONFIG, type DashboardAgentCollectionConfig, type DatabaseType, type Harness, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, MainAgent, type McpServerSpec, type Message, type ModelStrategy, type OutputContract, type OutputField, type OutputValidator, type RerankedResult, type RunAgentOptions, 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, type TriggerEvent, type TriggerFireInfo, UIBlock, UILogCollector, type User, UserManager, type UsersData, type WorkflowDescriptor, type Workspace, anthropicLLM, assertReadOnlySql, createCodexSession, createCodingAgentSession, dashboardConversationHistory, dataFingerprint, describeTriggers, emitAgentEvent, extractNamedExport, geminiLLM, getCodingAgent, getCodingAgentsConfig, groqLLM, hybridRerank, listCodingAgents, llmUsageLogger, logger, normalizeScriptBody, onAgentRun, openaiLLM, queryCache, registerCodingAgentCollection, registerCodingAgents, registerDashboardAgentCollection, rerankChromaResults, rerankConversationResults, resolveScriptRecipeStore, runCodingAgent, runScript, startAgentTriggers, stopAgentTriggers, userPromptErrorLogger, writeBridgeShims };