@superatomai/sdk-node 0.0.64 → 0.0.65-dsp

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,15 +1,1262 @@
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
+ * Restrictions an authorization policy injected into THIS query before it
259
+ * ran. Handed to getAnalysis/getComponents as `scope` so the answer can name
260
+ * the restriction without the recipe hardcoding a value that goes stale.
261
+ */
262
+ appliedPolicies?: string[];
263
+ }
264
+ /**
265
+ * Match tier returned by the LLM script matcher.
266
+ *
267
+ * - 'high': the script answers the question directly; only parameter values
268
+ * may differ. The runtime replays it with extracted params (cheapest path).
269
+ * - 'near': the script answers a STRUCTURALLY similar question but needs
270
+ * body modification (different metric, dimension, table, filter shape).
271
+ * The runtime forks the parent and adapts the body via MainAgent's normal
272
+ * write_script + execute_script loop — no SourceAgent dispatch needed.
273
+ * See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md for the full design.
274
+ * - 'edit': the user is INSTRUCTING a change to the script that produced the
275
+ * previous answer (not asking a new question). Only reachable when the turn
276
+ * carries a ScriptBinding — without one the matcher coerces it to 'none', so
277
+ * a prompt regression can't turn this into a loose similarity path. The
278
+ * runtime runs MainAgent in edit mode and commits the result in place.
279
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md.
280
+ * - 'none': no script is relevant; full agent flow runs.
281
+ */
282
+ type MatchTier = 'high' | 'near' | 'edit' | 'none';
283
+ /**
284
+ * Which recipe produced the answer the user is currently looking at.
285
+ *
286
+ * Set whenever a turn's answer came from a script (replay, fresh authoring, or
287
+ * a committed edit) and carried on the UIBlock + saved conversation row. Two
288
+ * consumers:
289
+ * 1. The matcher — the 'edit' tier is ONLY reachable when a binding exists, so
290
+ * "use mode instead of mean" resolves to a concrete script instead of being
291
+ * matched on keywords it shares with no script name.
292
+ * 2. Cache invalidation — after an edit commits, conversations bound to that
293
+ * recipeId must be dropped, or the exact-match cache replays the pre-edit
294
+ * answer and the edit looks like a no-op.
295
+ *
296
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
297
+ */
298
+ interface ScriptBinding {
299
+ recipeId: string;
300
+ /**
301
+ * The recipe's own version number at the moment THIS turn ran — not
302
+ * necessarily the recipe's current version. A later edit bumps the live
303
+ * version, so without this a past turn's binding would silently point at
304
+ * whatever the recipe looks like today instead of what actually produced
305
+ * that answer. Absent on bindings created before this field existed.
306
+ */
307
+ version?: number;
308
+ /** Params the script ran with — the edit's starting point. */
309
+ params: Record<string, any>;
310
+ /** Recipe name at bind time (matcher catalog + user-facing confirmation). */
311
+ name: string;
312
+ /** Columns the last run returned — grounds the editor without a re-query. */
313
+ columns?: string[];
314
+ /**
315
+ * The question that produced this answer. Required for disambiguation when a
316
+ * thread ran several scripts — without it the candidates are just names and
317
+ * the matcher cannot resolve "use the mode for the WSP one".
318
+ */
319
+ userPrompt?: string;
320
+ /**
321
+ * The polished analysis text this script actually produced last time it ran
322
+ * (the same programAnswer Thread.getConversationContext() shows elsewhere).
323
+ * Carried alongside the script's own shape (columns, params) so the matcher
324
+ * sees "what did this script actually say" right next to "what can I ask it
325
+ * to change", instead of needing a separate conversation-history transcript
326
+ * that would otherwise just repeat the same question this block already
327
+ * states. This is why ScriptMatcher's own prompt no longer receives a raw
328
+ * conversation-history transcript at all — this field is what replaced it.
329
+ */
330
+ answerSummary?: string;
331
+ }
332
+ /**
333
+ * Result from the LLM-based script matcher.
334
+ *
335
+ * For `tier: 'high'`, `extractedParams` carries the values to pass to the
336
+ * existing script. For `tier: 'near'`, `gaps` and `modificationHint` describe
337
+ * what the fork-author needs to change in the parent body.
338
+ */
339
+ interface ScriptMatch {
340
+ /** The matched script recipe */
341
+ recipe: ScriptRecipe;
342
+ /** Match tier — see MatchTier docs */
343
+ tier: MatchTier;
344
+ /** Similarity score (0-1, derived from LLM tier) */
345
+ similarity: number;
346
+ /**
347
+ * Legacy confidence level. Mirrors `tier === 'high'`/`'near'` for now;
348
+ * kept so existing callers compile while we migrate to tier-based logic.
349
+ */
350
+ confidence: 'high' | 'medium';
351
+ /** Parameters extracted from the user question by the LLM (tier='high') */
352
+ extractedParams?: Record<string, any>;
353
+ /**
354
+ * Proper nouns the question named, VERBATIM, with the parameter each fills.
355
+ *
356
+ * The matcher must NOT resolve these itself. Observed live: it substituted the
357
+ * customer name "PREMER ENRGES PHOTOOTAIC" into an id parameter believing that
358
+ * "the runtime will resolve the customer name to its PartyId(s)" — nothing on
359
+ * the replay path does, and `WHERE BillingPartyId IN (PREMER ENRGES
360
+ * PHOTOOTAIC)` reached SQL. Reported here, the runtime resolves them before
361
+ * replay and rejects the match when one cannot be resolved.
362
+ */
363
+ mentions?: Array<{
364
+ text: string;
365
+ param?: string;
366
+ }>;
367
+ /** Business concepts the question relies on (e.g. "outstanding balance"). */
368
+ entityTypes?: string[];
369
+ /** What the user question needs that the parent doesn't cover (tier='near') */
370
+ gaps?: string[];
371
+ /** One-sentence description of the change the fork-author should make (tier='near') */
372
+ modificationHint?: string;
373
+ /**
374
+ * Which HALF of the recipe the edit targets (tier='edit'). A recipe has two
375
+ * independently editable halves:
376
+ * - 'data' — the scriptBody: how the rows are produced (aggregation,
377
+ * filters, joins, grouping). Runs MainAgent in edit mode.
378
+ * - 'display' — the component specs: how those SAME rows are shown (chart
379
+ * type, orientation, columns, labels). Replays the proven SQL
380
+ * and regenerates the specs — never authors a script.
381
+ * Defaults to 'data' when the matcher omits it.
382
+ */
383
+ editTarget?: 'data' | 'display';
384
+ /**
385
+ * Self-contained restatement of the change the user asked for (tier='edit').
386
+ * MUST have pronouns/deixis resolved ("this", "it", "that column") — the edit
387
+ * prompt never sees the conversation history, so an unresolved instruction is
388
+ * unusable downstream.
389
+ */
390
+ editInstruction?: string;
391
+ /** Why the matcher made this choice (for logs and telemetry) */
392
+ reasoning?: string;
393
+ }
394
+
395
+ /**
396
+ * script-ipc.ts — Protocol definitions for parent/child IPC.
397
+ *
398
+ * Transport: newline-delimited JSON over the child's stdin/stdout.
399
+ * stderr is passed through for uncaught exceptions and compile errors.
400
+ *
401
+ * See backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md § IPC Bridge.
402
+ */
403
+
404
+ /**
405
+ * A name the user said, and what it resolved to.
406
+ *
407
+ * Handed to getAnalysis/getComponents so a narrative can NAME the thing the
408
+ * question was about without typing the name in. Before this, the runtime knew
409
+ * "Fusion5 Pty Ltd" and used that knowledge only to REJECT scripts that typed
410
+ * it — with no sanctioned way to obtain it, the only legal escape was to add a
411
+ * column to getData and re-run the query, spending an execute attempt to learn
412
+ * something the runtime already knew.
413
+ */
414
+ interface ResolvedEntityRef {
415
+ /** The text the user actually wrote. */
416
+ mention: string;
417
+ entityType: string;
418
+ instanceId: string;
419
+ displayName: string;
420
+ }
421
+ /**
422
+ * What getAnalysis returns. `analysis` is the narrative and `summary` the short
423
+ * bullets the markdown block binds to — siblings over one dataset, never a
424
+ * summary OF the narrative. See backend/docs/ANALYSIS-AS-PROGRAM-DESIGN.md § 4.3.
425
+ */
426
+ interface AnalysisOutput {
427
+ analysis?: string;
428
+ summary?: string[];
429
+ method?: string;
430
+ }
431
+
432
+ /**
433
+ * StreamBuffer - Buffered streaming utility for smoother text delivery
434
+ * Batches small chunks together and flushes at regular intervals
435
+ */
436
+ type StreamCallback = (chunk: string) => void;
437
+ /**
438
+ * StreamBuffer class for managing buffered streaming output
439
+ * Provides smooth text delivery by batching small chunks
440
+ */
441
+ declare class StreamBuffer {
442
+ private buffer;
443
+ private flushTimer;
444
+ private callback;
445
+ private fullText;
446
+ constructor(callback?: StreamCallback);
447
+ /**
448
+ * Check if the buffer has a callback configured
449
+ */
450
+ hasCallback(): boolean;
451
+ /**
452
+ * Get all text that has been written (including already flushed)
453
+ */
454
+ getFullText(): string;
455
+ /**
456
+ * Write a chunk to the buffer
457
+ * Large chunks or chunks with newlines are flushed immediately
458
+ * Small chunks are batched and flushed after a short interval
459
+ *
460
+ * @param chunk - Text chunk to write
461
+ */
462
+ write(chunk: string): void;
463
+ /**
464
+ * Flush the buffer immediately
465
+ * Call this before tool execution or other operations that need clean output
466
+ */
467
+ flush(): void;
468
+ /**
469
+ * Internal flush implementation
470
+ */
471
+ private flushNow;
472
+ /**
473
+ * Clean up resources
474
+ * Call this when done with the buffer
475
+ */
476
+ dispose(): void;
477
+ }
478
+
479
+ /**
480
+ * ToolExecutorService - Handles execution of SQL queries and external tools
481
+ * Extracted from BaseLLM.generateTextResponse for better separation of concerns
482
+ */
483
+
484
+ /**
485
+ * External tool definition
486
+ */
487
+ interface ExternalTool {
488
+ id: string;
489
+ name: string;
490
+ description?: string;
491
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
492
+ toolType?: 'source' | 'direct';
493
+ /** Full untruncated schema for source agent (all columns visible) */
494
+ fullSchema?: string;
495
+ /** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
496
+ schemaTier?: string;
497
+ /** Schema search function for very_large tier — keyword search over entities */
498
+ schemaSearchFn?: (keywords: string[]) => string;
499
+ /** `signal` fires when the user hits Stop mid-query — passed through to the backend's SourceTool.fn. */
500
+ fn: (input: any, signal?: AbortSignal) => Promise<any>;
501
+ limit?: number;
502
+ outputSchema?: any;
503
+ executionType?: 'immediate' | 'deferred';
504
+ userProvidedData?: any;
505
+ params?: Record<string, any>;
506
+ }
507
+ /**
508
+ * Executed tool tracking info
509
+ */
510
+ interface ExecutedToolInfo {
511
+ id: string;
512
+ name: string;
513
+ params: any;
514
+ result: {
515
+ _totalRecords: number;
516
+ _recordsShown: number;
517
+ _metadata?: any;
518
+ _sampleData: any[];
519
+ /** Bounded summary over the FULL fetched result (complete structure). */
520
+ _summary?: any;
521
+ /** Up to MAIN_AGENT_COMPLETE_ROWS rows — the complete result when small. */
522
+ _mainAgentRows?: any[];
523
+ /**
524
+ * Set when an authorization policy restricted the query before it ran.
525
+ * Read by BOTH agents: the source agent's tool response and the main
526
+ * agent's result block, because the main agent is the one that writes the
527
+ * titles, analysis and method line that must state the restriction.
528
+ */
529
+ _ACCESS_POLICY_APPLIED?: string;
530
+ };
531
+ /**
532
+ * THIS call's rows, at render size — deliberately a sibling of `result`, not a
533
+ * field inside it, because `result` is the object that gets picked apart for
534
+ * prompts (`_sampleData`, `_mainAgentRows`, `_summary`). Never put these in a
535
+ * prompt.
536
+ *
537
+ * Exists because a SourceAgentResult keeps only the LAST query's rows for a
538
+ * whole dispatch (see main-agent's "a follow-up query overwrites result.data"
539
+ * note). A component bound to an EARLIER query therefore rendered the later
540
+ * query's data — confirmed live: a revenue chart and a budget chart both drew
541
+ * budget, because both queries ran through one tool.
542
+ */
543
+ renderRows?: any[];
544
+ outputSchema?: any;
545
+ sourceSchema?: string;
546
+ sourceType?: string;
547
+ }
548
+
549
+ /**
550
+ * Multi-Agent Architecture Types
551
+ *
552
+ * Defines interfaces for the hierarchical agent system:
553
+ * - Main Agent: ONE LLM.streamWithTools() call with source agent tools
554
+ * - Source Agents: independent agents that query individual data sources
555
+ *
556
+ * The main agent sees only source summaries. When it calls a source tool,
557
+ * the SourceAgent runs independently (own LLM, own retries) and returns clean data.
558
+ */
559
+
560
+ /**
561
+ * Per-entity detail: name, row count, and column names.
562
+ * Gives the main agent enough context to route to the right source.
563
+ */
564
+ interface EntityDetail {
565
+ /** Entity name (table, sheet, endpoint) */
566
+ name: string;
567
+ /** Approximate row count */
568
+ rowCount?: number;
569
+ /** Column/field names */
570
+ columns: string[];
571
+ /** Entity-level semantic summary (what the table means) — for main-agent routing. */
572
+ summary?: string;
573
+ }
574
+ /**
575
+ * Representation of a data source for the main agent.
576
+ * Contains entity names WITH column names so the LLM can route accurately.
577
+ */
578
+ interface SourceSummary {
579
+ /** Source ID (matches tool ID prefix) */
580
+ id: string;
581
+ /** Human-readable source name */
582
+ name: string;
583
+ /** Source type: postgres, excel, rest_api, etc. */
584
+ type: string;
585
+ /** Brief description of what data this source contains */
586
+ description: string;
587
+ /** Detailed entity info with column names for routing */
588
+ entityDetails: EntityDetail[];
589
+ /** The tool ID associated with this source */
590
+ toolId: string;
591
+ }
592
+ /**
593
+ * What a source agent returns after querying its data source.
594
+ * The main agent uses this to analyze and compose the final response.
595
+ */
596
+ interface SourceAgentResult {
597
+ /** Source ID */
598
+ sourceId: string;
599
+ /** Source name */
600
+ sourceName: string;
601
+ /** Whether the query succeeded */
602
+ success: boolean;
603
+ /** Result data rows — bounded to MAIN_AGENT_COMPLETE_ROWS (Stage 2: what the LLM
604
+ * sees verbatim in its own prompt). NOT render-sized — do not bind a UI
605
+ * component's dataset to this field; use renderData instead. */
606
+ data: any[];
607
+ /** Result data rows bounded to MAX_ROWS_RENDERED (Stage 3: render-appropriate).
608
+ * This is what already-fetched (Stage 1, <=MAX_ROWS_FETCHED) rows look like
609
+ * before Stage 2 further truncates `data` down for the LLM's own context —
610
+ * use this, not `data`, whenever binding a UI component's dataset. */
611
+ renderData: any[];
612
+ /** Metadata about the query execution */
613
+ metadata: SourceAgentMetadata;
614
+ /** Tool execution info for the last successful query (backward compat) */
615
+ executedTool: ExecutedToolInfo;
616
+ /** All successful tool executions (primary + follow-up queries) */
617
+ allExecutedTools?: ExecutedToolInfo[];
618
+ /** Error message if failed */
619
+ error?: string;
620
+ }
621
+ interface SourceAgentMetadata {
622
+ /** Total rows that matched the query (before limit) */
623
+ totalRowsMatched: number;
624
+ /** Rows actually returned (after limit) */
625
+ rowsReturned: number;
626
+ /** Whether the result was truncated by the row limit */
627
+ isLimited: boolean;
628
+ /** The query/params that were executed */
629
+ queryExecuted?: string;
630
+ /** Execution time in milliseconds */
631
+ executionTimeMs: number;
632
+ }
633
+ /**
634
+ * A pre-built, multi-step UI flow registered with the SDK.
635
+ *
636
+ * When the main agent decides a user's question matches a workflow's whenToUse
637
+ * trigger, it picks the workflow instead of running source agents / generating
638
+ * dashboard components. The LLM extracts the workflow's required props from the
639
+ * prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
640
+ * workflow component directly — no analysis text, no chart generation. The
641
+ * frontend renders the registered workflow component with the LLM-extracted
642
+ * props.
643
+ */
644
+ interface WorkflowDescriptor {
645
+ /** Unique workflow id (used as the LLM tool name) */
646
+ id: string;
647
+ /** Component name on the frontend (matches the registered React component) */
648
+ name: string;
649
+ /** Short human-readable description of what this workflow does */
650
+ description: string;
651
+ /**
652
+ * 1–2 sentence trigger condition. The LLM uses this to decide if the
653
+ * user's prompt matches this workflow. Be specific — e.g.
654
+ * "User wants to *initiate* an inventory transfer (review + submit POs),
655
+ * not just see analysis or charts."
656
+ */
657
+ whenToUse: string;
658
+ /**
659
+ * JSON-schema-style description of the props the workflow needs. Becomes
660
+ * the LLM tool's input_schema, so the model fills these from the prompt.
661
+ * Use the same shape as `params` on direct tools — string descriptors with
662
+ * an optional "(optional)" suffix.
663
+ *
664
+ * Example:
665
+ * ```
666
+ * {
667
+ * selectedStore: 'object — { id, name } of the source branch',
668
+ * minROI: 'number (optional) — only show transfers with ROI ≥ this',
669
+ * }
670
+ * ```
671
+ */
672
+ propsSchema: Record<string, string>;
673
+ /**
674
+ * Optional: static prop defaults merged with LLM-extracted props before
675
+ * the component is returned. Useful for things like the embedded
676
+ * `externalTool` config that the workflow uses to fetch its own data.
677
+ */
678
+ defaultProps?: Record<string, any>;
679
+ }
680
+ /**
681
+ * The workflow selection captured during a routing call.
682
+ * Set on AgentResponse when the LLM picks a workflow tool.
683
+ */
684
+ interface SelectedWorkflow {
685
+ /** Component name (matches WorkflowDescriptor.name) */
686
+ name: string;
687
+ /** Props extracted from the prompt + merged with workflow.defaultProps */
688
+ props: Record<string, any>;
689
+ }
690
+ /**
691
+ * Set when this turn applies a user-directed edit to an existing script instead
692
+ * of authoring a new one. MainAgent keeps the SAME harness (tools, loop,
693
+ * write_script/execute_script verification) and swaps only the system prompt —
694
+ * `agent-main-edit` instead of `agent-main`.
695
+ *
696
+ * The two framings contradict each other on whether to query a source first, so
697
+ * they must never be resident in one rendered prompt.
698
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § D3.
699
+ */
700
+ interface EditContext {
701
+ /** Recipe being edited — the shadow draft records it as parentId. */
702
+ recipeId: string;
703
+ parentName: string;
704
+ parentBody: string;
705
+ /** Self-contained restatement of the change (from the matcher). */
706
+ instruction: string;
707
+ /** Columns the last run returned — grounds the edit without a re-query. */
708
+ lastResultColumns?: string[];
709
+ /** Rendered parameter list of the parent, for the prompt. */
710
+ parentParams?: string;
711
+ }
712
+ /**
713
+ * The complete response from the multi-agent system.
714
+ * Contains everything needed for text display + component generation.
715
+ */
716
+ interface AgentResponse {
717
+ /** Generated text response (analysis of the data) */
718
+ text: string;
719
+ /**
720
+ * Program-generated narrative when the script exported getAnalysis. `text`
721
+ * already carries `analysis.analysis`; this also exposes `summary`, which
722
+ * the markdown block binds to instead of being an LLM summary of the prose.
723
+ */
724
+ analysis?: AnalysisOutput;
725
+ /** All executed tools across all source agents (for component generation) */
726
+ executedTools: ExecutedToolInfo[];
727
+ /** Individual results from each source agent */
728
+ sourceResults: SourceAgentResult[];
729
+ /**
730
+ * Populated when MainAgent wrote AND successfully executed a script during its turn.
731
+ * Caller (agent-user-response.ts) persists it via ScriptStore.save().
732
+ * Absent when MainAgent didn't write one (trivial question / all attempts failed).
733
+ */
734
+ savedScript?: AgentWrittenScript;
735
+ /** Failed execute_script tool_result texts this turn, in order — see RunTrace.script.failedAttempts. */
736
+ failedScriptAttempts?: string[];
737
+ /**
738
+ * Set when the LLM routed the question to a registered workflow component.
739
+ * When present, the upstream caller should skip component generation and
740
+ * return this workflow as the response.
741
+ */
742
+ workflow?: SelectedWorkflow;
743
+ /**
744
+ * Validated component specs the agent authored via `write_components`.
745
+ * When present the caller assembles the dashboard from these instead of
746
+ * running the component-generation LLM. Absent when the agent didn't call
747
+ * the tool — the caller then falls back to `generateScriptComponents`.
748
+ * See backend/docs/COMPONENT-GENERATION-V2.md §2.2.
749
+ */
750
+ componentSpecs?: ScriptComponentSpec[];
751
+ /** Layout title/description from the same `write_components` call. */
752
+ componentLayout?: {
753
+ title: string;
754
+ description?: string;
755
+ };
756
+ }
757
+ /**
758
+ * A script MainAgent authored + verified during its turn. Shape aligns with
759
+ * what ScriptStore.save() needs — minus store-assigned fields (id, timestamps, counts).
760
+ */
761
+ interface AgentWrittenScript {
762
+ /**
763
+ * `ScriptRecipe.id` of the draft that was authored + verified during this turn.
764
+ * The caller passes this to `ScriptStore.promoteToVerified(recipeId, …)` to
765
+ * flip the draft to verified status and (when possible) drop the turn-suffix
766
+ * from its filename.
767
+ */
768
+ recipeId: string;
769
+ name: string;
770
+ intentDescription: string;
771
+ tags: string[];
772
+ parameters: Array<{
773
+ name: string;
774
+ type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
775
+ required: boolean;
776
+ default?: any;
777
+ enumValues?: Record<string, string>;
778
+ description: string;
779
+ }>;
780
+ scriptBody: string;
781
+ /** Source IDs referenced by the script (extracted from ctx.query calls) */
782
+ sourceIds: string[];
783
+ /** Tables referenced in the script's SQL (regex-extracted) */
784
+ tables: string[];
785
+ /** Executed queries from the verified run — fed to component generation */
786
+ executedQueries: Array<{
787
+ sourceId: string;
788
+ sourceName: string;
789
+ sql: string;
790
+ data: any[];
791
+ count: number;
792
+ totalCount?: number;
793
+ executionTimeMs: number;
794
+ /**
795
+ * True for synthetic entries (ctx.emit datasets, the computed:_final
796
+ * post-JS data). The component generator routes virtual sources through
797
+ * the script_dataset sentinel toolId so the frontend resolves them via
798
+ * queryCache instead of attempting to re-execute SQL.
799
+ */
800
+ virtual?: boolean;
801
+ }>;
802
+ /** The tool_result JSON MainAgent's LLM got back from execute_script — see RunTrace.script.executionResult. */
803
+ executionResult?: string;
804
+ }
805
+ /**
806
+ * Debug trace for a single chat_agent turn — which KB/schema nodes were
807
+ * retrieved and considered, and which script (if any) produced the answer.
808
+ * Persisted separately from the answer itself (fusion-5's
809
+ * `conversation_traces` table, written via `saveTrace`), never sent through
810
+ * `analyticsClient` (data-residency — see design doc §5).
811
+ */
812
+ interface RunTrace {
813
+ version: 1;
814
+ kbNodes: {
815
+ /**
816
+ * Always-on nodes included regardless of the question (getGlobalKnowledgeBase).
817
+ * `content` is the node's full text AS IT WAS at retrieval time — captured so a
818
+ * later edit/delete of the KB node doesn't erase what the LLM actually saw.
819
+ */
820
+ global: Array<{
821
+ kbId: string;
822
+ title: string;
823
+ content?: string;
824
+ }>;
825
+ /** Semantically matched for this specific question (getKnowledgeBase). Same `content` reasoning as above. */
826
+ query: Array<{
827
+ kbId: string;
828
+ title: string;
829
+ similarity?: number;
830
+ content?: string;
831
+ }>;
832
+ };
833
+ schemaNodes: {
834
+ /** MainAgent's cross-source prefilter — which sources were even considered. */
835
+ routing: Array<{
836
+ sourceId: string;
837
+ sourceName?: string;
838
+ similarity: number;
839
+ }>;
840
+ /** SourceAgent-scope per-source table resolution (MainAgent.preResolveSchema). */
841
+ preResolve: Array<{
842
+ sourceId: string;
843
+ table?: string;
844
+ description?: string;
845
+ similarity: number;
846
+ }>;
847
+ /**
848
+ * The exact {{SOURCE_SUMMARIES}} text injected into MainAgent's system prompt
849
+ * (agent-prompt-builder.ts's formatSummariesForPrompt output) — every
850
+ * registered source's catalog entry, not retrieval-specific, captured once per
851
+ * turn. This is what the main agent actually saw when deciding which source(s)
852
+ * to call.
853
+ */
854
+ mainAgentCatalog?: string;
855
+ /**
856
+ * One entry per SourceAgent dispatch (a source called twice in one turn gets
857
+ * two entries) — the exact {{FULL_SCHEMA}} text injected into that
858
+ * SourceAgent's own system prompt, however it was sourced, plus any
859
+ * search_schema follow-up lookups it made mid-conversation when the schema
860
+ * shown wasn't enough.
861
+ */
862
+ sourceAgentSchemas: Array<{
863
+ sourceId: string;
864
+ sourceName?: string;
865
+ /**
866
+ * The exact intent text this dispatch's own prompt was built from —
867
+ * captured in SourceAgent.buildPrompt, so it ALREADY includes the
868
+ * resolved-entities and resolved-concepts blocks MainAgent appends by
869
+ * code before calling execute() (see buildResolvedEntitiesBlock /
870
+ * buildResolvedConceptsBlock) — not just what the LLM itself wrote.
871
+ */
872
+ intent: string;
873
+ /** How `schemaText` was sourced — see SourceAgent.buildPrompt's fullSchema fallback chain. */
874
+ method: 'preresolved-embedding' | 'tool-full-schema' | 'tool-description' | 'none';
875
+ schemaText: string;
876
+ /** In call order — each search_schema tool call this SourceAgent made, and the exact result text handed back to its own LLM. */
877
+ searchSchemaLookups: Array<{
878
+ keywords: string[];
879
+ result: string;
880
+ }>;
881
+ /** The tool_result text MainAgent's LLM read back for this dispatch (formatResultForMainAgent output). */
882
+ result?: string;
883
+ /**
884
+ * The full resolved-concept bodies this dispatch's intent was built
885
+ * with (the same content already baked into `intent` via
886
+ * buildResolvedConceptsBlock, surfaced here structured/separately so a
887
+ * trace reader doesn't have to parse it back out of the raw text).
888
+ * Stamped AFTER execute() resolves — same timing as `result` above —
889
+ * specifically so its presence here is proof the concepts were part
890
+ * of the prompt actually sent, not just of what MainAgent intended to
891
+ * send before the call happened.
892
+ */
893
+ resolvedConcepts?: Array<{
894
+ name: string;
895
+ kind: string;
896
+ body: string;
897
+ }>;
898
+ /** This dispatch's `SourceToolInput.aggregation` ('raw' | 'pre-aggregate' | 'summary') — decides which AGGREGATION_MODE text this SourceAgent's own prompt got. */
899
+ aggregation?: string;
900
+ /** The exact DATABASE_RULES text this SourceAgent's own prompt got (promptLoader.loadDatabaseRulesForType). */
901
+ databaseRulesText?: string;
902
+ /** The exact ROW_LIMIT_SYNTAX text this SourceAgent's own prompt got. */
903
+ rowLimitSyntaxText?: string;
904
+ /** The exact SCHEMA_SEARCH_INSTRUCTIONS text this SourceAgent's own prompt got — the guidance, not the runtime searchSchemaLookups results above. */
905
+ schemaSearchInstructionsText?: string;
906
+ /** The literal tool definitions (query tool + search_schema tool, when offered) handed to this SourceAgent's own LLM.streamWithTools call. */
907
+ toolsSent?: any[];
908
+ /** This SourceAgent's own LLM.streamWithTools call config. */
909
+ callConfig?: {
910
+ model?: string;
911
+ maxTokens?: number;
912
+ temperature?: number;
913
+ maxIterations?: number;
914
+ };
915
+ /** 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. */
916
+ userAccessContextText?: string;
917
+ }>;
918
+ };
919
+ /**
920
+ * Concept-catalog activity this turn (see main-agent.ts's loadConceptCatalog /
921
+ * loadConceptInvariants / RESOLVE_CONCEPTS_TOOL_DEF). Parallel to
922
+ * `entityResolution` above. Absent/empty for a project with no concepts
923
+ * collection registered.
924
+ */
925
+ concepts: {
926
+ /** The exact {{CONCEPT_CATALOG}} text injected into MainAgent's system prompt (names + aliases only — bodies come back via resolve_concepts). */
927
+ catalogText?: string;
928
+ /** 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. */
929
+ invariantsText?: string;
930
+ /** 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. */
931
+ calls: Array<{
932
+ via: 'resolve_concepts' | 'resolve_entities' | 'dashboard-agent';
933
+ asked?: string[];
934
+ implied?: string[];
935
+ returned?: Array<{
936
+ kind: string;
937
+ name: string;
938
+ returns?: any;
939
+ definition: string;
940
+ viaRequires?: boolean;
941
+ }>;
942
+ viaFloor?: string[];
943
+ corrected?: Array<{
944
+ asked: string;
945
+ matched: string;
946
+ }>;
947
+ unmatched?: string[];
948
+ suggestions?: string[];
949
+ error?: string;
950
+ note?: string;
951
+ }>;
952
+ };
953
+ /** The script that produced this answer, if any. Null for a general (no-tool) answer. */
954
+ script: {
955
+ /** True when an existing recipe was replayed unchanged (ScriptMatcher tier='high'). */
956
+ reused: boolean;
957
+ recipeId?: string | null;
958
+ body?: string | null;
959
+ /** Set when reused — the matcher's reasoning for picking this recipe. */
960
+ reasoning?: string | null;
961
+ /** The winning execute_script tool_result text. Only set when reused=false — a replay never re-runs execute_script. Failed attempts aren't kept. */
962
+ executionResult?: string | null;
963
+ /** Failed execute_script tool_result texts this turn, in order (before the winning one, if any). */
964
+ failedAttempts?: string[];
965
+ } | null;
966
+ /**
967
+ * Everything ScriptMatcher.match() built and sent to its one LLM call this
968
+ * turn — Step 2 of the request flow, immediately after Step 1's exact-match
969
+ * check misses. Captured even when short-circuited before any LLM call, or
970
+ * when the call itself errored, so "why didn't this reuse a script" can
971
+ * always be answered from the trace alone, not just the outcome in `script`.
972
+ * See backend/docs/user-prompt-req-flow/SCRIPT-MATCH-IMPROVEMENTS.md.
973
+ */
974
+ scriptMatcher: {
975
+ /**
976
+ * Exactly what went INTO the one LLM call — every placeholder value
977
+ * substituted into `.prompts/script-match/system.md`, plus the routing
978
+ * facts (isExplicitEdit, the two counts) that aren't literal prompt text
979
+ * but explain WHY the catalog/active-script blocks look the way they do.
980
+ */
981
+ sent: {
982
+ /** Whether the raw prompt carried the explicit "edit :" prefix (see parseEditPrefix). */
983
+ isExplicitEdit: boolean;
984
+ /** The prefix-stripped question actually shown to the LLM (the USER_PROMPT placeholder). */
985
+ userPrompt: string;
986
+ /** The Edit Signal text handed to the LLM this turn (CONFIRMED/NOT CONFIRMED wording). */
987
+ editSignal: string;
988
+ /** The rendered "Scripts From Your Past Questions" catalog text (SCRIPT_CATALOG placeholder). */
989
+ scriptCatalog: string;
990
+ /** Distinct scripts actually in scriptCatalog, after health-filtering and the MAX_CATALOG_RECIPES cap. */
991
+ catalogRecipeCount: number;
992
+ /** The rendered "EDITABLE SCRIPTS" block text (ACTIVE_SCRIPT placeholder) — '' when the thread has no active bindings. */
993
+ activeScript: string;
994
+ /** Active bindings offered as edit candidates this turn. */
995
+ activeBindingCount: number;
996
+ /** This call's LLM.stream config. */
997
+ model?: string;
998
+ maxTokens?: number;
999
+ temperature?: number;
1000
+ };
1001
+ /**
1002
+ * Everything that came back OUT — the LLM's raw answer plus what the
1003
+ * runtime decided to do with it. `tier` here is the FINAL tier after
1004
+ * every coercion (near→none, the edit-prefix gate, candidate checks) —
1005
+ * it can legitimately differ from `rawResponse.tier`.
1006
+ */
1007
+ received: {
1008
+ /** False when short-circuited before any LLM call (no catalog match AND no active bindings) — `rawResponse`/`tier` below don't apply. */
1009
+ calledLLM: boolean;
1010
+ /** The raw JSON the LLM returned, when calledLLM is true and the call didn't throw. */
1011
+ rawResponse?: any;
1012
+ /** Set when calledLLM is true and the call threw, or the response named an unknown script id. */
1013
+ error?: string;
1014
+ /** Final tier after ALL coercions. Null when short-circuited, errored, or the call/coercions landed on no match. */
1015
+ tier: MatchTier | null;
1016
+ };
1017
+ } | null;
1018
+ /**
1019
+ * `resolve_entities` tool activity this turn (see main-agent.ts's
1020
+ * RESOLVE_ENTITIES_TOOL_DEF / handleResolveEntities) — names/identifiers the
1021
+ * user mentioned, resolved to database ids before any SQL was written.
1022
+ * Absent/empty entirely for a project with no entity-search collection
1023
+ * registered, or a turn that named nothing.
1024
+ */
1025
+ entityResolution: {
1026
+ /**
1027
+ * The entity-type catalog text injected into MainAgent's system prompt
1028
+ * (loadEntityCatalog's output) — what let the LLM name a concept instead
1029
+ * of guessing the project's vocabulary. Captured once per turn.
1030
+ */
1031
+ catalogText?: string;
1032
+ /**
1033
+ * One entry per `resolve_entities` tool call this turn (a turn can call it
1034
+ * more than once) — the FULL raw response from the entity-search
1035
+ * collection, not just the trimmed {mention,entityType,instanceId,
1036
+ * displayName} MainAgent keeps for itself to build the dispatch block.
1037
+ * `score`/`ambiguous`/`alternatives` only exist here, nowhere else.
1038
+ */
1039
+ calls: Array<{
1040
+ mentions: Array<{
1041
+ text: string;
1042
+ entityType?: string;
1043
+ }>;
1044
+ entityTypes: string[];
1045
+ resolved: Array<{
1046
+ mention: string;
1047
+ entityType: string;
1048
+ instanceId: string;
1049
+ displayName: string;
1050
+ attrs?: Record<string, any>;
1051
+ score?: number;
1052
+ ambiguous?: boolean;
1053
+ alternatives?: Array<{
1054
+ instanceId: string;
1055
+ displayName: string;
1056
+ score: number;
1057
+ }>;
1058
+ }>;
1059
+ unresolved: string[];
1060
+ entityMap: Record<string, any>;
1061
+ unmatchedEntityTypes?: Array<{
1062
+ requested: string;
1063
+ candidates?: string[];
1064
+ }>;
1065
+ /** Set when the collection call itself failed (fails open — see handleResolveEntities). */
1066
+ error?: string;
1067
+ /** Set on an early return (unavailable / nothing named) so the call is still visible in the trace, not indistinguishable from never having run. */
1068
+ note?: string;
1069
+ }>;
1070
+ };
1071
+ /**
1072
+ * The prior-turn conversation context injected into this turn's prompt as
1073
+ * CONVERSATION_HISTORY — exactly what each flow already builds for itself
1074
+ * (chat: thread.getConversationContext(); report/dashboard: their own
1075
+ * equivalents), captured as-is. Every call site sets this unconditionally
1076
+ * (empty string '' when there's no prior context — new thread, or history
1077
+ * trimmed to nothing), so an empty turn is visibly "no history" in the
1078
+ * saved trace rather than a silently missing key. Optional only because
1079
+ * traces saved before this field existed won't have it at all.
1080
+ */
1081
+ conversationHistory?: string;
1082
+ /**
1083
+ * The exact {{USER_ACCESS_CONTEXT}} text injected into MainAgent's system
1084
+ * prompt — the per-user authorization config (sa-api users.config)
1085
+ * rendered by buildUserAccessContext, as-is. Captured once (MainAgent's
1086
+ * prompt is what SourceAgent's identical value is derived from — no need
1087
+ * to duplicate it per source dispatch). Set unconditionally (empty string
1088
+ * '' when there's no config for this user), so "no restrictions" is
1089
+ * visible in the saved trace rather than a silently missing key. Optional
1090
+ * only because traces saved before this field existed won't have it.
1091
+ */
1092
+ userAccessContext?: string;
1093
+ /**
1094
+ * The exact per-user knowledge-base text injected into MainAgent's system
1095
+ * prompt (getUserKnowledgeBase's output, folded into KNOWLEDGE_BASE_CONTEXT
1096
+ * alongside the query-matched half already captured in kbNodes.query).
1097
+ * Captured separately because it's a distinct fetch with no node-level
1098
+ * structure to list, unlike kbNodes.
1099
+ */
1100
+ userKbContext?: string;
1101
+ /** 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. */
1102
+ toolsSent?: any[];
1103
+ /** The exact {{DIRECT_TOOLS}} text injected into MainAgent's system prompt. */
1104
+ directToolsText?: string;
1105
+ /** The exact {{WORKFLOW_COMPONENTS}} text injected into MainAgent's system prompt. */
1106
+ workflowsText?: string;
1107
+ /** The exact {{SCRIPT_BODY_CONTRACT}} text injected into MainAgent's system prompt (promptLoader.loadScriptBodyContract). */
1108
+ scriptBodyContractText?: string;
1109
+ /**
1110
+ * Full edit-mode context as sent to MainAgent this turn — every EditContext
1111
+ * field, not just the instruction already folded into `script.reasoning`.
1112
+ * Null for a non-edit turn.
1113
+ */
1114
+ editContext?: {
1115
+ recipeId?: string;
1116
+ parentName?: string;
1117
+ parentBody?: string;
1118
+ instruction?: string;
1119
+ lastResultColumns?: string[];
1120
+ parentParams?: string;
1121
+ } | null;
1122
+ /**
1123
+ * The fork-mode preamble as actually assembled and prepended to the user
1124
+ * prompt (agent-user-response.ts) — parentBody/gaps/modificationHint as
1125
+ * sent, plus the lineage fields also written to the script store separately
1126
+ * (parentRecipeId/forkDepth/forkReason). Null for a non-fork turn.
1127
+ */
1128
+ forkContext?: {
1129
+ parentBody?: string;
1130
+ gaps?: string;
1131
+ modificationHint?: string;
1132
+ parentRecipeId?: string;
1133
+ forkDepth?: number;
1134
+ forkReason?: string;
1135
+ } | null;
1136
+ /** The write_analysis tool call's analysisBody argument this turn, when called. */
1137
+ writeAnalysisBody?: string;
1138
+ /** The write_components tool call's componentsBody argument this turn, when called. */
1139
+ writeComponentsBody?: string;
1140
+ /**
1141
+ * Component-generation/re-authoring activity this turn — one entry per call
1142
+ * to `authorComponentsProgram` (script-component-generator.ts — the
1143
+ * display-edit path, reauthoring getComponents as a program),
1144
+ * `generateScriptComponents` (the script-replay fallback, spec/analysis-based
1145
+ * generation), or `summarizeToMarkdown` (its own small analysis-summary LLM
1146
+ * call, reached via `assembleComponentsFromSpecs`). A turn can hit more than
1147
+ * one of these across its fallback chain, so this is an array, not a
1148
+ * singleton — same pattern as `concepts.calls`/`entityResolution.calls`.
1149
+ */
1150
+ componentGen: Array<{
1151
+ via: 'authorComponentsProgram' | 'generateScriptComponents' | 'summarizeToMarkdown';
1152
+ /** authorComponentsProgram only: the edit instruction driving the re-author. */
1153
+ instruction?: string;
1154
+ /** authorComponentsProgram only: the component body being revised, before this attempt. */
1155
+ currentBody?: string;
1156
+ /** Dataset shapes/schemas the LLM was shown (both generation paths, different derivation). */
1157
+ datasetShapes?: string;
1158
+ /** The component catalog text/list handed to the LLM. */
1159
+ componentCatalog?: string;
1160
+ /** generateScriptComponents only: source name(s) shown (SOURCE_NAME). */
1161
+ sourceName?: string;
1162
+ /** generateScriptComponents only: row count(s) shown (ROW_COUNT). */
1163
+ rowCount?: string;
1164
+ /** generateScriptComponents only: column descriptions text shown. */
1165
+ columnDescriptions?: string;
1166
+ /** generateScriptComponents/summarizeToMarkdown: the analysis text handed to the LLM. */
1167
+ analysisText?: string;
1168
+ /** This call's LLM config. */
1169
+ callConfig?: {
1170
+ model?: string;
1171
+ maxTokens?: number;
1172
+ temperature?: number;
1173
+ };
1174
+ /** authorComponentsProgram only: one entry per retry attempt — the feedback fed back in and the raw response for that attempt, in order. */
1175
+ attempts?: Array<{
1176
+ feedback?: string;
1177
+ rawResponse?: string;
1178
+ }>;
1179
+ /** The final raw LLM response text for this call (last attempt, for authorComponentsProgram's retry loop; the single response otherwise). */
1180
+ rawResponse?: string;
1181
+ }>;
1182
+ }
1183
+ /**
1184
+ * Configuration for the multi-agent system.
1185
+ * Controls limits, models, and behavior.
1186
+ */
1187
+ interface AgentConfig {
1188
+ /** Max rows shown to the UI preview / inlined per source (default: 10) */
1189
+ maxRowsPerSource: number;
1190
+ /**
1191
+ * Max rows a source query may FETCH from the DB server-side (default: 2000).
1192
+ * Decoupled from what the main agent is shown: the full result is fetched and
1193
+ * summarized (bounded), but only a small/complete slice enters LLM context.
1194
+ * This lets small lookups (benchmark maps) arrive COMPLETE without letting
1195
+ * large results blow up context.
1196
+ */
1197
+ maxRowsFetched: number;
1198
+ /** Model for the main agent (routing + analysis in one LLM call) */
1199
+ mainAgentModel: string;
1200
+ /** Model for source agent query generation */
1201
+ sourceAgentModel: string;
1202
+ /** API key for LLM calls */
1203
+ apiKey?: string;
1204
+ /** Max retry attempts per source agent */
1205
+ maxRetries: number;
1206
+ /** Max tool calling iterations for the main agent loop */
1207
+ maxIterations: number;
1208
+ /** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
1209
+ globalKnowledgeBase?: string;
1210
+ /** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
1211
+ knowledgeBaseContext?: string;
1212
+ /** Per-user authorization config (sa-api users.config), rendered to text — see buildUserAccessContext */
1213
+ userAccessContext?: string;
1214
+ /** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
1215
+ collections?: any;
1216
+ /** Optional project ID for scoping embedding searches */
1217
+ projectId?: string;
1218
+ /**
1219
+ * Optional debug-trace accumulator for this turn (Phase 1, chat_agent only).
1220
+ * When present, MainAgent-scope retrieval call sites (e.g. preResolveSchema)
1221
+ * push their structured results into it. Absent for callers that don't care
1222
+ * about trace capture (e.g. headless flows) — every push site must treat
1223
+ * this as optional and never let a capture failure affect the real answer.
1224
+ */
1225
+ trace?: RunTrace;
1226
+ }
1227
+ /**
1228
+ * Default agent configuration
1229
+ */
1230
+ declare const DEFAULT_AGENT_CONFIG: AgentConfig;
1231
+
4
1232
  /**
5
1233
  * Unified UIBlock structure for database storage
6
- * Used in both bookmarks and user-conversations tables
1234
+ * Used in both bookmarks and user-conversations tables.
1235
+ *
1236
+ * `analysis` always holds whatever real narration exists — the full answer on
1237
+ * success, or whatever was actually streamed before a failure (may be empty).
1238
+ * `error` is a dedicated field, null on success — it can be a plain string OR
1239
+ * a structured object/array (e.g. the agent's raw `errors` list), whatever
1240
+ * shape the failure naturally has; it's never coerced into `analysis`.
7
1241
  */
