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