@superatomai/sdk-node 0.0.56 → 0.0.57-dsp

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