8
1242
  interface DBUIBlock {
9
1243
  id: string;
10
1244
  component: Record<string, any> | null;
11
1245
  analysis: string | null;
12
1246
  user_prompt: string;
1247
+ error?: unknown | null;
1248
+ /**
1249
+ * The script recipe that produced this answer, when one did. Read back via
1250
+ * `conversation-history.exactMatch` so an edit follow-up still has a target
1251
+ * after a reload (the in-memory thread is gone by then), and indexed so
1252
+ * committing an edit can purge every cached answer bound to the recipe.
1253
+ */
1254
+ scriptBinding?: {
1255
+ recipeId: string;
1256
+ params?: Record<string, any>;
1257
+ name?: string;
1258
+ columns?: string[];
1259
+ };
13
1260
  }
14
1261
 
15
1262
  /**
@@ -160,6 +1407,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
160
1407
  dependencies?: string[] | undefined;
161
1408
  } | undefined;
162
1409
  props?: Record<string, any> | undefined;
1410
+ data?: Record<string, any> | undefined;
163
1411
  render?: any;
164
1412
  states?: Record<string, any> | undefined;
165
1413
  methods?: Record<string, {
@@ -170,7 +1418,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
170
1418
  fn: string;
171
1419
  deps?: string[] | undefined;
172
1420
  }[] | undefined;
173
- data?: Record<string, any> | undefined;
174
1421
  pages?: {
175
1422
  id: string;
176
1423
  name: string;
@@ -192,6 +1439,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
192
1439
  dependencies?: string[] | undefined;
193
1440
  } | undefined;
194
1441
  props?: Record<string, any> | undefined;
1442
+ data?: Record<string, any> | undefined;
195
1443
  render?: any;
196
1444
  states?: Record<string, any> | undefined;
197
1445
  methods?: Record<string, {
@@ -202,7 +1450,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
202
1450
  fn: string;
203
1451
  deps?: string[] | undefined;
204
1452
  }[] | undefined;
205
- data?: Record<string, any> | undefined;
206
1453
  pages?: {
207
1454
  id: string;
208
1455
  name: string;
@@ -228,6 +1475,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
228
1475
  dependencies?: string[] | undefined;
229
1476
  } | undefined;
230
1477
  props?: Record<string, any> | undefined;
1478
+ data?: Record<string, any> | undefined;
231
1479
  render?: any;
232
1480
  states?: Record<string, any> | undefined;
233
1481
  methods?: Record<string, {
@@ -238,7 +1486,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
238
1486
  fn: string;
239
1487
  deps?: string[] | undefined;
240
1488
  }[] | undefined;
241
- data?: Record<string, any> | undefined;
242
1489
  pages?: {
243
1490
  id: string;
244
1491
  name: string;
@@ -264,6 +1511,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
264
1511
  dependencies?: string[] | undefined;
265
1512
  } | undefined;
266
1513
  props?: Record<string, any> | undefined;
1514
+ data?: Record<string, any> | undefined;
267
1515
  render?: any;
268
1516
  states?: Record<string, any> | undefined;
269
1517
  methods?: Record<string, {
@@ -274,7 +1522,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
274
1522
  fn: string;
275
1523
  deps?: string[] | undefined;
276
1524
  }[] | undefined;
277
- data?: Record<string, any> | undefined;
278
1525
  pages?: {
279
1526
  id: string;
280
1527
  name: string;
@@ -355,6 +1602,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
355
1602
  dependencies?: string[] | undefined;
356
1603
  } | undefined;
357
1604
  props?: Record<string, any> | undefined;
1605
+ data?: Record<string, any> | undefined;
358
1606
  render?: any;
359
1607
  states?: Record<string, any> | undefined;
360
1608
  methods?: Record<string, {
@@ -365,7 +1613,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
365
1613
  fn: string;
366
1614
  deps?: string[] | undefined;
367
1615
  }[] | undefined;
368
- data?: Record<string, any> | undefined;
369
1616
  }, {
370
1617
  id: string;
371
1618
  name?: string | undefined;
@@ -379,6 +1626,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
379
1626
  dependencies?: string[] | undefined;
380
1627
  } | undefined;
381
1628
  props?: Record<string, any> | undefined;
1629
+ data?: Record<string, any> | undefined;
382
1630
  render?: any;
383
1631
  states?: Record<string, any> | undefined;
384
1632
  methods?: Record<string, {
@@ -389,7 +1637,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
389
1637
  fn: string;
390
1638
  deps?: string[] | undefined;
391
1639
  }[] | undefined;
392
- data?: Record<string, any> | undefined;
393
1640
  }>;
394
1641
  data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
395
1642
  context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
@@ -407,6 +1654,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
407
1654
  dependencies?: string[] | undefined;
408
1655
  } | undefined;
409
1656
  props?: Record<string, any> | undefined;
1657
+ data?: Record<string, any> | undefined;
410
1658
  render?: any;
411
1659
  states?: Record<string, any> | undefined;
412
1660
  methods?: Record<string, {
@@ -417,7 +1665,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
417
1665
  fn: string;
418
1666
  deps?: string[] | undefined;
419
1667
  }[] | undefined;
420
- data?: Record<string, any> | undefined;
421
1668
  };
422
1669
  data?: Record<string, any> | undefined;
423
1670
  context?: Record<string, any> | undefined;
@@ -435,6 +1682,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
435
1682
  dependencies?: string[] | undefined;
436
1683
  } | undefined;
437
1684
  props?: Record<string, any> | undefined;
1685
+ data?: Record<string, any> | undefined;
438
1686
  render?: any;
439
1687
  states?: Record<string, any> | undefined;
440
1688
  methods?: Record<string, {
@@ -445,7 +1693,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
445
1693
  fn: string;
446
1694
  deps?: string[] | undefined;
447
1695
  }[] | undefined;
448
- data?: Record<string, any> | undefined;
449
1696
  };
450
1697
  data?: Record<string, any> | undefined;
451
1698
  context?: Record<string, any> | undefined;
@@ -634,23 +1881,20 @@ declare const ComponentSchema: z.ZodObject<{
634
1881
  type: z.ZodString;
635
1882
  description: z.ZodString;
636
1883
  props: z.ZodObject<{
637
- query: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>;
1884
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
638
1885
  title: z.ZodOptional<z.ZodString>;
639
1886
  description: z.ZodOptional<z.ZodString>;
640
1887
  config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
641
- actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
642
1888
  }, "passthrough", z.ZodTypeAny, z.objectOutputType<{
643
- query: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>;
1889
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
644
1890
  title: z.ZodOptional<z.ZodString>;
645
1891
  description: z.ZodOptional<z.ZodString>;
646
1892
  config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
647
- actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
648
1893
  }, z.ZodTypeAny, "passthrough">, z.objectInputType<{
649
- query: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>;
1894
+ query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
650
1895
  title: z.ZodOptional<z.ZodString>;
651
1896
  description: z.ZodOptional<z.ZodString>;
652
1897
  config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
653
- actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
654
1898
  }, z.ZodTypeAny, "passthrough">>;
655
1899
  category: z.ZodOptional<z.ZodString>;
656
1900
  keywords: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
@@ -661,10 +1905,9 @@ declare const ComponentSchema: z.ZodObject<{
661
1905
  description: string;
662
1906
  props: {
663
1907
  description?: string | undefined;
664
- query?: string | {} | undefined;
1908
+ query?: string | {} | null | undefined;
665
1909
  title?: string | undefined;
666
1910
  config?: Record<string, unknown> | undefined;
667
- actions?: any[] | undefined;
668
1911
  } & {
669
1912
  [k: string]: unknown;
670
1913
  };
@@ -679,10 +1922,9 @@ declare const ComponentSchema: z.ZodObject<{
679
1922
  description: string;
680
1923
  props: {
681
1924
  description?: string | undefined;
682
- query?: string | {} | undefined;
1925
+ query?: string | {} | null | undefined;
683
1926
  title?: string | undefined;
684
1927
  config?: Record<string, unknown> | undefined;
685
- actions?: any[] | undefined;
686
1928
  } & {
687
1929
  [k: string]: unknown;
688
1930
  };
@@ -741,6 +1983,10 @@ declare const ToolSchema: z.ZodObject<{
741
1983
  id: z.ZodString;
742
1984
  name: z.ZodString;
743
1985
  description: z.ZodString;
1986
+ /** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
1987
+ toolType: z.ZodOptional<z.ZodEnum<["source", "direct"]>>;
1988
+ /** Full untruncated schema for source agent (all columns visible) */
1989
+ fullSchema: z.ZodOptional<z.ZodString>;
744
1990
  params: z.ZodRecord<z.ZodString, z.ZodString>;
