@superatomai/sdk-node 0.0.53 → 0.0.54-dsp

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