745
1991
  fn: z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodAny>;
746
1992
  outputSchema: z.ZodOptional<z.ZodObject<{
@@ -773,12 +2019,22 @@ declare const ToolSchema: z.ZodObject<{
773
2019
  description: string;
774
2020
  }[];
775
2021
  }>>;
2022
+ /** Cache policy. `false` = never cache (live data, write ops). Mirrors HTTP `Cache-Control: no-store`. */
2023
+ cache: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<false>, z.ZodObject<{
2024
+ ttlMs: z.ZodOptional<z.ZodNumber>;
2025
+ }, "strip", z.ZodTypeAny, {
2026
+ ttlMs?: number | undefined;
2027
+ }, {
2028
+ ttlMs?: number | undefined;
2029
+ }>]>>;
776
2030
  }, "strip", z.ZodTypeAny, {
777
2031
  id: string;
778
2032
  params: Record<string, string>;
779
2033
  name: string;
780
2034
  description: string;
781
2035
  fn: (args_0: any, ...args: unknown[]) => any;
2036
+ toolType?: "source" | "direct" | undefined;
2037
+ fullSchema?: string | undefined;
782
2038
  outputSchema?: {
783
2039
  description: string;
784
2040
  fields: {
@@ -787,12 +2043,17 @@ declare const ToolSchema: z.ZodObject<{
787
2043
  description: string;
788
2044
  }[];
789
2045
  } | undefined;
2046
+ cache?: false | {
2047
+ ttlMs?: number | undefined;
2048
+ } | undefined;
790
2049
  }, {
791
2050
  id: string;
792
2051
  params: Record<string, string>;
793
2052
  name: string;
794
2053
  description: string;
795
2054
  fn: (args_0: any, ...args: unknown[]) => any;
2055
+ toolType?: "source" | "direct" | undefined;
2056
+ fullSchema?: string | undefined;
796
2057
  outputSchema?: {
797
2058
  description: string;
798
2059
  fields: {
@@ -801,6 +2062,9 @@ declare const ToolSchema: z.ZodObject<{
801
2062
  description: string;
802
2063
  }[];
803
2064
  } | undefined;
2065
+ cache?: false | {
2066
+ ttlMs?: number | undefined;
2067
+ } | undefined;
804
2068
  }>;
805
2069
  type Tool$1 = z.infer<typeof ToolSchema>;
806
2070
  type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
@@ -831,6 +2095,34 @@ interface DashCompModelConfig {
831
2095
  */
832
2096
  fastModel?: string;
833
2097
  }
2098
+ /**
2099
+ * Everything a replacement answer flow is handed for one question. Deliberately
2100
+ * the same material the built-in flow gets, so a provider is a drop-in and not a
2101
+ * second-class path.
2102
+ */
2103
+ interface AnswerProviderContext {
2104
+ prompt: string;
2105
+ /** The live frontend component catalog. */
2106
+ components: Component[];
2107
+ collections?: any;
2108
+ externalTools?: any[];
2109
+ userId?: string;
2110
+ threadId?: string;
2111
+ /** Per-user authorization config (users.config) — row policies come from here. */
2112
+ userConfig?: any;
2113
+ conversationHistory?: string;
2114
+ /** Stream user-facing prose. Do NOT stream tool/command output through this. */
2115
+ onStream?: (chunk: string) => void;
2116
+ signal?: AbortSignal;
2117
+ }
2118
+ /**
2119
+ * An alternative to the built-in MainAgent/SourceAgent flow.
2120
+ *
2121
+ * Returns the same T_RESPONSE the built-in flow does, so everything downstream —
2122
+ * the UIBlock, streaming, abort, the conversation save, component rendering — is
2123
+ * unchanged and the two flows stay comparable.
2124
+ */
2125
+ type AnswerProvider = (ctx: AnswerProviderContext) => Promise<T_RESPONSE>;
834
2126
  interface SuperatomSDKConfig {
835
2127
  url?: string;
836
2128
  apiKey?: string;
@@ -839,6 +2131,10 @@ interface SuperatomSDKConfig {
839
2131
  bundleDir?: string;
840
2132
  promptsDir?: string;
841
2133
  databaseType?: DatabaseType;
2134
+ /** BCP-47 locale for `fmt` in generated analyses, e.g. 'en-IN', 'en-US'. Defaults to 'en-IN'. */
2135
+ locale?: string;
2136
+ /** ISO-4217 currency for `fmt`, e.g. 'INR', 'USD'. Defaults to 'INR'. */
2137
+ currency?: string;
842
2138
  ANTHROPIC_API_KEY?: string;
843
2139
  GROQ_API_KEY?: string;
844
2140
  GEMINI_API_KEY?: string;
@@ -852,6 +2148,28 @@ interface SuperatomSDKConfig {
852
2148
  * - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
853
2149
  */
854
2150
  modelStrategy?: ModelStrategy;
2151
+ /**
2152
+ * Model for the main agent (routing + analysis).
2153
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
2154
+ * If not set, uses the provider's default model.
2155
+ */
2156
+ mainAgentModel?: string;
2157
+ /**
2158
+ * Model for source agents (per-source query generation).
2159
+ * Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
2160
+ * If not set, uses the provider's default model.
2161
+ */
2162
+ sourceAgentModel?: string;
2163
+ /**
2164
+ * Which flow answers a user question.
2165
+ * 'agents' — the built-in MainAgent + SourceAgent flow (default).
2166
+ * 'custom' — call `answerProvider` instead.
2167
+ * Set 'custom' WITHOUT a provider and the SDK warns and uses 'agents', rather
2168
+ * than failing every question.
2169
+ */
2170
+ answerFlow?: 'agents' | 'custom';
2171
+ /** Required when answerFlow is 'custom'. See AnswerProvider. */
2172
+ answerProvider?: AnswerProvider;
855
2173
  /**
856
2174
  * Separate model configuration for DASH_COMP flow (dashboard component picking)
857
2175
  * If not provided, falls back to provider-based model selection
@@ -870,6 +2188,12 @@ interface SuperatomSDKConfig {
870
2188
  * Default: 5 minutes
871
2189
  */
872
2190
  queryCacheTTL?: number;
2191
+ /**
2192
+ * Dashboard conversation history TTL (Time To Live) in minutes
2193
+ * Per-dashboard conversation histories expire after this duration
2194
+ * Default: 30 minutes
2195
+ */
2196
+ dashboardHistoryTTL?: number;
873
2197
  }
874
2198
 
875
2199
  declare const KbNodesQueryFiltersSchema: z.ZodObject<{
@@ -877,18 +2201,18 @@ declare const KbNodesQueryFiltersSchema: z.ZodObject<{
877
2201
  category: z.ZodOptional<z.ZodString>;
878
2202
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
879
2203
  type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
880
- createdBy: z.ZodOptional<z.ZodNumber>;
2204
+ createdBy: z.ZodOptional<z.ZodString>;
881
2205
  }, "strip", z.ZodTypeAny, {
882
2206
  type?: "query" | "user" | "global" | undefined;
883
2207
  query?: string | undefined;
884
2208
  category?: string | undefined;
885
- createdBy?: number | undefined;
2209
+ createdBy?: string | undefined;
886
2210
  tags?: string[] | undefined;
887
2211
  }, {
888
2212
  type?: "query" | "user" | "global" | undefined;
889
2213
  query?: string | undefined;
890
2214
  category?: string | undefined;
891
- createdBy?: number | undefined;
2215
+ createdBy?: string | undefined;
892
2216
  tags?: string[] | undefined;
893
2217
  }>;
894
2218
  type KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
@@ -901,27 +2225,27 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
901
2225
  category: z.ZodOptional<z.ZodString>;
902
2226
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
903
2227
  type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
904
- createdBy: z.ZodOptional<z.ZodNumber>;
905
- updatedBy: z.ZodOptional<z.ZodNumber>;
906
- userId: z.ZodOptional<z.ZodNumber>;
2228
+ createdBy: z.ZodOptional<z.ZodString>;
2229
+ updatedBy: z.ZodOptional<z.ZodString>;
2230
+ userId: z.ZodOptional<z.ZodString>;
907
2231
  query: z.ZodOptional<z.ZodString>;
908
2232
  filters: z.ZodOptional<z.ZodObject<{
909
2233
  query: z.ZodOptional<z.ZodString>;
910
2234
  category: z.ZodOptional<z.ZodString>;
911
2235
  tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
912
2236
  type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
913
- createdBy: z.ZodOptional<z.ZodNumber>;
2237
+ createdBy: z.ZodOptional<z.ZodString>;
914
2238
  }, "strip", z.ZodTypeAny, {
915
2239
  type?: "query" | "user" | "global" | undefined;
916
2240
  query?: string | undefined;
917
2241
  category?: string | undefined;
918
- createdBy?: number | undefined;
2242
+ createdBy?: string | undefined;
919
2243
  tags?: string[] | undefined;
920
2244
  }, {
921
2245
  type?: "query" | "user" | "global" | undefined;
922
2246
  query?: string | undefined;
923
2247
  category?: string | undefined;
924
- createdBy?: number | undefined;
2248
+ createdBy?: string | undefined;
925
2249
  tags?: string[] | undefined;
926
2250
  }>>;
927
2251
  limit: z.ZodOptional<z.ZodNumber>;
@@ -932,86 +2256,86 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
932
2256
  query?: string | undefined;
933
2257
  title?: string | undefined;
934
2258
  category?: string | undefined;
935
- userId?: number | undefined;
2259
+ userId?: string | undefined;
936
2260
  limit?: number | undefined;
937
2261
  filters?: {
938
2262
  type?: "query" | "user" | "global" | undefined;
939
2263
  query?: string | undefined;
940
2264
  category?: string | undefined;
941
- createdBy?: number | undefined;
2265
+ createdBy?: string | undefined;
942
2266
  tags?: string[] | undefined;
943
2267
  } | undefined;
944
- createdBy?: number | undefined;
945
- updatedBy?: number | undefined;
2268
+ createdBy?: string | undefined;
2269
+ updatedBy?: string | undefined;
2270
+ offset?: number | undefined;
946
2271
  tags?: string[] | undefined;
947
2272
  content?: string | undefined;
948
- offset?: number | undefined;
949
2273
  }, {
950
2274
  id?: number | undefined;
951
2275
  type?: "query" | "user" | "global" | undefined;
952
2276
  query?: string | undefined;
953
2277
  title?: string | undefined;
954
2278
  category?: string | undefined;
955
- userId?: number | undefined;
2279
+ userId?: string | undefined;
956
2280
  limit?: number | undefined;
957
2281
  filters?: {
958
2282
  type?: "query" | "user" | "global" | undefined;
959
2283
  query?: string | undefined;
960
2284
  category?: string | undefined;
961
- createdBy?: number | undefined;
2285
+ createdBy?: string | undefined;
962
2286
  tags?: string[] | undefined;
963
2287
  } | undefined;
964
- createdBy?: number | undefined;
965
- updatedBy?: number | undefined;
2288
+ createdBy?: string | undefined;
2289
+ updatedBy?: string | undefined;
2290
+ offset?: number | undefined;
966
2291
  tags?: string[] | undefined;
967
2292
  content?: string | undefined;
968
- offset?: number | undefined;
969
2293
  }>>;
970
2294
  }, "strip", z.ZodTypeAny, {
971
- operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
2295
+ operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
972
2296
  data?: {
973
2297
  id?: number | undefined;
974
2298
  type?: "query" | "user" | "global" | undefined;
975
2299
  query?: string | undefined;
976
2300
  title?: string | undefined;
977
2301
  category?: string | undefined;
978
- userId?: number | undefined;
2302
+ userId?: string | undefined;
979
2303
  limit?: number | undefined;
980
2304
  filters?: {
981
2305
  type?: "query" | "user" | "global" | undefined;
982
2306
  query?: string | undefined;
983
2307
  category?: string | undefined;
984
- createdBy?: number | undefined;
2308
+ createdBy?: string | undefined;
985
2309
  tags?: string[] | undefined;
986
2310
  } | undefined;
987
- createdBy?: number | undefined;
988
- updatedBy?: number | undefined;
2311
+ createdBy?: string | undefined;
2312
+ updatedBy?: string | undefined;
2313
+ offset?: number | undefined;
989
2314
  tags?: string[] | undefined;
990
2315
  content?: string | undefined;
991
- offset?: number | undefined;
992
2316
  } | undefined;
993
2317
  }, {
994
- operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
2318
+ operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
995
2319
  data?: {
996
2320
  id?: number | undefined;
997
2321
  type?: "query" | "user" | "global" | undefined;
998
2322
  query?: string | undefined;
999
2323
  title?: string | undefined;
1000
2324
  category?: string | undefined;
1001
- userId?: number | undefined;
2325
+ userId?: string | undefined;
1002
2326
  limit?: number | undefined;
1003
2327
  filters?: {
1004
2328
  type?: "query" | "user" | "global" | undefined;
1005
2329
  query?: string | undefined;
1006
2330
  category?: string | undefined;
1007
- createdBy?: number | undefined;
2331
+ createdBy?: string | undefined;
1008
2332
  tags?: string[] | undefined;
1009
2333
  } | undefined;
1010
- createdBy?: number | undefined;
1011
- updatedBy?: number | undefined;
2334
+ createdBy?: string | undefined;
2335
+ updatedBy?: string | undefined;
2336
+ offset?: number | undefined;
1012
2337
  tags?: string[] | undefined;
1013
2338
  content?: string | undefined;
1014
- offset?: number | undefined;
1015
2339
  } | undefined;
1016
2340
  }>;
1017
2341
  type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
@@ -1280,19 +2604,769 @@ declare class ReportManager {
1280
2604
  getReportCount(): number;
1281
2605
  }
1282
2606
 
1283
- type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
1284
- interface LLMMessages {
1285
- sys: SystemPrompt;
1286
- user: string;
1287
- prefill?: string;
2607
+ /**
2608
+ * ScriptRecipeStore — injected metadata backend for the script flow.
2609
+ *
2610
+ * The SDK is standalone (no DB dependency). The backend implements this
2611
+ * interface over Postgres (full-text search + atomic counters) and injects it
2612
+ * via `collections['script-recipes']`, exactly like `collections['source-embeddings']`.
2613
+ * `ScriptStore` consumes it for all METADATA operations while keeping the
2614
+ * executable body on disk as scripts-store/<fileBase>.ts.
2615
+ *
2616
+ * All metadata rows are plain JSON (no scriptBody — that lives on disk).
2617
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md (#1, #3, #7).
2618
+ */
2619
+
2620
+ /** One recipe's metadata as stored in Postgres (mirrors the script_recipes table). */
2621
+ interface ScriptRecipeMetaRow {
2622
+ id: string;
2623
+ projectId?: string | null;
2624
+ version: number;
2625
+ name: string;
2626
+ intentDescription: string;
2627
+ tags: string[] | null;
2628
+ createdFrom: string | null;
2629
+ sourceIds: string[] | null;
2630
+ tables: string[] | null;
2631
+ parameters: ScriptParameter[] | null;
2632
+ components?: ScriptComponentSpec[] | null;
2633
+ displayPreference?: ScriptDisplayPreference | null;
2634
+ fileBase: string;
2635
+ bodyHash?: string | null;
2636
+ successCount: number;
2637
+ failureCount: number;
2638
+ lastUsed: string | null;
2639
+ parentId?: string | null;
2640
+ forkDepth?: number | null;
2641
+ forkReason?: string | null;
2642
+ status: 'draft' | 'verified' | string;
2643
+ turnId?: string | null;
2644
+ editedBy?: string | null;
2645
+ editedFrom?: string | null;
2646
+ history?: ScriptVersionRecord[] | null;
2647
+ lastError?: {
2648
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2649
+ message: string;
2650
+ at: string;
2651
+ attempt: number;
2652
+ } | null;
2653
+ createdAt?: string | null;
2654
+ updatedAt?: string | null;
1288
2655
  }
1289
- interface LLMOptions {
1290
- model?: string;
2656
+ interface ScriptRecipeStore {
2657
+ /** FTS shortlist of healthy verified recipes for the matcher (metadata only). */
2658
+ search(params: {
2659
+ prompt: string;
2660
+ projectId?: string;
2661
+ limit?: number;
2662
+ }): Promise<ScriptRecipeMetaRow[]>;
2663
+ /** Fetch one recipe by id (any status). */
2664
+ getById(id: string): Promise<ScriptRecipeMetaRow | null>;
2665
+ /** Count healthy verified recipes (drives the "any scripts?" gate). */
2666
+ count(params?: {
2667
+ projectId?: string;
2668
+ }): Promise<number>;
2669
+ /** Insert or update a recipe row (keyed by id). */
2670
+ upsert(row: ScriptRecipeMetaRow): Promise<void>;
2671
+ /** Atomically bump counters / last-used. */
2672
+ updateStats(id: string, patch: {
2673
+ successDelta?: number;
2674
+ failureDelta?: number;
2675
+ lastUsed?: string;
2676
+ }): Promise<void>;
2677
+ /** Flip a draft to verified, applying provenance + optional fork lineage. */
2678
+ promote(id: string, patch: {
2679
+ sourceIds: string[];
2680
+ tables: string[];
2681
+ fileBase?: string;
2682
+ parentId?: string;
2683
+ forkDepth?: number;
2684
+ forkReason?: string;
2685
+ components?: ScriptComponentSpec[];
2686
+ }): Promise<ScriptRecipeMetaRow | null>;
2687
+ /**
2688
+ * Commit a verified edit onto an EXISTING recipe: bump `version`, replace the
2689
+ * body-bearing metadata, append a history record, reset health counters, and
2690
+ * clear the component specs (they were validated against the old shape).
2691
+ * Returns the updated row, or null when the target is gone.
2692
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5.
2693
+ */
2694
+ commitEdit?(id: string, patch: {
2695
+ name?: string;
2696
+ intentDescription?: string;
2697
+ tags?: string[];
2698
+ parameters?: ScriptParameter[];
2699
+ bodyHash: string;
2700
+ /** New on-disk stem when the edit renamed the script; omitted otherwise. */
2701
+ fileBase?: string;
2702
+ sourceIds?: string[];
2703
+ tables?: string[];
2704
+ editedBy?: string;
2705
+ editedFrom?: string;
2706
+ historyEntry: {
2707
+ version: number;
2708
+ at: string;
2709
+ by?: string;
2710
+ instruction?: string;
2711
+ changeSummary?: string;
2712
+ bodyHash?: string;
2713
+ };
2714
+ }): Promise<ScriptRecipeMetaRow | null>;
2715
+ /** Stamp a draft's last execution error. */
2716
+ recordDraftError(id: string, err: {
2717
+ phase: string;
2718
+ message: string;
2719
+ attempt: number;
2720
+ at: string;
2721
+ }): Promise<void>;
2722
+ /** Delete a recipe row (body file removed separately). */
2723
+ remove(id: string): Promise<void>;
2724
+ /** True if `fileBase` is taken by a different recipe in this project. */
2725
+ fileBaseTaken(fileBase: string, excludeId: string, projectId?: string): Promise<boolean>;
2726
+ }
2727
+ /** Pull the injected store off the collections bag (or null if not wired). */
2728
+ declare function resolveScriptRecipeStore(collections: any): ScriptRecipeStore | null;
2729
+
2730
+ /**
2731
+ * ScriptStore — Postgres metadata + on-disk body for script recipes.
2732
+ *
2733
+ * Split of responsibilities:
2734
+ * - METADATA → injected `ScriptRecipeStore` (Postgres FTS + atomic counters),
2735
+ * resolved from `collections['script-recipes']`.
2736
+ * - BODY → scripts-store/<fileBase>.ts, editable in your IDE. Written
2737
+ * atomically (temp + rename); `bodyHash` (sha256) detects edits.
2738
+ *
2739
+ * The old "read every file every turn + send the whole catalog to the LLM"
2740
+ * matcher is gone — matching is `store.search(prompt)` (FTS shortlist). The
2741
+ * draft/verified filename dance is gone too: `status` is a DB column and the
2742
+ * file keeps a stable `<fileBase>.ts` name across promotion.
2743
+ *
2744
+ * When no metadata store is injected, the store degrades to a safe no-op
2745
+ * (count 0 → script flow disabled) instead of crashing.
2746
+ *
2747
+ * See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md.
2748
+ */
2749
+
2750
+ interface SaveDraftInput {
2751
+ /** Reuse an existing draft (retry); omit to mint a new one. */
2752
+ recipeId?: string;
2753
+ /** Per-turn unique suffix, stable across retries within the turn. */
2754
+ turnId: string;
2755
+ name: string;
2756
+ intentDescription: string;
2757
+ tags: string[];
2758
+ parameters: ScriptParameter[];
2759
+ scriptBody: string;
2760
+ createdFrom: string;
2761
+ /**
2762
+ * Set when this draft is a SHADOW of an existing recipe being edited. The
2763
+ * draft is verified independently and merged back onto the parent via
2764
+ * `commitEdit`, so the working script is never clobbered by an edit that
2765
+ * turns out not to run. See backend/docs/SCRIPT-EDIT-DESIGN.md § D5.
2766
+ */
2767
+ parentId?: string;
2768
+ }
2769
+ interface PromoteToVerifiedInput {
2770
+ sourceIds: string[];
2771
+ tables: string[];
2772
+ parentId?: string;
2773
+ forkDepth?: number;
2774
+ forkReason?: string;
2775
+ components?: ScriptComponentSpec[];
2776
+ }
2777
+ interface ScriptStoreOptions {
2778
+ /** Explicit metadata store, or resolved from `collections['script-recipes']`. */
2779
+ store?: ScriptRecipeStore | null;
2780
+ collections?: any;
2781
+ /** Body directory (defaults to <cwd>/scripts-store). */
2782
+ baseDir?: string;
2783
+ /** Project scope stamped on every row. */
2784
+ projectId?: string;
2785
+ }
2786
+ /**
2787
+ * Fingerprint of everything that decides what `getData` PRODUCES.
2788
+ *
2789
+ * A recipe holds three programs in one file — getData, getAnalysis,
2790
+ * getComponents — but only getData costs a source query, and only getData's
2791
+ * output can invalidate a verified run. Editing the narrative or a chart title
2792
+ * cannot change a single row, yet a whole-body comparison says it did, because
2793
+ * `write_script` resubmits the entire file. That is what made a cosmetic edit
2794
+ * indistinguishable from a SQL change and cost a scarce execute attempt.
2795
+ *
2796
+ * Parameters are part of the fingerprint, not an afterthought: `execute_script`
2797
+ * runs with `{}`, so the DEFAULTS are the values getData actually sees. Same
2798
+ * getData text with a changed default is a genuinely different result, and
2799
+ * hashing the body alone would have called it unchanged.
2800
+ *
2801
+ * Deliberately conservative — trimmed, not whitespace-collapsed. The two ways
2802
+ * to be wrong are NOT symmetric: a false "unchanged" reuses a stale result and
2803
+ * reports wrong numbers, while a false "changed" merely costs an attempt. So it
2804
+ * biases toward detecting change, and a reformat is allowed to look like an edit.
2805
+ */
2806
+ declare function dataFingerprint(scriptBody: string, parameters?: ScriptParameter[]): string;
2807
+ /** Inverse of `stripNamedExport` — pulls the named export block OUT instead of removing it. Null when absent. */
2808
+ declare function extractNamedExport(body: string, fnName: string): string | null;
2809
+ declare function normalizeScriptBody(scriptBody: string): string;
2810
+ declare class ScriptStore {
2811
+ private store;
2812
+ private storeDir;
2813
+ private projectId?;
2814
+ constructor(opts?: ScriptStoreOptions);
2815
+ /** Whether a metadata store is wired (matcher / authoring are gated on this). */
2816
+ hasStore(): boolean;
2817
+ /** Number of healthy verified recipes (gates the script-matching path). */
2818
+ count(): Promise<number>;
2819
+ /**
2820
+ * FTS shortlist for the matcher (metadata only — bodies are loaded lazily by
2821
+ * `get()` once the LLM picks one). Returns verified, healthy recipes ranked
2822
+ * by relevance.
2823
+ */
2824
+ search(prompt: string, limit?: number): Promise<ScriptRecipe[]>;
2825
+ /** Fetch one recipe by id with its body loaded from disk. */
2826
+ get(id: string): Promise<ScriptRecipe | null>;
2827
+ /**
2828
+ * Fetch one recipe by id, pinned to a SPECIFIC past version rather than
2829
+ * whatever is live today. Needed to render a past turn's conversation
2830
+ * history accurately after the script has since been edited — get() alone
2831
+ * always returns the CURRENT body, which may no longer be what that turn
2832
+ * actually ran.
2833
+ *
2834
+ * Returns null (never a silently-wrong version) when the requested version
2835
+ * isn't the current one and its archived body can't be found — e.g. the
2836
+ * archive was cleaned up after the whole recipe was later deleted.
2837
+ */
2838
+ getVersion(id: string, version: number): Promise<ScriptRecipe | null>;
2839
+ /** Create or update a recipe (metadata upsert + body write when changed). */
2840
+ save(recipe: ScriptRecipe): Promise<void>;
2841
+ /**
2842
+ * Persist (or update) a draft. Within a turn, retries that pass the same
2843
+ * `recipeId` overwrite the same row + file; a fresh `recipeId` mints a new
2844
+ * draft. The body is visible at scripts-store/<fileBase>.ts immediately.
2845
+ */
2846
+ saveDraft(input: SaveDraftInput): Promise<ScriptRecipe>;
2847
+ /** Stamp a draft's last execution error (metadata only). */
2848
+ recordDraftError(recipeId: string, err: {
2849
+ phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
2850
+ message: string;
2851
+ attempt: number;
2852
+ }): Promise<void>;
2853
+ /**
2854
+ * Promote a successfully-executed draft into a verified script.
2855
+ * The on-disk body already exists at <fileBase>.ts (written at write_script
2856
+ * time) and keeps its name — only the DB row flips status + provenance.
2857
+ */
2858
+ promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): Promise<ScriptRecipe | null>;
2859
+ /**
2860
+ * Commit a user-directed edit: merge a VERIFIED shadow draft back onto the
2861
+ * recipe it was editing, as version N+1 under the SAME recipe id.
2862
+ *
2863
+ * Keeping the id stable is the point of the whole feature — every cached
2864
+ * conversation, `script_dataset` regeneration descriptor and persisted
2865
+ * component spec already points at it, so the correction applies retroactively
2866
+ * to replays instead of stranding them on the old body.
2867
+ *
2868
+ * Steps (see backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5):
2869
+ * 1. archive the current body as `<fileBase>.v<version>.ts`
2870
+ * 2. write the edited body to the original fileBase (atomic)
2871
+ * 3. version++, copy name/description/params, append a history record
2872
+ * 4. reset health counters — the pre-edit failure history is stale
2873
+ * 5. clear component specs — they were validated against the OLD shape
2874
+ * 6. delete the shadow draft (row + file)
2875
+ *
2876
+ * Returns the updated recipe, or null when the commit could not be applied
2877
+ * (caller should then fall back to treating the draft as a new script).
2878
+ */
2879
+ commitEdit(targetId: string, draft: {
2880
+ recipeId: string;
2881
+ name?: string;
2882
+ intentDescription?: string;
2883
+ tags?: string[];
2884
+ parameters?: ScriptParameter[];
2885
+ scriptBody: string;
2886
+ sourceIds?: string[];
2887
+ tables?: string[];
2888
+ }, meta: {
2889
+ instruction?: string;
2890
+ changeSummary?: string;
2891
+ editedBy?: string;
2892
+ }): Promise<ScriptRecipe | null>;
2893
+ /**
2894
+ * Drop a draft (row + body file). MainAgent calls this at end-of-turn when a
2895
+ * draft was authored but never verified — failed drafts are never matched, so
2896
+ * deleting them immediately avoids unbounded accumulation (#5). No-op if the
2897
+ * recipe isn't a draft (so a promoted/verified script is never removed here).
2898
+ */
2899
+ discardDraft(recipeId: string): Promise<void>;
2900
+ /** Delete a recipe (row + body file). */
2901
+ delete(id: string): Promise<void>;
2902
+ /** Record a successful execution (atomic counter bump). */
2903
+ recordSuccess(id: string): Promise<void>;
2904
+ /** Record a failed execution (atomic counter bump). */
2905
+ recordFailure(id: string): Promise<void>;
2906
+ /** Absolute path to the .ts body for a recipe (used by the runner/MainAgent). */
2907
+ getScriptPath(recipe: ScriptRecipe): string;
2908
+ private removeById;
2909
+ private rowToRecipe;
2910
+ private recipeToRow;
2911
+ /** slug of name, with a short id suffix when the bare slug is already taken. */
2912
+ private computeFileBase;
2913
+ private toSlug;
2914
+ private hash;
2915
+ /**
2916
+ * Attach getComponents to the recipe body. The stored `components` column is
2917
+ * cleared at promotion (see promoteToVerified): once the body computes its own
2918
+ * specs, a stale spec array beside a live program is how the wrong one gets
2919
+ * read later. See backend/docs/COMPONENTS-AS-PROGRAM-DESIGN.md § 4.4.
2920
+ */
2921
+ /**
2922
+ * Body text as it stands now, for reverting an attach that turns out to be
2923
+ * invalid.
2924
+ *
2925
+ * getComponents can only be VALIDATED by running it, and it can only be run
2926
+ * once it is on disk — so attachComponents necessarily writes before anyone
2927
+ * knows whether the body is good. Without a revert, a rejected body stays
2928
+ * attached: promote() then sees the recipe "exports getComponents", clears
2929
+ * the specs the fallback generator produced, and the recipe is verified with
2930
+ * component code that was already rejected. Confirmed live on
2931
+ * "Total Bookings by Branch", which shipped a sourceRef of 'computed:_final'
2932
+ * that validateSpecs had refused.
2933
+ */
2934
+ snapshotBody(recipeId: string): Promise<string | null>;
2935
+ /** Put back a body captured by {@link snapshotBody}. */
2936
+ restoreBody(recipeId: string, body: string): Promise<boolean>;
2937
+ attachComponents(recipeId: string, componentsBody: string): Promise<boolean>;
2938
+ /**
2939
+ * Append (or replace) the `getAnalysis` export on an existing draft body.
2940
+ *
2941
+ * The narrative is authored AFTER execution, so it lands on a file that
2942
+ * already holds a working getData — rewriting the whole body would risk
2943
+ * losing the query that just succeeded. Replaces any earlier getAnalysis so
2944
+ * a retry does not stack duplicate exports.
2945
+ */
2946
+ attachAnalysis(recipeId: string, analysisBody: string): Promise<boolean>;
2947
+ private bodyPath;
2948
+ private readBody;
2949
+ /** Directory holding superseded bodies. Dot-prefixed so IDEs/`ls` hide it. */
2950
+ private get archiveDir();
2951
+ /**
2952
+ * Archive a superseded body as `.versions/<fileBase>.v<n>.ts`.
2953
+ *
2954
+ * Kept out of the main store directory on purpose — see commitEdit step 1.
2955
+ * To roll back: copy the file back over `scripts-store/<fileBase>.ts`.
2956
+ */
2957
+ private writeArchive;
2958
+ /**
2959
+ * Move a recipe's archived versions to a new prefix when its fileBase changes,
2960
+ * so all versions of one recipe stay grouped. Without this, two renames would
2961
+ * scatter a single recipe's history across three prefixes in `.versions/` with
2962
+ * nothing linking them back to the live script.
2963
+ */
2964
+ private renameArchives;
2965
+ /** Atomic body write (temp + rename) so concurrent reads never see a partial file. */
2966
+ private writeBody;
2967
+ private unlinkBody;
2968
+ }
2969
+
2970
+ /**
2971
+ * Main Agent (Orchestrator)
2972
+ *
2973
+ * A single LLM.streamWithTools() call that handles everything:
2974
+ * - Routing: decides which source(s) to query based on summaries
2975
+ * - Querying: calls source tools (each wraps an independent SourceAgent)
2976
+ * - Direct tools: calls pre-built function tools directly with LLM-provided params
2977
+ * - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
2978
+ * - Analysis: generates final text response from the data
2979
+ *
2980
+ * Two tool types:
2981
+ * - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
2982
+ * - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
2983
+ */
2984
+
2985
+ declare class MainAgent {
2986
+ private externalTools;
2987
+ private workflows;
2988
+ private config;
2989
+ private streamBuffer;
2990
+ /**
2991
+ * Optional: when provided, MainAgent exposes the `write_script` /
2992
+ * `execute_script` tools to the LLM and persists drafts to disk via the
2993
+ * store. Headless callers (alert analyzer, metric resolver) omit these to
2994
+ * suppress script authoring entirely — drafts would otherwise leak onto
2995
+ * disk with no caller to promote or clean them up.
2996
+ */
2997
+ private scriptStore;
2998
+ private turnId;
2999
+ private createdFromPrompt;
3000
+ private scriptState;
3001
+ /** Answer-flow component catalog (filtered + projected by the caller). */
3002
+ private componentCatalog;
3003
+ /** Specs accepted by `write_components` this turn; empty until it succeeds. */
3004
+ /**
3005
+ * Entities resolved this turn, appended verbatim to every source dispatch.
3006
+ *
3007
+ * Not left to the model to copy into its intent prose: observed live, the
3008
+ * MainAgent wrote names instead of ids on the first dispatch AND re-spelled
3009
+ * 'F D C LIMITED' as 'FDC Limited', so the source agent fell back to
3010
+ * `PartyName LIKE '%FDC%'` and found 2 of 3 customers. Carrying the ids
3011
+ * structurally makes that impossible rather than instruction-dependent.
3012
+ */
3013
+ private resolvedEntities;
3014
+ /**
3015
+ * Concept bodies resolved this turn (via resolve_entities' embedded concept
3016
+ * lookup or a standalone resolve_concepts call) — retained the same way as
3017
+ * resolvedEntities above, so they can be attached to the SourceAgent dispatch.
3018
+ *
3019
+ * Without this, a concept resolved HERE (MainAgent's own tool loop) never
3020
+ * reaches SourceAgent at all: SourceAgent only gets the natural-language
3021
+ * `intent` MainAgent writes, which is a paraphrase, not the concept's
3022
+ * verbatim, authoritative body. Deduped on name so a mid-turn re-resolve
3023
+ * doesn't repeat an already-attached concept.
3024
+ */
3025
+ private resolvedConcepts;
3026
+ private componentSpecs;
3027
+ private componentLayout;
3028
+ private renderComponentAttempts;
3029
+ /** Same repeated-violation tracking as ScriptState.lastAnalysisViolationTexts, for write_components. */
3030
+ private lastComponentsViolationTexts;
3031
+ /**
3032
+ * Fork mode — set when this turn is adapting a near-matching parent script.
3033
+ * In fork mode there is no legitimate "answer with bare text" outcome: the
3034
+ * only correct first move is a tool call (write_script, or a source tool for
3035
+ * schema discovery). We therefore force tool use on the first LLM iteration
3036
+ * so the model can't end its turn with a bare "I'll adapt…" preamble and zero
3037
+ * tool calls. Never set on the fresh-authoring / general-question path.
3038
+ */
3039
+ private forkMode;
3040
+ /**
3041
+ * Edit mode — set when this turn applies a user-directed change to an
3042
+ * existing script. Swaps the system prompt to `agent-main-edit` and stamps
3043
+ * the shadow draft's parentId. Like fork mode there is no legitimate
3044
+ * "answer with bare text" outcome, so tool use is forced on iteration 1.
3045
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 4.
3046
+ */
3047
+ private editContext;
3048
+ /** The recipe's durable rendering choice — see the constructor. */
3049
+ private displayPreference;
3050
+ /**
3051
+ * Per-turn cancellation signal (user hit "Stop"). Set at the top of
3052
+ * handleQuestion and read by the tool handler, the SourceAgent dispatch, and
3053
+ * the script subprocess so an abort tears down every layer of the turn.
3054
+ */
3055
+ private abortSignal?;
3056
+ constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[], forkMode?: boolean, editContext?: EditContext, componentCatalog?: Component[],
3057
+ /**
3058
+ * The recipe's durable rendering choice, when it has one. A DATA edit
3059
+ * re-authors getComponents from scratch, so without this the user's chart
3060
+ * type is silently dropped whenever anyone changes the SQL.
3061
+ */
3062
+ displayPreference?: {
3063
+ componentTypes: string[];
3064
+ instruction: string;
3065
+ });
3066
+ /** True when the turn is applying a user-directed script edit. */
3067
+ private get editMode();
3068
+ private get scriptingEnabled();
3069
+ /**
3070
+ * Handle a user question using the multi-agent system.
3071
+ *
3072
+ * This is ONE LLM.streamWithTools() call. The LLM:
3073
+ * 1. Sees source summaries + direct tool descriptions in system prompt
3074
+ * 2. Decides which tool(s) to call (routing)
3075
+ * 3. Source tools → SourceAgent runs independently → returns data
3076
+ * 4. Direct tools → fn() called directly with LLM params → returns data
3077
+ * 5. Generates final analysis text
3078
+ */
3079
+ handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, signal?: AbortSignal): Promise<AgentResponse>;
3080
+ /**
3081
+ * Tool definition, with the catalog rendered from the registered `Metadata`
3082
+ * the caller passed in. Generated rather than hand-written so it cannot drift
3083
+ * from what the frontend actually ships.
3084
+ */
3085
+ private buildWriteComponentsToolDef;
3086
+ /**
3087
+ * Validate the agent's component picks against the REAL columns of each bound
3088
+ * dataset. All-or-nothing: any error rejects the whole call and returns the
3089
+ * findings, because a partially-accepted dashboard makes the retry ambiguous.
3090
+ */
3091
+ private validateSpecs;
3092
+ /**
3093
+ * Author the dashboard as a program. Attaches getComponents to the draft, runs
3094
+ * it over the verified rows, then validates the specs it RETURNED — the program
3095
+ * is never trusted because it is a program, exactly as an authored spec is not.
3096
+ */
3097
+ private handleWriteComponents;
3098
+ /**
3099
+ * Restrictions the seam reported while this run's queries executed.
3100
+ *
3101
+ * getData does NOT re-run for write_components/write_analysis, so the child
3102
+ * cannot observe these itself — the parent hands them across, exactly as it
3103
+ * does for `entities`.
3104
+ */
3105
+ private observedPolicies;
3106
+ /**
3107
+ * Author the answer as a program. Runs after execute_script, so the body is
3108
+ * written with the result already known and can react to what it found.
3109
+ *
3110
+ * Rejects a body that types numbers rather than computing them — see
3111
+ * analysis-lint. A hardcoded figure is worse than prose: it freezes into the
3112
+ * recipe and replays unchanged while the data moves underneath it.
3113
+ */
3114
+ private handleWriteAnalysis;
3115
+ private handleWriteScript;
3116
+ private handleExecuteScript;
3117
+ /**
3118
+ * Build the AgentWrittenScript payload the caller will hand to
3119
+ * `ScriptStore.promoteToVerified()`. Only returned when a verified
3120
+ * successful execution is on record.
3121
+ */
3122
+ private buildSavedScript;
3123
+ private normalizeParameterList;
3124
+ /**
3125
+ * Which declared parameter NAMES never actually appear wired into the
3126
+ * script body — checked as plain text, not a real parser, so it only
3127
+ * catches the worst case (completely unreferenced) rather than every
3128
+ * subtler variant (e.g. used for display text while the SQL itself still
3129
+ * hardcodes the value). That worst case is exactly what's been observed:
3130
+ * a parameter declared purely for show, with the actual filter hardcoded.
3131
+ * Accepts `params.name`, `params['name']`/`params["name"]`, and a
3132
+ * destructuring binding (`const { name } = params`) as valid wiring.
3133
+ */
3134
+ private findUnwiredParams;
3135
+ /**
3136
+ * Use the schema embedding collection to pre-select relevant tables for
3137
+ * this source + intent. Returns a formatted schema block if confidence is
3138
+ * high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
3139
+ *
3140
+ * When this returns a block, we can skip the SourceAgent's `search_schema`
3141
+ * loop and reduce iteration budget. When it returns null, the SourceAgent
3142
+ * falls back to the existing LLM-driven keyword search (same as today).
3143
+ */
3144
+ /**
3145
+ * Ids + verbatim names for everything resolved this turn, appended by CODE to
3146
+ * each source dispatch so neither omission nor re-spelling by the model can
3147
+ * lose them. Empty string when nothing was resolved, so intents are untouched
3148
+ * for questions that name no entities.
3149
+ *
3150
+ * Also appends `attrs.scopeSql` when the resolved instance carries one —
3151
+ * same "guaranteed by code" reasoning as the ids/names above, extended to
3152
+ * the one attrs field with a documented, cross-entity-type meaning: a
3153
+ * ready-made SQL predicate an entity's index precomputed (see
3154
+ * ENTITY-SEARCH-DESIGN.md's hierarchy-broadening pattern — branch/region/
3155
+ * state entity types attach it so a lane/route question never needs its
3156
+ * own city-matching join). Confirmed real cost of not doing this: a
3157
+ * branch/state resolved with scopeSql sat unused while the source agent
3158
+ * spent 4 failed exploratory queries rediscovering the exact same
3159
+ * branch-id list by hand (Invalid column name 'StateName'/'CityId'/
3160
+ * 'OrganizationLocationId', in that order, ~144s, before landing on ids
3161
+ * that were sitting in scopeSql from the very first resolve_entities
3162
+ * call). Other attrs (code, counts, etc.) are not dumped here — they are
3163
+ * descriptive, not actionable the way a precomputed predicate is, and
3164
+ * bloating every dispatch with all of them for no clear gain isn't worth
3165
+ * it; scopeSql is the one thing worth this guarantee today.
3166
+ */
3167
+ private buildResolvedEntitiesBlock;
3168
+ /** Dedupe-and-retain helper shared by resolveConceptsForTurn and handleResolveConcepts. */
3169
+ private retainResolvedConcepts;
3170
+ /**
3171
+ * Same purpose as buildResolvedEntitiesBlock, for concept bodies instead of
3172
+ * entity ids — appended to the dispatch intent so SourceAgent's own,
3173
+ * independent LLM call receives the resolved definitions verbatim rather
3174
+ * than only MainAgent's paraphrased intent text.
3175
+ */
3176
+ private buildResolvedConceptsBlock;
3177
+ /** True when the backend registered the entity-search collection. */
3178
+ private get entitySearchEnabled();
3179
+ /** True when the backend registered the concepts collection. */
3180
+ private get conceptsEnabled();
3181
+ /**
3182
+ * Concept names for the system prompt. Names ONLY — the body comes back from
3183
+ * resolve_concepts once the LLM has named one, exactly as with the entity
3184
+ * catalog. Putting bodies here would rebuild the always-on context problem
3185
+ * concepts exist to solve.
3186
+ *
3187
+ * Not cached, for the same reason loadEntityCatalog isn't: unchanged rows
3188
+ * render byte-identical text so the prompt-cache prefix still hits, and a
3189
+ * process cache would only buy a window where a new concept is invisible.
3190
+ */
3191
+ private loadConceptCatalog;
3192
+ /**
3193
+ * The ALWAYS-INJECTED tier: preconditions no question is semantically close
3194
+ * to — date encodings, valid-row filters. These cannot be retrieval-gated.
3195
+ * "What was revenue last quarter?" has no similarity to "dates are DD/MM/YYYY
3196
+ * text", so leaving them to be requested means they are silently dropped and
3197
+ * the answer is confidently wrong rather than visibly missing.
3198
+ *
3199
+ * Bodies ARE included here — unlike the catalog — because there is nothing to
3200
+ * request: being unrequestable is what makes them invariants.
3201
+ *
3202
+ * Also retained into resolvedConcepts (same as an explicit resolve_concepts
3203
+ * call) so these bodies reach SourceAgent's dispatch too — an invariant is
3204
+ * meant to apply everywhere, not just wherever the model happens to ask for
3205
+ * something whose `requires` chain reaches it.
3206
+ */
3207
+ private loadConceptInvariants;
3208
+ /**
3209
+ * Resolve the concepts for a turn, with a SERVER-SIDE FLOOR.
3210
+ *
3211
+ * Pinning a tool guarantees it is called; it does not guarantee the model
3212
+ * fills in the arguments. Observed: a question containing the exact words
3213
+ * "revenue forecast" produced a call with no concepts at all, and the agent
3214
+ * then used an incomplete copy of the formula from the knowledge base — the
3215
+ * resulting query filtered a customer id against a project column and
3216
+ * returned zero rows on every attempt.
3217
+ *
3218
+ * So when the model names nothing, scan the question itself for catalog names
3219
+ * and aliases on word boundaries. Precise (a literal name is evidence, not a
3220
+ * guess) and asymmetric in the safe direction: an unneeded definition costs a
3221
+ * few hundred ignorable tokens, a missing one costs a wrong answer.
3222
+ */
3223
+ /**
3224
+ * Returns the tool-facing fields to spread into the resolve_entities JSON
3225
+ * response, PLUS a `_trace` field with everything the trace needs that the
3226
+ * model does not (asked/viaFloor/unmatched). Callers must pull `_trace` out
3227
+ * before spreading the rest into what the model sees — see handleResolveEntities.
3228
+ */
3229
+ private resolveConceptsForTurn;
3230
+ /**
3231
+ * Never throws: a concept-store outage must degrade to "no definition found"
3232
+ * and leave the agent deriving the formula as it does today, not take the
3233
+ * whole answer down.
3234
+ */
3235
+ private handleResolveConcepts;
3236
+ /**
3237
+ * Compact catalog (type + gloss) for the system prompt. This is what lets the
3238
+ * LLM NAME a concept instead of guessing at our vocabulary — it can infer
3239
+ * that a question is about unpaid money, but not that we call that
3240
+ * `outstanding-balance`. Full `resolution` detail is fetched by the tool.
3241
+ *
3242
+ * Deliberately NOT cached in-process. The token cost is already handled by
3243
+ * prompt caching (the system prompt carries a cache_control breakpoint), and
3244
+ * re-reading a tiny PK-ordered table costs ~nothing. Fetching fresh does not
3245
+ * weaken the prompt cache either: unchanged data renders byte-identical text,
3246
+ * so the prefix still hits. A process cache would only buy a staleness window
3247
+ * in which a newly indexed entity is invisible to the agent.
3248
+ */
3249
+ private loadEntityCatalog;
3250
+ /**
3251
+ * Never throws: a resolver outage must degrade to "nothing resolved" and
3252
+ * leave the agent exactly as it was, not take the whole answer down.
3253
+ */
3254
+ private handleResolveEntities;
3255
+ private preResolveSchema;
3256
+ /**
3257
+ * Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
3258
+ */
3259
+ private handleDirectTool;
3260
+ /**
3261
+ * Build the main agent's system prompt with source summaries, direct tool descriptions,
3262
+ * and workflow component descriptions.
3263
+ */
3264
+ private buildSystemPrompt;
3265
+ /**
3266
+ * Build tool definitions for source tools — summary-only descriptions.
3267
+ * The full schema is inside the SourceAgent which runs independently.
3268
+ */
3269
+ private buildSourceToolDefinitions;
3270
+ /**
3271
+ * Build tool definitions for direct tools — expose their actual params.
3272
+ * These are called directly by the main agent LLM, no SourceAgent.
3273
+ */
3274
+ private buildDirectToolDefinitions;
3275
+ /**
3276
+ * Capture a workflow selection. We do NOT execute anything — the LLM has
3277
+ * already extracted the props it wants the workflow rendered with. We
3278
+ * record the selection (via the capture callback) and return a short
3279
+ * acknowledgement so the LLM ends its turn cleanly without writing
3280
+ * analysis text or calling more tools.
3281
+ */
3282
+ private handleWorkflow;
3283
+ /**
3284
+ * Build LLM tool definitions for workflow components. The workflow's
3285
+ * propsSchema becomes the tool's input_schema so the LLM extracts props
3286
+ * directly from the prompt — same mechanic as direct tools.
3287
+ */
3288
+ private buildWorkflowToolDefinitions;
3289
+ /**
3290
+ * Format a source agent's result as a clean string for the main agent LLM.
3291
+ */
3292
+ private formatResultForMainAgent;
3293
+ /**
3294
+ * Get source summaries (for external inspection/debugging).
3295
+ */
3296
+ getSourceSummaries(): SourceSummary[];
3297
+ }
3298
+
3299
+ interface FmtConfig {
3300
+ /** BCP-47 tag driving grouping and the scale vocabulary, e.g. 'en-IN', 'en-US'. */
3301
+ locale: string;
3302
+ /** ISO-4217 code for money, e.g. 'INR', 'USD'. */
3303
+ currency: string;
3304
+ }
3305
+ declare const DEFAULT_FMT_CONFIG: FmtConfig;
3306
+ interface Fmt {
3307
+ money(v: unknown, decimals?: number): string;
3308
+ num(v: unknown, decimals?: number): string;
3309
+ count(v: unknown, decimals?: number): string;
3310
+ pct(part: unknown, whole: unknown, decimals?: number): string;
3311
+ delta(current: unknown, previous: unknown, decimals?: number): string;
3312
+ date(v: unknown): string;
3313
+ range(from: unknown, to: unknown): string;
3314
+ list(items: unknown[], conjunction?: string): string;
3315
+ }
3316
+ /** Build a `fmt` bound to one locale/currency. */
3317
+ declare function makeFmt(cfg?: Partial<FmtConfig>): Fmt;
3318
+
3319
+ type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
3320
+ interface LLMMessages {
3321
+ sys: SystemPrompt;
3322
+ user: string;
3323
+ prefill?: string;
3324
+ }
3325
+ interface LLMOptions {
3326
+ model?: string;
1291
3327
  maxTokens?: number;
1292
3328
  temperature?: number;
1293
3329
  topP?: number;
1294
3330
  apiKey?: string;
3331
+ baseURL?: string;
1295
3332
  partial?: (chunk: string) => void;
3333
+ /**
3334
+ * Per-request cancellation. When the caller aborts this signal (user hit
3335
+ * "Stop"), the underlying provider request is cancelled and the call throws
3336
+ * a RequestAbortedError. Threaded into the provider `messages.create` request
3337
+ * options and checked between tool-loop iterations. Currently honored on the
3338
+ * Anthropic path (the agent flow's default provider).
3339
+ */
3340
+ signal?: AbortSignal;
3341
+ /**
3342
+ * Forces a tool call on the FIRST iteration of streamWithTools only
3343
+ * (subsequent iterations revert to auto). Used by fork mode to stop the
3344
+ * model from ending its turn with a bare "I'll adapt the script…" preamble
3345
+ * and zero tool calls. `{ type: 'any' }` lets the model pick which tool
3346
+ * (write_script in the common case, a source tool for schema discovery);
3347
+ * `{ type: 'tool', name }` pins a specific tool. Honored on both the
3348
+ * Anthropic path and the OpenAI/OpenRouter path (mapped to OpenAI's
3349
+ * tool_choice: 'required' / a named function).
3350
+ */
3351
+ firstIterationToolChoice?: {
3352
+ type: 'any';
3353
+ } | {
3354
+ type: 'tool';
3355
+ name: string;
3356
+ };
3357
+ /**
3358
+ * Internal — set only by the OpenRouter wrappers when the target is a Claude
3359
+ * model. Tells the OpenAI-wire path to emit Anthropic `cache_control`
3360
+ * breakpoints (OpenRouter forwards them to Anthropic for prompt caching).
3361
+ * Never set for direct OpenAI/Groq calls, so their requests are unchanged.
3362
+ */
3363
+ _openrouterClaudeCaching?: boolean;
3364
+ /**
3365
+ * Internal — OpenRouter provider-routing preferences (forwarded as the
3366
+ * `provider` body field). Set by the OpenRouter wrappers to steer routing to
3367
+ * a fast backend (e.g. {sort:'throughput'}). Never set for direct OpenAI/Groq.
3368
+ */
3369
+ _openrouterProvider?: Record<string, unknown>;
1296
3370
  }
1297
3371
  interface Tool {
1298
3372
  name: string;
@@ -1314,6 +3388,16 @@ declare class LLM {
1314
3388
  * @returns Normalized system prompt for Anthropic API
1315
3389
  */
1316
3390
  private static _normalizeSystemPrompt;
3391
+ /**
3392
+ * Strip unpaired UTF-16 surrogates from every text field of a message set.
3393
+ *
3394
+ * A lone surrogate (from mid-pair string slicing or corrupt source data)
3395
+ * serializes to a bare `\udXXX` escape that strict JSON parsers — including
3396
+ * the one on Anthropic's API — reject with "no low surrogate in string",
3397
+ * failing the whole request. Sanitizing here, at the single boundary every
3398
+ * provider call flows through, guarantees no request can carry one.
3399
+ */
3400
+ private static _sanitizeMessages;
1317
3401
  /**
1318
3402
  * Log cache usage metrics from Anthropic API response
1319
3403
  * Shows cache hits, costs, and savings
@@ -1330,16 +3414,76 @@ declare class LLM {
1330
3414
  * "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
1331
3415
  */
1332
3416
  private static _parseModel;
3417
+ /**
3418
+ * Map an Anthropic model id (e.g. "claude-sonnet-4-5-20250929") to the OpenRouter slug
3419
+ * (e.g. "claude-sonnet-4.5"). OpenRouter slugs drop the date suffix and use dotted versions.
3420
+ */
3421
+ private static _toOpenRouterSlug;
3422
+ /**
3423
+ * Per-provider proxy base URL. Returns `${SUPERATOM_LLM_PROXY_URL}/<provider>`
3424
+ * when our Cloudflare LLM proxy is configured, else undefined (→ talk to the
3425
+ * provider directly, legacy behaviour). An explicit options.baseURL (e.g.
3426
+ * OpenRouter) always wins and is never overridden. See backend/docs/llm-proxy.md.
3427
+ */
3428
+ private static _proxyBaseURL;
3429
+ private static _openrouterOptions;
3430
+ private static _isRetryableProviderError;
3431
+ private static _withOpenrouterRetry;
3432
+ private static _openrouterText;
3433
+ private static _openrouterStream;
3434
+ private static _openrouterStreamWithTools;
3435
+ /**
3436
+ * Build an Anthropic client. Routes through our Cloudflare LLM proxy when
3437
+ * SUPERATOM_LLM_PROXY_URL is set (each client ships a per-client proxy key as
3438
+ * ANTHROPIC_API_KEY and never holds the real key); otherwise talks to
3439
+ * api.anthropic.com directly. See backend/docs/llm-proxy.md.
3440
+ */
3441
+ private static _anthropicClient;
3442
+ /** True when OpenRouter is configured as a fail-open fallback for Claude. */
3443
+ private static _openrouterAvailable;
3444
+ /** Remap an Anthropic model id to the OpenRouter model path for fail-open. */
3445
+ private static _anthropicFallbackModel;
1333
3446
  private static _anthropicText;
1334
3447
  private static _anthropicStream;
1335
3448
  private static _anthropicStreamWithTools;
1336
3449
  private static _groqText;
1337
3450
  private static _groqStream;
3451
+ /**
3452
+ * Gemini request options carrying the proxy base URL, or undefined → talk to
3453
+ * generativelanguage.googleapis.com directly. The Google SDK takes baseUrl as a
3454
+ * per-model request option, not a constructor arg. See backend/docs/llm-proxy.md.
3455
+ */
3456
+ private static _geminiRequestOptions;
1338
3457
  private static _geminiText;
1339
3458
  private static _geminiStream;
3459
+ /**
3460
+ * Recursively strip unsupported JSON Schema properties for Gemini
3461
+ * Gemini doesn't support: additionalProperties, $schema, etc.
3462
+ */
3463
+ private static _cleanSchemaForGemini;
1340
3464
  private static _geminiStreamWithTools;
3465
+ /** True for Anthropic/Claude model ids — gates OpenRouter prompt caching. */
3466
+ private static _isClaudeModel;
3467
+ /**
3468
+ * Build the OpenAI-wire system message. For OpenRouter + Claude
3469
+ * (cacheClaude=true) it emits content parts carrying Anthropic
3470
+ * `cache_control` breakpoints (preserving any the caller set, else marking
3471
+ * the last block), so OpenRouter forwards them to Anthropic for prompt
3472
+ * caching. Otherwise it returns a plain flattened string — unchanged for
3473
+ * direct OpenAI/Groq.
3474
+ */
3475
+ private static _openaiSystemMessage;
3476
+ /**
3477
+ * Split an OpenAI-wire usage object. `prompt_tokens` INCLUDES cached tokens,
3478
+ * so we subtract them out (Anthropic-style: input excludes cache reads) and
3479
+ * report cached separately — this makes calculateCost price cache reads at
3480
+ * the discounted rate and reflects OpenRouter prompt-cache savings in logs.
3481
+ */
3482
+ private static _openaiUsage;
1341
3483
  private static _openaiText;
1342
3484
  private static _openaiStream;
3485
+ /** Map the Anthropic-style firstIterationToolChoice to OpenAI's tool_choice. */
3486
+ private static _openaiToolChoice;
1343
3487
  private static _openaiStreamWithTools;
1344
3488
  /**
1345
3489
  * Parse JSON string, handling markdown code blocks and surrounding text
@@ -1429,19 +3573,9 @@ declare class UILogCollector {
1429
3573
  setUIBlockId(uiBlockId: string): void;
1430
3574
  }
1431
3575
 
1432
- /**
1433
- * Represents an action that can be performed on a UIBlock
1434
- */
1435
- interface Action {
1436
- id: string;
1437
- name: string;
1438
- type: string;
1439
- [key: string]: any;
1440
- }
1441
-
1442
3576
  /**
1443
3577
  * UIBlock represents a single user and assistant message block in a thread
1444
- * Contains user question, component metadata, component data, text response, and available actions
3578
+ * Contains user question, component metadata, component data, and text response
1445
3579
  */
1446
3580
  declare class UIBlock {
1447
3581
  private id;
@@ -1449,18 +3583,23 @@ declare class UIBlock {
1449
3583
  private generatedComponentMetadata;
1450
3584
  private componentData;
1451
3585
  private textResponse;
1452
- private actions;
1453
3586
  private createdAt;
3587
+ /**
3588
+ * Which script recipe produced this answer, when a script did. Read on the
3589
+ * NEXT turn so the user can say "use mode instead" and have the matcher
3590
+ * resolve it to a concrete script (the `edit` tier is unreachable without it).
3591
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3592
+ */
3593
+ private scriptBinding;
1454
3594
  /**
1455
3595
  * Creates a new UIBlock instance
1456
3596
  * @param userQuestion - The user's question or input
1457
3597
  * @param componentData - The component data object
1458
3598
  * @param generatedComponentMetadata - Optional metadata about the generated component
1459
- * @param actions - Optional array of available actions
1460
3599
  * @param id - Optional custom ID, generates UUID if not provided
1461
3600
  * @param textResponse - Optional text response from LLM
1462
3601
  */
1463
- constructor(userQuestion: string, componentData?: Record<string, any>, generatedComponentMetadata?: Record<string, any>, actions?: Action[], id?: string, textResponse?: string | null);
3602
+ constructor(userQuestion: string, componentData?: Record<string, any>, generatedComponentMetadata?: Record<string, any>, id?: string, textResponse?: string | null);
1464
3603
  /**
1465
3604
  * Get the UIBlock ID
1466
3605
  */
@@ -1510,41 +3649,22 @@ declare class UIBlock {
1510
3649
  * Set or update text response
1511
3650
  */
1512
3651
  setTextResponse(textResponse: string | null): void;
3652
+ /** The program-generated half of the answer — see setProgramAnswer. */
3653
+ programAnswer?: string | null;
1513
3654
  /**
1514
- * Get all actions (only if they are resolved, not if fetching)
1515
- */
1516
- getActions(): Action[] | null | Promise<Action[]>;
1517
- /**
1518
- * Get or fetch actions
1519
- * If actions don't exist or are a Promise, calls the generateFn and stores the promise
1520
- * If actions already exist, returns them
1521
- * @param generateFn - Async function to generate actions
1522
- * @returns Promise resolving to Action[]
1523
- */
1524
- getOrFetchActions(generateFn: () => Promise<Action[]>): Promise<Action[]>;
1525
- /**
1526
- * Set or replace all actions
1527
- */
1528
- setActions(actions: Action[]): void;
1529
- /**
1530
- * Add a single action (only if actions are resolved)
1531
- */
1532
- addAction(action: Action): void;
1533
- /**
1534
- * Add multiple actions (only if actions are resolved)
1535
- */
1536
- addActions(actions: Action[]): void;
1537
- /**
1538
- * Remove an action by ID (only if actions are resolved)
3655
+ * Bind this block to the script recipe that produced its answer.
1539
3656
  */
1540
- removeAction(actionId: string): boolean;
3657
+ setScriptBinding(binding: Record<string, any> | null): void;
1541
3658
  /**
1542
- * Clear all actions
3659
+ * The program-generated half of the answer, kept verbatim so a reload can
3660
+ * replace exactly that text without disturbing the streamed narration.
1543
3661
  */
1544
- clearActions(): void;
3662
+ setProgramAnswer(text: string | null): void;
3663
+ getProgramAnswer(): string | null;
1545
3664
  /**
1546
- * Get creation timestamp
3665
+ * The script recipe bound to this block, if any.
1547
3666
  */
3667
+ getScriptBinding(): Record<string, any> | null;
1548
3668
  getCreatedAt(): Date;
1549
3669
  /**
1550
3670
  * Convert UIBlock to JSON-serializable object
@@ -1612,7 +3732,55 @@ declare class Thread {
1612
3732
  * @param currentUIBlockId - ID of current UIBlock to exclude from context (optional)
1613
3733
  * @returns Formatted conversation history string
1614
3734
  */
1615
- getConversationContext(limit?: number, currentUIBlockId?: string): string;
3735
+ /**
3736
+ * The script recipe bound to the most recent completed UIBlock — i.e. the
3737
+ * script behind the answer the user is currently looking at. Drives the
3738
+ * matcher's `edit` tier: without it, "use mode instead" has no target and
3739
+ * falls through to regeneration.
3740
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3741
+ */
3742
+ getActiveScriptBinding(currentUIBlockId?: string): Record<string, any> | null;
3743
+ /**
3744
+ * The recent script-backed answers in this thread, newest first — the
3745
+ * candidate set a user-directed edit can target.
3746
+ *
3747
+ * Returning several rather than only the newest is what lets an instruction
3748
+ * name its own target ("use the mode for the WSP one"). With a single
3749
+ * candidate every edit lands on the most recent script, which silently edits
3750
+ * the wrong recipe whenever the user meant an earlier one.
3751
+ *
3752
+ * Deduped by recipeId (newest occurrence wins) so a long editing session on
3753
+ * one script doesn't crowd out the others. Each entry carries the question
3754
+ * that produced it — without that the candidates are indistinguishable.
3755
+ *
3756
+ * In-memory only: dies with the process. The caller falls back to the
3757
+ * persisted bindings when this comes back empty.
3758
+ * See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
3759
+ */
3760
+ getScriptBindings(limit?: number, currentUIBlockId?: string): Record<string, any>[];
3761
+ /**
3762
+ * @param getScriptBody Resolves a script-backed turn's EXACT script, pinned
3763
+ * to the version that turn actually ran — never today's (possibly
3764
+ * since-edited) live body. Owned by the caller (needs a ScriptStore, which
3765
+ * Thread doesn't hold) — omit it and every turn falls back to the
3766
+ * no-script summary below.
3767
+ * @param fetchRecentFromDb When provided, this is now the SOURCE OF TRUTH
3768
+ * for history instead of this process's in-memory `uiblocks` map — reads
3769
+ * the persisted `user_conversations` rows (DB `response` jsonb shape, see
3770
+ * transformUIBlockForDB in conversation-saver.ts) via the caller's own
3771
+ * `user-conversations.getRecentForContext` collection. Rows come back
3772
+ * newest-first (already excluding status='aborted' — the query itself
3773
+ * filters that, matching what the in-memory path achieved via
3774
+ * thread.removeUIBlock() on abort). Fixes the standing gap where a backend
3775
+ * restart lost every thread's history (ThreadManager has no DB-backed
3776
+ * rehydration) — DB-backed history survives that, and is correct even if
3777
+ * a different process instance saved the row. Omit it and this falls back
3778
+ * to the in-memory map, for any caller not yet updated.
3779
+ */
3780
+ getConversationContext(limit?: number, currentUIBlockId?: string, getScriptBody?: (recipeId: string, version: number) => Promise<string | null>, fetchRecentFromDb?: (limit: number) => Promise<Array<{
3781
+ userprompt?: string;
3782
+ response?: Record<string, any>;
3783
+ }>>): Promise<string>;
1616
3784
  /**
1617
3785
  * Convert Thread to JSON-serializable object
1618
3786
  */
@@ -1621,12 +3789,20 @@ declare class Thread {
1621
3789
 
1622
3790
  /**
1623
3791
  * ThreadManager manages all threads globally
1624
- * Provides methods to create, retrieve, and delete threads
3792
+ * Provides methods to create, retrieve, and delete threads.
3793
+ * Includes automatic cleanup to prevent unbounded memory growth.
1625
3794
  */
1626
3795
  declare class ThreadManager {
1627
3796
  private static instance;
1628
3797
  private threads;
3798
+ private cleanupInterval;
3799
+ private readonly threadTtlMs;
1629
3800
  private constructor();
3801
+ /**
3802
+ * Periodically remove threads older than 7 days.
3803
+ * Runs every hour to avoid frequent iteration over the map.
3804
+ */
3805
+ private startCleanup;
1630
3806
  /**
1631
3807
  * Get singleton instance of ThreadManager
1632
3808
  */
@@ -2025,6 +4201,92 @@ declare function rerankConversationResults<T extends {
2025
4201
  bm25Score: number;
2026
4202
  }>;
2027
4203
 
4204
+ /**
4205
+ * QueryExecutionService - Handles all query execution, validation, and retry logic
4206
+ * Extracted from BaseLLM for better separation of concerns
4207
+ */
4208
+
4209
+ /**
4210
+ * Context for component when requesting query fix
4211
+ */
4212
+ interface ComponentContext {
4213
+ name: string;
4214
+ type: string;
4215
+ title?: string;
4216
+ }
4217
+ /**
4218
+ * Result of query validation
4219
+ */
4220
+ interface QueryValidationResult {
4221
+ component: Component | null;
4222
+ queryKey: string;
4223
+ result: any;
4224
+ validated: boolean;
4225
+ }
4226
+ /**
4227
+ * Result of batch query validation
4228
+ */
4229
+ interface BatchValidationResult {
4230
+ components: Component[];
4231
+ queryResults: Map<string, any>;
4232
+ }
4233
+ /**
4234
+ * Configuration for QueryExecutionService
4235
+ */
4236
+ interface QueryExecutionServiceConfig {
4237
+ defaultLimit: number;
4238
+ getModelForTask: (taskType: 'simple' | 'complex') => string;
4239
+ getApiKey: (apiKey?: string) => string | undefined;
4240
+ providerName: string;
4241
+ }
4242
+ /**
4243
+ * QueryExecutionService handles all query-related operations
4244
+ */
4245
+ declare class QueryExecutionService {
4246
+ private config;
4247
+ constructor(config: QueryExecutionServiceConfig);
4248
+ /**
4249
+ * Get the cache key for a query
4250
+ * This ensures the cache key matches what the frontend will send
4251
+ */
4252
+ getQueryCacheKey(query: any): string;
4253
+ /**
4254
+ * Execute a query against the database
4255
+ * @param query - The SQL query to execute (string or object with sql/values)
4256
+ * @param collections - Collections object containing database execute function
4257
+ * @returns Object with result data and cache key
4258
+ */
4259
+ executeQuery(query: any, collections: any): Promise<{
4260
+ result: any;
4261
+ cacheKey: string;
4262
+ }>;
4263
+ /**
4264
+ * Request the LLM to fix a failed SQL query
4265
+ * @param failedQuery - The query that failed execution
4266
+ * @param errorMessage - The error message from the failed execution
4267
+ * @param componentContext - Context about the component
4268
+ * @param apiKey - Optional API key
4269
+ * @returns Fixed query string
4270
+ */
4271
+ requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
4272
+ /**
4273
+ * Validate a single component's query with retry logic
4274
+ * @param component - The component to validate
4275
+ * @param collections - Collections object containing database execute function
4276
+ * @param apiKey - Optional API key for LLM calls
4277
+ * @returns Validation result with component, query key, and result
4278
+ */
4279
+ validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
4280
+ /**
4281
+ * Validate multiple component queries in parallel
4282
+ * @param components - Array of components with potential queries
4283
+ * @param collections - Collections object containing database execute function
4284
+ * @param apiKey - Optional API key for LLM calls
4285
+ * @returns Object with validated components and query results map
4286
+ */
4287
+ validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
4288
+ }
4289
+
2028
4290
  /**
2029
4291
  * Task types for model selection
2030
4292
  * - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
@@ -2056,6 +4318,7 @@ declare abstract class BaseLLM {
2056
4318
  protected apiKey?: string;
2057
4319
  protected modelStrategy: ModelStrategy;
2058
4320
  protected conversationSimilarityThreshold: number;
4321
+ protected queryService: QueryExecutionService;
2059
4322
  constructor(config?: BaseLLMConfig);
2060
4323
  /**
2061
4324
  * Get the appropriate model based on task type and model strategy
@@ -2111,60 +4374,26 @@ declare abstract class BaseLLM {
2111
4374
  */
2112
4375
  protected containsFormComponent(component: any): boolean;
2113
4376
  /**
2114
- * Get the cache key for a query (the exact sql param that would be sent to execute)
2115
- * This ensures the cache key matches what the frontend will send
2116
- * Used for both caching and internal deduplication
2117
- */
2118
- private getQueryCacheKey;
2119
- /**
2120
- * Execute a query against the database for validation and caching
2121
- * @param query - The SQL query to execute (string or object with sql/values)
2122
- * @param collections - Collections object containing database execute function
2123
- * @returns Object with result data and cache key
2124
- * @throws Error if query execution fails
2125
- */
2126
- private executeQueryForValidation;
2127
- /**
2128
- * Request the LLM to fix a failed SQL query
2129
- * @param failedQuery - The query that failed execution
2130
- * @param errorMessage - The error message from the failed execution
2131
- * @param componentContext - Context about the component (name, type, title)
2132
- * @param apiKey - Optional API key
2133
- * @returns Fixed query string
2134
- */
2135
- private requestQueryFix;
2136
- /**
2137
- * Match components from text response suggestions and generate follow-up questions
4377
+ * Match components from text response suggestions
2138
4378
  * Takes a text response with component suggestions (c1:type format) and matches with available components
2139
- * Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
4379
+ * Also generates title and description based on the analysis
2140
4380
  * All components are placed in a default MultiComponentContainer layout
2141
4381
  * @param analysisContent - The text response containing component suggestions
2142
4382
  * @param components - List of available components
2143
4383
  * @param apiKey - Optional API key
2144
- * @param logCollector - Optional log collector
2145
4384
  * @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
2146
- * @returns Object containing matched components, layout title/description, and follow-up actions
4385
+ * @returns Object containing matched components and layout title/description
2147
4386
  */
2148
- matchComponentsFromAnalysis(analysisContent: string, components: Component[], apiKey?: string, logCollector?: any, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string, userPrompt?: string): Promise<{
4387
+ matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
2149
4388
  components: Component[];
2150
4389
  layoutTitle: string;
2151
4390
  layoutDescription: string;
2152
- actions: Action[];
2153
4391
  }>;
2154
- /**
2155
- * Validate component queries against the database and retry with LLM fixes if they fail
2156
- * @param components - Array of components with potential queries
2157
- * @param collections - Collections object containing database execute function
2158
- * @param apiKey - Optional API key for LLM calls
2159
- * @param logCollector - Optional log collector for logging
2160
- * @returns Object with validated components and a map of query results
2161
- */
2162
- private validateAndRetryComponentQueries;
2163
4392
  /**
2164
4393
  * Classify user question into category and detect external tools needed
2165
4394
  * Determines if question is for data analysis, requires external tools, or needs text response
2166
4395
  */
2167
- classifyQuestionCategory(userPrompt: string, apiKey?: string, logCollector?: any, conversationHistory?: string, externalTools?: any[]): Promise<{
4396
+ classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
2168
4397
  category: 'data_analysis' | 'data_modification' | 'general';
2169
4398
  externalTools: Array<{
2170
4399
  type: string;
@@ -2181,7 +4410,7 @@ declare abstract class BaseLLM {
2181
4410
  * Takes a matched UI block from semantic search and modifies its props to answer the new question
2182
4411
  * Also adapts the cached text response to match the new question
2183
4412
  */
2184
- adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, logCollector?: any, cachedTextResponse?: string): Promise<{
4413
+ adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
2185
4414
  success: boolean;
2186
4415
  adaptedComponent?: Component;
2187
4416
  adaptedTextResponse?: string;
@@ -2197,7 +4426,7 @@ declare abstract class BaseLLM {
2197
4426
  * Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
2198
4427
  * After generating text response, if components are provided, matches suggested components
2199
4428
  */
2200
- 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', userId?: string): Promise<T_RESPONSE>;
4429
+ 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>;
2201
4430
  /**
2202
4431
  * Main orchestration function with semantic search and multi-step classification
2203
4432
  * NEW FLOW (Recommended):
@@ -2206,13 +4435,7 @@ declare abstract class BaseLLM {
2206
4435
  * 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
2207
4436
  * 3. Route appropriately based on category and response mode
2208
4437
  */
2209
- 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>;
2210
- /**
2211
- * Generate next questions that the user might ask based on the original prompt and generated component
2212
- * This helps provide intelligent suggestions for follow-up queries
2213
- * For general/conversational questions without components, pass textResponse instead
2214
- */
2215
- generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, logCollector?: any, conversationHistory?: string, textResponse?: string): Promise<string[]>;
4438
+ 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>;
2216
4439
  }
2217
4440
 
2218
4441
  interface AnthropicLLMConfig extends BaseLLMConfig {
@@ -2272,17 +4495,30 @@ declare class OpenAILLM extends BaseLLM {
2272
4495
  declare const openaiLLM: OpenAILLM;
2273
4496
 
2274
4497
  /**
2275
- * Query Cache - Stores query results with configurable TTL
2276
- * Used to avoid re-executing queries that were already validated
4498
+ * Query Cache — Two mechanisms:
4499
+ *
4500
+ * 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
4501
+ * of recently validated queries. True LRU eviction: reads bubble entries to the back via
4502
+ * delete+re-set so the oldest *unused* entry is evicted, not the oldest *inserted*.
4503
+ *
4504
+ * 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
4505
+ * No server-side storage needed for SQL mappings. The token is decrypted on each request.
4506
+ * This eliminates the unbounded queryIdCache that previously grew forever and caused
4507
+ * memory bloat (hundreds of MBs after thousands of queries).
4508
+ *
4509
+ * Result data can still be cached temporarily via the data cache (mechanism 1).
2277
4510
  */
2278
4511
  declare class QueryCache {
2279
4512
  private cache;
2280
4513
  private ttlMs;
4514
+ private maxCacheSize;
2281
4515
  private cleanupInterval;
4516
+ private readonly algorithm;
4517
+ private encryptionKey;
2282
4518
  constructor();
2283
4519
  /**
2284
4520
  * Set the cache TTL (Time To Live)
2285
- * @param minutes - TTL in minutes (default: 5)
4521
+ * @param minutes - TTL in minutes (default: 10)
2286
4522
  */
2287
4523
  setTTL(minutes: number): void;
2288
4524
  /**
@@ -2290,12 +4526,25 @@ declare class QueryCache {
2290
4526
  */
2291
4527
  getTTL(): number;
2292
4528
  /**
2293
- * Store query result in cache
2294
- * Key is the exact query string (or JSON for parameterized queries)
4529
+ * Which access bucket this call reads and writes.
4530
+ *
4531
+ * `''` means the unrestricted bucket and produces a key identical to the one
4532
+ * used before authorization existed. `null` means do not touch the cache.
4533
+ */
4534
+ private scope;
4535
+ /** The stored key: the scope namespace, then the caller's key. NUL cannot occur in SQL. */
4536
+ private scopedKey;
4537
+ /**
4538
+ * Store query result in data cache.
4539
+ * If the key already exists, it's removed first so the re-insert places it
4540
+ * at the back of the iteration order (LRU). Eviction only fires when adding
4541
+ * a genuinely new key past the size limit.
2295
4542
  */
2296
4543
  set(query: string, data: any): void;
2297
4544
  /**
2298
- * Get cached result if exists and not expired
4545
+ * Get cached result if exists and not expired.
4546
+ * On hit, re-inserts the entry so it moves to the back of the Map's
4547
+ * iteration order — turning FIFO eviction into true LRU.
2299
4548
  */
2300
4549
  get(query: string): any | null;
2301
4550
  /**
@@ -2315,12 +4564,39 @@ declare class QueryCache {
2315
4564
  */
2316
4565
  getStats(): {
2317
4566
  size: number;
4567
+ queryIdCount: number;
2318
4568
  oldestEntryAge: number | null;
2319
4569
  };
2320
4570
  /**
2321
- * Start periodic cleanup of expired entries
4571
+ * Start periodic cleanup of expired data cache entries.
2322
4572
  */
2323
4573
  private startCleanup;
4574
+ /**
4575
+ * Encrypt a payload into a self-contained token.
4576
+ */
4577
+ private encrypt;
4578
+ /**
4579
+ * Decrypt a token back to the original payload.
4580
+ */
4581
+ private decrypt;
4582
+ /**
4583
+ * Store a query by generating an encrypted token as queryId.
4584
+ * The SQL is encrypted INTO the token — nothing stored in memory.
4585
+ * If data is provided, it's cached temporarily in the data cache.
4586
+ */
4587
+ storeQuery(query: any, data?: any): string;
4588
+ /**
4589
+ * Get a stored query by decrypting its token.
4590
+ * Returns the SQL + any cached result data.
4591
+ */
4592
+ getQuery(queryId: string): {
4593
+ query: any;
4594
+ data: any;
4595
+ } | null;
4596
+ /**
4597
+ * Update cached data for a queryId token
4598
+ */
4599
+ setQueryData(queryId: string, data: any): void;
2324
4600
  /**
2325
4601
  * Stop cleanup interval (for graceful shutdown)
2326
4602
  */
@@ -2328,30 +4604,1315 @@ declare class QueryCache {
2328
4604
  }
2329
4605
  declare const queryCache: QueryCache;
2330
4606
 
2331
- declare const SDK_VERSION = "0.0.8";
2332
- type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
2333
- declare class SuperatomSDK {
2334
- private ws;
2335
- private url;
2336
- private apiKey?;
2337
- private projectId;
2338
- private type;
2339
- private bundleDir;
2340
- private messageHandlers;
2341
- private messageTypeHandlers;
2342
- private connected;
2343
- private reconnectAttempts;
2344
- private maxReconnectAttempts;
2345
- private collections;
2346
- private components;
2347
- private tools;
2348
- private anthropicApiKey;
2349
- private groqApiKey;
4607
+ /**
4608
+ * Request context — who is asking, carried to wherever it is needed.
4609
+ *
4610
+ * The data seam (`BaseSource.prepareSql()` in the backend) has to know which
4611
+ * user a query is for, so the SQL rewriter has a policy to inject. Identity
4612
+ * arrives here, in the SDK's message handlers; the seam is several layers and
4613
+ * one package away. This module is the carrier for the paths where the async
4614
+ * chain stays intact.
4615
+ *
4616
+ * Design and the paths where it does NOT reach:
4617
+ * backend/docs/REQUEST-CONTEXT-DESIGN.md
4618
+ *
4619
+ * Two rules the rest of the system depends on:
4620
+ *
4621
+ * 1. **Absence is not `system`.** No context means we do not know who is
4622
+ * asking, which is a different thing from knowing this is a trusted job.
4623
+ * Conflating them turns every call site anyone forgets into an unpoliced
4624
+ * one. Trust has to be written down, by name, via `runAsSystem()`.
4625
+ *
4626
+ * 2. **This is not a security boundary on its own.** It carries whatever it
4627
+ * is given. It is only worth something once the value it carries comes
4628
+ * from a verified identity rather than the request payload — see the
4629
+ * Prerequisite section of SQL-AUTHORIZATION-DESIGN.md.
4630
+ */
4631
+ /**
4632
+ * Who a unit of work is running on behalf of.
4633
+ *
4634
+ * `system` requires a reason because it appears in the audit log and because
4635
+ * an unexplained escalation is indistinguishable from a bug.
4636
+ */
4637
+ type Principal = {
4638
+ kind: 'user';
4639
+ userId: string;
4640
+ orgId?: string;
4641
+ role?: string;
4642
+ } | {
4643
+ kind: 'system';
4644
+ reason: string;
4645
+ };
4646
+ /**
4647
+ * One row restriction, in the shape the rewriter's inject_policies() consumes
4648
+ * directly — no translation layer, deliberately: a mapping step between what an
4649
+ * admin writes and what gets injected is somewhere for the two to drift apart.
4650
+ */
4651
+ interface RowFilter {
4652
+ /** Unqualified matches on table name alone; qualified ("dw.FactSales") must match exactly. */
4653
+ table?: string;
4654
+ column: string;
4655
+ op?: 'in' | 'not_in' | 'eq' | 'ne';
4656
+ values: unknown[];
4657
+ /**
4658
+ * How to SAY this restriction to an end user, e.g. "Hyderabad branch".
4659
+ *
4660
+ * Without it the agent has only the predicate, and pastes
4661
+ * `com_trn_documentstamp.LocationId IN (110)` into the answer — accurate and
4662
+ * meaningless to the person reading it. Only whoever writes the policy knows
4663
+ * that 110 is Hyderabad, so only they can supply this.
4664
+ */
4665
+ label?: string;
4666
+ }
4667
+ /**
4668
+ * What one user may see in one source. `sourceId` is not optional in spirit: a
4669
+ * filter naming a column of one database must never be injected into another's
4670
+ * SQL. Omitting it means "every source", which is only correct for a column that
4671
+ * genuinely exists everywhere.
4672
+ */
4673
+ interface SourcePolicy {
4674
+ sourceId?: string | null;
4675
+ /** Default {@link RowFilter.label} for every filter in this policy that lacks its own. */
4676
+ label?: string;
4677
+ rowFilters?: RowFilter[];
4678
+ /** Gate 3. Empty means no table restriction — see SQL-AUTHORIZATION-DESIGN.md. */
4679
+ readableTables?: string[];
4680
+ }
4681
+ interface RequestContext {
4682
+ principal: Principal;
4683
+ projectId?: string;
4684
+ /**
4685
+ * Access policies resolved ONCE per request, not per query. Empty means
4686
+ * "no restrictions apply". Narrowed to the source being queried at the seam
4687
+ * — see the backend's policy-gate.
4688
+ */
4689
+ policies?: SourcePolicy[];
4690
+ /** Correlates the audit log with a chat turn. */
4691
+ requestId?: string;
4692
+ }
4693
+ /** The context for the current async chain, or `undefined` if none was established. */
4694
+ declare function getRequestContext(): RequestContext | undefined;
4695
+ /**
4696
+ * Like `getRequestContext()`, but throws when there is none.
4697
+ *
4698
+ * For call sites that must not proceed anonymously. Prefer this over
4699
+ * `getRequestContext() ?? somethingPermissive` — the fallback is exactly the
4700
+ * silent bypass this module exists to prevent.
4701
+ */
4702
+ declare function requireRequestContext(what?: string): RequestContext;
4703
+ declare class MissingRequestContextError extends Error {
4704
+ constructor(message: string);
4705
+ }
4706
+ /** Run `fn` with `ctx` visible to everything it awaits. */
4707
+ declare function runWithContext<T>(ctx: RequestContext, fn: () => T): T;
4708
+ /** Convenience for the common case: a request on behalf of a signed-in user. */
4709
+ declare function runAsUser<T>(user: {
4710
+ userId: string;
4711
+ orgId?: string;
4712
+ role?: string;
4713
+ projectId?: string;
4714
+ requestId?: string;
4715
+ policies?: SourcePolicy[];
4716
+ }, fn: () => T): T;
4717
+ /**
4718
+ * Declare a unit of work as trusted, naming why.
4719
+ *
4720
+ * For entry points with no user behind them: schedulers, admin tooling, the
4721
+ * cross-machine proxy. `reason` is not decoration — it is what the audit log
4722
+ * shows in place of a user, and it is what makes these paths greppable when
4723
+ * someone asks "what runs unpoliced?".
4724
+ *
4725
+ * Nesting inside a user context deliberately REPLACES it: a system subtask is
4726
+ * an escalation, and it should look like one in the log rather than silently
4727
+ * inheriting a user's restrictions.
4728
+ */
4729
+ declare function runAsSystem<T>(reason: string, fn: () => T, opts?: {
4730
+ projectId?: string;
4731
+ requestId?: string;
4732
+ }): T;
4733
+ /**
4734
+ * Capture the current context so it can be re-entered later.
4735
+ *
4736
+ * For boundaries where the async chain breaks but a reference survives — an
4737
+ * event listener registered outside the request, a callback stored in a
4738
+ * registry. Does NOT help across a process or HTTP boundary (the script
4739
+ * bridge); that needs a token, see the design doc.
4740
+ */
4741
+ declare function captureContext(): RequestContext | undefined;
4742
+ /** Re-enter a captured context. A no-op wrapper when `ctx` is undefined. */
4743
+ declare function withCapturedContext<T>(ctx: RequestContext | undefined, fn: () => T): T;
4744
+ /**
4745
+ * Bind a function to the context active at bind time.
4746
+ *
4747
+ * The trap this exists for, stated the right way round (verified, because it
4748
+ * is easy to get backwards): context propagates through ASYNC RESOURCE
4749
+ * creation, and `EventEmitter.emit` is an ordinary synchronous call. So a
4750
+ * plain listener runs in the context active at EMIT time, whatever it was
4751
+ * registered inside. A handler registered during a request and fired later
4752
+ * from another chain therefore sees nothing at all.
4753
+ *
4754
+ * Bind it when the registering context is the one that matters.
4755
+ */
4756
+ declare function bindContext<A extends unknown[], R>(fn: (...args: A) => R): (...args: A) => R;
4757
+ /** Short label for logs and audit rows: `user:u_123` / `system:alert-scheduler` / `anonymous`. */
4758
+ declare function describeContext(ctx?: RequestContext | undefined): string;
4759
+ /** True when the context represents a signed-in user rather than a trusted job. */
4760
+ declare function isUserContext(ctx?: RequestContext | undefined): boolean;
4761
+
4762
+ /**
4763
+ * Deriving "who is asking" from an incoming WebSocket message.
4764
+ *
4765
+ * Separate from `utils/request-context.ts` on purpose: that module is a pure
4766
+ * carrier with no opinion about where identity comes from, this one knows the
4767
+ * message shape and the trust level of each field.
4768
+ *
4769
+ * See backend/docs/REQUEST-CONTEXT-DESIGN.md and the Prerequisite section of
4770
+ * backend/docs/SQL-AUTHORIZATION-DESIGN.md.
4771
+ */
4772
+
4773
+ /**
4774
+ * Read access policies out of the admin-authored per-user config.
4775
+ *
4776
+ * The config is free-form JSON typed by a human into an admin field, so every
4777
+ * step here is defensive: a malformed entry is DROPPED, never guessed at. That
4778
+ * is a deliberate trade-off with a sharp edge — a typo'd policy silently
4779
+ * becomes no policy, i.e. unrestricted. Validating shapes against the source
4780
+ * schema (and refusing, rather than dropping) is the fix, and is not built yet.
4781
+ *
4782
+ * Accepts either a single object or an array, so one user can be scoped across
4783
+ * several sources.
4784
+ */
4785
+ declare function policiesFromConfig(config: unknown): SourcePolicy[];
4786
+ /**
4787
+ * Run `fn` with the caller's identity established.
4788
+ *
4789
+ * Trust order:
4790
+ *
4791
+ * 1. `message.authContext` — stamped by the relay from a verified session.
4792
+ * Trustworthy. Does not exist yet.
4793
+ * 2. `payload.userId` — sent by the browser, which can put anything there.
4794
+ * Enough to prove the plumbing works end to end; NOT enough to enforce
4795
+ * anything on. Used because it is what exists today.
4796
+ * 3. Neither — no context is established at all.
4797
+ *
4798
+ * Case 3 is deliberately not a `system` context. "We don't know who this is"
4799
+ * and "this is a trusted job" must stay distinguishable, or every path that
4800
+ * loses identity silently becomes an unpoliced one. With no context, the data
4801
+ * seam decides what to do (see SA_SQL_POLICY_ENFORCE), and the honest answer
4802
+ * there is a refusal rather than an unfiltered read.
4803
+ */
4804
+ declare function runWithMessageIdentity<T>(message: any, fn: () => T): T;
4805
+
4806
+ /**
4807
+ * Context tokens — carrying identity across a boundary AsyncLocalStorage cannot.
4808
+ *
4809
+ * The script flow is the one path where the async chain genuinely breaks:
4810
+ * scripts run in a separate OS process and call back into the backend over
4811
+ * loopback HTTP (`script-bootstrap.ts` → `script-bridge.ts`), so the bridge's
4812
+ * request handler starts a fresh async context with no relationship to the
4813
+ * chat turn that launched the script. Nothing ambient crosses that; the
4814
+ * identity has to be handed over explicitly.
4815
+ *
4816
+ * So: the parent mints a token bound to the live context before spawning, the
4817
+ * child presents it on every bridge call, and the bridge resolves it back and
4818
+ * runs the query inside that context.
4819
+ *
4820
+ * The registry is in-memory and process-local, which is exactly right here —
4821
+ * the minting side (script-runner) and the resolving side (script-bridge) are
4822
+ * both in the backend process; only the script itself is elsewhere. A token is
4823
+ * therefore never valid anywhere but the process that issued it, and never
4824
+ * outlives that process.
4825
+ *
4826
+ * See backend/docs/REQUEST-CONTEXT-DESIGN.md.
4827
+ */
4828
+
4829
+ /**
4830
+ * Mint a token for the context active right now.
4831
+ *
4832
+ * Returns `undefined` when there is no context — deliberately, so that an
4833
+ * unidentified script run stays unidentified rather than being handed a token
4834
+ * that vouches for nothing. The bridge then sees no token and the data seam
4835
+ * treats it as anonymous, which is the truth.
4836
+ */
4837
+ declare function mintContextToken(ttlMs?: number): string | undefined;
4838
+ /** Resolve a token back to its context, or `undefined` if unknown or expired. */
4839
+ declare function resolveContextToken(token: string | undefined | null): RequestContext | undefined;
4840
+ /** Drop a token. Call when the work it was minted for is finished. */
4841
+ declare function revokeContextToken(token: string | undefined | null): void;
4842
+ /** Diagnostics only. */
4843
+ declare function contextTokenCount(): number;
4844
+ /** Test seam. */
4845
+ declare function clearContextTokens(): void;
4846
+
4847
+ /**
4848
+ * Manages conversation history scoped per user + dashboard.
4849
+ * Each user-dashboard pair has its own isolated history that expires after a configurable TTL.
4850
+ */
4851
+ declare class DashboardConversationHistory {
4852
+ private histories;
4853
+ private ttlMs;
4854
+ private maxEntries;
4855
+ private cleanupInterval;
4856
+ constructor();
4857
+ /**
4858
+ * Set the TTL for dashboard histories
4859
+ * @param minutes - TTL in minutes
4860
+ */
4861
+ setTTL(minutes: number): void;
4862
+ /**
4863
+ * Set max entries per dashboard
4864
+ */
4865
+ setMaxEntries(max: number): void;
4866
+ /**
4867
+ * Add a conversation entry for a user's dashboard
4868
+ */
4869
+ addEntry(dashboardId: string, userPrompt: string, componentSummary: string, userId?: string): void;
4870
+ /**
4871
+ * Get formatted conversation history for a user's dashboard
4872
+ */
4873
+ getHistory(dashboardId: string, userId?: string): string;
4874
+ /**
4875
+ * Clear history for a specific user's dashboard
4876
+ */
4877
+ clearDashboard(dashboardId: string, userId?: string): void;
4878
+ /**
4879
+ * Clear all dashboard histories
4880
+ */
4881
+ clearAll(): void;
4882
+ /**
4883
+ * Start periodic cleanup of expired histories
4884
+ */
4885
+ private startCleanup;
4886
+ /**
4887
+ * Stop cleanup interval (for graceful shutdown)
4888
+ */
4889
+ destroy(): void;
4890
+ }
4891
+ declare const dashboardConversationHistory: DashboardConversationHistory;
4892
+
4893
+ /**
4894
+ * Whole-dashboard generation via Pi, a terminal coding agent — as opposed to
4895
+ * DASH_COMP_REQ's single-widget-at-a-time flow. Runs Pi in-process via its
4896
+ * SDK (createAgentSession), not as a subprocess: no shell, no argument
4897
+ * quoting, no stdin/stdout piping, none of the Windows-specific subprocess
4898
+ * issues that came with spawning the `pi` CLI directly.
4899
+ *
4900
+ * Called from sdk-nodejs/src/dashboardAgent/index.ts (DASHBOARD_AGENT_REQ),
4901
+ * which owns the generic streaming/abort machinery (mirrors USER_PROMPT_REQ)
4902
+ * and passes `signal`/`onProgress` alongside the normal params — this stays
4903
+ * within CollectionHandler's loose (params) => Promise<result> typing, no
4904
+ * change needed to that shared type.
4905
+ *
4906
+ * This mechanism is generic and reusable across any deployment. What's
4907
+ * genuinely project-specific — where AGENTS.md lives, which model to use —
4908
+ * is supplied via `DashboardAgentCollectionConfig`, with defaults sensible
4909
+ * enough that most callers don't need to override them (see below). The
4910
+ * data-source tool list and the dashboard's current state both come from
4911
+ * things sdk-nodejs already exposes generically: `sdk.getTools()` (whatever
4912
+ * this deployment registered via `sdk.setTools()`) and `sdk.callCollection
4913
+ * ('dashboards', 'query', ...)` (whatever this deployment already registered
4914
+ * under that name/shape) — no per-deployment callback needed for either.
4915
+ * Same convention on the way out: after a successful run, the prompt and the
4916
+ * full response text are handed to `sdk.callCollection('dashboard-agent-
4917
+ * conversations', 'create', ...)` if this deployment has registered one —
4918
+ * skipped silently otherwise, since conversation history is optional.
4919
+ *
4920
+ * Pi verifies every query against the live database itself (via whatever
4921
+ * local tool-execution bridge the deployment exposes, e.g. an HTTP bridge
4922
+ * on localhost), but does NOT persist the result itself — it writes the
4923
+ * finished DSL to an absolute path inside `runtimeDir`, told to it explicitly
4924
+ * in the prompt, and stops there. This handler reads that file after the run
4925
+ * finishes and returns its content as `dashboard` in the result. The caller
4926
+ * (frontend) is the one that actually saves it, via whatever authenticated
4927
+ * create/update path any other dashboard edit goes through — Pi has no user
4928
+ * session/auth context of its own, so persistence shouldn't happen from
4929
+ * inside it.
4930
+ *
4931
+ * Session persistence: the FIRST call for a dashboardId pays the full cost
4932
+ * (explore KB, discover schema, plan, verify, build). Every call after that
4933
+ * resumes the same session file (SessionManager.open) so Pi has everything
4934
+ * it already learned — it only needs to reason about the new, smaller ask,
4935
+ * not rediscover the whole dashboard from scratch. The session's file path
4936
+ * (AgentSession.sessionFile) is captured right after creation and persisted
4937
+ * in a small local file, keyed by dashboardId, inside `runtimeDir`.
4938
+ */
4939
+ interface DashboardAgentCollectionConfig {
4940
+ /**
4941
+ * Working directory Pi runs from — must contain AGENTS.md. This is a
4942
+ * version-controlled prompt file, so `cwd` is expected to live somewhere
4943
+ * like a `.prompts/` folder alongside the deployment's other prompts.
4944
+ * Default: `<process.cwd()>/.prompts/dashboard-agent` — the same
4945
+ * process.cwd()-based convention PromptLoader already uses for the main
4946
+ * agent's prompts, which needs no explicit override in the common case
4947
+ * (the backend process's own cwd already is its project root).
4948
+ */
4949
+ cwd?: string;
4950
+ /**
4951
+ * Where drafts/, the session-id map, and dashboard.log get written —
4952
+ * separate from `cwd` deliberately, so this deployment's runtime state
4953
+ * (regenerated per session, safe to gitignore) doesn't sit inside the
4954
+ * same folder as the version-controlled AGENTS.md prompt.
4955
+ * Default: `<process.cwd()>/.pi-dashboard-agent-runtime`.
4956
+ */
4957
+ runtimeDir?: string;
4958
+ /** Model provider (default: process.env.PI_AGENT_PROVIDER || 'openrouter'). */
4959
+ provider?: string;
4960
+ /** Model id (default: process.env.PI_AGENT_MODEL || 'anthropic/claude-sonnet-4.5'). */
4961
+ model?: string;
4962
+ /**
4963
+ * true (default): every request starts a brand-new pi session, with the 2
4964
+ * most recent prior responses (if any) injected into the prompt as
4965
+ * context — bounded cost per request, but pi re-explores schema/KB facts
4966
+ * it already verified in an earlier turn on this same dashboard.
4967
+ * false: resumes the same session file across requests on a given
4968
+ * dashboard — pi keeps everything it already learned, but context (and
4969
+ * cost) grows unbounded across turns (one observed turn: 2M+ cache-read
4970
+ * tokens after a handful of edits on the same dashboard).
4971
+ * Default: process.env.PI_AGENT_FRESH_SESSION !== 'false'.
4972
+ */
4973
+ freshSession?: boolean;
4974
+ }
4975
+ declare function registerDashboardAgentCollection(sdk: SuperatomSDK, config?: DashboardAgentCollectionConfig): void;
4976
+
4977
+ /**
4978
+ * Coding-agent driver contract — one shape over every harness (codex today;
4979
+ * claude-code / opencode / pi next). Callers depend on this file only, never on
4980
+ * a harness SDK, so swapping the agent behind a task is a config change.
4981
+ *
4982
+ * Deliberately narrower than the harness SDKs it wraps: the three things a
4983
+ * production run needs and that harness abstractions usually omit — real abort,
4984
+ * real token accounting, and structured tool args — are part of the contract,
4985
+ * not per-driver extras.
4986
+ */
4987
+ type AgentEventKind = 'turn' | 'message' | 'reasoning' | 'command' | 'tool' | 'file' | 'todo' | 'error';
4988
+ interface AgentEvent {
4989
+ kind: AgentEventKind;
4990
+ /** Stable across started→updated→completed, so a UI updates one block in place. */
4991
+ id?: string;
4992
+ text?: string;
4993
+ command?: string;
4994
+ output?: string;
4995
+ /** Tool calls carry real parsed args — never SQL scraped back out of a shell string. */
4996
+ tool?: {
4997
+ server?: string;
4998
+ name: string;
4999
+ args?: unknown;
5000
+ };
5001
+ status?: 'in_progress' | 'completed' | 'failed';
5002
+ done?: boolean;
5003
+ }
5004
+ interface AgentUsage {
5005
+ inputTokens: number;
5006
+ outputTokens: number;
5007
+ reasoningTokens: number;
5008
+ cacheReadTokens: number;
5009
+ cacheWriteTokens: number;
5010
+ /** Tool + command invocations. With tokens, separates "silently did nothing" from a real run. */
5011
+ toolCalls: number;
5012
+ /** Only when the harness reports it — codex reports tokens but not cost. */
5013
+ costUSD?: number;
5014
+ }
5015
+ interface AgentRunHandlers {
5016
+ /** Formatted live stream: assistant text deltas plus one-line tool/command markers. */
5017
+ onOutput?: (chunk: string) => void;
5018
+ onEvent?: (event: AgentEvent) => void;
5019
+ /** Assistant prose only — safe to show a non-technical user as progress. */
5020
+ onNarration?: (text: string) => void;
5021
+ onUsage?: (usage: AgentUsage) => void;
5022
+ /**
5023
+ * Polled once the turn is live. When it returns true the run ends immediately —
5024
+ * for tasks whose deliverable is a file, the moment it exists there is nothing
5025
+ * left to wait for.
5026
+ */
5027
+ doneWhen?: () => boolean | Promise<boolean>;
5028
+ }
5029
+ type AgentRunStatus = 'completed' | 'early' | 'aborted' | 'error';
5030
+ interface AgentRunResult {
5031
+ status: AgentRunStatus;
5032
+ /** The final assistant message. */
5033
+ answer: string;
5034
+ ms: number;
5035
+ usage: AgentUsage;
5036
+ /**
5037
+ * Set when status is 'error'. Covers stream-reported failures too, which arrive
5038
+ * as events rather than thrown exceptions — a swallowed provider error is the
5039
+ * failure mode that otherwise looks like a successful empty run.
5040
+ */
5041
+ error?: string;
5042
+ sessionId?: string;
5043
+ }
5044
+ interface McpServerSpec {
5045
+ command: string;
5046
+ args?: string[];
5047
+ env?: Record<string, string>;
5048
+ }
5049
+ interface CodingAgentSessionOptions {
5050
+ /** Working directory the agent operates in. Scope it to a runtime dir, not a source checkout. */
5051
+ cwd: string;
5052
+ model?: string;
5053
+ /** Resume a prior conversation — the value a previous run returned as sessionId. */
5054
+ resumeId?: string;
5055
+ /** Tools, as MCP servers. Keyed by server name, which shows up on every tool event. */
5056
+ mcpServers?: Record<string, McpServerSpec>;
5057
+ /**
5058
+ * Extra env for the agent process. By default only a small allowlist is passed
5059
+ * through (see ENV_ALLOWLIST) so an agent with shell access can't read the
5060
+ * backend's own secrets out of its environment.
5061
+ */
5062
+ env?: Record<string, string>;
5063
+ /** Opt out of env scrubbing. Only for local debugging. */
5064
+ inheritEnv?: boolean;
5065
+ }
5066
+ interface CodingAgentSession {
5067
+ readonly harness: string;
5068
+ /** Structured event log vs. a raw terminal stream — the UI picks its renderer from this. */
5069
+ readonly kind: 'events' | 'pty';
5070
+ run(prompt: string, handlers?: AgentRunHandlers, signal?: AbortSignal): Promise<AgentRunResult>;
5071
+ /** Rolling structured events, for replay when a client reconnects mid-run. */
5072
+ events(): AgentEvent[];
5073
+ /** Rolling formatted text, same purpose as events() for text-oriented views. */
5074
+ buffer(): string;
5075
+ busy(): boolean;
5076
+ /** Persist this and pass it back as resumeId to continue the conversation. */
5077
+ sessionId(): string | undefined;
5078
+ /** Abandon the conversation; the next run starts fresh. */
5079
+ reset(): void;
5080
+ dispose(): void;
5081
+ }
5082
+
5083
+ /**
5084
+ * Harness registry. Kept separate from index.ts so collection.ts can reach the
5085
+ * factory without importing the module's own barrel (a cycle tsup would have to
5086
+ * resolve at bundle time).
5087
+ */
5088
+ type Harness = 'codex';
5089
+ declare function createCodingAgentSession(harness: Harness, opts: CodingAgentSessionOptions): CodingAgentSession;
5090
+
5091
+ /**
5092
+ * Codex driver — OpenAI Codex via @openai/codex-sdk.
5093
+ *
5094
+ * FORMAT CONTRACT: written against @openai/codex-sdk 0.149.1. Harness event
5095
+ * shapes drift; if the event log goes blank after an SDK bump, check normEvent
5096
+ * against the package's dist/index.d.ts first.
5097
+ *
5098
+ * Three things this leans on that the SDK gives natively, so we don't reinvent
5099
+ * them: TurnOptions.signal (real cancellation), TurnCompletedEvent.usage (token
5100
+ * accounting), and mcp_tool_call items (tool args arrive parsed, not scraped
5101
+ * out of a shell command string).
5102
+ *
5103
+ * The package is an optionalDependency: every deployment gets it, but an
5104
+ * install that cannot fetch the ~309MB platform binary skips it rather than
5105
+ * failing. It is therefore loaded dynamically and its types mirrored
5106
+ * structurally below, so a VM without it still builds, starts, and runs
5107
+ * everything else — only the coding agent reports itself unavailable.
5108
+ */
5109
+ type CodexSandboxMode = 'read-only' | 'workspace-write' | 'danger-full-access';
5110
+ type CodexReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra';
5111
+ interface CodexSessionOptions extends CodingAgentSessionOptions {
5112
+ reasoningEffort?: CodexReasoningEffort;
5113
+ /**
5114
+ * Filesystem reach. Default 'workspace-write' — the agent writes its
5115
+ * deliverable into cwd and nothing else. 'danger-full-access' hands a
5116
+ * shell-capable agent the whole box; don't use it on a client VM.
5117
+ */
5118
+ sandboxMode?: CodexSandboxMode;
5119
+ /** Network for commands the agent runs. Off by default; MCP tools don't need it. */
5120
+ networkAccessEnabled?: boolean;
5121
+ apiKey?: string;
5122
+ baseUrl?: string;
5123
+ /** Raw `--config` overrides merged into the codex config. */
5124
+ extraConfig?: Record<string, unknown>;
5125
+ approvalPolicy?: 'never' | 'on-request' | 'on-failure' | 'untrusted';
5126
+ }
5127
+ declare function createCodexSession(opts: CodexSessionOptions): CodingAgentSession;
5128
+
5129
+ /**
5130
+ * What makes an agent fire.
5131
+ *
5132
+ * Declared ON the definition, deliberately. If triggers lived at the call sites
5133
+ * instead — a counter in the conversation handler, a hook in the kb-nodes
5134
+ * collection — then adding an agent would mean editing unrelated files across
5135
+ * the backend, and no one file would tell you when an agent actually runs.
5136
+ * Here, an agent's folder plus its definition is the whole story.
5137
+ *
5138
+ * The deployment's only job is to announce that something happened:
5139
+ *
5140
+ * emitAgentEvent('conversation.answered', { threadId })
5141
+ * emitAgentEvent('kb-node.changed', { id, op: 'update' })
5142
+ *
5143
+ * Which agents care, and how many events it takes, is the agents' business.
5144
+ * The emitter therefore speaks the WORLD's vocabulary, never any one agent's —
5145
+ * translating an event into a particular agent's input is `buildInput` below.
5146
+ */
5147
+ /** One announced fact, as it reaches a trigger. */
5148
+ interface TriggerEvent {
5149
+ /** The event name passed to emitAgentEvent. */
5150
+ name: string;
5151
+ payload?: unknown;
5152
+ }
5153
+ /**
5154
+ * Turns the events that caused this run into the agent's `input`.
5155
+ *
5156
+ * Takes the whole list, not one payload, because every batching trigger here
5157
+ * fires for MANY events: a debounced burst, or N counted occurrences. Handing
5158
+ * over only the last one silently discarded the rest — five edited nodes became
5159
+ * one.
5160
+ *
5161
+ * Omit it and the agent receives the most recent payload unchanged, which is
5162
+ * the historical behaviour. Any agent that batches should declare one.
5163
+ */
5164
+ type BuildTriggerInput = (events: TriggerEvent[]) => unknown;
5165
+ type AgentTrigger =
5166
+ /** Only runCodingAgent(). The default. */
5167
+ {
5168
+ type: 'manual';
5169
+ }
5170
+ /** Every N milliseconds while the process is up. Fires with no events. */
5171
+ | {
5172
+ type: 'interval';
5173
+ everyMs: number;
5174
+ buildInput?: BuildTriggerInput;
5175
+ }
5176
+ /**
5177
+ * On a named event. `debounceMs` collapses a burst into one run — editing
5178
+ * five knowledge nodes in a row is one reason to rebuild, not five. The run
5179
+ * still receives all five events; only the RUNS are collapsed.
5180
+ */
5181
+ | {
5182
+ type: 'event';
5183
+ on: string | string[];
5184
+ debounceMs?: number;
5185
+ buildInput?: BuildTriggerInput;
5186
+ }
5187
+ /**
5188
+ * Every Nth occurrence of an event. The events are PERSISTED, so "after 10
5189
+ * questions" survives a restart instead of silently starting over.
5190
+ */
5191
+ | {
5192
+ type: 'count';
5193
+ on: string;
5194
+ every: number;
5195
+ buildInput?: BuildTriggerInput;
5196
+ };
5197
+ interface TriggerFireInfo {
5198
+ agentId: string;
5199
+ /** What set it off, for the log line. */
5200
+ reason: string;
5201
+ /** Everything that caused this run, in arrival order. */
5202
+ events: TriggerEvent[];
5203
+ /** What buildInput produced — exactly what the agent was handed. */
5204
+ input?: unknown;
5205
+ }
5206
+ /** Notified after every triggered run — for recording history or alerting. */
5207
+ type RunListener = (record: AgentRunRecord, info: TriggerFireInfo) => void;
5208
+ declare function onAgentRun(fn: RunListener): () => void;
5209
+ /**
5210
+ * Tell the agents something happened. Safe to call from anywhere, including a
5211
+ * request path — it never throws and never blocks: matching runs are started,
5212
+ * not awaited.
5213
+ */
5214
+ declare function emitAgentEvent(event: string, payload?: unknown): void;
5215
+ /**
5216
+ * Start interval triggers. Call once at startup, after registerCodingAgents.
5217
+ * Event and count triggers need nothing started — they wake on emitAgentEvent.
5218
+ */
5219
+ declare function startAgentTriggers(): void;
5220
+ declare function stopAgentTriggers(): void;
5221
+ /** What fires each agent — for a startup log or an admin screen. */
5222
+ declare function describeTriggers(): Array<{
5223
+ agentId: string;
5224
+ triggers: string[];
5225
+ }>;
5226
+
5227
+ /**
5228
+ * What a coding agent IS.
5229
+ *
5230
+ * An agent is a job description, not code that does the job: instructions, the
5231
+ * inputs it should be handed, the tools it may reach, the deliverable it must
5232
+ * produce, and what we do with that deliverable. The agent itself decides HOW —
5233
+ * it can read the inputs, write and run scripts over them, check its own work,
5234
+ * and iterate. That is the whole reason for using a coding agent rather than a
5235
+ * single LLM call: the job's data never has to fit in a context window.
5236
+ *
5237
+ * Adding an agent is a folder with a system.md, one file implementing this
5238
+ * interface, and one line in the registry. Nothing else changes.
5239
+ */
5240
+ /** The disposable directory one run happens in. */
5241
+ interface Workspace {
5242
+ /** Absolute path the agent runs in. Everything below is relative to it. */
5243
+ dir: string;
5244
+ /** Unique per run — also the folder name, so runs never collide. */
5245
+ runId: string;
5246
+ /** Write a file into the workspace, creating parent directories. */
5247
+ write(relPath: string, contents: string): Promise<void>;
5248
+ /** Write JSON (pretty-printed — the agent reads these by eye as often as by script). */
5249
+ writeJson(relPath: string, value: unknown): Promise<void>;
5250
+ /** Write one JSON object per line. The right shape for anything the agent will stream or grep. */
5251
+ writeJsonl(relPath: string, rows: unknown[]): Promise<void>;
5252
+ /** Read a file the agent produced. Returns null when it isn't there. */
5253
+ read(relPath: string): Promise<string | null>;
5254
+ /** Absolute path for a workspace-relative path — for telling the agent where to write. */
5255
+ pathTo(relPath: string): string;
5256
+ }
5257
+ /** Minimal validator shape, so this file needn't depend on a schema library. */
5258
+ interface OutputValidator<T> {
5259
+ /** Throw with a useful message, or return the parsed value. Zod's `.parse` satisfies this. */
5260
+ parse(value: unknown): T;
5261
+ }
5262
+ interface OutputContract<T> {
5263
+ /**
5264
+ * Workspace-relative path the agent must write, e.g. 'out/concepts.json'.
5265
+ * Nothing else counts as the deliverable: the run ends the moment this
5266
+ * appears, and a run that finishes without it is a failure, not a partial
5267
+ * success.
5268
+ */
5269
+ file: string;
5270
+ /** Validated before anything is persisted, so a malformed run fails loudly and applies nothing. */
5271
+ schema: OutputValidator<T>;
5272
+ }
5273
+ /** What apply() reports back — surfaced in the run record and to the caller. */
5274
+ interface ApplySummary {
5275
+ /** One line a human can read in a log or the UI. */
5276
+ summary: string;
5277
+ /** Whatever counts for this agent: {created, updated, skipped}, etc. */
5278
+ counts?: Record<string, number>;
5279
+ /** Anything the caller may want to inspect or show. */
5280
+ details?: unknown;
5281
+ }
5282
+ interface AgentRunContext {
5283
+ projectId?: string;
5284
+ userId?: string;
5285
+ /**
5286
+ * This run's id — also the workspace directory name. Passed so apply() can
5287
+ * stamp whatever it persists with the run that produced it, which is the
5288
+ * only link from a stored result back to the inputs and scripts behind it.
5289
+ */
5290
+ runId?: string;
5291
+ /** The run's workspace, for an apply() that needs a file the agent left. */
5292
+ workspaceDir?: string;
5293
+ /** Cancels the run; forwarded to the driver's real abort. */
5294
+ signal?: AbortSignal;
5295
+ /** Live progress. Populated for chat mode; a task run may also stream to a log. */
5296
+ onOutput?: (chunk: string) => void;
5297
+ onEvent?: (event: AgentEvent) => void;
5298
+ /**
5299
+ * Assistant prose only — safe to show a non-technical user as progress.
5300
+ * Distinct from onOutput, which also carries command and tool lines and so
5301
+ * would leak SQL and shell text into a user-facing stream.
5302
+ */
5303
+ onNarration?: (text: string) => void;
5304
+ onUsage?: (usage: AgentUsage) => void;
5305
+ }
5306
+ /**
5307
+ * How much an agent carries between runs.
5308
+ *
5309
+ * Codex manages its own context: it tracks the window and compacts when it
5310
+ * crosses `auto_compact_token_limit`, emitting a ContextCompacted event. That
5311
+ * happens with no involvement from us, so a persistent session survives
5312
+ * indefinitely on its own. (The mechanism is in the engine but not the
5313
+ * TypeScript SDK — Thread exposes only id/run/runStreamed — which is why there
5314
+ * is nothing here to call.)
5315
+ *
5316
+ * What compaction cannot do is make the session authoritative. It summarises to
5317
+ * make room, so detail is lost by design; and ~/.codex/sessions is a directory
5318
+ * on one machine, not the database. So durable facts belong in `memory/` files
5319
+ * and in the tables the agent writes through apply(), with the session free to
5320
+ * compact itself as it likes. Memory on disk, context managed by codex.
5321
+ */
5322
+ interface SessionPolicy {
5323
+ /**
5324
+ * 'per-run' a fresh harness session each time (default).
5325
+ * 'persistent' resume the same session across runs, so the agent keeps its
5326
+ * working context. Always paired with durable files — never rely
5327
+ * on it alone.
5328
+ */
5329
+ scope?: 'per-run' | 'persistent';
5330
+ /**
5331
+ * 'per-run' a throwaway directory per run (default); pruned by keepRuns.
5332
+ * 'persistent' one directory the agent owns across runs. `memory/` survives
5333
+ * untouched; `input/` is cleared each run so a stale input can
5334
+ * never be mistaken for this run's.
5335
+ */
5336
+ workspace?: 'per-run' | 'persistent';
5337
+ /**
5338
+ * Safety valve, not the compaction mechanism — codex already compacts on its
5339
+ * own. Starts a fresh session after this many runs while keeping the
5340
+ * workspace, for when you want a hard ceiling on how much summarised history
5341
+ * an agent drags along, or a clean slate on a cadence. Omit by default.
5342
+ */
5343
+ resetAfterTurns?: number;
5344
+ }
5345
+ interface CodingAgentDefinition<TInput = unknown, TOutput = unknown> {
5346
+ /** Stable id: the folder name under .prompts/coding-agents, and the key callers use. */
5347
+ id: string;
5348
+ /** Human-readable, for the UI and logs. */
5349
+ title: string;
5350
+ /** One line: what this agent is for. */
5351
+ description?: string;
5352
+ /**
5353
+ * 'task' — headless. Runs from a cron, an event, or a command; produces the
5354
+ * deliverable and applies it. Nobody is watching.
5355
+ * 'chat' — a person is typing. Streams, keeps its session across turns, and
5356
+ * is not required to produce a deliverable at all.
5357
+ */
5358
+ mode: 'task' | 'chat';
5359
+ /**
5360
+ * Directory holding this agent's system.md. Defaults to
5361
+ * `<promptRoot>/<id>`. The runner copies system.md into the workspace as
5362
+ * AGENTS.md, which is the filename the harness actually reads from its
5363
+ * working directory — that indirection is what lets the instructions stay
5364
+ * version-controlled while the workspace stays disposable.
5365
+ */
5366
+ promptDir?: string;
5367
+ /** Override the deployment default for this agent alone. */
5368
+ harness?: Harness;
5369
+ model?: string;
5370
+ /**
5371
+ * Let this agent's shell reach the network. Off by default.
5372
+ *
5373
+ * Needed by any agent given bridge shims (writeBridgeShims), which reach the
5374
+ * backend over localhost HTTP. Note the sandbox has no host allowlist, so
5375
+ * this grants the whole internet, not just the bridge — scope it to agents
5376
+ * that genuinely need it.
5377
+ */
5378
+ networkAccessEnabled?: boolean;
5379
+ /**
5380
+ * Filesystem reach. Defaults to the driver's 'workspace-write'.
5381
+ * 'danger-full-access' removes the sandbox entirely — it is the only mode in
5382
+ * which codex permits MCP tool calls headlessly, which is exactly why the
5383
+ * shims exist instead.
5384
+ */
5385
+ sandboxMode?: 'read-only' | 'workspace-write' | 'danger-full-access';
5386
+ /**
5387
+ * Tools this agent may reach, as MCP servers. Deliberately per-agent: an
5388
+ * agent that reads the knowledge base has no business holding a database
5389
+ * connection. Omit for an agent that only needs the files it is given.
5390
+ */
5391
+ tools?: Record<string, McpServerSpec>;
5392
+ /**
5393
+ * Environment for this run's session — how a SHARED executable learns what is
5394
+ * specific to this run (bridge URL, identity token, source id).
5395
+ *
5396
+ * The alternative is a per-workspace copy of each tool with those values
5397
+ * baked in, which makes a tool edit reach only new workspaces and leaves the
5398
+ * run's identity token on disk after it is revoked.
5399
+ */
5400
+ env?(input: TInput, ctx: AgentRunContext): Record<string, string> | Promise<Record<string, string>>;
5401
+ /**
5402
+ * Put the job's inputs in the workspace as FILES, not prompt text. A coding
5403
+ * agent can grep, aggregate and script over a file; it cannot do any of that
5404
+ * with text pasted into its prompt, and a large input would not fit there
5405
+ * anyway.
5406
+ */
5407
+ prepare?(ws: Workspace, input: TInput, ctx: AgentRunContext): Promise<void>;
5408
+ /**
5409
+ * The short framing sent as the turn's prompt. Keep it short — the standing
5410
+ * instructions belong in system.md and the data belongs in files. Defaults
5411
+ * to a generic instruction naming the output path.
5412
+ */
5413
+ buildPrompt?(ws: Workspace, input: TInput, ctx: AgentRunContext): string | Promise<string>;
5414
+ /** Required for 'task' mode; meaningless for 'chat'. */
5415
+ output?: OutputContract<TOutput>;
5416
+ /**
5417
+ * Persist the validated deliverable — through existing services, never raw
5418
+ * SQL from inside the agent. Keeping the write on this side is what makes a
5419
+ * run auditable and replayable: the artifact on disk is the same input
5420
+ * apply() would get again tomorrow.
5421
+ */
5422
+ apply?(result: TOutput, input: TInput, ctx: AgentRunContext): Promise<ApplySummary>;
5423
+ /**
5424
+ * What makes this agent run. Declared here so an agent's folder plus this
5425
+ * file is the complete story of when it fires. See triggers.ts.
5426
+ */
5427
+ trigger?: AgentTrigger | AgentTrigger[];
5428
+ /**
5429
+ * WHO this agent's accumulated state belongs to. Distinct from `mode`, which
5430
+ * is only how a run was triggered — the two were conflated before, so a
5431
+ * project agent someone chatted with silently got a private per-thread
5432
+ * workspace and lost its memory.
5433
+ *
5434
+ * 'project' ONE workspace and session for the whole deployment, whoever
5435
+ * invokes it. A concept builder is project-wide: everything it
5436
+ * learns should accumulate in one place, and a chat turn joins
5437
+ * that same workspace rather than forking a copy. Concurrent
5438
+ * runs serialise.
5439
+ * 'user' one per user, shared across that user's threads.
5440
+ * 'thread' one per conversation — an ordinary chat assistant.
5441
+ *
5442
+ * Default: 'thread' for mode 'chat', 'project' for mode 'task'.
5443
+ */
5444
+ scope?: 'project' | 'user' | 'thread';
5445
+ /**
5446
+ * Kill the turn the moment the deliverable file appears, instead of letting
5447
+ * the agent finish.
5448
+ *
5449
+ * Off by default, and the reason is measured: an agent typically writes its
5450
+ * output and then keeps going — verifying, re-reading, summarising — so
5451
+ * stopping at the write cuts the turn well before codex emits
5452
+ * turn.completed, which is the only event carrying token usage. Early stop
5453
+ * therefore costs you all cost tracking, and skips the agent's own
5454
+ * self-check. Turn it on for a long-tailed agent where the file really is
5455
+ * the last thing that matters.
5456
+ */
5457
+ stopOnDeliverable?: boolean;
5458
+ /** What this agent carries between runs. Default: nothing (fresh session and workspace). */
5459
+ session?: SessionPolicy;
5460
+ /** Hard cap for one run. Default 15 minutes. */
5461
+ timeoutMs?: number;
5462
+ }
5463
+ /** What a completed run reports. */
5464
+ interface AgentRunRecord<TOutput = unknown> {
5465
+ agentId: string;
5466
+ runId: string;
5467
+ /** The run's directory — instructions, inputs, scripts and output all still there. */
5468
+ workspaceDir: string;
5469
+ /**
5470
+ * 'early' the deliverable landed and we stopped the turn — a success, kept
5471
+ * distinct from 'completed' so a masked early exit is visible.
5472
+ * 'skipped' another run of this agent held the lock; nothing was done.
5473
+ */
5474
+ status: 'completed' | 'early' | 'aborted' | 'error' | 'skipped';
5475
+ /** The agent's closing message. */
5476
+ answer: string;
5477
+ ms: number;
5478
+ usage: AgentUsage;
5479
+ /** Present when the agent produced and validated its deliverable. */
5480
+ output?: TOutput;
5481
+ /** Present when apply() ran. */
5482
+ applied?: ApplySummary;
5483
+ error?: string;
5484
+ /** Harness session id, for resuming a chat. */
5485
+ sessionId?: string;
5486
+ }
5487
+
5488
+ /**
5489
+ * The agent registry — one place that knows which agents this deployment has.
5490
+ *
5491
+ * Deliberately a plain module-level map rather than something on the SDK: a
5492
+ * cron job, a CLI command and the websocket handler all need to reach the same
5493
+ * agents, and only one of those has an SDK instance in hand.
5494
+ */
5495
+ interface CodingAgentsConfig {
5496
+ /**
5497
+ * Where per-agent instruction folders live. Each agent reads
5498
+ * `<promptRoot>/<agent.id>/system.md`.
5499
+ * Default: `<cwd>/.prompts/coding-agents`, matching the .prompts convention
5500
+ * the rest of the deployment already uses.
5501
+ */
5502
+ promptRoot?: string;
5503
+ /**
5504
+ * Root for run workspaces: `<runtimeDir>/<agentId>/<runId>/`. Regenerated
5505
+ * per run and safe to gitignore — deliberately not inside promptRoot, which
5506
+ * is version-controlled.
5507
+ * Default: `<cwd>/.coding-agent-runtime`.
5508
+ */
5509
+ runtimeDir?: string;
5510
+ /** Fallback harness for agents that don't name one. */
5511
+ harness?: Harness;
5512
+ /** Fallback model. */
5513
+ model?: string;
5514
+ /** Tools every agent gets, merged under each agent's own (the agent's win on a name clash). */
5515
+ sharedTools?: Record<string, McpServerSpec>;
5516
+ /** Keep this many run directories per agent; older ones are pruned. 0 keeps everything. */
5517
+ keepRuns?: number;
5518
+ /**
5519
+ * Keep this many THREAD workspaces per thread-scoped agent; the least
5520
+ * recently used are deleted. A persistent workspace is never pruned by
5521
+ * keepRuns, so without this one directory per UI thread accumulates forever
5522
+ * (~3.4 MB each for the answer agent). 0 keeps everything.
5523
+ * Env: CODING_AGENT_KEEP_THREADS.
5524
+ */
5525
+ keepThreads?: number;
5526
+ }
5527
+ /**
5528
+ * Register this deployment's agents. Call once at startup.
5529
+ *
5530
+ * Re-registering an id replaces it — that keeps hot-reload working in dev and
5531
+ * makes a double registration a no-op rather than a silent duplicate.
5532
+ */
5533
+ declare function registerCodingAgents(definitions: CodingAgentDefinition<any, any>[], options?: CodingAgentsConfig): void;
5534
+ declare function getCodingAgent(id: string): CodingAgentDefinition<any, any> | undefined;
5535
+ declare function listCodingAgents(): Array<{
5536
+ id: string;
5537
+ title: string;
5538
+ description?: string;
5539
+ mode: 'task' | 'chat';
5540
+ }>;
5541
+ declare function getCodingAgentsConfig(): Required<Pick<CodingAgentsConfig, "harness" | "promptRoot" | "runtimeDir" | "keepRuns" | "keepThreads">> & CodingAgentsConfig;
5542
+
5543
+ interface RunAgentOptions<TInput> extends AgentRunContext {
5544
+ input?: TInput;
5545
+ /** Scopes a 'thread' agent. Ignored by a project-scoped one. */
5546
+ threadId?: string;
5547
+ /**
5548
+ * Escape hatch that pins the workspace directory outright. Almost never
5549
+ * right — it defeats the agent's own scope, which is how a project agent
5550
+ * ends up with a private copy per caller. Left for tests and one-offs.
5551
+ */
5552
+ workspaceDir?: string;
5553
+ /** Resume the harness session — chat continuity across turns and restarts. */
5554
+ resumeId?: string;
5555
+ /** Overrides the definition's prompt entirely. Chat mode: this is the user's message. */
5556
+ prompt?: string;
5557
+ /**
5558
+ * A person is typing, rather than a job running.
5559
+ *
5560
+ * For an agent whose mode is 'task' this turns off the JOB — prepare(), the
5561
+ * deliverable contract and apply() are one unit that sets work up and
5562
+ * consumes it, and a conversation should do neither. The turn joins the
5563
+ * workspace as it stands and its answer is the whole result.
5564
+ *
5565
+ * Without this, chatting with a task agent could only ever fail: the user's
5566
+ * message replaces the prompt that names the output path, so the agent never
5567
+ * writes the deliverable, and the run is then reported as an error despite
5568
+ * having answered perfectly well. Worse, prepare() ran on every turn — for a
5569
+ * batching agent that means a chat turn quietly consumed a batch of work.
5570
+ *
5571
+ * An agent whose mode is 'chat' is unaffected: its prepare() is per-turn
5572
+ * context setup, not job setup, so it still runs.
5573
+ */
5574
+ chat?: boolean;
5575
+ }
5576
+ /**
5577
+ * Run one agent, end to end.
5578
+ *
5579
+ * Never throws for an agent-side failure — a bad run comes back as a record
5580
+ * with status 'error', because callers are usually crons and message handlers
5581
+ * that must keep going. Genuinely programmer errors (unknown agent id) do throw.
5582
+ */
5583
+ declare function runCodingAgent<TInput = unknown, TOutput = unknown>(agentId: string, options?: RunAgentOptions<TInput>): Promise<AgentRunRecord<TOutput>>;
5584
+
5585
+ /**
5586
+ * Write `./sources` and `./query` into an agent's workspace: read-only data
5587
+ * access as plain executables it runs with bash.
5588
+ *
5589
+ * Why not MCP: codex gates MCP tool calls on the sandbox. Under any sandboxed
5590
+ * mode they need approval, and a headless run must set approvalPolicy 'never',
5591
+ * which denies rather than grants — measured, not assumed. Only
5592
+ * danger-full-access permits them, and that removes the filesystem sandbox
5593
+ * entirely. Bash commands under workspace-write need no approval, so a shim
5594
+ * buys the same capability while the agent stays confined to its workspace.
5595
+ *
5596
+ * An MCP server for this was written and then removed: the same approval gate
5597
+ * applies to the Agents chat tab, which is equally headless from codex's point
5598
+ * of view, so it was unreachable everywhere. `mcpServers` stays plumbed through
5599
+ * the driver for third-party servers; see git history for the removed one.
5600
+ *
5601
+ * The cost is structured tool events: calls arrive as `bash → ./query ...`
5602
+ * rather than typed items with parsed arguments. That matters for a chat UI
5603
+ * with a human watching; for a headless task agent it does not.
5604
+ *
5605
+ * Requires networkAccessEnabled on the session — the shim reaches the bridge
5606
+ * over HTTP, and that is the whole point of it.
5607
+ */
5608
+ declare function writeBridgeShims(ws: Workspace, opts: {
5609
+ bridgeUrl: string;
5610
+ sources: Array<{
5611
+ id: string;
5612
+ name?: string;
5613
+ description?: string;
5614
+ }>;
5615
+ maxRows?: number;
5616
+ /**
5617
+ * Identity for the queries this agent runs, from mintContextToken().
5618
+ *
5619
+ * The agent is a separate OS process calling the bridge over loopback
5620
+ * HTTP, so nothing ambient crosses that gap — the same break the script
5621
+ * flow has (see utils/context-token.ts). Without this the bridge sees an
5622
+ * anonymous query, and under SA_SQL_REWRITE_MODE=enforce the data seam
5623
+ * refuses it outright rather than guessing whose data it is.
5624
+ *
5625
+ * Omit ONLY when the caller genuinely has no identity to grant; the
5626
+ * queries are then anonymous, which is the truth rather than a default.
5627
+ */
5628
+ contextToken?: string;
5629
+ }): void;
5630
+
5631
+ /**
5632
+ * Read-only SQL guard for any path that hands an agent a database.
5633
+ *
5634
+ * Defence in depth, NOT a boundary. The agent has a shell and can reach the
5635
+ * bridge directly, so anything enforced only here is advisory — it stops
5636
+ * mistakes, not determination. The real boundary is a database user without
5637
+ * write permission; this exists so a confused agent gets a clear correction
5638
+ * instead of a silent partial write.
5639
+ */
5640
+ /** Throws with a message written for the agent to act on. */
5641
+ declare function assertReadOnlySql(sql: string): void;
5642
+
5643
+ /**
5644
+ * The 'coding-agent'.'run' collection — a chat turn against a coding agent.
5645
+ *
5646
+ * Generic on purpose: nothing here knows about dashboards, reports, or any
5647
+ * particular deliverable. It owns what every harness-backed chat needs — one
5648
+ * session per thread, a per-thread workspace, a run lock, and forwarding the
5649
+ * driver's callbacks to the transport. Task-specific flows (prompt assembly, a
5650
+ * draft-file contract, persistence) build on top of this rather than inside it.
5651
+ */
5652
+ interface CodingAgentCollectionConfig {
5653
+ /**
5654
+ * Root for per-thread agent workspaces. Each thread gets its own directory
5655
+ * underneath, so one chat can't read or clobber another's files, and none of
5656
+ * them sit inside the backend's own source tree.
5657
+ * Default: `<process.cwd()>/.coding-agent-runtime`.
5658
+ */
5659
+ runtimeDir?: string;
5660
+ /** Default harness when the request doesn't name one. */
5661
+ harness?: Harness;
5662
+ model?: string;
5663
+ /** Tools, as MCP servers, handed to every session. */
5664
+ mcpServers?: Record<string, McpServerSpec>;
5665
+ }
5666
+ declare function registerCodingAgentCollection(sdk: SuperatomSDK, config?: CodingAgentCollectionConfig): void;
5667
+
5668
+ declare class ScriptMatcher {
5669
+ private store;
5670
+ private collections?;
5671
+ private userId?;
5672
+ private trace?;
5673
+ constructor(store: ScriptStore, opts?: {
5674
+ collections?: any;
5675
+ userId?: string;
5676
+ trace?: RunTrace;
5677
+ });
5678
+ /**
5679
+ * Find the best matching script for a user question.
5680
+ * Uses ONE LLM call that picks the script AND extracts parameters.
5681
+ * Returns null if no script matches.
5682
+ *
5683
+ * Thin wrapper around `doMatch` whose only job is guaranteeing the trace
5684
+ * capture happens exactly once, on every exit path (short-circuit, normal
5685
+ * return, or the LLM call erroring) — see RunTrace.scriptMatcher.
5686
+ */
5687
+ match(userPrompt: string, apiKey?: string, model?: string, signal?: AbortSignal, activeBindings?: ScriptBinding[]): Promise<ScriptMatch | null>;
5688
+ private doMatch;
5689
+ /**
5690
+ * Renders a recipe's declared parameters the same way in every prompt
5691
+ * section (catalog, active-script, edit candidates) so the LLM sees one
5692
+ * consistent format regardless of which block a script came from.
5693
+ */
5694
+ private formatParamList;
5695
+ /**
5696
+ * Semantic search over THIS user's own past prompts (`conversation-history`
5697
+ * ChromaDB embeddings, already user-scoped) — not a project-wide name/tag
5698
+ * search. Groups hits by the recipe that answered them, so a script gets
5699
+ * ONE catalog entry carrying every matched past question, not one per hit.
5700
+ *
5701
+ * Scope is deliberate (see SCRIPT-MATCH-IMPROVEMENTS.md, Change 2): a
5702
+ * script only shows up here because THIS user has, before, asked something
5703
+ * similar that it answered — not because some other user's question did.
5704
+ */
5705
+ private searchPromptHistory;
5706
+ /**
5707
+ * Build the script catalog string for the LLM prompt from prompt-history
5708
+ * matches: each script's declared parameters PLUS the actual past questions
5709
+ * of this user's that it answered (real precedent, not a hand-written
5710
+ * description) and what params they ran with.
5711
+ */
5712
+ private buildPromptHistoryCatalog;
5713
+ /**
5714
+ * The most recent script-backed answer in this thread — the one an `edit`
5715
+ * targets. Rendered as its own prompt section (never merged into the ranked
5716
+ * catalog) so the `edit` rules have an unambiguous referent.
5717
+ *
5718
+ * `candidates` holds at most one entry (see doMatch) — `edit` always means
5719
+ * "the answer I just got", so there is nothing else to show here.
5720
+ *
5721
+ * Carries the QUESTION that produced it plus the columns it returned — that
5722
+ * is what lets the matcher resolve "use the mode for the WSP one" against
5723
+ * this one script's own context.
5724
+ */
5725
+ private buildActiveScriptBlock;
5726
+ }
5727
+
5728
+ /**
5729
+ * ScriptRunner — Execute scripts in an isolated tsx subprocess.
5730
+ *
5731
+ * The subprocess approach replaces the earlier `new Function()` eval and gives us:
5732
+ * - Real sandbox (separate process, SIGKILL on timeout).
5733
+ * - Real TypeScript (tsx transpiles on the fly).
5734
+ * - npm imports available to scripts (clustering, stats, geo, etc.).
5735
+ *
5736
+ * Protocol: NDJSON over the child's stdin/stdout. See script-ipc.ts + backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md.
5737
+ */
5738
+
5739
+ interface RunScriptOptions {
5740
+ /** Data sources the script is allowed to query via ctx.query */
5741
+ externalTools: ExternalTool[];
5742
+ /** Optional — for propagating per-query UI progress to the user */
5743
+ streamBuffer?: StreamBuffer;
5744
+ /** Override the wall-clock timeout (default `SCRIPT_TIMEOUT_MS`, 60s). */
5745
+ timeoutMs?: number;
5746
+ /**
5747
+ * Per-turn cancellation signal. When the user hits "Stop" mid-run, the child
5748
+ * process group is SIGKILLed and the run resolves as an aborted failure (the
5749
+ * caller is already unwinding, so the result is discarded).
5750
+ */
5751
+ signal?: AbortSignal;
5752
+ /**
5753
+ * Names resolved for this run, handed to getAnalysis/getComponents as their
5754
+ * 5th argument. Supplying these is what stops "the narrative needs the
5755
+ * subsidiary's name" from being a reason to rewrite getData and re-query.
5756
+ */
5757
+ entities?: ResolvedEntityRef[];
5758
+ /**
5759
+ * Restrictions an authorization policy imposed on this run, handed to
5760
+ * getAnalysis/getComponents as their 6th argument.
5761
+ *
5762
+ * Supplied at RUN time rather than written into the recipe: a policy is
5763
+ * per-request and mutable, a recipe is durable. Baked in, it goes stale the
5764
+ * moment the user's scope changes — the recipe would keep naming the old
5765
+ * scope while the seam injects the new one. Supplied here, a replay always
5766
+ * describes what was actually applied to THAT run.
5767
+ */
5768
+ appliedPolicies?: string[];
5769
+ }
5770
+ /**
5771
+ * Execute a recipe by spawning a tsx child on the script's .ts file.
5772
+ * `scriptPath` is the absolute path to the saved `.ts` body.
5773
+ */
5774
+ declare function runScript(recipe: ScriptRecipe, scriptPath: string, params: Record<string, any>, options: RunScriptOptions): Promise<ScriptResult>;
5775
+
5776
+ /**
5777
+ * Answer-flow component catalog (§2.6 a/e).
5778
+ *
5779
+ * The frontend sends ONE catalog to the SDK; five consumers read it and four of
5780
+ * them narrow it for their own purpose (dashComp strips the container,
5781
+ * create-filter selects Filter*, suggestions selects isDisplayComp). The answer
5782
+ * flow was the only one that didn't. These helpers are its narrowing.
5783
+ *
5784
+ * Nothing here mutates the stored `Metadata` — dashboard and report generation
5785
+ * legitimately need the SQL-authoring contract that the answer flow must not see,
5786
+ * so the answer flow gets a PROJECTION instead.
5787
+ *
5788
+ * See backend/docs/COMPONENT-GENERATION-V2.md §2.6.
5789
+ */
5790
+
5791
+ /**
5792
+ * The only components that can answer a data question. Everything else in the
5793
+ * catalog belongs to dashboards (filters, forms), is a whole page (Home,
5794
+ * DatabaseOverview), is a UI primitive, or is the wrapper this flow builds.
5795
+ *
5796
+ * DynamicWaterfallChart is deliberately excluded — see §2.6(e). Adding it back
5797
+ * is a one-line change here.
5798
+ */
5799
+ declare const ANSWER_COMPONENT_NAMES: readonly string[];
5800
+ /**
5801
+ * Narrow the registered catalog to the components that can answer a question.
5802
+ * Safe for every answer-flow generator — none of them should ever nominate a
5803
+ * filter widget, a text input, or the MultiComponentContainer the flow itself
5804
+ * builds around their output.
5805
+ */
5806
+ declare function answerComponents(components: Component[] | undefined): Component[];
5807
+ /**
5808
+ * Rewrite the catalog for a flow that binds pre-executed datasets rather than
5809
+ * authoring SQL. Apply ONLY where the flow discards component-authored SQL —
5810
+ * `generateScriptComponents` and the `write_components` tool.
5811
+ *
5812
+ * Do NOT apply to `generateAgentComponents`: that path really does write SQL
5813
+ * into externalTool.parameters.sql and validates it by executing it.
5814
+ */
5815
+ declare function projectForDatasetBinding(components: Component[]): Component[];
5816
+ /** Filter + project in one call — the catalog the tool and script generator see. */
5817
+ declare function answerCatalogForBinding(components: Component[] | undefined): Component[];
5818
+
5819
+ /**
5820
+ * Component Spec Validator — V1–V8
5821
+ *
5822
+ * Deterministic checks of a component spec against the REAL columns of the
5823
+ * dataset it binds. Pure: no LLM, no mutation, no I/O. Shared by the fallback
5824
+ * generator (report-only today) and the `write_components` tool, which hands the
5825
+ * findings back to the agent so it can fix getComponents and retry.
5826
+ *
5827
+ * See backend/docs/COMPONENT-GENERATION-V2.md §2.3.
5828
+ */
5829
+ type ColType = 'NUMBER' | 'TEXT' | 'DATE' | 'BOOLEAN';
5830
+ interface ColInfo {
5831
+ name: string;
5832
+ type: ColType;
5833
+ /** Every sampled non-null value is identical — a per-row invariant (e.g. a
5834
+ * total the script computed the same on every row). Must not be summed. */
5835
+ invariant: boolean;
5836
+ }
5837
+ /** Infer column name + type + invariance from a sample of rows. */
5838
+ declare function inferColumns(rows: any[]): Map<string, ColInfo>;
5839
+ /** Keys that must resolve to a NUMBER column. */
5840
+ declare const NUMERIC_KEYS: readonly ["yAxisKey", "valueKey", "aggregationField", "sizeKey", "latitudeField", "longitudeField", "orderField"];
5841
+ /** Keys that must resolve to a TEXT or DATE column. */
5842
+ declare const CATEGORY_KEYS: readonly ["xAxisKey", "nameKey", "seriesKey", "groupBy", "categoryKey", "dimensionKey", "labelField", "stageField"];
5843
+ /**
5844
+ * Every config key that names a column. Superset of the generator's original
5845
+ * list — it omitted dimensionKey (Radar), sizeKey (Scatter) and the five
5846
+ * MapView geo fields, so those passed through unvalidated. §2.6(d).
5847
+ */
5848
+ declare const ALL_COLUMN_KEYS: string[];
5849
+ type FindingCode = 'V1' | 'V2' | 'V3' | 'V4' | 'V5' | 'V6' | 'V7' | 'V8';
5850
+ interface ValidationFinding {
5851
+ code: FindingCode;
5852
+ /** `error` blocks the spec; `warn` is advisory (logged, never rejects). */
5853
+ severity: 'error' | 'warn';
5854
+ componentType: string;
5855
+ /** Message written FOR THE AGENT — states the problem and the fix. */
5856
+ message: string;
5857
+ }
5858
+ interface SpecToValidate {
5859
+ componentType: string;
5860
+ sourceRef?: string;
5861
+ title?: string;
5862
+ description?: string;
5863
+ content?: string;
5864
+ config?: Record<string, any>;
5865
+ }
5866
+ interface ValidationContext {
5867
+ /** Columns of the bound dataset. */
5868
+ cols: Map<string, ColInfo>;
5869
+ /** UNCAPPED row count of the bound dataset — the cap is applied later, so
5870
+ * validating on the capped count would hide exactly the truncation we check. */
5871
+ rowCount: number;
5872
+ /** Rows for the mark-identity check (V4). Pass every row: a sample that happens
5873
+ * to hold no duplicate would report a collapsing chart as sound. */
5874
+ rows: any[];
5875
+ /** Valid `sourceRef` values for this run. */
5876
+ availableSourceRefs: string[];
5877
+ renderCap?: number;
5878
+ }
5879
+ /**
5880
+ * Validate one component spec. Returns every finding; the caller decides
5881
+ * whether to reject (tool path) or log (fallback path).
5882
+ */
5883
+ declare function validateComponentSpec(spec: SpecToValidate, ctx: ValidationContext): ValidationFinding[];
5884
+ /** Render findings as the text tool-result the agent reads on a rejection. */
5885
+ declare function formatFindingsForAgent(findings: ValidationFinding[]): string;
5886
+
5887
+ type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
5888
+ declare class SuperatomSDK {
5889
+ private ws;
5890
+ private url;
5891
+ private apiKey?;
5892
+ private projectId;
5893
+ private type;
5894
+ private bundleDir;
5895
+ private messageHandlers;
5896
+ private messageTypeHandlers;
5897
+ private connected;
5898
+ private reconnectAttempts;
5899
+ private maxReconnectAttempts;
5900
+ private collections;
5901
+ private components;
5902
+ private tools;
5903
+ private workflows;
5904
+ private anthropicApiKey;
5905
+ private groqApiKey;
2350
5906
  private geminiApiKey;
2351
5907
  private openaiApiKey;
2352
5908
  private llmProviders;
2353
5909
  private databaseType;
2354
5910
  private modelStrategy;
5911
+ private mainAgentModel;
5912
+ private sourceAgentModel;
5913
+ private answerFlow;
5914
+ private answerProvider?;
5915
+ private dashCompModels?;
2355
5916
  private conversationSimilarityThreshold;
2356
5917
  private userManager;
2357
5918
  private dashboardManager;
@@ -2360,6 +5921,8 @@ declare class SuperatomSDK {
2360
5921
  private lastPong;
2361
5922
  private readonly PING_INTERVAL_MS;
2362
5923
  private readonly PONG_TIMEOUT_MS;
5924
+ private pendingOutbox;
5925
+ private readonly MAX_OUTBOX_SIZE;
2363
5926
  constructor(config: SuperatomSDKConfig);
2364
5927
  /**
2365
5928
  * Initialize PromptLoader and load prompts into memory
@@ -2399,9 +5962,25 @@ declare class SuperatomSDK {
2399
5962
  */
2400
5963
  private handleMessage;
2401
5964
  /**
2402
- * Send a message to the Superatom service
5965
+ * Send a message to the Superatom service.
5966
+ * Returns true if the message was sent, false if the WebSocket is not connected.
5967
+ * Does NOT throw on closed connections — callers can check the return value if needed.
5968
+ */
5969
+ send(message: Message): boolean;
5970
+ /**
5971
+ * Queue a message that couldn't be delivered because the socket was down,
5972
+ * to be resent once it reconnects. Drops the oldest entry once the bound is
5973
+ * hit — an outage long enough to fill this queue means the oldest queued
5974
+ * responses are for requests the caller has likely already given up on.
2403
5975
  */
2404
- send(message: Message): void;
5976
+ private queuePendingMessage;
5977
+ /**
5978
+ * Resend everything queued while the socket was down, now that it's back
5979
+ * up. Uses this.ws.send() directly (not send()) so a message that fails
5980
+ * again goes back through queuePendingMessage() rather than being silently
5981
+ * dropped a second time.
5982
+ */
5983
+ private flushPendingOutbox;
2405
5984
  /**
2406
5985
  * Register a message handler to receive all messages
2407
5986
  */
@@ -2441,6 +6020,14 @@ declare class SuperatomSDK {
2441
6020
  */
2442
6021
  private handlePong;
2443
6022
  private storeComponents;
6023
+ /**
6024
+ * The live, frontend-registered component catalog (name, type, description,
6025
+ * and full prop schema per component) — the same authoritative source
6026
+ * DASH_COMP_REQ's LLM prompt is built from. Exposed so other integrations
6027
+ * (e.g. the dashboard-agent script bridge) can read real component
6028
+ * contracts instead of maintaining a separate, driftable hand-written copy.
6029
+ */
6030
+ getComponents(): Component[];
2444
6031
  /**
2445
6032
  * Set tools for the SDK instance
2446
6033
  */
@@ -2449,6 +6036,29 @@ declare class SuperatomSDK {
2449
6036
  * Get the stored tools
2450
6037
  */
2451
6038
  getTools(): Tool$1[];
6039
+ /**
6040
+ * Call a registered collection operation in-process — no WebSocket
6041
+ * round-trip, since the caller is already running inside this same SDK
6042
+ * instance. Lets SDK-internal features (e.g. the dashboard agent) reuse
6043
+ * whatever collection a deployment has already registered (e.g.
6044
+ * 'dashboards'.'query') by name/convention, instead of requiring a
6045
+ * separate callback purely to re-expose data a collection already serves.
6046
+ * Throws if the collection or operation isn't registered.
6047
+ */
6048
+ callCollection<TResult = any>(collectionName: string, operation: string, params?: any): Promise<TResult>;
6049
+ /**
6050
+ * Register workflow components for the SDK instance.
6051
+ *
6052
+ * Workflows are pre-built multi-step UI flows the main agent can pick when
6053
+ * the user's prompt matches a workflow's `whenToUse` trigger. Picking a
6054
+ * workflow short-circuits analysis text + dashboard component generation —
6055
+ * the workflow component is returned directly, with the LLM-extracted props.
6056
+ */
6057
+ setWorkflows(workflows: WorkflowDescriptor[]): void;
6058
+ /**
6059
+ * Get the registered workflow components.
6060
+ */
6061
+ getWorkflows(): WorkflowDescriptor[];
2452
6062
  /**
2453
6063
  * Apply model strategy to all LLM provider singletons
2454
6064
  * @param strategy - 'best', 'fast', or 'balanced'
@@ -2479,4 +6089,4 @@ declare class SuperatomSDK {
2479
6089
  getConversationSimilarityThreshold(): number;
2480
6090
  }
2481
6091
 
2482
- 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, queryCache, rerankChromaResults, rerankConversationResults, userPromptErrorLogger };
6092
+ export { ALL_COLUMN_KEYS, ANSWER_COMPONENT_NAMES, type AgentConfig, type AgentEvent, type AgentResponse, type AgentRunContext, type AgentRunHandlers, type AgentRunRecord, type AgentRunResult, type AgentTrigger, type AgentUsage, type AnswerProvider, type AnswerProviderContext, type ApplySummary, BM25L, type BM25LOptions, type BaseLLMConfig, type BuildTriggerInput, CATEGORY_KEYS, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CodexSessionOptions, type CodingAgentCollectionConfig, type CodingAgentDefinition, type CodingAgentSession, type CodingAgentSessionOptions, type CodingAgentsConfig, type ColInfo, type ColType, type CollectionHandler, type CollectionOperation, type Component, type DBUIBlock, DEFAULT_AGENT_CONFIG, DEFAULT_FMT_CONFIG, type DashboardAgentCollectionConfig, type DatabaseType, type FindingCode, type Fmt, type FmtConfig, type Harness, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, MainAgent, type McpServerSpec, type Message, MissingRequestContextError, type ModelStrategy, NUMERIC_KEYS, type OutputContract, type OutputField, type OutputValidator, type Principal, type RequestContext, type RerankedResult, type RowFilter, type RunAgentOptions, STORAGE_CONFIG, type ScriptComponentSpec, ScriptMatcher, type ScriptParameter, type ScriptRecipe, type ScriptRecipeMetaRow, type ScriptRecipeStore, type ScriptResult, ScriptStore, type ScriptStoreOptions, type SelectedWorkflow, type SourcePolicy, type SpecToValidate, SuperatomSDK, type SuperatomSDKConfig, type T_RESPONSE, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, type ToolOutputSchema, type TriggerEvent, type TriggerFireInfo, UIBlock, UILogCollector, type User, UserManager, type UsersData, type ValidationContext, type ValidationFinding, type WorkflowDescriptor, type Workspace, answerCatalogForBinding, answerComponents, anthropicLLM, assertReadOnlySql, bindContext, captureContext, clearContextTokens, contextTokenCount, createCodexSession, createCodingAgentSession, dashboardConversationHistory, dataFingerprint, describeContext, describeTriggers, emitAgentEvent, extractNamedExport, formatFindingsForAgent, geminiLLM, getCodingAgent, getCodingAgentsConfig, getRequestContext, groqLLM, hybridRerank, inferColumns, isUserContext, listCodingAgents, llmUsageLogger, logger, makeFmt, mintContextToken, normalizeScriptBody, onAgentRun, openaiLLM, policiesFromConfig, projectForDatasetBinding, queryCache, registerCodingAgentCollection, registerCodingAgents, registerDashboardAgentCollection, requireRequestContext, rerankChromaResults, rerankConversationResults, resolveContextToken, resolveScriptRecipeStore, revokeContextToken, runAsSystem, runAsUser, runCodingAgent, runScript, runWithContext, runWithMessageIdentity, startAgentTriggers, stopAgentTriggers, userPromptErrorLogger, validateComponentSpec, withCapturedContext, writeBridgeShims };