@superatomai/sdk-node 0.0.36 → 0.0.37-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/README.md +942 -942
- package/dist/index.d.mts +2635 -62
- package/dist/index.d.ts +2635 -62
- package/dist/index.js +22505 -7826
- package/dist/index.mjs +22506 -7842
- package/dist/userResponse/scripts/script-bootstrap.d.mts +2 -0
- package/dist/userResponse/scripts/script-bootstrap.d.ts +2 -0
- package/dist/userResponse/scripts/script-bootstrap.js +336 -0
- package/dist/userResponse/scripts/script-bootstrap.mjs +334 -0
- package/package.json +10 -6
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,15 +1,846 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import Anthropic from '@anthropic-ai/sdk';
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* StreamBuffer - Buffered streaming utility for smoother text delivery
|
|
6
|
+
* Batches small chunks together and flushes at regular intervals
|
|
7
|
+
*/
|
|
8
|
+
type StreamCallback = (chunk: string) => void;
|
|
9
|
+
/**
|
|
10
|
+
* StreamBuffer class for managing buffered streaming output
|
|
11
|
+
* Provides smooth text delivery by batching small chunks
|
|
12
|
+
*/
|
|
13
|
+
declare class StreamBuffer {
|
|
14
|
+
private buffer;
|
|
15
|
+
private flushTimer;
|
|
16
|
+
private callback;
|
|
17
|
+
private fullText;
|
|
18
|
+
constructor(callback?: StreamCallback);
|
|
19
|
+
/**
|
|
20
|
+
* Check if the buffer has a callback configured
|
|
21
|
+
*/
|
|
22
|
+
hasCallback(): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Get all text that has been written (including already flushed)
|
|
25
|
+
*/
|
|
26
|
+
getFullText(): string;
|
|
27
|
+
/**
|
|
28
|
+
* Write a chunk to the buffer
|
|
29
|
+
* Large chunks or chunks with newlines are flushed immediately
|
|
30
|
+
* Small chunks are batched and flushed after a short interval
|
|
31
|
+
*
|
|
32
|
+
* @param chunk - Text chunk to write
|
|
33
|
+
*/
|
|
34
|
+
write(chunk: string): void;
|
|
35
|
+
/**
|
|
36
|
+
* Flush the buffer immediately
|
|
37
|
+
* Call this before tool execution or other operations that need clean output
|
|
38
|
+
*/
|
|
39
|
+
flush(): void;
|
|
40
|
+
/**
|
|
41
|
+
* Internal flush implementation
|
|
42
|
+
*/
|
|
43
|
+
private flushNow;
|
|
44
|
+
/**
|
|
45
|
+
* Clean up resources
|
|
46
|
+
* Call this when done with the buffer
|
|
47
|
+
*/
|
|
48
|
+
dispose(): void;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* ToolExecutorService - Handles execution of SQL queries and external tools
|
|
53
|
+
* Extracted from BaseLLM.generateTextResponse for better separation of concerns
|
|
54
|
+
*/
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* External tool definition
|
|
58
|
+
*/
|
|
59
|
+
interface ExternalTool {
|
|
60
|
+
id: string;
|
|
61
|
+
name: string;
|
|
62
|
+
description?: string;
|
|
63
|
+
/** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
|
|
64
|
+
toolType?: 'source' | 'direct';
|
|
65
|
+
/** Full untruncated schema for source agent (all columns visible) */
|
|
66
|
+
fullSchema?: string;
|
|
67
|
+
/** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
|
|
68
|
+
schemaTier?: string;
|
|
69
|
+
/** Schema search function for very_large tier — keyword search over entities */
|
|
70
|
+
schemaSearchFn?: (keywords: string[]) => string;
|
|
71
|
+
fn: (input: any) => Promise<any>;
|
|
72
|
+
limit?: number;
|
|
73
|
+
outputSchema?: any;
|
|
74
|
+
executionType?: 'immediate' | 'deferred';
|
|
75
|
+
userProvidedData?: any;
|
|
76
|
+
params?: Record<string, any>;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Executed tool tracking info
|
|
80
|
+
*/
|
|
81
|
+
interface ExecutedToolInfo {
|
|
82
|
+
id: string;
|
|
83
|
+
name: string;
|
|
84
|
+
params: any;
|
|
85
|
+
result: {
|
|
86
|
+
_totalRecords: number;
|
|
87
|
+
_recordsShown: number;
|
|
88
|
+
_metadata?: any;
|
|
89
|
+
_sampleData: any[];
|
|
90
|
+
/** Bounded summary over the FULL fetched result (complete structure). */
|
|
91
|
+
_summary?: any;
|
|
92
|
+
/** Up to MAIN_AGENT_COMPLETE_ROWS rows — the complete result when small. */
|
|
93
|
+
_mainAgentRows?: any[];
|
|
94
|
+
};
|
|
95
|
+
outputSchema?: any;
|
|
96
|
+
sourceSchema?: string;
|
|
97
|
+
sourceType?: string;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Script Flow Types
|
|
102
|
+
*
|
|
103
|
+
* Defines interfaces for the script-based query architecture:
|
|
104
|
+
* - ScriptRecipe: metadata for matching, validation, and quality tracking
|
|
105
|
+
* - ScriptResult: output from executing a script
|
|
106
|
+
* - ScriptMatch: result from the LLM-based script matcher
|
|
107
|
+
*/
|
|
108
|
+
/**
|
|
109
|
+
* Recipe metadata stored alongside each script.
|
|
110
|
+
* Used for matching, validation, and quality tracking.
|
|
111
|
+
*/
|
|
112
|
+
interface ScriptRecipe {
|
|
113
|
+
/** Unique script identifier */
|
|
114
|
+
id: string;
|
|
115
|
+
/** Version number (incremented on regeneration) */
|
|
116
|
+
version: number;
|
|
117
|
+
/** Human-readable name (e.g., "Revenue by Dimension") */
|
|
118
|
+
name: string;
|
|
119
|
+
/** Natural language description of what this script does */
|
|
120
|
+
intentDescription: string;
|
|
121
|
+
/** Keyword tags for quick filtering */
|
|
122
|
+
tags: string[];
|
|
123
|
+
/** Source tool IDs this script queries (e.g., ["mssql-abc123_query"]) */
|
|
124
|
+
sourceIds: string[];
|
|
125
|
+
/** Table names used (for future schema drift detection) */
|
|
126
|
+
tables: string[];
|
|
127
|
+
/** Parameter definitions — what can vary */
|
|
128
|
+
parameters: ScriptParameter[];
|
|
129
|
+
/** The script function body as a string. Loaded from disk (scripts-store/<fileBase>.ts). */
|
|
130
|
+
scriptBody: string;
|
|
131
|
+
/**
|
|
132
|
+
* On-disk filename stem for the body: scripts-store/<fileBase>.ts.
|
|
133
|
+
* Editable in the IDE. Decided at authoring time (slug of `name`, with a
|
|
134
|
+
* short id suffix on collision) and stable across promotion.
|
|
135
|
+
*/
|
|
136
|
+
fileBase?: string;
|
|
137
|
+
/** sha256 of the on-disk body — lets the runtime detect manual edits. */
|
|
138
|
+
bodyHash?: string;
|
|
139
|
+
/** Project scope (single-VM deployments may leave this undefined). */
|
|
140
|
+
projectId?: string;
|
|
141
|
+
/** Times this script was used successfully */
|
|
142
|
+
successCount: number;
|
|
143
|
+
/** Times this script failed */
|
|
144
|
+
failureCount: number;
|
|
145
|
+
/** ISO timestamp of last usage */
|
|
146
|
+
lastUsed: string;
|
|
147
|
+
/** Original user question that created this script */
|
|
148
|
+
createdFrom: string;
|
|
149
|
+
/** ISO timestamp */
|
|
150
|
+
createdAt: string;
|
|
151
|
+
/** ISO timestamp */
|
|
152
|
+
updatedAt: string;
|
|
153
|
+
/**
|
|
154
|
+
* `recipe.id` of the parent this script was forked from.
|
|
155
|
+
* Undefined for root scripts (those written from scratch by MainAgent).
|
|
156
|
+
* See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md.
|
|
157
|
+
*/
|
|
158
|
+
parentId?: string;
|
|
159
|
+
/** 0 for root scripts; `parent.forkDepth + 1` for forks. Capped at 3. */
|
|
160
|
+
forkDepth?: number;
|
|
161
|
+
/**
|
|
162
|
+
* Brief description of what this fork changed vs its parent
|
|
163
|
+
* (sourced from the matcher's `modificationHint`).
|
|
164
|
+
*/
|
|
165
|
+
forkReason?: string;
|
|
166
|
+
/**
|
|
167
|
+
* Validated component specs captured at authoring time. On a tier-high
|
|
168
|
+
* replay these are rebound to fresh queryIds deterministically — no
|
|
169
|
+
* component-generation LLM call, and the rendered columns can't drift from
|
|
170
|
+
* what was validated when the script was authored. Absent on recipes
|
|
171
|
+
* authored before this landed; those fall back to LLM component generation.
|
|
172
|
+
* See backend/docs/SCRIPT-COMPONENT-CONSISTENCY.md.
|
|
173
|
+
*/
|
|
174
|
+
components?: ScriptComponentSpec[];
|
|
175
|
+
/**
|
|
176
|
+
* What the user explicitly asked the output to LOOK like, set by a display
|
|
177
|
+
* edit ("show that as a bar chart", "make the bars horizontal").
|
|
178
|
+
*
|
|
179
|
+
* Deliberately SEPARATE from `components`. Those are validated bindings that
|
|
180
|
+
* must be cleared on a data edit — after "break it down by brand" the axis
|
|
181
|
+
* keys are wrong, and after "use the mode" the stored title still says
|
|
182
|
+
* "Average…". A rendering CHOICE, by contrast, is still valid afterwards.
|
|
183
|
+
* Keeping them in one field meant every data edit silently discarded the
|
|
184
|
+
* user's chart type.
|
|
185
|
+
*
|
|
186
|
+
* Fed to the component generator as a hint whenever specs are (re)generated,
|
|
187
|
+
* so the chosen rendering comes back even after the SQL changes.
|
|
188
|
+
*/
|
|
189
|
+
displayPreference?: ScriptDisplayPreference;
|
|
190
|
+
/**
|
|
191
|
+
* Lifecycle stage of this recipe on disk.
|
|
192
|
+
* - 'draft': written by MainAgent's write_script during a turn; filtered out
|
|
193
|
+
* of FTS results (status='verified' only) so the matcher never picks it.
|
|
194
|
+
* Filename is suffixed with `turnId` to keep concurrent turns
|
|
195
|
+
* from clobbering each other's drafts.
|
|
196
|
+
* - 'verified': promoted after `execute_script` succeeded; the matcher sees it.
|
|
197
|
+
* Filename drops the turn suffix unless a verified file with
|
|
198
|
+
* the same slug already exists (collision case keeps the suffix).
|
|
199
|
+
*
|
|
200
|
+
* Recipes loaded from disk without this field default to 'verified' so
|
|
201
|
+
* existing scripts keep working unchanged.
|
|
202
|
+
*/
|
|
203
|
+
status?: 'draft' | 'verified';
|
|
204
|
+
/**
|
|
205
|
+
* Per-turn unique suffix used for draft filenames (e.g. `1714745623-x9k2`).
|
|
206
|
+
* Set when the draft is saved; carried until the recipe is promoted.
|
|
207
|
+
*/
|
|
208
|
+
turnId?: string;
|
|
209
|
+
/**
|
|
210
|
+
* Last execution error captured by `recordDraftError` while the recipe was
|
|
211
|
+
* still a draft. Lets users open the draft .json file and see why it failed
|
|
212
|
+
* without grepping logs. Cleared on promotion to 'verified'.
|
|
213
|
+
*/
|
|
214
|
+
lastError?: {
|
|
215
|
+
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
216
|
+
message: string;
|
|
217
|
+
at: string;
|
|
218
|
+
attempt: number;
|
|
219
|
+
};
|
|
220
|
+
/** userId who committed the most recent edit (audit trail — recipes are project-scoped). */
|
|
221
|
+
editedBy?: string;
|
|
222
|
+
/** The instruction that produced the current version. */
|
|
223
|
+
editedFrom?: string;
|
|
224
|
+
/**
|
|
225
|
+
* Prior versions, newest last. The body itself is archived on disk as
|
|
226
|
+
* `<fileBase>.v<version>.ts`; this records what changed and who did it.
|
|
227
|
+
*/
|
|
228
|
+
history?: ScriptVersionRecord[];
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* A durable, user-stated rendering choice for a recipe. Survives data edits.
|
|
232
|
+
*/
|
|
233
|
+
interface ScriptDisplayPreference {
|
|
234
|
+
/** Component types the user's chosen rendering resolved to, e.g. ["DynamicBarChart"]. */
|
|
235
|
+
componentTypes: string[];
|
|
236
|
+
/** The instruction itself — carries nuance the types can't ("horizontal", "sorted descending"). */
|
|
237
|
+
instruction: string;
|
|
238
|
+
/** ISO timestamp of the display edit that set this. */
|
|
239
|
+
at: string;
|
|
240
|
+
}
|
|
241
|
+
/** One superseded version of a recipe body (see ScriptStore.commitEdit). */
|
|
242
|
+
interface ScriptVersionRecord {
|
|
243
|
+
/** Version number this record superseded (i.e. the OLD version). */
|
|
244
|
+
version: number;
|
|
245
|
+
/** ISO timestamp of the edit that superseded it. */
|
|
246
|
+
at: string;
|
|
247
|
+
/** userId who made the edit, when known. */
|
|
248
|
+
by?: string;
|
|
249
|
+
/** The edit instruction that caused the supersede. */
|
|
250
|
+
instruction?: string;
|
|
251
|
+
/** One-line summary of what changed, for the version picker. */
|
|
252
|
+
changeSummary?: string;
|
|
253
|
+
/** sha256 of the superseded body — pairs with `<fileBase>.v<version>.ts`. */
|
|
254
|
+
bodyHash?: string;
|
|
255
|
+
}
|
|
256
|
+
interface ScriptParameter {
|
|
257
|
+
/** Parameter name (used in script body as params.name) */
|
|
258
|
+
name: string;
|
|
259
|
+
/** Parameter type */
|
|
260
|
+
type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
|
|
261
|
+
/** Whether this parameter is required */
|
|
262
|
+
required: boolean;
|
|
263
|
+
/** Default value if not provided */
|
|
264
|
+
default?: any;
|
|
265
|
+
/** For enum type — maps user-facing values to internal values */
|
|
266
|
+
enumValues?: Record<string, string>;
|
|
267
|
+
/** Human-readable description (used in the matcher LLM prompt) */
|
|
268
|
+
description: string;
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* A reusable component binding captured when a script is authored. Stored on
|
|
272
|
+
* the recipe so tier-high replays rebuild components deterministically (rebind
|
|
273
|
+
* to fresh queryIds) instead of re-running the component-picker LLM.
|
|
274
|
+
*/
|
|
275
|
+
interface ScriptComponentSpec {
|
|
276
|
+
/** Registered component name (e.g. "DynamicBarChart") — matched against the available component library. */
|
|
277
|
+
componentType: string;
|
|
278
|
+
/** `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). */
|
|
279
|
+
sourceRef: string;
|
|
280
|
+
/** Present only when sourceRef === 'federation' — the DuckDB SQL to re-execute on replay. */
|
|
281
|
+
federationSql?: string;
|
|
282
|
+
/** Present only when sourceRef === 'markdown' — the narrative text to render on replay (markdown has no data source, so its content must be persisted). */
|
|
283
|
+
content?: string;
|
|
284
|
+
title?: string;
|
|
285
|
+
description?: string;
|
|
286
|
+
/** Validated axis/value keys + aggregation — all referencing real columns of the bound source. */
|
|
287
|
+
config: Record<string, any>;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Result from executing a script via ScriptRunner.
|
|
291
|
+
*/
|
|
292
|
+
interface ScriptResult {
|
|
293
|
+
/** Whether the script executed successfully */
|
|
294
|
+
success: boolean;
|
|
295
|
+
/** Combined data from all queries */
|
|
296
|
+
data: any[];
|
|
297
|
+
/** Individual query results tracked during execution */
|
|
298
|
+
executedQueries: ScriptQueryResult[];
|
|
299
|
+
/** Error message if failed */
|
|
300
|
+
error?: string;
|
|
301
|
+
/**
|
|
302
|
+
* Where in the lifecycle the error occurred. Lets MainAgent's fix-loop
|
|
303
|
+
* decide between "rewrite the whole draft" (compile) and "patch the
|
|
304
|
+
* specific line" (runtime).
|
|
305
|
+
*/
|
|
306
|
+
errorPhase?: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
307
|
+
/** Total execution time in milliseconds */
|
|
308
|
+
executionTimeMs: number;
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* A single query executed during script runtime.
|
|
312
|
+
* Tracked by ScriptContext for component generation and debugging.
|
|
313
|
+
*/
|
|
314
|
+
interface ScriptQueryResult {
|
|
315
|
+
/** Source tool ID */
|
|
316
|
+
sourceId: string;
|
|
317
|
+
/** Human-readable source name */
|
|
318
|
+
sourceName: string;
|
|
319
|
+
/** The SQL that was executed */
|
|
320
|
+
sql: string;
|
|
321
|
+
/** Result data rows */
|
|
322
|
+
data: any[];
|
|
323
|
+
/** Number of rows returned */
|
|
324
|
+
count: number;
|
|
325
|
+
/** Total rows that matched before limit (if available) */
|
|
326
|
+
totalCount?: number;
|
|
327
|
+
/** Query execution time in milliseconds */
|
|
328
|
+
executionTimeMs: number;
|
|
329
|
+
/**
|
|
330
|
+
* True for rows that did NOT come from a real SQL execution — either a
|
|
331
|
+
* ctx.emit() dataset or the synthesized "computed:_final" entry that
|
|
332
|
+
* carries the script's post-JS returned data. The component generator
|
|
333
|
+
* uses this to route the resulting component through the script_dataset
|
|
334
|
+
* sentinel toolId so the frontend resolves it via the queryCache short-circuit.
|
|
335
|
+
*/
|
|
336
|
+
virtual?: boolean;
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Match tier returned by the LLM script matcher.
|
|
340
|
+
*
|
|
341
|
+
* - 'high': the script answers the question directly; only parameter values
|
|
342
|
+
* may differ. The runtime replays it with extracted params (cheapest path).
|
|
343
|
+
* - 'near': the script answers a STRUCTURALLY similar question but needs
|
|
344
|
+
* body modification (different metric, dimension, table, filter shape).
|
|
345
|
+
* The runtime forks the parent and adapts the body via MainAgent's normal
|
|
346
|
+
* write_script + execute_script loop — no SourceAgent dispatch needed.
|
|
347
|
+
* See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md for the full design.
|
|
348
|
+
* - 'edit': the user is INSTRUCTING a change to the script that produced the
|
|
349
|
+
* previous answer (not asking a new question). Only reachable when the turn
|
|
350
|
+
* carries a ScriptBinding — without one the matcher coerces it to 'none', so
|
|
351
|
+
* a prompt regression can't turn this into a loose similarity path. The
|
|
352
|
+
* runtime runs MainAgent in edit mode and commits the result in place.
|
|
353
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md.
|
|
354
|
+
* - 'none': no script is relevant; full agent flow runs.
|
|
355
|
+
*/
|
|
356
|
+
type MatchTier = 'high' | 'near' | 'edit' | 'none';
|
|
357
|
+
/**
|
|
358
|
+
* Which recipe produced the answer the user is currently looking at.
|
|
359
|
+
*
|
|
360
|
+
* Set whenever a turn's answer came from a script (replay, fresh authoring, or
|
|
361
|
+
* a committed edit) and carried on the UIBlock + saved conversation row. Two
|
|
362
|
+
* consumers:
|
|
363
|
+
* 1. The matcher — the 'edit' tier is ONLY reachable when a binding exists, so
|
|
364
|
+
* "use mode instead of mean" resolves to a concrete script instead of being
|
|
365
|
+
* matched on keywords it shares with no script name.
|
|
366
|
+
* 2. Cache invalidation — after an edit commits, conversations bound to that
|
|
367
|
+
* recipeId must be dropped, or the exact-match cache replays the pre-edit
|
|
368
|
+
* answer and the edit looks like a no-op.
|
|
369
|
+
*
|
|
370
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
371
|
+
*/
|
|
372
|
+
interface ScriptBinding {
|
|
373
|
+
recipeId: string;
|
|
374
|
+
/** Params the script ran with — the edit's starting point. */
|
|
375
|
+
params: Record<string, any>;
|
|
376
|
+
/** Recipe name at bind time (matcher catalog + user-facing confirmation). */
|
|
377
|
+
name: string;
|
|
378
|
+
/** Columns the last run returned — grounds the editor without a re-query. */
|
|
379
|
+
columns?: string[];
|
|
380
|
+
/**
|
|
381
|
+
* The question that produced this answer. Required for disambiguation when a
|
|
382
|
+
* thread ran several scripts — without it the candidates are just names and
|
|
383
|
+
* the matcher cannot resolve "use the mode for the WSP one".
|
|
384
|
+
*/
|
|
385
|
+
userPrompt?: string;
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Result from the LLM-based script matcher.
|
|
389
|
+
*
|
|
390
|
+
* For `tier: 'high'`, `extractedParams` carries the values to pass to the
|
|
391
|
+
* existing script. For `tier: 'near'`, `gaps` and `modificationHint` describe
|
|
392
|
+
* what the fork-author needs to change in the parent body.
|
|
393
|
+
*/
|
|
394
|
+
interface ScriptMatch {
|
|
395
|
+
/** The matched script recipe */
|
|
396
|
+
recipe: ScriptRecipe;
|
|
397
|
+
/** Match tier — see MatchTier docs */
|
|
398
|
+
tier: MatchTier;
|
|
399
|
+
/** Similarity score (0-1, derived from LLM tier) */
|
|
400
|
+
similarity: number;
|
|
401
|
+
/**
|
|
402
|
+
* Legacy confidence level. Mirrors `tier === 'high'`/`'near'` for now;
|
|
403
|
+
* kept so existing callers compile while we migrate to tier-based logic.
|
|
404
|
+
*/
|
|
405
|
+
confidence: 'high' | 'medium';
|
|
406
|
+
/** Parameters extracted from the user question by the LLM (tier='high') */
|
|
407
|
+
extractedParams?: Record<string, any>;
|
|
408
|
+
/**
|
|
409
|
+
* Proper nouns the question named, VERBATIM, with the parameter each fills.
|
|
410
|
+
*
|
|
411
|
+
* The matcher must NOT resolve these itself. Observed live: it substituted the
|
|
412
|
+
* customer name "PREMER ENRGES PHOTOOTAIC" into an id parameter believing that
|
|
413
|
+
* "the runtime will resolve the customer name to its PartyId(s)" — nothing on
|
|
414
|
+
* the replay path does, and `WHERE BillingPartyId IN (PREMER ENRGES
|
|
415
|
+
* PHOTOOTAIC)` reached SQL. Reported here, the runtime resolves them before
|
|
416
|
+
* replay and rejects the match when one cannot be resolved.
|
|
417
|
+
*/
|
|
418
|
+
mentions?: Array<{
|
|
419
|
+
text: string;
|
|
420
|
+
param?: string;
|
|
421
|
+
}>;
|
|
422
|
+
/** Business concepts the question relies on (e.g. "outstanding balance"). */
|
|
423
|
+
entityTypes?: string[];
|
|
424
|
+
/** What the user question needs that the parent doesn't cover (tier='near') */
|
|
425
|
+
gaps?: string[];
|
|
426
|
+
/** One-sentence description of the change the fork-author should make (tier='near') */
|
|
427
|
+
modificationHint?: string;
|
|
428
|
+
/**
|
|
429
|
+
* Which HALF of the recipe the edit targets (tier='edit'). A recipe has two
|
|
430
|
+
* independently editable halves:
|
|
431
|
+
* - 'data' — the scriptBody: how the rows are produced (aggregation,
|
|
432
|
+
* filters, joins, grouping). Runs MainAgent in edit mode.
|
|
433
|
+
* - 'display' — the component specs: how those SAME rows are shown (chart
|
|
434
|
+
* type, orientation, columns, labels). Replays the proven SQL
|
|
435
|
+
* and regenerates the specs — never authors a script.
|
|
436
|
+
* Defaults to 'data' when the matcher omits it.
|
|
437
|
+
*/
|
|
438
|
+
editTarget?: 'data' | 'display';
|
|
439
|
+
/**
|
|
440
|
+
* Self-contained restatement of the change the user asked for (tier='edit').
|
|
441
|
+
* MUST have pronouns/deixis resolved ("this", "it", "that column") — the edit
|
|
442
|
+
* prompt never sees the conversation history, so an unresolved instruction is
|
|
443
|
+
* unusable downstream.
|
|
444
|
+
*/
|
|
445
|
+
editInstruction?: string;
|
|
446
|
+
/** Why the matcher made this choice (for logs and telemetry) */
|
|
447
|
+
reasoning?: string;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Multi-Agent Architecture Types
|
|
452
|
+
*
|
|
453
|
+
* Defines interfaces for the hierarchical agent system:
|
|
454
|
+
* - Main Agent: ONE LLM.streamWithTools() call with source agent tools
|
|
455
|
+
* - Source Agents: independent agents that query individual data sources
|
|
456
|
+
*
|
|
457
|
+
* The main agent sees only source summaries. When it calls a source tool,
|
|
458
|
+
* the SourceAgent runs independently (own LLM, own retries) and returns clean data.
|
|
459
|
+
*/
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Per-entity detail: name, row count, and column names.
|
|
463
|
+
* Gives the main agent enough context to route to the right source.
|
|
464
|
+
*/
|
|
465
|
+
interface EntityDetail {
|
|
466
|
+
/** Entity name (table, sheet, endpoint) */
|
|
467
|
+
name: string;
|
|
468
|
+
/** Approximate row count */
|
|
469
|
+
rowCount?: number;
|
|
470
|
+
/** Column/field names */
|
|
471
|
+
columns: string[];
|
|
472
|
+
/** Entity-level semantic summary (what the table means) — for main-agent routing. */
|
|
473
|
+
summary?: string;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Representation of a data source for the main agent.
|
|
477
|
+
* Contains entity names WITH column names so the LLM can route accurately.
|
|
478
|
+
*/
|
|
479
|
+
interface SourceSummary {
|
|
480
|
+
/** Source ID (matches tool ID prefix) */
|
|
481
|
+
id: string;
|
|
482
|
+
/** Human-readable source name */
|
|
483
|
+
name: string;
|
|
484
|
+
/** Source type: postgres, excel, rest_api, etc. */
|
|
485
|
+
type: string;
|
|
486
|
+
/** Brief description of what data this source contains */
|
|
487
|
+
description: string;
|
|
488
|
+
/** Detailed entity info with column names for routing */
|
|
489
|
+
entityDetails: EntityDetail[];
|
|
490
|
+
/** The tool ID associated with this source */
|
|
491
|
+
toolId: string;
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* What a source agent returns after querying its data source.
|
|
495
|
+
* The main agent uses this to analyze and compose the final response.
|
|
496
|
+
*/
|
|
497
|
+
interface SourceAgentResult {
|
|
498
|
+
/** Source ID */
|
|
499
|
+
sourceId: string;
|
|
500
|
+
/** Source name */
|
|
501
|
+
sourceName: string;
|
|
502
|
+
/** Whether the query succeeded */
|
|
503
|
+
success: boolean;
|
|
504
|
+
/** Result data rows */
|
|
505
|
+
data: any[];
|
|
506
|
+
/** Metadata about the query execution */
|
|
507
|
+
metadata: SourceAgentMetadata;
|
|
508
|
+
/** Tool execution info for the last successful query (backward compat) */
|
|
509
|
+
executedTool: ExecutedToolInfo;
|
|
510
|
+
/** All successful tool executions (primary + follow-up queries) */
|
|
511
|
+
allExecutedTools?: ExecutedToolInfo[];
|
|
512
|
+
/** Error message if failed */
|
|
513
|
+
error?: string;
|
|
514
|
+
}
|
|
515
|
+
interface SourceAgentMetadata {
|
|
516
|
+
/** Total rows that matched the query (before limit) */
|
|
517
|
+
totalRowsMatched: number;
|
|
518
|
+
/** Rows actually returned (after limit) */
|
|
519
|
+
rowsReturned: number;
|
|
520
|
+
/** Whether the result was truncated by the row limit */
|
|
521
|
+
isLimited: boolean;
|
|
522
|
+
/** The query/params that were executed */
|
|
523
|
+
queryExecuted?: string;
|
|
524
|
+
/** Execution time in milliseconds */
|
|
525
|
+
executionTimeMs: number;
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* A pre-built, multi-step UI flow registered with the SDK.
|
|
529
|
+
*
|
|
530
|
+
* When the main agent decides a user's question matches a workflow's whenToUse
|
|
531
|
+
* trigger, it picks the workflow instead of running source agents / generating
|
|
532
|
+
* dashboard components. The LLM extracts the workflow's required props from the
|
|
533
|
+
* prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
|
|
534
|
+
* workflow component directly — no analysis text, no chart generation. The
|
|
535
|
+
* frontend renders the registered workflow component with the LLM-extracted
|
|
536
|
+
* props.
|
|
537
|
+
*/
|
|
538
|
+
interface WorkflowDescriptor {
|
|
539
|
+
/** Unique workflow id (used as the LLM tool name) */
|
|
540
|
+
id: string;
|
|
541
|
+
/** Component name on the frontend (matches the registered React component) */
|
|
542
|
+
name: string;
|
|
543
|
+
/** Short human-readable description of what this workflow does */
|
|
544
|
+
description: string;
|
|
545
|
+
/**
|
|
546
|
+
* 1–2 sentence trigger condition. The LLM uses this to decide if the
|
|
547
|
+
* user's prompt matches this workflow. Be specific — e.g.
|
|
548
|
+
* "User wants to *initiate* an inventory transfer (review + submit POs),
|
|
549
|
+
* not just see analysis or charts."
|
|
550
|
+
*/
|
|
551
|
+
whenToUse: string;
|
|
552
|
+
/**
|
|
553
|
+
* JSON-schema-style description of the props the workflow needs. Becomes
|
|
554
|
+
* the LLM tool's input_schema, so the model fills these from the prompt.
|
|
555
|
+
* Use the same shape as `params` on direct tools — string descriptors with
|
|
556
|
+
* an optional "(optional)" suffix.
|
|
557
|
+
*
|
|
558
|
+
* Example:
|
|
559
|
+
* ```
|
|
560
|
+
* {
|
|
561
|
+
* selectedStore: 'object — { id, name } of the source branch',
|
|
562
|
+
* minROI: 'number (optional) — only show transfers with ROI ≥ this',
|
|
563
|
+
* }
|
|
564
|
+
* ```
|
|
565
|
+
*/
|
|
566
|
+
propsSchema: Record<string, string>;
|
|
567
|
+
/**
|
|
568
|
+
* Optional: static prop defaults merged with LLM-extracted props before
|
|
569
|
+
* the component is returned. Useful for things like the embedded
|
|
570
|
+
* `externalTool` config that the workflow uses to fetch its own data.
|
|
571
|
+
*/
|
|
572
|
+
defaultProps?: Record<string, any>;
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* The workflow selection captured during a routing call.
|
|
576
|
+
* Set on AgentResponse when the LLM picks a workflow tool.
|
|
577
|
+
*/
|
|
578
|
+
interface SelectedWorkflow {
|
|
579
|
+
/** Component name (matches WorkflowDescriptor.name) */
|
|
580
|
+
name: string;
|
|
581
|
+
/** Props extracted from the prompt + merged with workflow.defaultProps */
|
|
582
|
+
props: Record<string, any>;
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* Set when this turn applies a user-directed edit to an existing script instead
|
|
586
|
+
* of authoring a new one. MainAgent keeps the SAME harness (tools, loop,
|
|
587
|
+
* write_script/execute_script verification) and swaps only the system prompt —
|
|
588
|
+
* `agent-main-edit` instead of `agent-main`.
|
|
589
|
+
*
|
|
590
|
+
* The two framings contradict each other on whether to query a source first, so
|
|
591
|
+
* they must never be resident in one rendered prompt.
|
|
592
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § D3.
|
|
593
|
+
*/
|
|
594
|
+
interface EditContext {
|
|
595
|
+
/** Recipe being edited — the shadow draft records it as parentId. */
|
|
596
|
+
recipeId: string;
|
|
597
|
+
parentName: string;
|
|
598
|
+
parentBody: string;
|
|
599
|
+
/** Self-contained restatement of the change (from the matcher). */
|
|
600
|
+
instruction: string;
|
|
601
|
+
/** Columns the last run returned — grounds the edit without a re-query. */
|
|
602
|
+
lastResultColumns?: string[];
|
|
603
|
+
/** Rendered parameter list of the parent, for the prompt. */
|
|
604
|
+
parentParams?: string;
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* The complete response from the multi-agent system.
|
|
608
|
+
* Contains everything needed for text display + component generation.
|
|
609
|
+
*/
|
|
610
|
+
interface AgentResponse {
|
|
611
|
+
/** Generated text response (analysis of the data) */
|
|
612
|
+
text: string;
|
|
613
|
+
/** All executed tools across all source agents (for component generation) */
|
|
614
|
+
executedTools: ExecutedToolInfo[];
|
|
615
|
+
/** Individual results from each source agent */
|
|
616
|
+
sourceResults: SourceAgentResult[];
|
|
617
|
+
/**
|
|
618
|
+
* Populated when MainAgent wrote AND successfully executed a script during its turn.
|
|
619
|
+
* Caller (agent-user-response.ts) persists it via ScriptStore.save().
|
|
620
|
+
* Absent when MainAgent didn't write one (trivial question / all attempts failed).
|
|
621
|
+
*/
|
|
622
|
+
savedScript?: AgentWrittenScript;
|
|
623
|
+
/**
|
|
624
|
+
* Set when the LLM routed the question to a registered workflow component.
|
|
625
|
+
* When present, the upstream caller should skip component generation and
|
|
626
|
+
* return this workflow as the response.
|
|
627
|
+
*/
|
|
628
|
+
workflow?: SelectedWorkflow;
|
|
629
|
+
/**
|
|
630
|
+
* Validated component specs the agent authored via `render_components`.
|
|
631
|
+
* When present the caller assembles the dashboard from these instead of
|
|
632
|
+
* running the component-generation LLM. Absent when the agent didn't call
|
|
633
|
+
* the tool — the caller then falls back to `generateScriptComponents`.
|
|
634
|
+
* See backend/docs/COMPONENT-GENERATION-V2.md §2.2.
|
|
635
|
+
*/
|
|
636
|
+
componentSpecs?: ScriptComponentSpec[];
|
|
637
|
+
/** Layout title/description from the same `render_components` call. */
|
|
638
|
+
componentLayout?: {
|
|
639
|
+
title: string;
|
|
640
|
+
description?: string;
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* A script MainAgent authored + verified during its turn. Shape aligns with
|
|
645
|
+
* what ScriptStore.save() needs — minus store-assigned fields (id, timestamps, counts).
|
|
646
|
+
*/
|
|
647
|
+
interface AgentWrittenScript {
|
|
648
|
+
/**
|
|
649
|
+
* `ScriptRecipe.id` of the draft that was authored + verified during this turn.
|
|
650
|
+
* The caller passes this to `ScriptStore.promoteToVerified(recipeId, …)` to
|
|
651
|
+
* flip the draft to verified status and (when possible) drop the turn-suffix
|
|
652
|
+
* from its filename.
|
|
653
|
+
*/
|
|
654
|
+
recipeId: string;
|
|
655
|
+
name: string;
|
|
656
|
+
intentDescription: string;
|
|
657
|
+
tags: string[];
|
|
658
|
+
parameters: Array<{
|
|
659
|
+
name: string;
|
|
660
|
+
type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
|
|
661
|
+
required: boolean;
|
|
662
|
+
default?: any;
|
|
663
|
+
enumValues?: Record<string, string>;
|
|
664
|
+
description: string;
|
|
665
|
+
}>;
|
|
666
|
+
scriptBody: string;
|
|
667
|
+
/** Source IDs referenced by the script (extracted from ctx.query calls) */
|
|
668
|
+
sourceIds: string[];
|
|
669
|
+
/** Tables referenced in the script's SQL (regex-extracted) */
|
|
670
|
+
tables: string[];
|
|
671
|
+
/** Executed queries from the verified run — fed to component generation */
|
|
672
|
+
executedQueries: Array<{
|
|
673
|
+
sourceId: string;
|
|
674
|
+
sourceName: string;
|
|
675
|
+
sql: string;
|
|
676
|
+
data: any[];
|
|
677
|
+
count: number;
|
|
678
|
+
totalCount?: number;
|
|
679
|
+
executionTimeMs: number;
|
|
680
|
+
/**
|
|
681
|
+
* True for synthetic entries (ctx.emit datasets, the computed:_final
|
|
682
|
+
* post-JS data). The component generator routes virtual sources through
|
|
683
|
+
* the script_dataset sentinel toolId so the frontend resolves them via
|
|
684
|
+
* queryCache instead of attempting to re-execute SQL.
|
|
685
|
+
*/
|
|
686
|
+
virtual?: boolean;
|
|
687
|
+
}>;
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Debug trace for a single chat_agent turn — which KB/schema nodes were
|
|
691
|
+
* retrieved and considered, and which script (if any) produced the answer.
|
|
692
|
+
* Persisted separately from the answer itself (fusion-5's
|
|
693
|
+
* `conversation_traces` table, written via `saveTrace`), never sent through
|
|
694
|
+
* `analyticsClient` (data-residency — see design doc §5).
|
|
695
|
+
*/
|
|
696
|
+
interface RunTrace {
|
|
697
|
+
version: 1;
|
|
698
|
+
kbNodes: {
|
|
699
|
+
/**
|
|
700
|
+
* Always-on nodes included regardless of the question (getGlobalKnowledgeBase).
|
|
701
|
+
* `content` is the node's full text AS IT WAS at retrieval time — captured so a
|
|
702
|
+
* later edit/delete of the KB node doesn't erase what the LLM actually saw.
|
|
703
|
+
*/
|
|
704
|
+
global: Array<{
|
|
705
|
+
kbId: string;
|
|
706
|
+
title: string;
|
|
707
|
+
content?: string;
|
|
708
|
+
}>;
|
|
709
|
+
/** Semantically matched for this specific question (getKnowledgeBase). Same `content` reasoning as above. */
|
|
710
|
+
query: Array<{
|
|
711
|
+
kbId: string;
|
|
712
|
+
title: string;
|
|
713
|
+
similarity?: number;
|
|
714
|
+
content?: string;
|
|
715
|
+
}>;
|
|
716
|
+
};
|
|
717
|
+
schemaNodes: {
|
|
718
|
+
/** MainAgent's cross-source prefilter — which sources were even considered. */
|
|
719
|
+
routing: Array<{
|
|
720
|
+
sourceId: string;
|
|
721
|
+
sourceName?: string;
|
|
722
|
+
similarity: number;
|
|
723
|
+
}>;
|
|
724
|
+
/** SourceAgent-scope per-source table resolution (MainAgent.preResolveSchema). */
|
|
725
|
+
preResolve: Array<{
|
|
726
|
+
sourceId: string;
|
|
727
|
+
table?: string;
|
|
728
|
+
description?: string;
|
|
729
|
+
similarity: number;
|
|
730
|
+
}>;
|
|
731
|
+
/**
|
|
732
|
+
* The exact {{SOURCE_SUMMARIES}} text injected into MainAgent's system prompt
|
|
733
|
+
* (agent-prompt-builder.ts's formatSummariesForPrompt output) — every
|
|
734
|
+
* registered source's catalog entry, not retrieval-specific, captured once per
|
|
735
|
+
* turn. This is what the main agent actually saw when deciding which source(s)
|
|
736
|
+
* to call.
|
|
737
|
+
*/
|
|
738
|
+
mainAgentCatalog?: string;
|
|
739
|
+
/**
|
|
740
|
+
* One entry per SourceAgent dispatch (a source called twice in one turn gets
|
|
741
|
+
* two entries) — the exact {{FULL_SCHEMA}} text injected into that
|
|
742
|
+
* SourceAgent's own system prompt, however it was sourced, plus any
|
|
743
|
+
* search_schema follow-up lookups it made mid-conversation when the schema
|
|
744
|
+
* shown wasn't enough.
|
|
745
|
+
*/
|
|
746
|
+
sourceAgentSchemas: Array<{
|
|
747
|
+
sourceId: string;
|
|
748
|
+
sourceName?: string;
|
|
749
|
+
/** How `schemaText` was sourced — see SourceAgent.buildPrompt's fullSchema fallback chain. */
|
|
750
|
+
method: 'preresolved-embedding' | 'tool-full-schema' | 'tool-description' | 'none';
|
|
751
|
+
schemaText: string;
|
|
752
|
+
/** In call order — each search_schema tool call this SourceAgent made, and the exact result text handed back to its own LLM. */
|
|
753
|
+
searchSchemaLookups: Array<{
|
|
754
|
+
keywords: string[];
|
|
755
|
+
result: string;
|
|
756
|
+
}>;
|
|
757
|
+
}>;
|
|
758
|
+
};
|
|
759
|
+
/** The script that produced this answer, if any. Null for a general (no-tool) answer. */
|
|
760
|
+
script: {
|
|
761
|
+
/** True when an existing recipe was replayed unchanged (ScriptMatcher tier='high'). */
|
|
762
|
+
reused: boolean;
|
|
763
|
+
recipeId?: string | null;
|
|
764
|
+
body?: string | null;
|
|
765
|
+
/** Set when reused — the matcher's reasoning for picking this recipe. */
|
|
766
|
+
reasoning?: string | null;
|
|
767
|
+
} | null;
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* Configuration for the multi-agent system.
|
|
771
|
+
* Controls limits, models, and behavior.
|
|
772
|
+
*/
|
|
773
|
+
interface AgentConfig {
|
|
774
|
+
/** Max rows shown to the UI preview / inlined per source (default: 10) */
|
|
775
|
+
maxRowsPerSource: number;
|
|
776
|
+
/**
|
|
777
|
+
* Max rows a source query may FETCH from the DB server-side (default: 2000).
|
|
778
|
+
* Decoupled from what the main agent is shown: the full result is fetched and
|
|
779
|
+
* summarized (bounded), but only a small/complete slice enters LLM context.
|
|
780
|
+
* This lets small lookups (benchmark maps) arrive COMPLETE without letting
|
|
781
|
+
* large results blow up context.
|
|
782
|
+
*/
|
|
783
|
+
maxRowsFetched: number;
|
|
784
|
+
/** Model for the main agent (routing + analysis in one LLM call) */
|
|
785
|
+
mainAgentModel: string;
|
|
786
|
+
/** Model for source agent query generation */
|
|
787
|
+
sourceAgentModel: string;
|
|
788
|
+
/** API key for LLM calls */
|
|
789
|
+
apiKey?: string;
|
|
790
|
+
/** Max retry attempts per source agent */
|
|
791
|
+
maxRetries: number;
|
|
792
|
+
/** Max tool calling iterations for the main agent loop */
|
|
793
|
+
maxIterations: number;
|
|
794
|
+
/** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
|
|
795
|
+
globalKnowledgeBase?: string;
|
|
796
|
+
/** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
|
|
797
|
+
knowledgeBaseContext?: string;
|
|
798
|
+
/** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
|
|
799
|
+
collections?: any;
|
|
800
|
+
/** Optional project ID for scoping embedding searches */
|
|
801
|
+
projectId?: string;
|
|
802
|
+
/**
|
|
803
|
+
* Optional debug-trace accumulator for this turn (Phase 1, chat_agent only).
|
|
804
|
+
* When present, MainAgent-scope retrieval call sites (e.g. preResolveSchema)
|
|
805
|
+
* push their structured results into it. Absent for callers that don't care
|
|
806
|
+
* about trace capture (e.g. headless flows) — every push site must treat
|
|
807
|
+
* this as optional and never let a capture failure affect the real answer.
|
|
808
|
+
*/
|
|
809
|
+
trace?: RunTrace;
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Default agent configuration
|
|
813
|
+
*/
|
|
814
|
+
declare const DEFAULT_AGENT_CONFIG: AgentConfig;
|
|
815
|
+
|
|
4
816
|
/**
|
|
5
817
|
* Unified UIBlock structure for database storage
|
|
6
|
-
* Used in both bookmarks and user-conversations tables
|
|
818
|
+
* Used in both bookmarks and user-conversations tables.
|
|
819
|
+
*
|
|
820
|
+
* `analysis` always holds whatever real narration exists — the full answer on
|
|
821
|
+
* success, or whatever was actually streamed before a failure (may be empty).
|
|
822
|
+
* `error` is a dedicated field, null on success — it can be a plain string OR
|
|
823
|
+
* a structured object/array (e.g. the agent's raw `errors` list), whatever
|
|
824
|
+
* shape the failure naturally has; it's never coerced into `analysis`.
|
|
7
825
|
*/
|
|
8
826
|
interface DBUIBlock {
|
|
9
827
|
id: string;
|
|
10
828
|
component: Record<string, any> | null;
|
|
11
829
|
analysis: string | null;
|
|
12
830
|
user_prompt: string;
|
|
831
|
+
error?: unknown | null;
|
|
832
|
+
/**
|
|
833
|
+
* The script recipe that produced this answer, when one did. Read back via
|
|
834
|
+
* `conversation-history.exactMatch` so an edit follow-up still has a target
|
|
835
|
+
* after a reload (the in-memory thread is gone by then), and indexed so
|
|
836
|
+
* committing an edit can purge every cached answer bound to the recipe.
|
|
837
|
+
*/
|
|
838
|
+
scriptBinding?: {
|
|
839
|
+
recipeId: string;
|
|
840
|
+
params?: Record<string, any>;
|
|
841
|
+
name?: string;
|
|
842
|
+
columns?: string[];
|
|
843
|
+
};
|
|
13
844
|
}
|
|
14
845
|
|
|
15
846
|
/**
|
|
@@ -59,7 +890,18 @@ declare class Logger {
|
|
|
59
890
|
* Log debug message (only shown for verbose level)
|
|
60
891
|
*/
|
|
61
892
|
debug(...args: any[]): void;
|
|
893
|
+
/**
|
|
894
|
+
* Write to log file
|
|
895
|
+
*/
|
|
62
896
|
file(...args: any[]): void;
|
|
897
|
+
/**
|
|
898
|
+
* Clear the log file (call at start of new user request)
|
|
899
|
+
*/
|
|
900
|
+
clearFile(): void;
|
|
901
|
+
/**
|
|
902
|
+
* Log LLM method prompts with clear labeling
|
|
903
|
+
*/
|
|
904
|
+
logLLMPrompt(methodName: string, promptType: 'system' | 'user', content: string | object | any[]): void;
|
|
63
905
|
}
|
|
64
906
|
declare const logger: Logger;
|
|
65
907
|
|
|
@@ -149,6 +991,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
149
991
|
dependencies?: string[] | undefined;
|
|
150
992
|
} | undefined;
|
|
151
993
|
props?: Record<string, any> | undefined;
|
|
994
|
+
data?: Record<string, any> | undefined;
|
|
152
995
|
render?: any;
|
|
153
996
|
states?: Record<string, any> | undefined;
|
|
154
997
|
methods?: Record<string, {
|
|
@@ -159,7 +1002,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
159
1002
|
fn: string;
|
|
160
1003
|
deps?: string[] | undefined;
|
|
161
1004
|
}[] | undefined;
|
|
162
|
-
data?: Record<string, any> | undefined;
|
|
163
1005
|
pages?: {
|
|
164
1006
|
id: string;
|
|
165
1007
|
name: string;
|
|
@@ -181,6 +1023,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
181
1023
|
dependencies?: string[] | undefined;
|
|
182
1024
|
} | undefined;
|
|
183
1025
|
props?: Record<string, any> | undefined;
|
|
1026
|
+
data?: Record<string, any> | undefined;
|
|
184
1027
|
render?: any;
|
|
185
1028
|
states?: Record<string, any> | undefined;
|
|
186
1029
|
methods?: Record<string, {
|
|
@@ -191,7 +1034,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
191
1034
|
fn: string;
|
|
192
1035
|
deps?: string[] | undefined;
|
|
193
1036
|
}[] | undefined;
|
|
194
|
-
data?: Record<string, any> | undefined;
|
|
195
1037
|
pages?: {
|
|
196
1038
|
id: string;
|
|
197
1039
|
name: string;
|
|
@@ -217,6 +1059,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
217
1059
|
dependencies?: string[] | undefined;
|
|
218
1060
|
} | undefined;
|
|
219
1061
|
props?: Record<string, any> | undefined;
|
|
1062
|
+
data?: Record<string, any> | undefined;
|
|
220
1063
|
render?: any;
|
|
221
1064
|
states?: Record<string, any> | undefined;
|
|
222
1065
|
methods?: Record<string, {
|
|
@@ -227,7 +1070,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
227
1070
|
fn: string;
|
|
228
1071
|
deps?: string[] | undefined;
|
|
229
1072
|
}[] | undefined;
|
|
230
|
-
data?: Record<string, any> | undefined;
|
|
231
1073
|
pages?: {
|
|
232
1074
|
id: string;
|
|
233
1075
|
name: string;
|
|
@@ -253,6 +1095,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
253
1095
|
dependencies?: string[] | undefined;
|
|
254
1096
|
} | undefined;
|
|
255
1097
|
props?: Record<string, any> | undefined;
|
|
1098
|
+
data?: Record<string, any> | undefined;
|
|
256
1099
|
render?: any;
|
|
257
1100
|
states?: Record<string, any> | undefined;
|
|
258
1101
|
methods?: Record<string, {
|
|
@@ -263,7 +1106,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
263
1106
|
fn: string;
|
|
264
1107
|
deps?: string[] | undefined;
|
|
265
1108
|
}[] | undefined;
|
|
266
|
-
data?: Record<string, any> | undefined;
|
|
267
1109
|
pages?: {
|
|
268
1110
|
id: string;
|
|
269
1111
|
name: string;
|
|
@@ -344,6 +1186,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
344
1186
|
dependencies?: string[] | undefined;
|
|
345
1187
|
} | undefined;
|
|
346
1188
|
props?: Record<string, any> | undefined;
|
|
1189
|
+
data?: Record<string, any> | undefined;
|
|
347
1190
|
render?: any;
|
|
348
1191
|
states?: Record<string, any> | undefined;
|
|
349
1192
|
methods?: Record<string, {
|
|
@@ -354,7 +1197,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
354
1197
|
fn: string;
|
|
355
1198
|
deps?: string[] | undefined;
|
|
356
1199
|
}[] | undefined;
|
|
357
|
-
data?: Record<string, any> | undefined;
|
|
358
1200
|
}, {
|
|
359
1201
|
id: string;
|
|
360
1202
|
name?: string | undefined;
|
|
@@ -368,6 +1210,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
368
1210
|
dependencies?: string[] | undefined;
|
|
369
1211
|
} | undefined;
|
|
370
1212
|
props?: Record<string, any> | undefined;
|
|
1213
|
+
data?: Record<string, any> | undefined;
|
|
371
1214
|
render?: any;
|
|
372
1215
|
states?: Record<string, any> | undefined;
|
|
373
1216
|
methods?: Record<string, {
|
|
@@ -378,7 +1221,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
378
1221
|
fn: string;
|
|
379
1222
|
deps?: string[] | undefined;
|
|
380
1223
|
}[] | undefined;
|
|
381
|
-
data?: Record<string, any> | undefined;
|
|
382
1224
|
}>;
|
|
383
1225
|
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
384
1226
|
context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
@@ -396,6 +1238,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
396
1238
|
dependencies?: string[] | undefined;
|
|
397
1239
|
} | undefined;
|
|
398
1240
|
props?: Record<string, any> | undefined;
|
|
1241
|
+
data?: Record<string, any> | undefined;
|
|
399
1242
|
render?: any;
|
|
400
1243
|
states?: Record<string, any> | undefined;
|
|
401
1244
|
methods?: Record<string, {
|
|
@@ -406,7 +1249,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
406
1249
|
fn: string;
|
|
407
1250
|
deps?: string[] | undefined;
|
|
408
1251
|
}[] | undefined;
|
|
409
|
-
data?: Record<string, any> | undefined;
|
|
410
1252
|
};
|
|
411
1253
|
data?: Record<string, any> | undefined;
|
|
412
1254
|
context?: Record<string, any> | undefined;
|
|
@@ -424,6 +1266,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
424
1266
|
dependencies?: string[] | undefined;
|
|
425
1267
|
} | undefined;
|
|
426
1268
|
props?: Record<string, any> | undefined;
|
|
1269
|
+
data?: Record<string, any> | undefined;
|
|
427
1270
|
render?: any;
|
|
428
1271
|
states?: Record<string, any> | undefined;
|
|
429
1272
|
methods?: Record<string, {
|
|
@@ -434,7 +1277,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
434
1277
|
fn: string;
|
|
435
1278
|
deps?: string[] | undefined;
|
|
436
1279
|
}[] | undefined;
|
|
437
|
-
data?: Record<string, any> | undefined;
|
|
438
1280
|
};
|
|
439
1281
|
data?: Record<string, any> | undefined;
|
|
440
1282
|
context?: Record<string, any> | undefined;
|
|
@@ -615,24 +1457,203 @@ declare const IncomingMessageSchema: z.ZodObject<{
|
|
|
615
1457
|
payload?: unknown;
|
|
616
1458
|
}>;
|
|
617
1459
|
type IncomingMessage = z.infer<typeof IncomingMessageSchema>;
|
|
1460
|
+
declare const ComponentSchema: z.ZodObject<{
|
|
1461
|
+
id: z.ZodString;
|
|
1462
|
+
name: z.ZodString;
|
|
1463
|
+
displayName: z.ZodOptional<z.ZodString>;
|
|
1464
|
+
isDisplayComp: z.ZodOptional<z.ZodBoolean>;
|
|
1465
|
+
type: z.ZodString;
|
|
1466
|
+
description: z.ZodString;
|
|
1467
|
+
props: z.ZodObject<{
|
|
1468
|
+
query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
|
|
1469
|
+
title: z.ZodOptional<z.ZodString>;
|
|
1470
|
+
description: z.ZodOptional<z.ZodString>;
|
|
1471
|
+
config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
1472
|
+
actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
|
|
1473
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
1474
|
+
query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
|
|
1475
|
+
title: z.ZodOptional<z.ZodString>;
|
|
1476
|
+
description: z.ZodOptional<z.ZodString>;
|
|
1477
|
+
config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
1478
|
+
actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
|
|
1479
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
1480
|
+
query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
|
|
1481
|
+
title: z.ZodOptional<z.ZodString>;
|
|
1482
|
+
description: z.ZodOptional<z.ZodString>;
|
|
1483
|
+
config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
1484
|
+
actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
|
|
1485
|
+
}, z.ZodTypeAny, "passthrough">>;
|
|
1486
|
+
category: z.ZodOptional<z.ZodString>;
|
|
1487
|
+
keywords: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
1488
|
+
}, "strip", z.ZodTypeAny, {
|
|
1489
|
+
id: string;
|
|
1490
|
+
type: string;
|
|
1491
|
+
name: string;
|
|
1492
|
+
description: string;
|
|
1493
|
+
props: {
|
|
1494
|
+
description?: string | undefined;
|
|
1495
|
+
query?: string | {} | null | undefined;
|
|
1496
|
+
title?: string | undefined;
|
|
1497
|
+
config?: Record<string, unknown> | undefined;
|
|
1498
|
+
actions?: any[] | undefined;
|
|
1499
|
+
} & {
|
|
1500
|
+
[k: string]: unknown;
|
|
1501
|
+
};
|
|
1502
|
+
displayName?: string | undefined;
|
|
1503
|
+
isDisplayComp?: boolean | undefined;
|
|
1504
|
+
category?: string | undefined;
|
|
1505
|
+
keywords?: string[] | undefined;
|
|
1506
|
+
}, {
|
|
1507
|
+
id: string;
|
|
1508
|
+
type: string;
|
|
1509
|
+
name: string;
|
|
1510
|
+
description: string;
|
|
1511
|
+
props: {
|
|
1512
|
+
description?: string | undefined;
|
|
1513
|
+
query?: string | {} | null | undefined;
|
|
1514
|
+
title?: string | undefined;
|
|
1515
|
+
config?: Record<string, unknown> | undefined;
|
|
1516
|
+
actions?: any[] | undefined;
|
|
1517
|
+
} & {
|
|
1518
|
+
[k: string]: unknown;
|
|
1519
|
+
};
|
|
1520
|
+
displayName?: string | undefined;
|
|
1521
|
+
isDisplayComp?: boolean | undefined;
|
|
1522
|
+
category?: string | undefined;
|
|
1523
|
+
keywords?: string[] | undefined;
|
|
1524
|
+
}>;
|
|
1525
|
+
type Component = z.infer<typeof ComponentSchema>;
|
|
1526
|
+
declare const OutputFieldSchema: z.ZodObject<{
|
|
1527
|
+
name: z.ZodString;
|
|
1528
|
+
type: z.ZodEnum<["string", "number", "boolean", "date"]>;
|
|
1529
|
+
description: z.ZodString;
|
|
1530
|
+
}, "strip", z.ZodTypeAny, {
|
|
1531
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1532
|
+
name: string;
|
|
1533
|
+
description: string;
|
|
1534
|
+
}, {
|
|
1535
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1536
|
+
name: string;
|
|
1537
|
+
description: string;
|
|
1538
|
+
}>;
|
|
1539
|
+
type OutputField = z.infer<typeof OutputFieldSchema>;
|
|
1540
|
+
declare const OutputSchema: z.ZodObject<{
|
|
1541
|
+
description: z.ZodString;
|
|
1542
|
+
fields: z.ZodArray<z.ZodObject<{
|
|
1543
|
+
name: z.ZodString;
|
|
1544
|
+
type: z.ZodEnum<["string", "number", "boolean", "date"]>;
|
|
1545
|
+
description: z.ZodString;
|
|
1546
|
+
}, "strip", z.ZodTypeAny, {
|
|
1547
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1548
|
+
name: string;
|
|
1549
|
+
description: string;
|
|
1550
|
+
}, {
|
|
1551
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1552
|
+
name: string;
|
|
1553
|
+
description: string;
|
|
1554
|
+
}>, "many">;
|
|
1555
|
+
}, "strip", z.ZodTypeAny, {
|
|
1556
|
+
description: string;
|
|
1557
|
+
fields: {
|
|
1558
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1559
|
+
name: string;
|
|
1560
|
+
description: string;
|
|
1561
|
+
}[];
|
|
1562
|
+
}, {
|
|
1563
|
+
description: string;
|
|
1564
|
+
fields: {
|
|
1565
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1566
|
+
name: string;
|
|
1567
|
+
description: string;
|
|
1568
|
+
}[];
|
|
1569
|
+
}>;
|
|
1570
|
+
type ToolOutputSchema = z.infer<typeof OutputSchema>;
|
|
618
1571
|
declare const ToolSchema: z.ZodObject<{
|
|
619
1572
|
id: z.ZodString;
|
|
620
1573
|
name: z.ZodString;
|
|
621
1574
|
description: z.ZodString;
|
|
1575
|
+
/** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
|
|
1576
|
+
toolType: z.ZodOptional<z.ZodEnum<["source", "direct"]>>;
|
|
1577
|
+
/** Full untruncated schema for source agent (all columns visible) */
|
|
1578
|
+
fullSchema: z.ZodOptional<z.ZodString>;
|
|
622
1579
|
params: z.ZodRecord<z.ZodString, z.ZodString>;
|
|
623
1580
|
fn: z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodAny>;
|
|
1581
|
+
outputSchema: z.ZodOptional<z.ZodObject<{
|
|
1582
|
+
description: z.ZodString;
|
|
1583
|
+
fields: z.ZodArray<z.ZodObject<{
|
|
1584
|
+
name: z.ZodString;
|
|
1585
|
+
type: z.ZodEnum<["string", "number", "boolean", "date"]>;
|
|
1586
|
+
description: z.ZodString;
|
|
1587
|
+
}, "strip", z.ZodTypeAny, {
|
|
1588
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1589
|
+
name: string;
|
|
1590
|
+
description: string;
|
|
1591
|
+
}, {
|
|
1592
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1593
|
+
name: string;
|
|
1594
|
+
description: string;
|
|
1595
|
+
}>, "many">;
|
|
1596
|
+
}, "strip", z.ZodTypeAny, {
|
|
1597
|
+
description: string;
|
|
1598
|
+
fields: {
|
|
1599
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1600
|
+
name: string;
|
|
1601
|
+
description: string;
|
|
1602
|
+
}[];
|
|
1603
|
+
}, {
|
|
1604
|
+
description: string;
|
|
1605
|
+
fields: {
|
|
1606
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1607
|
+
name: string;
|
|
1608
|
+
description: string;
|
|
1609
|
+
}[];
|
|
1610
|
+
}>>;
|
|
1611
|
+
/** Cache policy. `false` = never cache (live data, write ops). Mirrors HTTP `Cache-Control: no-store`. */
|
|
1612
|
+
cache: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<false>, z.ZodObject<{
|
|
1613
|
+
ttlMs: z.ZodOptional<z.ZodNumber>;
|
|
1614
|
+
}, "strip", z.ZodTypeAny, {
|
|
1615
|
+
ttlMs?: number | undefined;
|
|
1616
|
+
}, {
|
|
1617
|
+
ttlMs?: number | undefined;
|
|
1618
|
+
}>]>>;
|
|
624
1619
|
}, "strip", z.ZodTypeAny, {
|
|
625
1620
|
id: string;
|
|
626
1621
|
params: Record<string, string>;
|
|
627
1622
|
name: string;
|
|
628
1623
|
description: string;
|
|
629
1624
|
fn: (args_0: any, ...args: unknown[]) => any;
|
|
1625
|
+
toolType?: "source" | "direct" | undefined;
|
|
1626
|
+
fullSchema?: string | undefined;
|
|
1627
|
+
outputSchema?: {
|
|
1628
|
+
description: string;
|
|
1629
|
+
fields: {
|
|
1630
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1631
|
+
name: string;
|
|
1632
|
+
description: string;
|
|
1633
|
+
}[];
|
|
1634
|
+
} | undefined;
|
|
1635
|
+
cache?: false | {
|
|
1636
|
+
ttlMs?: number | undefined;
|
|
1637
|
+
} | undefined;
|
|
630
1638
|
}, {
|
|
631
1639
|
id: string;
|
|
632
1640
|
params: Record<string, string>;
|
|
633
1641
|
name: string;
|
|
634
1642
|
description: string;
|
|
635
1643
|
fn: (args_0: any, ...args: unknown[]) => any;
|
|
1644
|
+
toolType?: "source" | "direct" | undefined;
|
|
1645
|
+
fullSchema?: string | undefined;
|
|
1646
|
+
outputSchema?: {
|
|
1647
|
+
description: string;
|
|
1648
|
+
fields: {
|
|
1649
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1650
|
+
name: string;
|
|
1651
|
+
description: string;
|
|
1652
|
+
}[];
|
|
1653
|
+
} | undefined;
|
|
1654
|
+
cache?: false | {
|
|
1655
|
+
ttlMs?: number | undefined;
|
|
1656
|
+
} | undefined;
|
|
636
1657
|
}>;
|
|
637
1658
|
type Tool$1 = z.infer<typeof ToolSchema>;
|
|
638
1659
|
type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
|
|
@@ -640,11 +1661,33 @@ type CollectionHandler<TParams = any, TResult = any> = (params: TParams) => Prom
|
|
|
640
1661
|
type LLMProvider = 'anthropic' | 'groq' | 'gemini' | 'openai';
|
|
641
1662
|
|
|
642
1663
|
type DatabaseType = 'postgresql' | 'mssql' | 'snowflake' | 'mysql';
|
|
1664
|
+
/**
|
|
1665
|
+
* Model strategy for controlling which models are used for different tasks
|
|
1666
|
+
* - 'best': Use the best model (e.g., Sonnet) for all tasks - highest quality, higher cost
|
|
1667
|
+
* - 'fast': Use the fast model (e.g., Haiku) for all tasks - lower quality, lower cost
|
|
1668
|
+
* - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
|
|
1669
|
+
*/
|
|
1670
|
+
type ModelStrategy = 'best' | 'fast' | 'balanced';
|
|
1671
|
+
/**
|
|
1672
|
+
* Model configuration for DASH_COMP flow (dashboard component picking)
|
|
1673
|
+
* Allows separate control of models used for component selection
|
|
1674
|
+
*/
|
|
1675
|
+
interface DashCompModelConfig {
|
|
1676
|
+
/**
|
|
1677
|
+
* Primary model for DASH_COMP requests
|
|
1678
|
+
* Format: "provider/model-name" (e.g., "anthropic/claude-sonnet-4-5-20250929")
|
|
1679
|
+
*/
|
|
1680
|
+
model?: string;
|
|
1681
|
+
/**
|
|
1682
|
+
* Fast model for simpler DASH_COMP tasks (optional)
|
|
1683
|
+
* Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
|
|
1684
|
+
*/
|
|
1685
|
+
fastModel?: string;
|
|
1686
|
+
}
|
|
643
1687
|
interface SuperatomSDKConfig {
|
|
644
1688
|
url?: string;
|
|
645
1689
|
apiKey?: string;
|
|
646
1690
|
projectId: string;
|
|
647
|
-
userId?: string;
|
|
648
1691
|
type?: string;
|
|
649
1692
|
bundleDir?: string;
|
|
650
1693
|
promptsDir?: string;
|
|
@@ -655,22 +1698,68 @@ interface SuperatomSDKConfig {
|
|
|
655
1698
|
OPENAI_API_KEY?: string;
|
|
656
1699
|
LLM_PROVIDERS?: LLMProvider[];
|
|
657
1700
|
logLevel?: LogLevel;
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
1701
|
+
/**
|
|
1702
|
+
* Model selection strategy for LLM API calls:
|
|
1703
|
+
* - 'best': Use best model for all tasks (highest quality, higher cost)
|
|
1704
|
+
* - 'fast': Use fast model for all tasks (lower quality, lower cost)
|
|
1705
|
+
* - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
|
|
1706
|
+
*/
|
|
1707
|
+
modelStrategy?: ModelStrategy;
|
|
1708
|
+
/**
|
|
1709
|
+
* Model for the main agent (routing + analysis).
|
|
1710
|
+
* Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
|
|
1711
|
+
* If not set, uses the provider's default model.
|
|
1712
|
+
*/
|
|
1713
|
+
mainAgentModel?: string;
|
|
1714
|
+
/**
|
|
1715
|
+
* Model for source agents (per-source query generation).
|
|
1716
|
+
* Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
|
|
1717
|
+
* If not set, uses the provider's default model.
|
|
1718
|
+
*/
|
|
1719
|
+
sourceAgentModel?: string;
|
|
1720
|
+
/**
|
|
1721
|
+
* Separate model configuration for DASH_COMP flow (dashboard component picking)
|
|
1722
|
+
* If not provided, falls back to provider-based model selection
|
|
1723
|
+
*/
|
|
1724
|
+
dashCompModels?: DashCompModelConfig;
|
|
1725
|
+
/**
|
|
1726
|
+
* Similarity threshold for conversation search (semantic matching)
|
|
1727
|
+
* Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
|
|
1728
|
+
* Higher values require closer matches, lower values allow more distant matches
|
|
1729
|
+
* Default: 0.8
|
|
1730
|
+
*/
|
|
1731
|
+
conversationSimilarityThreshold?: number;
|
|
1732
|
+
/**
|
|
1733
|
+
* Query cache TTL (Time To Live) in minutes
|
|
1734
|
+
* Cached query results expire after this duration
|
|
1735
|
+
* Default: 5 minutes
|
|
1736
|
+
*/
|
|
1737
|
+
queryCacheTTL?: number;
|
|
1738
|
+
/**
|
|
1739
|
+
* Dashboard conversation history TTL (Time To Live) in minutes
|
|
1740
|
+
* Per-dashboard conversation histories expire after this duration
|
|
1741
|
+
* Default: 30 minutes
|
|
1742
|
+
*/
|
|
1743
|
+
dashboardHistoryTTL?: number;
|
|
1744
|
+
}
|
|
1745
|
+
|
|
1746
|
+
declare const KbNodesQueryFiltersSchema: z.ZodObject<{
|
|
1747
|
+
query: z.ZodOptional<z.ZodString>;
|
|
1748
|
+
category: z.ZodOptional<z.ZodString>;
|
|
663
1749
|
tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
664
|
-
|
|
1750
|
+
type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
|
|
1751
|
+
createdBy: z.ZodOptional<z.ZodString>;
|
|
665
1752
|
}, "strip", z.ZodTypeAny, {
|
|
1753
|
+
type?: "query" | "user" | "global" | undefined;
|
|
666
1754
|
query?: string | undefined;
|
|
667
1755
|
category?: string | undefined;
|
|
668
|
-
createdBy?:
|
|
1756
|
+
createdBy?: string | undefined;
|
|
669
1757
|
tags?: string[] | undefined;
|
|
670
1758
|
}, {
|
|
1759
|
+
type?: "query" | "user" | "global" | undefined;
|
|
671
1760
|
query?: string | undefined;
|
|
672
1761
|
category?: string | undefined;
|
|
673
|
-
createdBy?:
|
|
1762
|
+
createdBy?: string | undefined;
|
|
674
1763
|
tags?: string[] | undefined;
|
|
675
1764
|
}>;
|
|
676
1765
|
type KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
|
|
@@ -682,109 +1771,126 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
|
|
|
682
1771
|
content: z.ZodOptional<z.ZodString>;
|
|
683
1772
|
category: z.ZodOptional<z.ZodString>;
|
|
684
1773
|
tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
1774
|
+
type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
|
|
1775
|
+
createdBy: z.ZodOptional<z.ZodString>;
|
|
1776
|
+
updatedBy: z.ZodOptional<z.ZodString>;
|
|
1777
|
+
userId: z.ZodOptional<z.ZodString>;
|
|
688
1778
|
query: z.ZodOptional<z.ZodString>;
|
|
689
1779
|
filters: z.ZodOptional<z.ZodObject<{
|
|
690
1780
|
query: z.ZodOptional<z.ZodString>;
|
|
691
1781
|
category: z.ZodOptional<z.ZodString>;
|
|
692
1782
|
tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
693
|
-
|
|
1783
|
+
type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
|
|
1784
|
+
createdBy: z.ZodOptional<z.ZodString>;
|
|
694
1785
|
}, "strip", z.ZodTypeAny, {
|
|
1786
|
+
type?: "query" | "user" | "global" | undefined;
|
|
695
1787
|
query?: string | undefined;
|
|
696
1788
|
category?: string | undefined;
|
|
697
|
-
createdBy?:
|
|
1789
|
+
createdBy?: string | undefined;
|
|
698
1790
|
tags?: string[] | undefined;
|
|
699
1791
|
}, {
|
|
1792
|
+
type?: "query" | "user" | "global" | undefined;
|
|
700
1793
|
query?: string | undefined;
|
|
701
1794
|
category?: string | undefined;
|
|
702
|
-
createdBy?:
|
|
1795
|
+
createdBy?: string | undefined;
|
|
703
1796
|
tags?: string[] | undefined;
|
|
704
1797
|
}>>;
|
|
705
1798
|
limit: z.ZodOptional<z.ZodNumber>;
|
|
706
1799
|
offset: z.ZodOptional<z.ZodNumber>;
|
|
707
1800
|
}, "strip", z.ZodTypeAny, {
|
|
708
1801
|
id?: number | undefined;
|
|
1802
|
+
type?: "query" | "user" | "global" | undefined;
|
|
709
1803
|
query?: string | undefined;
|
|
710
1804
|
title?: string | undefined;
|
|
711
1805
|
category?: string | undefined;
|
|
712
|
-
userId?:
|
|
1806
|
+
userId?: string | undefined;
|
|
713
1807
|
limit?: number | undefined;
|
|
714
1808
|
filters?: {
|
|
1809
|
+
type?: "query" | "user" | "global" | undefined;
|
|
715
1810
|
query?: string | undefined;
|
|
716
1811
|
category?: string | undefined;
|
|
717
|
-
createdBy?:
|
|
1812
|
+
createdBy?: string | undefined;
|
|
718
1813
|
tags?: string[] | undefined;
|
|
719
1814
|
} | undefined;
|
|
720
|
-
createdBy?:
|
|
721
|
-
updatedBy?:
|
|
1815
|
+
createdBy?: string | undefined;
|
|
1816
|
+
updatedBy?: string | undefined;
|
|
1817
|
+
offset?: number | undefined;
|
|
722
1818
|
tags?: string[] | undefined;
|
|
723
1819
|
content?: string | undefined;
|
|
724
|
-
offset?: number | undefined;
|
|
725
1820
|
}, {
|
|
726
1821
|
id?: number | undefined;
|
|
1822
|
+
type?: "query" | "user" | "global" | undefined;
|
|
727
1823
|
query?: string | undefined;
|
|
728
1824
|
title?: string | undefined;
|
|
729
1825
|
category?: string | undefined;
|
|
730
|
-
userId?:
|
|
1826
|
+
userId?: string | undefined;
|
|
731
1827
|
limit?: number | undefined;
|
|
732
1828
|
filters?: {
|
|
1829
|
+
type?: "query" | "user" | "global" | undefined;
|
|
733
1830
|
query?: string | undefined;
|
|
734
1831
|
category?: string | undefined;
|
|
735
|
-
createdBy?:
|
|
1832
|
+
createdBy?: string | undefined;
|
|
736
1833
|
tags?: string[] | undefined;
|
|
737
1834
|
} | undefined;
|
|
738
|
-
createdBy?:
|
|
739
|
-
updatedBy?:
|
|
1835
|
+
createdBy?: string | undefined;
|
|
1836
|
+
updatedBy?: string | undefined;
|
|
1837
|
+
offset?: number | undefined;
|
|
740
1838
|
tags?: string[] | undefined;
|
|
741
1839
|
content?: string | undefined;
|
|
742
|
-
offset?: number | undefined;
|
|
743
1840
|
}>>;
|
|
744
1841
|
}, "strip", z.ZodTypeAny, {
|
|
745
|
-
operation: "create" | "getOne" | "
|
|
1842
|
+
operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
|
|
746
1843
|
data?: {
|
|
747
1844
|
id?: number | undefined;
|
|
1845
|
+
type?: "query" | "user" | "global" | undefined;
|
|
748
1846
|
query?: string | undefined;
|
|
749
1847
|
title?: string | undefined;
|
|
750
1848
|
category?: string | undefined;
|
|
751
|
-
userId?:
|
|
1849
|
+
userId?: string | undefined;
|
|
752
1850
|
limit?: number | undefined;
|
|
753
1851
|
filters?: {
|
|
1852
|
+
type?: "query" | "user" | "global" | undefined;
|
|
754
1853
|
query?: string | undefined;
|
|
755
1854
|
category?: string | undefined;
|
|
756
|
-
createdBy?:
|
|
1855
|
+
createdBy?: string | undefined;
|
|
757
1856
|
tags?: string[] | undefined;
|
|
758
1857
|
} | undefined;
|
|
759
|
-
createdBy?:
|
|
760
|
-
updatedBy?:
|
|
1858
|
+
createdBy?: string | undefined;
|
|
1859
|
+
updatedBy?: string | undefined;
|
|
1860
|
+
offset?: number | undefined;
|
|
761
1861
|
tags?: string[] | undefined;
|
|
762
1862
|
content?: string | undefined;
|
|
763
|
-
offset?: number | undefined;
|
|
764
1863
|
} | undefined;
|
|
765
1864
|
}, {
|
|
766
|
-
operation: "create" | "getOne" | "
|
|
1865
|
+
operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
|
|
767
1866
|
data?: {
|
|
768
1867
|
id?: number | undefined;
|
|
1868
|
+
type?: "query" | "user" | "global" | undefined;
|
|
769
1869
|
query?: string | undefined;
|
|
770
1870
|
title?: string | undefined;
|
|
771
1871
|
category?: string | undefined;
|
|
772
|
-
userId?:
|
|
1872
|
+
userId?: string | undefined;
|
|
773
1873
|
limit?: number | undefined;
|
|
774
1874
|
filters?: {
|
|
1875
|
+
type?: "query" | "user" | "global" | undefined;
|
|
775
1876
|
query?: string | undefined;
|
|
776
1877
|
category?: string | undefined;
|
|
777
|
-
createdBy?:
|
|
1878
|
+
createdBy?: string | undefined;
|
|
778
1879
|
tags?: string[] | undefined;
|
|
779
1880
|
} | undefined;
|
|
780
|
-
createdBy?:
|
|
781
|
-
updatedBy?:
|
|
1881
|
+
createdBy?: string | undefined;
|
|
1882
|
+
updatedBy?: string | undefined;
|
|
1883
|
+
offset?: number | undefined;
|
|
782
1884
|
tags?: string[] | undefined;
|
|
783
1885
|
content?: string | undefined;
|
|
784
|
-
offset?: number | undefined;
|
|
785
1886
|
} | undefined;
|
|
786
1887
|
}>;
|
|
787
1888
|
type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
|
|
1889
|
+
interface T_RESPONSE {
|
|
1890
|
+
success: boolean;
|
|
1891
|
+
data?: any;
|
|
1892
|
+
errors: string[];
|
|
1893
|
+
}
|
|
788
1894
|
|
|
789
1895
|
/**
|
|
790
1896
|
* UserManager class to handle CRUD operations on users with file persistence
|
|
@@ -1045,6 +2151,503 @@ declare class ReportManager {
|
|
|
1045
2151
|
getReportCount(): number;
|
|
1046
2152
|
}
|
|
1047
2153
|
|
|
2154
|
+
/**
|
|
2155
|
+
* ScriptRecipeStore — injected metadata backend for the script flow.
|
|
2156
|
+
*
|
|
2157
|
+
* The SDK is standalone (no DB dependency). The backend implements this
|
|
2158
|
+
* interface over Postgres (full-text search + atomic counters) and injects it
|
|
2159
|
+
* via `collections['script-recipes']`, exactly like `collections['source-embeddings']`.
|
|
2160
|
+
* `ScriptStore` consumes it for all METADATA operations while keeping the
|
|
2161
|
+
* executable body on disk as scripts-store/<fileBase>.ts.
|
|
2162
|
+
*
|
|
2163
|
+
* All metadata rows are plain JSON (no scriptBody — that lives on disk).
|
|
2164
|
+
* See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md (#1, #3, #7).
|
|
2165
|
+
*/
|
|
2166
|
+
|
|
2167
|
+
/** One recipe's metadata as stored in Postgres (mirrors the script_recipes table). */
|
|
2168
|
+
interface ScriptRecipeMetaRow {
|
|
2169
|
+
id: string;
|
|
2170
|
+
projectId?: string | null;
|
|
2171
|
+
version: number;
|
|
2172
|
+
name: string;
|
|
2173
|
+
intentDescription: string;
|
|
2174
|
+
tags: string[] | null;
|
|
2175
|
+
createdFrom: string | null;
|
|
2176
|
+
sourceIds: string[] | null;
|
|
2177
|
+
tables: string[] | null;
|
|
2178
|
+
parameters: ScriptParameter[] | null;
|
|
2179
|
+
components?: ScriptComponentSpec[] | null;
|
|
2180
|
+
displayPreference?: ScriptDisplayPreference | null;
|
|
2181
|
+
fileBase: string;
|
|
2182
|
+
bodyHash?: string | null;
|
|
2183
|
+
successCount: number;
|
|
2184
|
+
failureCount: number;
|
|
2185
|
+
lastUsed: string | null;
|
|
2186
|
+
parentId?: string | null;
|
|
2187
|
+
forkDepth?: number | null;
|
|
2188
|
+
forkReason?: string | null;
|
|
2189
|
+
status: 'draft' | 'verified' | string;
|
|
2190
|
+
turnId?: string | null;
|
|
2191
|
+
editedBy?: string | null;
|
|
2192
|
+
editedFrom?: string | null;
|
|
2193
|
+
history?: ScriptVersionRecord[] | null;
|
|
2194
|
+
lastError?: {
|
|
2195
|
+
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
2196
|
+
message: string;
|
|
2197
|
+
at: string;
|
|
2198
|
+
attempt: number;
|
|
2199
|
+
} | null;
|
|
2200
|
+
createdAt?: string | null;
|
|
2201
|
+
updatedAt?: string | null;
|
|
2202
|
+
}
|
|
2203
|
+
interface ScriptRecipeStore {
|
|
2204
|
+
/** FTS shortlist of healthy verified recipes for the matcher (metadata only). */
|
|
2205
|
+
search(params: {
|
|
2206
|
+
prompt: string;
|
|
2207
|
+
projectId?: string;
|
|
2208
|
+
limit?: number;
|
|
2209
|
+
}): Promise<ScriptRecipeMetaRow[]>;
|
|
2210
|
+
/** Fetch one recipe by id (any status). */
|
|
2211
|
+
getById(id: string): Promise<ScriptRecipeMetaRow | null>;
|
|
2212
|
+
/** Count healthy verified recipes (drives the "any scripts?" gate). */
|
|
2213
|
+
count(params?: {
|
|
2214
|
+
projectId?: string;
|
|
2215
|
+
}): Promise<number>;
|
|
2216
|
+
/** Insert or update a recipe row (keyed by id). */
|
|
2217
|
+
upsert(row: ScriptRecipeMetaRow): Promise<void>;
|
|
2218
|
+
/** Atomically bump counters / last-used. */
|
|
2219
|
+
updateStats(id: string, patch: {
|
|
2220
|
+
successDelta?: number;
|
|
2221
|
+
failureDelta?: number;
|
|
2222
|
+
lastUsed?: string;
|
|
2223
|
+
}): Promise<void>;
|
|
2224
|
+
/** Flip a draft to verified, applying provenance + optional fork lineage. */
|
|
2225
|
+
promote(id: string, patch: {
|
|
2226
|
+
sourceIds: string[];
|
|
2227
|
+
tables: string[];
|
|
2228
|
+
fileBase?: string;
|
|
2229
|
+
parentId?: string;
|
|
2230
|
+
forkDepth?: number;
|
|
2231
|
+
forkReason?: string;
|
|
2232
|
+
components?: ScriptComponentSpec[];
|
|
2233
|
+
}): Promise<ScriptRecipeMetaRow | null>;
|
|
2234
|
+
/**
|
|
2235
|
+
* Commit a verified edit onto an EXISTING recipe: bump `version`, replace the
|
|
2236
|
+
* body-bearing metadata, append a history record, reset health counters, and
|
|
2237
|
+
* clear the component specs (they were validated against the old shape).
|
|
2238
|
+
* Returns the updated row, or null when the target is gone.
|
|
2239
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5.
|
|
2240
|
+
*/
|
|
2241
|
+
commitEdit?(id: string, patch: {
|
|
2242
|
+
name?: string;
|
|
2243
|
+
intentDescription?: string;
|
|
2244
|
+
tags?: string[];
|
|
2245
|
+
parameters?: ScriptParameter[];
|
|
2246
|
+
bodyHash: string;
|
|
2247
|
+
/** New on-disk stem when the edit renamed the script; omitted otherwise. */
|
|
2248
|
+
fileBase?: string;
|
|
2249
|
+
sourceIds?: string[];
|
|
2250
|
+
tables?: string[];
|
|
2251
|
+
editedBy?: string;
|
|
2252
|
+
editedFrom?: string;
|
|
2253
|
+
historyEntry: {
|
|
2254
|
+
version: number;
|
|
2255
|
+
at: string;
|
|
2256
|
+
by?: string;
|
|
2257
|
+
instruction?: string;
|
|
2258
|
+
changeSummary?: string;
|
|
2259
|
+
bodyHash?: string;
|
|
2260
|
+
};
|
|
2261
|
+
}): Promise<ScriptRecipeMetaRow | null>;
|
|
2262
|
+
/** Stamp a draft's last execution error. */
|
|
2263
|
+
recordDraftError(id: string, err: {
|
|
2264
|
+
phase: string;
|
|
2265
|
+
message: string;
|
|
2266
|
+
attempt: number;
|
|
2267
|
+
at: string;
|
|
2268
|
+
}): Promise<void>;
|
|
2269
|
+
/** Delete a recipe row (body file removed separately). */
|
|
2270
|
+
remove(id: string): Promise<void>;
|
|
2271
|
+
/** True if `fileBase` is taken by a different recipe in this project. */
|
|
2272
|
+
fileBaseTaken(fileBase: string, excludeId: string, projectId?: string): Promise<boolean>;
|
|
2273
|
+
}
|
|
2274
|
+
/** Pull the injected store off the collections bag (or null if not wired). */
|
|
2275
|
+
declare function resolveScriptRecipeStore(collections: any): ScriptRecipeStore | null;
|
|
2276
|
+
|
|
2277
|
+
/**
|
|
2278
|
+
* ScriptStore — Postgres metadata + on-disk body for script recipes.
|
|
2279
|
+
*
|
|
2280
|
+
* Split of responsibilities:
|
|
2281
|
+
* - METADATA → injected `ScriptRecipeStore` (Postgres FTS + atomic counters),
|
|
2282
|
+
* resolved from `collections['script-recipes']`.
|
|
2283
|
+
* - BODY → scripts-store/<fileBase>.ts, editable in your IDE. Written
|
|
2284
|
+
* atomically (temp + rename); `bodyHash` (sha256) detects edits.
|
|
2285
|
+
*
|
|
2286
|
+
* The old "read every file every turn + send the whole catalog to the LLM"
|
|
2287
|
+
* matcher is gone — matching is `store.search(prompt)` (FTS shortlist). The
|
|
2288
|
+
* draft/verified filename dance is gone too: `status` is a DB column and the
|
|
2289
|
+
* file keeps a stable `<fileBase>.ts` name across promotion.
|
|
2290
|
+
*
|
|
2291
|
+
* When no metadata store is injected, the store degrades to a safe no-op
|
|
2292
|
+
* (count 0 → script flow disabled) instead of crashing.
|
|
2293
|
+
*
|
|
2294
|
+
* See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md.
|
|
2295
|
+
*/
|
|
2296
|
+
|
|
2297
|
+
interface SaveDraftInput {
|
|
2298
|
+
/** Reuse an existing draft (retry); omit to mint a new one. */
|
|
2299
|
+
recipeId?: string;
|
|
2300
|
+
/** Per-turn unique suffix, stable across retries within the turn. */
|
|
2301
|
+
turnId: string;
|
|
2302
|
+
name: string;
|
|
2303
|
+
intentDescription: string;
|
|
2304
|
+
tags: string[];
|
|
2305
|
+
parameters: ScriptParameter[];
|
|
2306
|
+
scriptBody: string;
|
|
2307
|
+
createdFrom: string;
|
|
2308
|
+
/**
|
|
2309
|
+
* Set when this draft is a SHADOW of an existing recipe being edited. The
|
|
2310
|
+
* draft is verified independently and merged back onto the parent via
|
|
2311
|
+
* `commitEdit`, so the working script is never clobbered by an edit that
|
|
2312
|
+
* turns out not to run. See backend/docs/SCRIPT-EDIT-DESIGN.md § D5.
|
|
2313
|
+
*/
|
|
2314
|
+
parentId?: string;
|
|
2315
|
+
}
|
|
2316
|
+
interface PromoteToVerifiedInput {
|
|
2317
|
+
sourceIds: string[];
|
|
2318
|
+
tables: string[];
|
|
2319
|
+
parentId?: string;
|
|
2320
|
+
forkDepth?: number;
|
|
2321
|
+
forkReason?: string;
|
|
2322
|
+
components?: ScriptComponentSpec[];
|
|
2323
|
+
}
|
|
2324
|
+
interface ScriptStoreOptions {
|
|
2325
|
+
/** Explicit metadata store, or resolved from `collections['script-recipes']`. */
|
|
2326
|
+
store?: ScriptRecipeStore | null;
|
|
2327
|
+
collections?: any;
|
|
2328
|
+
/** Body directory (defaults to <cwd>/scripts-store). */
|
|
2329
|
+
baseDir?: string;
|
|
2330
|
+
/** Project scope stamped on every row. */
|
|
2331
|
+
projectId?: string;
|
|
2332
|
+
}
|
|
2333
|
+
/**
|
|
2334
|
+
* Normalize a scriptBody into the on-disk form (strip a leading comment block,
|
|
2335
|
+
* ensure `export async function getData`). Exported for MainAgent.
|
|
2336
|
+
*/
|
|
2337
|
+
declare function normalizeScriptBody(scriptBody: string): string;
|
|
2338
|
+
declare class ScriptStore {
|
|
2339
|
+
private store;
|
|
2340
|
+
private storeDir;
|
|
2341
|
+
private projectId?;
|
|
2342
|
+
constructor(opts?: ScriptStoreOptions);
|
|
2343
|
+
/** Whether a metadata store is wired (matcher / authoring are gated on this). */
|
|
2344
|
+
hasStore(): boolean;
|
|
2345
|
+
/** Number of healthy verified recipes (gates the script-matching path). */
|
|
2346
|
+
count(): Promise<number>;
|
|
2347
|
+
/**
|
|
2348
|
+
* FTS shortlist for the matcher (metadata only — bodies are loaded lazily by
|
|
2349
|
+
* `get()` once the LLM picks one). Returns verified, healthy recipes ranked
|
|
2350
|
+
* by relevance.
|
|
2351
|
+
*/
|
|
2352
|
+
search(prompt: string, limit?: number): Promise<ScriptRecipe[]>;
|
|
2353
|
+
/** Fetch one recipe by id with its body loaded from disk. */
|
|
2354
|
+
get(id: string): Promise<ScriptRecipe | null>;
|
|
2355
|
+
/** Create or update a recipe (metadata upsert + body write when changed). */
|
|
2356
|
+
save(recipe: ScriptRecipe): Promise<void>;
|
|
2357
|
+
/**
|
|
2358
|
+
* Persist (or update) a draft. Within a turn, retries that pass the same
|
|
2359
|
+
* `recipeId` overwrite the same row + file; a fresh `recipeId` mints a new
|
|
2360
|
+
* draft. The body is visible at scripts-store/<fileBase>.ts immediately.
|
|
2361
|
+
*/
|
|
2362
|
+
saveDraft(input: SaveDraftInput): Promise<ScriptRecipe>;
|
|
2363
|
+
/** Stamp a draft's last execution error (metadata only). */
|
|
2364
|
+
recordDraftError(recipeId: string, err: {
|
|
2365
|
+
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
2366
|
+
message: string;
|
|
2367
|
+
attempt: number;
|
|
2368
|
+
}): Promise<void>;
|
|
2369
|
+
/**
|
|
2370
|
+
* Promote a successfully-executed draft into a verified script.
|
|
2371
|
+
* The on-disk body already exists at <fileBase>.ts (written at write_script
|
|
2372
|
+
* time) and keeps its name — only the DB row flips status + provenance.
|
|
2373
|
+
*/
|
|
2374
|
+
promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): Promise<ScriptRecipe | null>;
|
|
2375
|
+
/**
|
|
2376
|
+
* Commit a user-directed edit: merge a VERIFIED shadow draft back onto the
|
|
2377
|
+
* recipe it was editing, as version N+1 under the SAME recipe id.
|
|
2378
|
+
*
|
|
2379
|
+
* Keeping the id stable is the point of the whole feature — every cached
|
|
2380
|
+
* conversation, `script_dataset` regeneration descriptor and persisted
|
|
2381
|
+
* component spec already points at it, so the correction applies retroactively
|
|
2382
|
+
* to replays instead of stranding them on the old body.
|
|
2383
|
+
*
|
|
2384
|
+
* Steps (see backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5):
|
|
2385
|
+
* 1. archive the current body as `<fileBase>.v<version>.ts`
|
|
2386
|
+
* 2. write the edited body to the original fileBase (atomic)
|
|
2387
|
+
* 3. version++, copy name/description/params, append a history record
|
|
2388
|
+
* 4. reset health counters — the pre-edit failure history is stale
|
|
2389
|
+
* 5. clear component specs — they were validated against the OLD shape
|
|
2390
|
+
* 6. delete the shadow draft (row + file)
|
|
2391
|
+
*
|
|
2392
|
+
* Returns the updated recipe, or null when the commit could not be applied
|
|
2393
|
+
* (caller should then fall back to treating the draft as a new script).
|
|
2394
|
+
*/
|
|
2395
|
+
commitEdit(targetId: string, draft: {
|
|
2396
|
+
recipeId: string;
|
|
2397
|
+
name?: string;
|
|
2398
|
+
intentDescription?: string;
|
|
2399
|
+
tags?: string[];
|
|
2400
|
+
parameters?: ScriptParameter[];
|
|
2401
|
+
scriptBody: string;
|
|
2402
|
+
sourceIds?: string[];
|
|
2403
|
+
tables?: string[];
|
|
2404
|
+
}, meta: {
|
|
2405
|
+
instruction?: string;
|
|
2406
|
+
changeSummary?: string;
|
|
2407
|
+
editedBy?: string;
|
|
2408
|
+
}): Promise<ScriptRecipe | null>;
|
|
2409
|
+
/**
|
|
2410
|
+
* Drop a draft (row + body file). MainAgent calls this at end-of-turn when a
|
|
2411
|
+
* draft was authored but never verified — failed drafts are never matched, so
|
|
2412
|
+
* deleting them immediately avoids unbounded accumulation (#5). No-op if the
|
|
2413
|
+
* recipe isn't a draft (so a promoted/verified script is never removed here).
|
|
2414
|
+
*/
|
|
2415
|
+
discardDraft(recipeId: string): Promise<void>;
|
|
2416
|
+
/** Delete a recipe (row + body file). */
|
|
2417
|
+
delete(id: string): Promise<void>;
|
|
2418
|
+
/** Record a successful execution (atomic counter bump). */
|
|
2419
|
+
recordSuccess(id: string): Promise<void>;
|
|
2420
|
+
/** Record a failed execution (atomic counter bump). */
|
|
2421
|
+
recordFailure(id: string): Promise<void>;
|
|
2422
|
+
/** Absolute path to the .ts body for a recipe (used by the runner/MainAgent). */
|
|
2423
|
+
getScriptPath(recipe: ScriptRecipe): string;
|
|
2424
|
+
private removeById;
|
|
2425
|
+
private rowToRecipe;
|
|
2426
|
+
private recipeToRow;
|
|
2427
|
+
/** slug of name, with a short id suffix when the bare slug is already taken. */
|
|
2428
|
+
private computeFileBase;
|
|
2429
|
+
private toSlug;
|
|
2430
|
+
private hash;
|
|
2431
|
+
private bodyPath;
|
|
2432
|
+
private readBody;
|
|
2433
|
+
/** Directory holding superseded bodies. Dot-prefixed so IDEs/`ls` hide it. */
|
|
2434
|
+
private get archiveDir();
|
|
2435
|
+
/**
|
|
2436
|
+
* Archive a superseded body as `.versions/<fileBase>.v<n>.ts`.
|
|
2437
|
+
*
|
|
2438
|
+
* Kept out of the main store directory on purpose — see commitEdit step 1.
|
|
2439
|
+
* To roll back: copy the file back over `scripts-store/<fileBase>.ts`.
|
|
2440
|
+
*/
|
|
2441
|
+
private writeArchive;
|
|
2442
|
+
/**
|
|
2443
|
+
* Move a recipe's archived versions to a new prefix when its fileBase changes,
|
|
2444
|
+
* so all versions of one recipe stay grouped. Without this, two renames would
|
|
2445
|
+
* scatter a single recipe's history across three prefixes in `.versions/` with
|
|
2446
|
+
* nothing linking them back to the live script.
|
|
2447
|
+
*/
|
|
2448
|
+
private renameArchives;
|
|
2449
|
+
/** Atomic body write (temp + rename) so concurrent reads never see a partial file. */
|
|
2450
|
+
private writeBody;
|
|
2451
|
+
private unlinkBody;
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
/**
|
|
2455
|
+
* Main Agent (Orchestrator)
|
|
2456
|
+
*
|
|
2457
|
+
* A single LLM.streamWithTools() call that handles everything:
|
|
2458
|
+
* - Routing: decides which source(s) to query based on summaries
|
|
2459
|
+
* - Querying: calls source tools (each wraps an independent SourceAgent)
|
|
2460
|
+
* - Direct tools: calls pre-built function tools directly with LLM-provided params
|
|
2461
|
+
* - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
|
|
2462
|
+
* - Analysis: generates final text response from the data
|
|
2463
|
+
*
|
|
2464
|
+
* Two tool types:
|
|
2465
|
+
* - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
|
|
2466
|
+
* - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
|
|
2467
|
+
*/
|
|
2468
|
+
|
|
2469
|
+
declare class MainAgent {
|
|
2470
|
+
private externalTools;
|
|
2471
|
+
private workflows;
|
|
2472
|
+
private config;
|
|
2473
|
+
private streamBuffer;
|
|
2474
|
+
/**
|
|
2475
|
+
* Optional: when provided, MainAgent exposes the `write_script` /
|
|
2476
|
+
* `execute_script` tools to the LLM and persists drafts to disk via the
|
|
2477
|
+
* store. Headless callers (alert analyzer, metric resolver) omit these to
|
|
2478
|
+
* suppress script authoring entirely — drafts would otherwise leak onto
|
|
2479
|
+
* disk with no caller to promote or clean them up.
|
|
2480
|
+
*/
|
|
2481
|
+
private scriptStore;
|
|
2482
|
+
private turnId;
|
|
2483
|
+
private createdFromPrompt;
|
|
2484
|
+
private scriptState;
|
|
2485
|
+
/** Answer-flow component catalog (filtered + projected by the caller). */
|
|
2486
|
+
private componentCatalog;
|
|
2487
|
+
/** Specs accepted by `render_components` this turn; empty until it succeeds. */
|
|
2488
|
+
/**
|
|
2489
|
+
* Entities resolved this turn, appended verbatim to every source dispatch.
|
|
2490
|
+
*
|
|
2491
|
+
* Not left to the model to copy into its intent prose: observed live, the
|
|
2492
|
+
* MainAgent wrote names instead of ids on the first dispatch AND re-spelled
|
|
2493
|
+
* 'F D C LIMITED' as 'FDC Limited', so the source agent fell back to
|
|
2494
|
+
* `PartyName LIKE '%FDC%'` and found 2 of 3 customers. Carrying the ids
|
|
2495
|
+
* structurally makes that impossible rather than instruction-dependent.
|
|
2496
|
+
*/
|
|
2497
|
+
private resolvedEntities;
|
|
2498
|
+
private componentSpecs;
|
|
2499
|
+
private componentLayout;
|
|
2500
|
+
private renderComponentAttempts;
|
|
2501
|
+
/**
|
|
2502
|
+
* Fork mode — set when this turn is adapting a near-matching parent script.
|
|
2503
|
+
* In fork mode there is no legitimate "answer with bare text" outcome: the
|
|
2504
|
+
* only correct first move is a tool call (write_script, or a source tool for
|
|
2505
|
+
* schema discovery). We therefore force tool use on the first LLM iteration
|
|
2506
|
+
* so the model can't end its turn with a bare "I'll adapt…" preamble and zero
|
|
2507
|
+
* tool calls. Never set on the fresh-authoring / general-question path.
|
|
2508
|
+
*/
|
|
2509
|
+
private forkMode;
|
|
2510
|
+
/**
|
|
2511
|
+
* Edit mode — set when this turn applies a user-directed change to an
|
|
2512
|
+
* existing script. Swaps the system prompt to `agent-main-edit` and stamps
|
|
2513
|
+
* the shadow draft's parentId. Like fork mode there is no legitimate
|
|
2514
|
+
* "answer with bare text" outcome, so tool use is forced on iteration 1.
|
|
2515
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 4.
|
|
2516
|
+
*/
|
|
2517
|
+
private editContext;
|
|
2518
|
+
/**
|
|
2519
|
+
* Per-turn cancellation signal (user hit "Stop"). Set at the top of
|
|
2520
|
+
* handleQuestion and read by the tool handler, the SourceAgent dispatch, and
|
|
2521
|
+
* the script subprocess so an abort tears down every layer of the turn.
|
|
2522
|
+
*/
|
|
2523
|
+
private abortSignal?;
|
|
2524
|
+
constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[], forkMode?: boolean, editContext?: EditContext, componentCatalog?: Component[]);
|
|
2525
|
+
/** True when the turn is applying a user-directed script edit. */
|
|
2526
|
+
private get editMode();
|
|
2527
|
+
private get scriptingEnabled();
|
|
2528
|
+
/**
|
|
2529
|
+
* Handle a user question using the multi-agent system.
|
|
2530
|
+
*
|
|
2531
|
+
* This is ONE LLM.streamWithTools() call. The LLM:
|
|
2532
|
+
* 1. Sees source summaries + direct tool descriptions in system prompt
|
|
2533
|
+
* 2. Decides which tool(s) to call (routing)
|
|
2534
|
+
* 3. Source tools → SourceAgent runs independently → returns data
|
|
2535
|
+
* 4. Direct tools → fn() called directly with LLM params → returns data
|
|
2536
|
+
* 5. Generates final analysis text
|
|
2537
|
+
*/
|
|
2538
|
+
handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, signal?: AbortSignal): Promise<AgentResponse>;
|
|
2539
|
+
/**
|
|
2540
|
+
* Tool definition, with the catalog rendered from the registered `Metadata`
|
|
2541
|
+
* the caller passed in. Generated rather than hand-written so it cannot drift
|
|
2542
|
+
* from what the frontend actually ships.
|
|
2543
|
+
*/
|
|
2544
|
+
private buildRenderComponentsToolDef;
|
|
2545
|
+
/**
|
|
2546
|
+
* Validate the agent's component picks against the REAL columns of each bound
|
|
2547
|
+
* dataset. All-or-nothing: any error rejects the whole call and returns the
|
|
2548
|
+
* findings, because a partially-accepted dashboard makes the retry ambiguous.
|
|
2549
|
+
*/
|
|
2550
|
+
private handleRenderComponents;
|
|
2551
|
+
private handleWriteScript;
|
|
2552
|
+
private handleExecuteScript;
|
|
2553
|
+
/**
|
|
2554
|
+
* Build the AgentWrittenScript payload the caller will hand to
|
|
2555
|
+
* `ScriptStore.promoteToVerified()`. Only returned when a verified
|
|
2556
|
+
* successful execution is on record.
|
|
2557
|
+
*/
|
|
2558
|
+
private buildSavedScript;
|
|
2559
|
+
private normalizeParameterList;
|
|
2560
|
+
/**
|
|
2561
|
+
* Use the schema embedding collection to pre-select relevant tables for
|
|
2562
|
+
* this source + intent. Returns a formatted schema block if confidence is
|
|
2563
|
+
* high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
|
|
2564
|
+
*
|
|
2565
|
+
* When this returns a block, we can skip the SourceAgent's `search_schema`
|
|
2566
|
+
* loop and reduce iteration budget. When it returns null, the SourceAgent
|
|
2567
|
+
* falls back to the existing LLM-driven keyword search (same as today).
|
|
2568
|
+
*/
|
|
2569
|
+
/**
|
|
2570
|
+
* Ids + verbatim names for everything resolved this turn, appended by CODE to
|
|
2571
|
+
* each source dispatch so neither omission nor re-spelling by the model can
|
|
2572
|
+
* lose them. Empty string when nothing was resolved, so intents are untouched
|
|
2573
|
+
* for questions that name no entities.
|
|
2574
|
+
*/
|
|
2575
|
+
private buildResolvedEntitiesBlock;
|
|
2576
|
+
/** True when the backend registered the entity-search collection. */
|
|
2577
|
+
private get entitySearchEnabled();
|
|
2578
|
+
/**
|
|
2579
|
+
* Compact catalog (type + gloss) for the system prompt. This is what lets the
|
|
2580
|
+
* LLM NAME a concept instead of guessing at our vocabulary — it can infer
|
|
2581
|
+
* that a question is about unpaid money, but not that we call that
|
|
2582
|
+
* `outstanding-balance`. Full `resolution` detail is fetched by the tool.
|
|
2583
|
+
*
|
|
2584
|
+
* Deliberately NOT cached in-process. The token cost is already handled by
|
|
2585
|
+
* prompt caching (the system prompt carries a cache_control breakpoint), and
|
|
2586
|
+
* re-reading a tiny PK-ordered table costs ~nothing. Fetching fresh does not
|
|
2587
|
+
* weaken the prompt cache either: unchanged data renders byte-identical text,
|
|
2588
|
+
* so the prefix still hits. A process cache would only buy a staleness window
|
|
2589
|
+
* in which a newly indexed entity is invisible to the agent.
|
|
2590
|
+
*/
|
|
2591
|
+
private loadEntityCatalog;
|
|
2592
|
+
/**
|
|
2593
|
+
* Never throws: a resolver outage must degrade to "nothing resolved" and
|
|
2594
|
+
* leave the agent exactly as it was, not take the whole answer down.
|
|
2595
|
+
*/
|
|
2596
|
+
private handleResolveEntities;
|
|
2597
|
+
private preResolveSchema;
|
|
2598
|
+
/**
|
|
2599
|
+
* Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
|
|
2600
|
+
*/
|
|
2601
|
+
private handleDirectTool;
|
|
2602
|
+
/**
|
|
2603
|
+
* Build the main agent's system prompt with source summaries, direct tool descriptions,
|
|
2604
|
+
* and workflow component descriptions.
|
|
2605
|
+
*/
|
|
2606
|
+
private buildSystemPrompt;
|
|
2607
|
+
/**
|
|
2608
|
+
* Build tool definitions for source tools — summary-only descriptions.
|
|
2609
|
+
* The full schema is inside the SourceAgent which runs independently.
|
|
2610
|
+
*/
|
|
2611
|
+
private buildSourceToolDefinitions;
|
|
2612
|
+
/**
|
|
2613
|
+
* Build tool definitions for direct tools — expose their actual params.
|
|
2614
|
+
* These are called directly by the main agent LLM, no SourceAgent.
|
|
2615
|
+
*/
|
|
2616
|
+
private buildDirectToolDefinitions;
|
|
2617
|
+
/**
|
|
2618
|
+
* Capture a workflow selection. We do NOT execute anything — the LLM has
|
|
2619
|
+
* already extracted the props it wants the workflow rendered with. We
|
|
2620
|
+
* record the selection (via the capture callback) and return a short
|
|
2621
|
+
* acknowledgement so the LLM ends its turn cleanly without writing
|
|
2622
|
+
* analysis text or calling more tools.
|
|
2623
|
+
*/
|
|
2624
|
+
private handleWorkflow;
|
|
2625
|
+
/**
|
|
2626
|
+
* Build LLM tool definitions for workflow components. The workflow's
|
|
2627
|
+
* propsSchema becomes the tool's input_schema so the LLM extracts props
|
|
2628
|
+
* directly from the prompt — same mechanic as direct tools.
|
|
2629
|
+
*/
|
|
2630
|
+
private buildWorkflowToolDefinitions;
|
|
2631
|
+
/**
|
|
2632
|
+
* Format a source agent's result as a clean string for the main agent LLM.
|
|
2633
|
+
*/
|
|
2634
|
+
private formatResultForMainAgent;
|
|
2635
|
+
/**
|
|
2636
|
+
* Get source summaries (for external inspection/debugging).
|
|
2637
|
+
*/
|
|
2638
|
+
getSourceSummaries(): SourceSummary[];
|
|
2639
|
+
}
|
|
2640
|
+
|
|
2641
|
+
/**
|
|
2642
|
+
* Represents an action that can be performed on a UIBlock
|
|
2643
|
+
*/
|
|
2644
|
+
interface Action {
|
|
2645
|
+
id: string;
|
|
2646
|
+
name: string;
|
|
2647
|
+
type: string;
|
|
2648
|
+
[key: string]: any;
|
|
2649
|
+
}
|
|
2650
|
+
|
|
1048
2651
|
type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
|
|
1049
2652
|
interface LLMMessages {
|
|
1050
2653
|
sys: SystemPrompt;
|
|
@@ -1057,7 +2660,45 @@ interface LLMOptions {
|
|
|
1057
2660
|
temperature?: number;
|
|
1058
2661
|
topP?: number;
|
|
1059
2662
|
apiKey?: string;
|
|
2663
|
+
baseURL?: string;
|
|
1060
2664
|
partial?: (chunk: string) => void;
|
|
2665
|
+
/**
|
|
2666
|
+
* Per-request cancellation. When the caller aborts this signal (user hit
|
|
2667
|
+
* "Stop"), the underlying provider request is cancelled and the call throws
|
|
2668
|
+
* a RequestAbortedError. Threaded into the provider `messages.create` request
|
|
2669
|
+
* options and checked between tool-loop iterations. Currently honored on the
|
|
2670
|
+
* Anthropic path (the agent flow's default provider).
|
|
2671
|
+
*/
|
|
2672
|
+
signal?: AbortSignal;
|
|
2673
|
+
/**
|
|
2674
|
+
* Forces a tool call on the FIRST iteration of streamWithTools only
|
|
2675
|
+
* (subsequent iterations revert to auto). Used by fork mode to stop the
|
|
2676
|
+
* model from ending its turn with a bare "I'll adapt the script…" preamble
|
|
2677
|
+
* and zero tool calls. `{ type: 'any' }` lets the model pick which tool
|
|
2678
|
+
* (write_script in the common case, a source tool for schema discovery);
|
|
2679
|
+
* `{ type: 'tool', name }` pins a specific tool. Honored on both the
|
|
2680
|
+
* Anthropic path and the OpenAI/OpenRouter path (mapped to OpenAI's
|
|
2681
|
+
* tool_choice: 'required' / a named function).
|
|
2682
|
+
*/
|
|
2683
|
+
firstIterationToolChoice?: {
|
|
2684
|
+
type: 'any';
|
|
2685
|
+
} | {
|
|
2686
|
+
type: 'tool';
|
|
2687
|
+
name: string;
|
|
2688
|
+
};
|
|
2689
|
+
/**
|
|
2690
|
+
* Internal — set only by the OpenRouter wrappers when the target is a Claude
|
|
2691
|
+
* model. Tells the OpenAI-wire path to emit Anthropic `cache_control`
|
|
2692
|
+
* breakpoints (OpenRouter forwards them to Anthropic for prompt caching).
|
|
2693
|
+
* Never set for direct OpenAI/Groq calls, so their requests are unchanged.
|
|
2694
|
+
*/
|
|
2695
|
+
_openrouterClaudeCaching?: boolean;
|
|
2696
|
+
/**
|
|
2697
|
+
* Internal — OpenRouter provider-routing preferences (forwarded as the
|
|
2698
|
+
* `provider` body field). Set by the OpenRouter wrappers to steer routing to
|
|
2699
|
+
* a fast backend (e.g. {sort:'throughput'}). Never set for direct OpenAI/Groq.
|
|
2700
|
+
*/
|
|
2701
|
+
_openrouterProvider?: Record<string, unknown>;
|
|
1061
2702
|
}
|
|
1062
2703
|
interface Tool {
|
|
1063
2704
|
name: string;
|
|
@@ -1079,6 +2720,16 @@ declare class LLM {
|
|
|
1079
2720
|
* @returns Normalized system prompt for Anthropic API
|
|
1080
2721
|
*/
|
|
1081
2722
|
private static _normalizeSystemPrompt;
|
|
2723
|
+
/**
|
|
2724
|
+
* Strip unpaired UTF-16 surrogates from every text field of a message set.
|
|
2725
|
+
*
|
|
2726
|
+
* A lone surrogate (from mid-pair string slicing or corrupt source data)
|
|
2727
|
+
* serializes to a bare `\udXXX` escape that strict JSON parsers — including
|
|
2728
|
+
* the one on Anthropic's API — reject with "no low surrogate in string",
|
|
2729
|
+
* failing the whole request. Sanitizing here, at the single boundary every
|
|
2730
|
+
* provider call flows through, guarantees no request can carry one.
|
|
2731
|
+
*/
|
|
2732
|
+
private static _sanitizeMessages;
|
|
1082
2733
|
/**
|
|
1083
2734
|
* Log cache usage metrics from Anthropic API response
|
|
1084
2735
|
* Shows cache hits, costs, and savings
|
|
@@ -1095,16 +2746,76 @@ declare class LLM {
|
|
|
1095
2746
|
* "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
|
|
1096
2747
|
*/
|
|
1097
2748
|
private static _parseModel;
|
|
2749
|
+
/**
|
|
2750
|
+
* Map an Anthropic model id (e.g. "claude-sonnet-4-5-20250929") to the OpenRouter slug
|
|
2751
|
+
* (e.g. "claude-sonnet-4.5"). OpenRouter slugs drop the date suffix and use dotted versions.
|
|
2752
|
+
*/
|
|
2753
|
+
private static _toOpenRouterSlug;
|
|
2754
|
+
/**
|
|
2755
|
+
* Per-provider proxy base URL. Returns `${SUPERATOM_LLM_PROXY_URL}/<provider>`
|
|
2756
|
+
* when our Cloudflare LLM proxy is configured, else undefined (→ talk to the
|
|
2757
|
+
* provider directly, legacy behaviour). An explicit options.baseURL (e.g.
|
|
2758
|
+
* OpenRouter) always wins and is never overridden. See backend/docs/llm-proxy.md.
|
|
2759
|
+
*/
|
|
2760
|
+
private static _proxyBaseURL;
|
|
2761
|
+
private static _openrouterOptions;
|
|
2762
|
+
private static _isRetryableProviderError;
|
|
2763
|
+
private static _withOpenrouterRetry;
|
|
2764
|
+
private static _openrouterText;
|
|
2765
|
+
private static _openrouterStream;
|
|
2766
|
+
private static _openrouterStreamWithTools;
|
|
2767
|
+
/**
|
|
2768
|
+
* Build an Anthropic client. Routes through our Cloudflare LLM proxy when
|
|
2769
|
+
* SUPERATOM_LLM_PROXY_URL is set (each client ships a per-client proxy key as
|
|
2770
|
+
* ANTHROPIC_API_KEY and never holds the real key); otherwise talks to
|
|
2771
|
+
* api.anthropic.com directly. See backend/docs/llm-proxy.md.
|
|
2772
|
+
*/
|
|
2773
|
+
private static _anthropicClient;
|
|
2774
|
+
/** True when OpenRouter is configured as a fail-open fallback for Claude. */
|
|
2775
|
+
private static _openrouterAvailable;
|
|
2776
|
+
/** Remap an Anthropic model id to the OpenRouter model path for fail-open. */
|
|
2777
|
+
private static _anthropicFallbackModel;
|
|
1098
2778
|
private static _anthropicText;
|
|
1099
2779
|
private static _anthropicStream;
|
|
1100
2780
|
private static _anthropicStreamWithTools;
|
|
1101
2781
|
private static _groqText;
|
|
1102
2782
|
private static _groqStream;
|
|
2783
|
+
/**
|
|
2784
|
+
* Gemini request options carrying the proxy base URL, or undefined → talk to
|
|
2785
|
+
* generativelanguage.googleapis.com directly. The Google SDK takes baseUrl as a
|
|
2786
|
+
* per-model request option, not a constructor arg. See backend/docs/llm-proxy.md.
|
|
2787
|
+
*/
|
|
2788
|
+
private static _geminiRequestOptions;
|
|
1103
2789
|
private static _geminiText;
|
|
1104
2790
|
private static _geminiStream;
|
|
2791
|
+
/**
|
|
2792
|
+
* Recursively strip unsupported JSON Schema properties for Gemini
|
|
2793
|
+
* Gemini doesn't support: additionalProperties, $schema, etc.
|
|
2794
|
+
*/
|
|
2795
|
+
private static _cleanSchemaForGemini;
|
|
1105
2796
|
private static _geminiStreamWithTools;
|
|
2797
|
+
/** True for Anthropic/Claude model ids — gates OpenRouter prompt caching. */
|
|
2798
|
+
private static _isClaudeModel;
|
|
2799
|
+
/**
|
|
2800
|
+
* Build the OpenAI-wire system message. For OpenRouter + Claude
|
|
2801
|
+
* (cacheClaude=true) it emits content parts carrying Anthropic
|
|
2802
|
+
* `cache_control` breakpoints (preserving any the caller set, else marking
|
|
2803
|
+
* the last block), so OpenRouter forwards them to Anthropic for prompt
|
|
2804
|
+
* caching. Otherwise it returns a plain flattened string — unchanged for
|
|
2805
|
+
* direct OpenAI/Groq.
|
|
2806
|
+
*/
|
|
2807
|
+
private static _openaiSystemMessage;
|
|
2808
|
+
/**
|
|
2809
|
+
* Split an OpenAI-wire usage object. `prompt_tokens` INCLUDES cached tokens,
|
|
2810
|
+
* so we subtract them out (Anthropic-style: input excludes cache reads) and
|
|
2811
|
+
* report cached separately — this makes calculateCost price cache reads at
|
|
2812
|
+
* the discounted rate and reflects OpenRouter prompt-cache savings in logs.
|
|
2813
|
+
*/
|
|
2814
|
+
private static _openaiUsage;
|
|
1106
2815
|
private static _openaiText;
|
|
1107
2816
|
private static _openaiStream;
|
|
2817
|
+
/** Map the Anthropic-style firstIterationToolChoice to OpenAI's tool_choice. */
|
|
2818
|
+
private static _openaiToolChoice;
|
|
1108
2819
|
private static _openaiStreamWithTools;
|
|
1109
2820
|
/**
|
|
1110
2821
|
* Parse JSON string, handling markdown code blocks and surrounding text
|
|
@@ -1194,16 +2905,6 @@ declare class UILogCollector {
|
|
|
1194
2905
|
setUIBlockId(uiBlockId: string): void;
|
|
1195
2906
|
}
|
|
1196
2907
|
|
|
1197
|
-
/**
|
|
1198
|
-
* Represents an action that can be performed on a UIBlock
|
|
1199
|
-
*/
|
|
1200
|
-
interface Action {
|
|
1201
|
-
id: string;
|
|
1202
|
-
name: string;
|
|
1203
|
-
type: string;
|
|
1204
|
-
[key: string]: any;
|
|
1205
|
-
}
|
|
1206
|
-
|
|
1207
2908
|
/**
|
|
1208
2909
|
* UIBlock represents a single user and assistant message block in a thread
|
|
1209
2910
|
* Contains user question, component metadata, component data, text response, and available actions
|
|
@@ -1216,6 +2917,13 @@ declare class UIBlock {
|
|
|
1216
2917
|
private textResponse;
|
|
1217
2918
|
private actions;
|
|
1218
2919
|
private createdAt;
|
|
2920
|
+
/**
|
|
2921
|
+
* Which script recipe produced this answer, when a script did. Read on the
|
|
2922
|
+
* NEXT turn so the user can say "use mode instead" and have the matcher
|
|
2923
|
+
* resolve it to a concrete script (the `edit` tier is unreachable without it).
|
|
2924
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
2925
|
+
*/
|
|
2926
|
+
private scriptBinding;
|
|
1219
2927
|
/**
|
|
1220
2928
|
* Creates a new UIBlock instance
|
|
1221
2929
|
* @param userQuestion - The user's question or input
|
|
@@ -1310,6 +3018,14 @@ declare class UIBlock {
|
|
|
1310
3018
|
/**
|
|
1311
3019
|
* Get creation timestamp
|
|
1312
3020
|
*/
|
|
3021
|
+
/**
|
|
3022
|
+
* Bind this block to the script recipe that produced its answer.
|
|
3023
|
+
*/
|
|
3024
|
+
setScriptBinding(binding: Record<string, any> | null): void;
|
|
3025
|
+
/**
|
|
3026
|
+
* The script recipe bound to this block, if any.
|
|
3027
|
+
*/
|
|
3028
|
+
getScriptBinding(): Record<string, any> | null;
|
|
1313
3029
|
getCreatedAt(): Date;
|
|
1314
3030
|
/**
|
|
1315
3031
|
* Convert UIBlock to JSON-serializable object
|
|
@@ -1377,6 +3093,32 @@ declare class Thread {
|
|
|
1377
3093
|
* @param currentUIBlockId - ID of current UIBlock to exclude from context (optional)
|
|
1378
3094
|
* @returns Formatted conversation history string
|
|
1379
3095
|
*/
|
|
3096
|
+
/**
|
|
3097
|
+
* The script recipe bound to the most recent completed UIBlock — i.e. the
|
|
3098
|
+
* script behind the answer the user is currently looking at. Drives the
|
|
3099
|
+
* matcher's `edit` tier: without it, "use mode instead" has no target and
|
|
3100
|
+
* falls through to regeneration.
|
|
3101
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
3102
|
+
*/
|
|
3103
|
+
getActiveScriptBinding(currentUIBlockId?: string): Record<string, any> | null;
|
|
3104
|
+
/**
|
|
3105
|
+
* The recent script-backed answers in this thread, newest first — the
|
|
3106
|
+
* candidate set a user-directed edit can target.
|
|
3107
|
+
*
|
|
3108
|
+
* Returning several rather than only the newest is what lets an instruction
|
|
3109
|
+
* name its own target ("use the mode for the WSP one"). With a single
|
|
3110
|
+
* candidate every edit lands on the most recent script, which silently edits
|
|
3111
|
+
* the wrong recipe whenever the user meant an earlier one.
|
|
3112
|
+
*
|
|
3113
|
+
* Deduped by recipeId (newest occurrence wins) so a long editing session on
|
|
3114
|
+
* one script doesn't crowd out the others. Each entry carries the question
|
|
3115
|
+
* that produced it — without that the candidates are indistinguishable.
|
|
3116
|
+
*
|
|
3117
|
+
* In-memory only: dies with the process. The caller falls back to the
|
|
3118
|
+
* persisted bindings when this comes back empty.
|
|
3119
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
3120
|
+
*/
|
|
3121
|
+
getScriptBindings(limit?: number, currentUIBlockId?: string): Record<string, any>[];
|
|
1380
3122
|
getConversationContext(limit?: number, currentUIBlockId?: string): string;
|
|
1381
3123
|
/**
|
|
1382
3124
|
* Convert Thread to JSON-serializable object
|
|
@@ -1386,12 +3128,20 @@ declare class Thread {
|
|
|
1386
3128
|
|
|
1387
3129
|
/**
|
|
1388
3130
|
* ThreadManager manages all threads globally
|
|
1389
|
-
* Provides methods to create, retrieve, and delete threads
|
|
3131
|
+
* Provides methods to create, retrieve, and delete threads.
|
|
3132
|
+
* Includes automatic cleanup to prevent unbounded memory growth.
|
|
1390
3133
|
*/
|
|
1391
3134
|
declare class ThreadManager {
|
|
1392
3135
|
private static instance;
|
|
1393
3136
|
private threads;
|
|
3137
|
+
private cleanupInterval;
|
|
3138
|
+
private readonly threadTtlMs;
|
|
1394
3139
|
private constructor();
|
|
3140
|
+
/**
|
|
3141
|
+
* Periodically remove threads older than 7 days.
|
|
3142
|
+
* Runs every hour to avoid frequent iteration over the map.
|
|
3143
|
+
*/
|
|
3144
|
+
private startCleanup;
|
|
1395
3145
|
/**
|
|
1396
3146
|
* Get singleton instance of ThreadManager
|
|
1397
3147
|
*/
|
|
@@ -1548,6 +3298,120 @@ declare const CONTEXT_CONFIG: {
|
|
|
1548
3298
|
MAX_CONVERSATION_CONTEXT_BLOCKS: number;
|
|
1549
3299
|
};
|
|
1550
3300
|
|
|
3301
|
+
/**
|
|
3302
|
+
* LLM Usage Logger - Tracks token usage, costs, and timing for all LLM API calls
|
|
3303
|
+
*/
|
|
3304
|
+
interface LLMUsageEntry {
|
|
3305
|
+
timestamp: string;
|
|
3306
|
+
requestId: string;
|
|
3307
|
+
provider: string;
|
|
3308
|
+
model: string;
|
|
3309
|
+
method: string;
|
|
3310
|
+
inputTokens: number;
|
|
3311
|
+
outputTokens: number;
|
|
3312
|
+
cacheReadTokens?: number;
|
|
3313
|
+
cacheWriteTokens?: number;
|
|
3314
|
+
totalTokens: number;
|
|
3315
|
+
costUSD: number;
|
|
3316
|
+
durationMs: number;
|
|
3317
|
+
toolCalls?: number;
|
|
3318
|
+
success: boolean;
|
|
3319
|
+
error?: string;
|
|
3320
|
+
}
|
|
3321
|
+
declare class LLMUsageLogger {
|
|
3322
|
+
private logStream;
|
|
3323
|
+
private logPath;
|
|
3324
|
+
private enabled;
|
|
3325
|
+
private sessionStats;
|
|
3326
|
+
constructor();
|
|
3327
|
+
private initLogStream;
|
|
3328
|
+
private writeHeader;
|
|
3329
|
+
/**
|
|
3330
|
+
* Calculate cost based on token usage and model
|
|
3331
|
+
*/
|
|
3332
|
+
calculateCost(model: string, inputTokens: number, outputTokens: number, cacheReadTokens?: number, cacheWriteTokens?: number): number;
|
|
3333
|
+
/**
|
|
3334
|
+
* Log an LLM API call
|
|
3335
|
+
*/
|
|
3336
|
+
log(entry: LLMUsageEntry): void;
|
|
3337
|
+
/**
|
|
3338
|
+
* Log session summary (call at end of request)
|
|
3339
|
+
*/
|
|
3340
|
+
logSessionSummary(requestContext?: string): void;
|
|
3341
|
+
/**
|
|
3342
|
+
* Reset session stats (call at start of new user request)
|
|
3343
|
+
*/
|
|
3344
|
+
resetSession(): void;
|
|
3345
|
+
/**
|
|
3346
|
+
* Reset the log file for a new request (clears previous logs)
|
|
3347
|
+
* Call this at the start of each USER_PROMPT_REQ
|
|
3348
|
+
*/
|
|
3349
|
+
resetLogFile(requestContext?: string): void;
|
|
3350
|
+
/**
|
|
3351
|
+
* Get current session stats
|
|
3352
|
+
*/
|
|
3353
|
+
getSessionStats(): {
|
|
3354
|
+
totalCalls: number;
|
|
3355
|
+
totalInputTokens: number;
|
|
3356
|
+
totalOutputTokens: number;
|
|
3357
|
+
totalCacheReadTokens: number;
|
|
3358
|
+
totalCacheWriteTokens: number;
|
|
3359
|
+
totalCostUSD: number;
|
|
3360
|
+
totalDurationMs: number;
|
|
3361
|
+
};
|
|
3362
|
+
/**
|
|
3363
|
+
* Generate a unique request ID
|
|
3364
|
+
*/
|
|
3365
|
+
generateRequestId(): string;
|
|
3366
|
+
}
|
|
3367
|
+
declare const llmUsageLogger: LLMUsageLogger;
|
|
3368
|
+
|
|
3369
|
+
/**
|
|
3370
|
+
* User Prompt Error Logger - Captures detailed errors for USER_PROMPT_REQ
|
|
3371
|
+
* Logs full error details including raw strings for parse failures
|
|
3372
|
+
*/
|
|
3373
|
+
declare class UserPromptErrorLogger {
|
|
3374
|
+
private logStream;
|
|
3375
|
+
private logPath;
|
|
3376
|
+
private enabled;
|
|
3377
|
+
private hasErrors;
|
|
3378
|
+
constructor();
|
|
3379
|
+
/**
|
|
3380
|
+
* Reset the error log file for a new request
|
|
3381
|
+
*/
|
|
3382
|
+
resetLogFile(requestContext?: string): void;
|
|
3383
|
+
/**
|
|
3384
|
+
* Log a JSON parse error with the raw string that failed
|
|
3385
|
+
*/
|
|
3386
|
+
logJsonParseError(context: string, rawString: string, error: Error): void;
|
|
3387
|
+
/**
|
|
3388
|
+
* Log a general error with full details
|
|
3389
|
+
*/
|
|
3390
|
+
logError(context: string, error: Error | string, additionalData?: Record<string, any>): void;
|
|
3391
|
+
/**
|
|
3392
|
+
* Log a SQL query error with the full query
|
|
3393
|
+
*/
|
|
3394
|
+
logSqlError(query: string, error: Error | string, params?: any[]): void;
|
|
3395
|
+
/**
|
|
3396
|
+
* Log an LLM API error
|
|
3397
|
+
*/
|
|
3398
|
+
logLlmError(provider: string, model: string, method: string, error: Error | string, requestData?: any): void;
|
|
3399
|
+
/**
|
|
3400
|
+
* Log tool execution error
|
|
3401
|
+
*/
|
|
3402
|
+
logToolError(toolName: string, toolInput: any, error: Error | string): void;
|
|
3403
|
+
/**
|
|
3404
|
+
* Write final summary if there were errors
|
|
3405
|
+
*/
|
|
3406
|
+
writeSummary(): void;
|
|
3407
|
+
/**
|
|
3408
|
+
* Check if any errors were logged
|
|
3409
|
+
*/
|
|
3410
|
+
hadErrors(): boolean;
|
|
3411
|
+
private write;
|
|
3412
|
+
}
|
|
3413
|
+
declare const userPromptErrorLogger: UserPromptErrorLogger;
|
|
3414
|
+
|
|
1551
3415
|
/**
|
|
1552
3416
|
* BM25L Reranker for hybrid semantic search
|
|
1553
3417
|
*
|
|
@@ -1676,14 +3540,640 @@ declare function rerankConversationResults<T extends {
|
|
|
1676
3540
|
bm25Score: number;
|
|
1677
3541
|
}>;
|
|
1678
3542
|
|
|
1679
|
-
|
|
3543
|
+
/**
|
|
3544
|
+
* QueryExecutionService - Handles all query execution, validation, and retry logic
|
|
3545
|
+
* Extracted from BaseLLM for better separation of concerns
|
|
3546
|
+
*/
|
|
3547
|
+
|
|
3548
|
+
/**
|
|
3549
|
+
* Context for component when requesting query fix
|
|
3550
|
+
*/
|
|
3551
|
+
interface ComponentContext {
|
|
3552
|
+
name: string;
|
|
3553
|
+
type: string;
|
|
3554
|
+
title?: string;
|
|
3555
|
+
}
|
|
3556
|
+
/**
|
|
3557
|
+
* Result of query validation
|
|
3558
|
+
*/
|
|
3559
|
+
interface QueryValidationResult {
|
|
3560
|
+
component: Component | null;
|
|
3561
|
+
queryKey: string;
|
|
3562
|
+
result: any;
|
|
3563
|
+
validated: boolean;
|
|
3564
|
+
}
|
|
3565
|
+
/**
|
|
3566
|
+
* Result of batch query validation
|
|
3567
|
+
*/
|
|
3568
|
+
interface BatchValidationResult {
|
|
3569
|
+
components: Component[];
|
|
3570
|
+
queryResults: Map<string, any>;
|
|
3571
|
+
}
|
|
3572
|
+
/**
|
|
3573
|
+
* Configuration for QueryExecutionService
|
|
3574
|
+
*/
|
|
3575
|
+
interface QueryExecutionServiceConfig {
|
|
3576
|
+
defaultLimit: number;
|
|
3577
|
+
getModelForTask: (taskType: 'simple' | 'complex') => string;
|
|
3578
|
+
getApiKey: (apiKey?: string) => string | undefined;
|
|
3579
|
+
providerName: string;
|
|
3580
|
+
}
|
|
3581
|
+
/**
|
|
3582
|
+
* QueryExecutionService handles all query-related operations
|
|
3583
|
+
*/
|
|
3584
|
+
declare class QueryExecutionService {
|
|
3585
|
+
private config;
|
|
3586
|
+
constructor(config: QueryExecutionServiceConfig);
|
|
3587
|
+
/**
|
|
3588
|
+
* Get the cache key for a query
|
|
3589
|
+
* This ensures the cache key matches what the frontend will send
|
|
3590
|
+
*/
|
|
3591
|
+
getQueryCacheKey(query: any): string;
|
|
3592
|
+
/**
|
|
3593
|
+
* Execute a query against the database
|
|
3594
|
+
* @param query - The SQL query to execute (string or object with sql/values)
|
|
3595
|
+
* @param collections - Collections object containing database execute function
|
|
3596
|
+
* @returns Object with result data and cache key
|
|
3597
|
+
*/
|
|
3598
|
+
executeQuery(query: any, collections: any): Promise<{
|
|
3599
|
+
result: any;
|
|
3600
|
+
cacheKey: string;
|
|
3601
|
+
}>;
|
|
3602
|
+
/**
|
|
3603
|
+
* Request the LLM to fix a failed SQL query
|
|
3604
|
+
* @param failedQuery - The query that failed execution
|
|
3605
|
+
* @param errorMessage - The error message from the failed execution
|
|
3606
|
+
* @param componentContext - Context about the component
|
|
3607
|
+
* @param apiKey - Optional API key
|
|
3608
|
+
* @returns Fixed query string
|
|
3609
|
+
*/
|
|
3610
|
+
requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
|
|
3611
|
+
/**
|
|
3612
|
+
* Validate a single component's query with retry logic
|
|
3613
|
+
* @param component - The component to validate
|
|
3614
|
+
* @param collections - Collections object containing database execute function
|
|
3615
|
+
* @param apiKey - Optional API key for LLM calls
|
|
3616
|
+
* @returns Validation result with component, query key, and result
|
|
3617
|
+
*/
|
|
3618
|
+
validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
|
|
3619
|
+
/**
|
|
3620
|
+
* Validate multiple component queries in parallel
|
|
3621
|
+
* @param components - Array of components with potential queries
|
|
3622
|
+
* @param collections - Collections object containing database execute function
|
|
3623
|
+
* @param apiKey - Optional API key for LLM calls
|
|
3624
|
+
* @returns Object with validated components and query results map
|
|
3625
|
+
*/
|
|
3626
|
+
validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
|
|
3627
|
+
}
|
|
3628
|
+
|
|
3629
|
+
/**
|
|
3630
|
+
* Task types for model selection
|
|
3631
|
+
* - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
|
|
3632
|
+
* - 'simple': Classification, action generation (uses fast model in balanced mode)
|
|
3633
|
+
*/
|
|
3634
|
+
type TaskType = 'complex' | 'simple';
|
|
3635
|
+
interface BaseLLMConfig {
|
|
3636
|
+
model?: string;
|
|
3637
|
+
fastModel?: string;
|
|
3638
|
+
defaultLimit?: number;
|
|
3639
|
+
apiKey?: string;
|
|
3640
|
+
/**
|
|
3641
|
+
* Model selection strategy:
|
|
3642
|
+
* - 'best': Use best model for all tasks (highest quality, higher cost)
|
|
3643
|
+
* - 'fast': Use fast model for all tasks (lower quality, lower cost)
|
|
3644
|
+
* - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
|
|
3645
|
+
*/
|
|
3646
|
+
modelStrategy?: ModelStrategy;
|
|
3647
|
+
conversationSimilarityThreshold?: number;
|
|
3648
|
+
}
|
|
3649
|
+
/**
|
|
3650
|
+
* BaseLLM abstract class for AI-powered component generation and matching
|
|
3651
|
+
* Provides common functionality for all LLM providers
|
|
3652
|
+
*/
|
|
3653
|
+
declare abstract class BaseLLM {
|
|
3654
|
+
protected model: string;
|
|
3655
|
+
protected fastModel: string;
|
|
3656
|
+
protected defaultLimit: number;
|
|
3657
|
+
protected apiKey?: string;
|
|
3658
|
+
protected modelStrategy: ModelStrategy;
|
|
3659
|
+
protected conversationSimilarityThreshold: number;
|
|
3660
|
+
protected queryService: QueryExecutionService;
|
|
3661
|
+
constructor(config?: BaseLLMConfig);
|
|
3662
|
+
/**
|
|
3663
|
+
* Get the appropriate model based on task type and model strategy
|
|
3664
|
+
* @param taskType - 'complex' for text generation/matching, 'simple' for classification/actions
|
|
3665
|
+
* @returns The model string to use for this task
|
|
3666
|
+
*/
|
|
3667
|
+
protected getModelForTask(taskType: TaskType): string;
|
|
3668
|
+
/**
|
|
3669
|
+
* Set the model strategy at runtime
|
|
3670
|
+
* @param strategy - 'best', 'fast', or 'balanced'
|
|
3671
|
+
*/
|
|
3672
|
+
setModelStrategy(strategy: ModelStrategy): void;
|
|
3673
|
+
/**
|
|
3674
|
+
* Get the current model strategy
|
|
3675
|
+
* @returns The current model strategy
|
|
3676
|
+
*/
|
|
3677
|
+
getModelStrategy(): ModelStrategy;
|
|
3678
|
+
/**
|
|
3679
|
+
* Set the conversation similarity threshold at runtime
|
|
3680
|
+
* @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
|
|
3681
|
+
*/
|
|
3682
|
+
setConversationSimilarityThreshold(threshold: number): void;
|
|
3683
|
+
/**
|
|
3684
|
+
* Get the current conversation similarity threshold
|
|
3685
|
+
* @returns The current threshold value
|
|
3686
|
+
*/
|
|
3687
|
+
getConversationSimilarityThreshold(): number;
|
|
3688
|
+
/**
|
|
3689
|
+
* Get the default model for this provider (used for complex tasks like text generation)
|
|
3690
|
+
*/
|
|
3691
|
+
protected abstract getDefaultModel(): string;
|
|
3692
|
+
/**
|
|
3693
|
+
* Get the default fast model for this provider (used for simple tasks: classification, matching, actions)
|
|
3694
|
+
* Should return a cheaper/faster model like Haiku for Anthropic
|
|
3695
|
+
*/
|
|
3696
|
+
protected abstract getDefaultFastModel(): string;
|
|
3697
|
+
/**
|
|
3698
|
+
* Get the default API key from environment
|
|
3699
|
+
*/
|
|
3700
|
+
protected abstract getDefaultApiKey(): string | undefined;
|
|
3701
|
+
/**
|
|
3702
|
+
* Get the provider name (for logging)
|
|
3703
|
+
*/
|
|
3704
|
+
protected abstract getProviderName(): string;
|
|
3705
|
+
/**
|
|
3706
|
+
* Get the API key (from instance, parameter, or environment)
|
|
3707
|
+
*/
|
|
3708
|
+
protected getApiKey(apiKey?: string): string | undefined;
|
|
3709
|
+
/**
|
|
3710
|
+
* Check if a component contains a Form (data_modification component)
|
|
3711
|
+
* Forms have hardcoded defaultValues that become stale when cached
|
|
3712
|
+
* This checks both single Form components and Forms inside MultiComponentContainer
|
|
3713
|
+
*/
|
|
3714
|
+
protected containsFormComponent(component: any): boolean;
|
|
3715
|
+
/**
|
|
3716
|
+
* Match components from text response suggestions and generate follow-up questions
|
|
3717
|
+
* Takes a text response with component suggestions (c1:type format) and matches with available components
|
|
3718
|
+
* Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
|
|
3719
|
+
* All components are placed in a default MultiComponentContainer layout
|
|
3720
|
+
* @param analysisContent - The text response containing component suggestions
|
|
3721
|
+
* @param components - List of available components
|
|
3722
|
+
* @param apiKey - Optional API key
|
|
3723
|
+
* @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
|
|
3724
|
+
* @returns Object containing matched components, layout title/description, and follow-up actions
|
|
3725
|
+
*/
|
|
3726
|
+
matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
|
|
3727
|
+
components: Component[];
|
|
3728
|
+
layoutTitle: string;
|
|
3729
|
+
layoutDescription: string;
|
|
3730
|
+
actions: Action[];
|
|
3731
|
+
}>;
|
|
3732
|
+
/**
|
|
3733
|
+
* Classify user question into category and detect external tools needed
|
|
3734
|
+
* Determines if question is for data analysis, requires external tools, or needs text response
|
|
3735
|
+
*/
|
|
3736
|
+
classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
|
|
3737
|
+
category: 'data_analysis' | 'data_modification' | 'general';
|
|
3738
|
+
externalTools: Array<{
|
|
3739
|
+
type: string;
|
|
3740
|
+
name: string;
|
|
3741
|
+
description: string;
|
|
3742
|
+
parameters: Record<string, any>;
|
|
3743
|
+
}>;
|
|
3744
|
+
dataAnalysisType?: 'visualization' | 'calculation' | 'comparison' | 'trend';
|
|
3745
|
+
reasoning: string;
|
|
3746
|
+
confidence: number;
|
|
3747
|
+
}>;
|
|
3748
|
+
/**
|
|
3749
|
+
* Adapt UI block parameters based on current user question
|
|
3750
|
+
* Takes a matched UI block from semantic search and modifies its props to answer the new question
|
|
3751
|
+
* Also adapts the cached text response to match the new question
|
|
3752
|
+
*/
|
|
3753
|
+
adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
|
|
3754
|
+
success: boolean;
|
|
3755
|
+
adaptedComponent?: Component;
|
|
3756
|
+
adaptedTextResponse?: string;
|
|
3757
|
+
parametersChanged?: Array<{
|
|
3758
|
+
field: string;
|
|
3759
|
+
reason: string;
|
|
3760
|
+
}>;
|
|
3761
|
+
explanation: string;
|
|
3762
|
+
}>;
|
|
3763
|
+
/**
|
|
3764
|
+
* Generate text-based response for user question
|
|
3765
|
+
* This provides conversational text responses instead of component generation
|
|
3766
|
+
* Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
|
|
3767
|
+
* After generating text response, if components are provided, matches suggested components
|
|
3768
|
+
*/
|
|
3769
|
+
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>;
|
|
3770
|
+
/**
|
|
3771
|
+
* Main orchestration function with semantic search and multi-step classification
|
|
3772
|
+
* NEW FLOW (Recommended):
|
|
3773
|
+
* 1. Semantic search: Check previous conversations (>60% match)
|
|
3774
|
+
* - If match found → Adapt UI block parameters and return
|
|
3775
|
+
* 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
|
|
3776
|
+
* 3. Route appropriately based on category and response mode
|
|
3777
|
+
*/
|
|
3778
|
+
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>;
|
|
3779
|
+
/**
|
|
3780
|
+
* Generate next questions that the user might ask based on the original prompt and generated component
|
|
3781
|
+
* This helps provide intelligent suggestions for follow-up queries
|
|
3782
|
+
* For general/conversational questions without components, pass textResponse instead
|
|
3783
|
+
*/
|
|
3784
|
+
generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string, signal?: AbortSignal): Promise<string[]>;
|
|
3785
|
+
}
|
|
3786
|
+
|
|
3787
|
+
interface AnthropicLLMConfig extends BaseLLMConfig {
|
|
3788
|
+
}
|
|
3789
|
+
/**
|
|
3790
|
+
* AnthropicLLM class for handling AI-powered component generation and matching using Anthropic Claude
|
|
3791
|
+
*/
|
|
3792
|
+
declare class AnthropicLLM extends BaseLLM {
|
|
3793
|
+
constructor(config?: AnthropicLLMConfig);
|
|
3794
|
+
protected getDefaultModel(): string;
|
|
3795
|
+
protected getDefaultFastModel(): string;
|
|
3796
|
+
protected getDefaultApiKey(): string | undefined;
|
|
3797
|
+
protected getProviderName(): string;
|
|
3798
|
+
}
|
|
3799
|
+
declare const anthropicLLM: AnthropicLLM;
|
|
3800
|
+
|
|
3801
|
+
interface GroqLLMConfig extends BaseLLMConfig {
|
|
3802
|
+
}
|
|
3803
|
+
/**
|
|
3804
|
+
* GroqLLM class for handling AI-powered component generation and matching using Groq
|
|
3805
|
+
*/
|
|
3806
|
+
declare class GroqLLM extends BaseLLM {
|
|
3807
|
+
constructor(config?: GroqLLMConfig);
|
|
3808
|
+
protected getDefaultModel(): string;
|
|
3809
|
+
protected getDefaultFastModel(): string;
|
|
3810
|
+
protected getDefaultApiKey(): string | undefined;
|
|
3811
|
+
protected getProviderName(): string;
|
|
3812
|
+
}
|
|
3813
|
+
declare const groqLLM: GroqLLM;
|
|
3814
|
+
|
|
3815
|
+
interface GeminiLLMConfig extends BaseLLMConfig {
|
|
3816
|
+
}
|
|
3817
|
+
/**
|
|
3818
|
+
* GeminiLLM class for handling AI-powered component generation and matching using Google Gemini
|
|
3819
|
+
*/
|
|
3820
|
+
declare class GeminiLLM extends BaseLLM {
|
|
3821
|
+
constructor(config?: GeminiLLMConfig);
|
|
3822
|
+
protected getDefaultModel(): string;
|
|
3823
|
+
protected getDefaultFastModel(): string;
|
|
3824
|
+
protected getDefaultApiKey(): string | undefined;
|
|
3825
|
+
protected getProviderName(): string;
|
|
3826
|
+
}
|
|
3827
|
+
declare const geminiLLM: GeminiLLM;
|
|
3828
|
+
|
|
3829
|
+
interface OpenAILLMConfig extends BaseLLMConfig {
|
|
3830
|
+
}
|
|
3831
|
+
/**
|
|
3832
|
+
* OpenAILLM class for handling AI-powered component generation and matching using OpenAI GPT models
|
|
3833
|
+
*/
|
|
3834
|
+
declare class OpenAILLM extends BaseLLM {
|
|
3835
|
+
constructor(config?: OpenAILLMConfig);
|
|
3836
|
+
protected getDefaultModel(): string;
|
|
3837
|
+
protected getDefaultFastModel(): string;
|
|
3838
|
+
protected getDefaultApiKey(): string | undefined;
|
|
3839
|
+
protected getProviderName(): string;
|
|
3840
|
+
}
|
|
3841
|
+
declare const openaiLLM: OpenAILLM;
|
|
3842
|
+
|
|
3843
|
+
/**
|
|
3844
|
+
* Query Cache — Two mechanisms:
|
|
3845
|
+
*
|
|
3846
|
+
* 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
|
|
3847
|
+
* of recently validated queries. True LRU eviction: reads bubble entries to the back via
|
|
3848
|
+
* delete+re-set so the oldest *unused* entry is evicted, not the oldest *inserted*.
|
|
3849
|
+
*
|
|
3850
|
+
* 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
|
|
3851
|
+
* No server-side storage needed for SQL mappings. The token is decrypted on each request.
|
|
3852
|
+
* This eliminates the unbounded queryIdCache that previously grew forever and caused
|
|
3853
|
+
* memory bloat (hundreds of MBs after thousands of queries).
|
|
3854
|
+
*
|
|
3855
|
+
* Result data can still be cached temporarily via the data cache (mechanism 1).
|
|
3856
|
+
*/
|
|
3857
|
+
declare class QueryCache {
|
|
3858
|
+
private cache;
|
|
3859
|
+
private ttlMs;
|
|
3860
|
+
private maxCacheSize;
|
|
3861
|
+
private cleanupInterval;
|
|
3862
|
+
private readonly algorithm;
|
|
3863
|
+
private encryptionKey;
|
|
3864
|
+
constructor();
|
|
3865
|
+
/**
|
|
3866
|
+
* Set the cache TTL (Time To Live)
|
|
3867
|
+
* @param minutes - TTL in minutes (default: 10)
|
|
3868
|
+
*/
|
|
3869
|
+
setTTL(minutes: number): void;
|
|
3870
|
+
/**
|
|
3871
|
+
* Get the current TTL in minutes
|
|
3872
|
+
*/
|
|
3873
|
+
getTTL(): number;
|
|
3874
|
+
/**
|
|
3875
|
+
* Store query result in data cache.
|
|
3876
|
+
* If the key already exists, it's removed first so the re-insert places it
|
|
3877
|
+
* at the back of the iteration order (LRU). Eviction only fires when adding
|
|
3878
|
+
* a genuinely new key past the size limit.
|
|
3879
|
+
*/
|
|
3880
|
+
set(query: string, data: any): void;
|
|
3881
|
+
/**
|
|
3882
|
+
* Get cached result if exists and not expired.
|
|
3883
|
+
* On hit, re-inserts the entry so it moves to the back of the Map's
|
|
3884
|
+
* iteration order — turning FIFO eviction into true LRU.
|
|
3885
|
+
*/
|
|
3886
|
+
get(query: string): any | null;
|
|
3887
|
+
/**
|
|
3888
|
+
* Check if query exists in cache (not expired)
|
|
3889
|
+
*/
|
|
3890
|
+
has(query: string): boolean;
|
|
3891
|
+
/**
|
|
3892
|
+
* Remove a specific query from cache
|
|
3893
|
+
*/
|
|
3894
|
+
delete(query: string): void;
|
|
3895
|
+
/**
|
|
3896
|
+
* Clear all cached entries
|
|
3897
|
+
*/
|
|
3898
|
+
clear(): void;
|
|
3899
|
+
/**
|
|
3900
|
+
* Get cache statistics
|
|
3901
|
+
*/
|
|
3902
|
+
getStats(): {
|
|
3903
|
+
size: number;
|
|
3904
|
+
queryIdCount: number;
|
|
3905
|
+
oldestEntryAge: number | null;
|
|
3906
|
+
};
|
|
3907
|
+
/**
|
|
3908
|
+
* Start periodic cleanup of expired data cache entries.
|
|
3909
|
+
*/
|
|
3910
|
+
private startCleanup;
|
|
3911
|
+
/**
|
|
3912
|
+
* Encrypt a payload into a self-contained token.
|
|
3913
|
+
*/
|
|
3914
|
+
private encrypt;
|
|
3915
|
+
/**
|
|
3916
|
+
* Decrypt a token back to the original payload.
|
|
3917
|
+
*/
|
|
3918
|
+
private decrypt;
|
|
3919
|
+
/**
|
|
3920
|
+
* Store a query by generating an encrypted token as queryId.
|
|
3921
|
+
* The SQL is encrypted INTO the token — nothing stored in memory.
|
|
3922
|
+
* If data is provided, it's cached temporarily in the data cache.
|
|
3923
|
+
*/
|
|
3924
|
+
storeQuery(query: any, data?: any): string;
|
|
3925
|
+
/**
|
|
3926
|
+
* Get a stored query by decrypting its token.
|
|
3927
|
+
* Returns the SQL + any cached result data.
|
|
3928
|
+
*/
|
|
3929
|
+
getQuery(queryId: string): {
|
|
3930
|
+
query: any;
|
|
3931
|
+
data: any;
|
|
3932
|
+
} | null;
|
|
3933
|
+
/**
|
|
3934
|
+
* Update cached data for a queryId token
|
|
3935
|
+
*/
|
|
3936
|
+
setQueryData(queryId: string, data: any): void;
|
|
3937
|
+
/**
|
|
3938
|
+
* Stop cleanup interval (for graceful shutdown)
|
|
3939
|
+
*/
|
|
3940
|
+
destroy(): void;
|
|
3941
|
+
}
|
|
3942
|
+
declare const queryCache: QueryCache;
|
|
3943
|
+
|
|
3944
|
+
/**
|
|
3945
|
+
* Manages conversation history scoped per user + dashboard.
|
|
3946
|
+
* Each user-dashboard pair has its own isolated history that expires after a configurable TTL.
|
|
3947
|
+
*/
|
|
3948
|
+
declare class DashboardConversationHistory {
|
|
3949
|
+
private histories;
|
|
3950
|
+
private ttlMs;
|
|
3951
|
+
private maxEntries;
|
|
3952
|
+
private cleanupInterval;
|
|
3953
|
+
constructor();
|
|
3954
|
+
/**
|
|
3955
|
+
* Set the TTL for dashboard histories
|
|
3956
|
+
* @param minutes - TTL in minutes
|
|
3957
|
+
*/
|
|
3958
|
+
setTTL(minutes: number): void;
|
|
3959
|
+
/**
|
|
3960
|
+
* Set max entries per dashboard
|
|
3961
|
+
*/
|
|
3962
|
+
setMaxEntries(max: number): void;
|
|
3963
|
+
/**
|
|
3964
|
+
* Add a conversation entry for a user's dashboard
|
|
3965
|
+
*/
|
|
3966
|
+
addEntry(dashboardId: string, userPrompt: string, componentSummary: string, userId?: string): void;
|
|
3967
|
+
/**
|
|
3968
|
+
* Get formatted conversation history for a user's dashboard
|
|
3969
|
+
*/
|
|
3970
|
+
getHistory(dashboardId: string, userId?: string): string;
|
|
3971
|
+
/**
|
|
3972
|
+
* Clear history for a specific user's dashboard
|
|
3973
|
+
*/
|
|
3974
|
+
clearDashboard(dashboardId: string, userId?: string): void;
|
|
3975
|
+
/**
|
|
3976
|
+
* Clear all dashboard histories
|
|
3977
|
+
*/
|
|
3978
|
+
clearAll(): void;
|
|
3979
|
+
/**
|
|
3980
|
+
* Start periodic cleanup of expired histories
|
|
3981
|
+
*/
|
|
3982
|
+
private startCleanup;
|
|
3983
|
+
/**
|
|
3984
|
+
* Stop cleanup interval (for graceful shutdown)
|
|
3985
|
+
*/
|
|
3986
|
+
destroy(): void;
|
|
3987
|
+
}
|
|
3988
|
+
declare const dashboardConversationHistory: DashboardConversationHistory;
|
|
3989
|
+
|
|
3990
|
+
/**
|
|
3991
|
+
* Whole-dashboard generation via Pi, a terminal coding agent — as opposed to
|
|
3992
|
+
* DASH_COMP_REQ's single-widget-at-a-time flow. Runs Pi in-process via its
|
|
3993
|
+
* SDK (createAgentSession), not as a subprocess: no shell, no argument
|
|
3994
|
+
* quoting, no stdin/stdout piping, none of the Windows-specific subprocess
|
|
3995
|
+
* issues that came with spawning the `pi` CLI directly.
|
|
3996
|
+
*
|
|
3997
|
+
* Called from sdk-nodejs/src/dashboardAgent/index.ts (DASHBOARD_AGENT_REQ),
|
|
3998
|
+
* which owns the generic streaming/abort machinery (mirrors USER_PROMPT_REQ)
|
|
3999
|
+
* and passes `signal`/`onProgress` alongside the normal params — this stays
|
|
4000
|
+
* within CollectionHandler's loose (params) => Promise<result> typing, no
|
|
4001
|
+
* change needed to that shared type.
|
|
4002
|
+
*
|
|
4003
|
+
* This mechanism is generic and reusable across any deployment. What's
|
|
4004
|
+
* genuinely project-specific — where AGENTS.md lives, which model to use —
|
|
4005
|
+
* is supplied via `DashboardAgentCollectionConfig`, with defaults sensible
|
|
4006
|
+
* enough that most callers don't need to override them (see below). The
|
|
4007
|
+
* data-source tool list and the dashboard's current state both come from
|
|
4008
|
+
* things sdk-nodejs already exposes generically: `sdk.getTools()` (whatever
|
|
4009
|
+
* this deployment registered via `sdk.setTools()`) and `sdk.callCollection
|
|
4010
|
+
* ('dashboards', 'query', ...)` (whatever this deployment already registered
|
|
4011
|
+
* under that name/shape) — no per-deployment callback needed for either.
|
|
4012
|
+
* Same convention on the way out: after a successful run, the prompt and the
|
|
4013
|
+
* full response text are handed to `sdk.callCollection('dashboard-agent-
|
|
4014
|
+
* conversations', 'create', ...)` if this deployment has registered one —
|
|
4015
|
+
* skipped silently otherwise, since conversation history is optional.
|
|
4016
|
+
*
|
|
4017
|
+
* Pi verifies every query against the live database itself (via whatever
|
|
4018
|
+
* local tool-execution bridge the deployment exposes, e.g. an HTTP bridge
|
|
4019
|
+
* on localhost), but does NOT persist the result itself — it writes the
|
|
4020
|
+
* finished DSL to an absolute path inside `runtimeDir`, told to it explicitly
|
|
4021
|
+
* in the prompt, and stops there. This handler reads that file after the run
|
|
4022
|
+
* finishes and returns its content as `dashboard` in the result. The caller
|
|
4023
|
+
* (frontend) is the one that actually saves it, via whatever authenticated
|
|
4024
|
+
* create/update path any other dashboard edit goes through — Pi has no user
|
|
4025
|
+
* session/auth context of its own, so persistence shouldn't happen from
|
|
4026
|
+
* inside it.
|
|
4027
|
+
*
|
|
4028
|
+
* Session persistence: the FIRST call for a dashboardId pays the full cost
|
|
4029
|
+
* (explore KB, discover schema, plan, verify, build). Every call after that
|
|
4030
|
+
* resumes the same session file (SessionManager.open) so Pi has everything
|
|
4031
|
+
* it already learned — it only needs to reason about the new, smaller ask,
|
|
4032
|
+
* not rediscover the whole dashboard from scratch. The session's file path
|
|
4033
|
+
* (AgentSession.sessionFile) is captured right after creation and persisted
|
|
4034
|
+
* in a small local file, keyed by dashboardId, inside `runtimeDir`.
|
|
4035
|
+
*/
|
|
4036
|
+
interface DashboardAgentCollectionConfig {
|
|
4037
|
+
/**
|
|
4038
|
+
* Working directory Pi runs from — must contain AGENTS.md. This is a
|
|
4039
|
+
* version-controlled prompt file, so `cwd` is expected to live somewhere
|
|
4040
|
+
* like a `.prompts/` folder alongside the deployment's other prompts.
|
|
4041
|
+
* Default: `<process.cwd()>/.prompts/dashboard-agent` — the same
|
|
4042
|
+
* process.cwd()-based convention PromptLoader already uses for the main
|
|
4043
|
+
* agent's prompts, which needs no explicit override in the common case
|
|
4044
|
+
* (the backend process's own cwd already is its project root).
|
|
4045
|
+
*/
|
|
4046
|
+
cwd?: string;
|
|
4047
|
+
/**
|
|
4048
|
+
* Where drafts/, the session-id map, and dashboard.log get written —
|
|
4049
|
+
* separate from `cwd` deliberately, so this deployment's runtime state
|
|
4050
|
+
* (regenerated per session, safe to gitignore) doesn't sit inside the
|
|
4051
|
+
* same folder as the version-controlled AGENTS.md prompt.
|
|
4052
|
+
* Default: `<process.cwd()>/.pi-dashboard-agent-runtime`.
|
|
4053
|
+
*/
|
|
4054
|
+
runtimeDir?: string;
|
|
4055
|
+
/** Model provider (default: process.env.PI_AGENT_PROVIDER || 'openrouter'). */
|
|
4056
|
+
provider?: string;
|
|
4057
|
+
/** Model id (default: process.env.PI_AGENT_MODEL || 'anthropic/claude-sonnet-4.5'). */
|
|
4058
|
+
model?: string;
|
|
4059
|
+
/**
|
|
4060
|
+
* true (default): every request starts a brand-new pi session, with the 2
|
|
4061
|
+
* most recent prior responses (if any) injected into the prompt as
|
|
4062
|
+
* context — bounded cost per request, but pi re-explores schema/KB facts
|
|
4063
|
+
* it already verified in an earlier turn on this same dashboard.
|
|
4064
|
+
* false: resumes the same session file across requests on a given
|
|
4065
|
+
* dashboard — pi keeps everything it already learned, but context (and
|
|
4066
|
+
* cost) grows unbounded across turns (one observed turn: 2M+ cache-read
|
|
4067
|
+
* tokens after a handful of edits on the same dashboard).
|
|
4068
|
+
* Default: process.env.PI_AGENT_FRESH_SESSION !== 'false'.
|
|
4069
|
+
*/
|
|
4070
|
+
freshSession?: boolean;
|
|
4071
|
+
}
|
|
4072
|
+
declare function registerDashboardAgentCollection(sdk: SuperatomSDK, config?: DashboardAgentCollectionConfig): void;
|
|
4073
|
+
|
|
4074
|
+
/**
|
|
4075
|
+
* ScriptMatcher — LLM-Based Script Matching + Parameter Extraction
|
|
4076
|
+
*
|
|
4077
|
+
* Uses ONE LLM call to:
|
|
4078
|
+
* 1. Pick the best matching script from the library (or "none")
|
|
4079
|
+
* 2. Extract parameter values from the user question
|
|
4080
|
+
*
|
|
4081
|
+
* Why LLM over embeddings:
|
|
4082
|
+
* - Embeddings capture topic similarity ("overstock" ≈ "inventory" ≈ "revenue")
|
|
4083
|
+
* but can't distinguish structurally different questions about the same domain
|
|
4084
|
+
* - LLM understands that "overstock by warehouse" needs a different script than
|
|
4085
|
+
* "revenue by warehouse" even though they're semantically close
|
|
4086
|
+
* - One call does both matching AND parameter extraction
|
|
4087
|
+
*
|
|
4088
|
+
* When script library grows past ~50, add an embedding pre-filter
|
|
4089
|
+
* (ChromaDB narrows to top 10 → LLM picks from those 10).
|
|
4090
|
+
*/
|
|
4091
|
+
|
|
4092
|
+
declare class ScriptMatcher {
|
|
4093
|
+
private store;
|
|
4094
|
+
constructor(store: ScriptStore);
|
|
4095
|
+
/**
|
|
4096
|
+
* Find the best matching script for a user question.
|
|
4097
|
+
* Uses ONE LLM call that picks the script AND extracts parameters.
|
|
4098
|
+
* Returns null if no script matches.
|
|
4099
|
+
*/
|
|
4100
|
+
match(userPrompt: string, apiKey?: string, model?: string, signal?: AbortSignal,
|
|
4101
|
+
/**
|
|
4102
|
+
* Recent script-backed answers in this thread, newest first. Presence of at
|
|
4103
|
+
* least one is what makes the `edit` tier reachable at all (see the guards
|
|
4104
|
+
* below), and handing over SEVERAL is what lets an instruction name its own
|
|
4105
|
+
* target instead of always hitting the most recent script.
|
|
4106
|
+
*/
|
|
4107
|
+
activeBindings?: ScriptBinding[],
|
|
4108
|
+
/**
|
|
4109
|
+
* Recent conversation turns, most recent last. The gate needs this to tell
|
|
4110
|
+
* "this reply is an edit instruction for the active script" apart from
|
|
4111
|
+
* "this reply is answering a clarifying question about a DIFFERENT,
|
|
4112
|
+
* unresolved topic that never became a script" — a bare parameter-shaped
|
|
4113
|
+
* reply ("April 2025 to March 2026") is textually indistinguishable
|
|
4114
|
+
* between those two cases without seeing what the assistant just asked.
|
|
4115
|
+
* Once this tier is decided, nothing downstream re-checks it — the edit
|
|
4116
|
+
* path hands MainAgent a system prompt that explicitly instructs it to
|
|
4117
|
+
* trust the premise and not treat the turn as a new question — so this
|
|
4118
|
+
* gate is the only place that can catch a mismatch.
|
|
4119
|
+
*/
|
|
4120
|
+
conversationHistory?: string): Promise<ScriptMatch | null>;
|
|
4121
|
+
/**
|
|
4122
|
+
* Build the script catalog string for the LLM prompt.
|
|
4123
|
+
* Each script gets: index, ID, name, description, and parameter definitions.
|
|
4124
|
+
*/
|
|
4125
|
+
private buildScriptCatalog;
|
|
4126
|
+
/**
|
|
4127
|
+
* The recent script-backed answers in this thread — the bounded set an edit
|
|
4128
|
+
* may target. Rendered as its own prompt section (never merged into the
|
|
4129
|
+
* ranked catalog) so the `edit` rules have an unambiguous referent set, and
|
|
4130
|
+
* numbered newest-first so the prompt's "prefer the most recent when the
|
|
4131
|
+
* instruction is ambiguous" tie-break has something to point at.
|
|
4132
|
+
*
|
|
4133
|
+
* Each entry carries the QUESTION that produced it plus the columns it
|
|
4134
|
+
* returned — that is what lets the matcher resolve "use the mode for the WSP
|
|
4135
|
+
* one" instead of blindly taking the newest.
|
|
4136
|
+
*/
|
|
4137
|
+
private buildActiveScriptBlock;
|
|
4138
|
+
}
|
|
4139
|
+
|
|
4140
|
+
/**
|
|
4141
|
+
* ScriptRunner — Execute scripts in an isolated tsx subprocess.
|
|
4142
|
+
*
|
|
4143
|
+
* The subprocess approach replaces the earlier `new Function()` eval and gives us:
|
|
4144
|
+
* - Real sandbox (separate process, SIGKILL on timeout).
|
|
4145
|
+
* - Real TypeScript (tsx transpiles on the fly).
|
|
4146
|
+
* - npm imports available to scripts (clustering, stats, geo, etc.).
|
|
4147
|
+
*
|
|
4148
|
+
* Protocol: NDJSON over the child's stdin/stdout. See script-ipc.ts + backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md.
|
|
4149
|
+
*/
|
|
4150
|
+
|
|
4151
|
+
interface RunScriptOptions {
|
|
4152
|
+
/** Data sources the script is allowed to query via ctx.query */
|
|
4153
|
+
externalTools: ExternalTool[];
|
|
4154
|
+
/** Optional — for propagating per-query UI progress to the user */
|
|
4155
|
+
streamBuffer?: StreamBuffer;
|
|
4156
|
+
/** Override the wall-clock timeout (default `SCRIPT_TIMEOUT_MS`, 60s). */
|
|
4157
|
+
timeoutMs?: number;
|
|
4158
|
+
/**
|
|
4159
|
+
* Per-turn cancellation signal. When the user hits "Stop" mid-run, the child
|
|
4160
|
+
* process group is SIGKILLed and the run resolves as an aborted failure (the
|
|
4161
|
+
* caller is already unwinding, so the result is discarded).
|
|
4162
|
+
*/
|
|
4163
|
+
signal?: AbortSignal;
|
|
4164
|
+
}
|
|
4165
|
+
/**
|
|
4166
|
+
* Execute a recipe by spawning a tsx child on the script's .ts file.
|
|
4167
|
+
* `scriptPath` is the absolute path to the saved `.ts` body.
|
|
4168
|
+
*/
|
|
4169
|
+
declare function runScript(recipe: ScriptRecipe, scriptPath: string, params: Record<string, any>, options: RunScriptOptions): Promise<ScriptResult>;
|
|
4170
|
+
|
|
1680
4171
|
type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
|
|
1681
4172
|
declare class SuperatomSDK {
|
|
1682
4173
|
private ws;
|
|
1683
4174
|
private url;
|
|
1684
4175
|
private apiKey?;
|
|
1685
4176
|
private projectId;
|
|
1686
|
-
private userId;
|
|
1687
4177
|
private type;
|
|
1688
4178
|
private bundleDir;
|
|
1689
4179
|
private messageHandlers;
|
|
@@ -1694,12 +4184,18 @@ declare class SuperatomSDK {
|
|
|
1694
4184
|
private collections;
|
|
1695
4185
|
private components;
|
|
1696
4186
|
private tools;
|
|
4187
|
+
private workflows;
|
|
1697
4188
|
private anthropicApiKey;
|
|
1698
4189
|
private groqApiKey;
|
|
1699
4190
|
private geminiApiKey;
|
|
1700
4191
|
private openaiApiKey;
|
|
1701
4192
|
private llmProviders;
|
|
1702
4193
|
private databaseType;
|
|
4194
|
+
private modelStrategy;
|
|
4195
|
+
private mainAgentModel;
|
|
4196
|
+
private sourceAgentModel;
|
|
4197
|
+
private dashCompModels?;
|
|
4198
|
+
private conversationSimilarityThreshold;
|
|
1703
4199
|
private userManager;
|
|
1704
4200
|
private dashboardManager;
|
|
1705
4201
|
private reportManager;
|
|
@@ -1707,6 +4203,8 @@ declare class SuperatomSDK {
|
|
|
1707
4203
|
private lastPong;
|
|
1708
4204
|
private readonly PING_INTERVAL_MS;
|
|
1709
4205
|
private readonly PONG_TIMEOUT_MS;
|
|
4206
|
+
private pendingOutbox;
|
|
4207
|
+
private readonly MAX_OUTBOX_SIZE;
|
|
1710
4208
|
constructor(config: SuperatomSDKConfig);
|
|
1711
4209
|
/**
|
|
1712
4210
|
* Initialize PromptLoader and load prompts into memory
|
|
@@ -1746,9 +4244,25 @@ declare class SuperatomSDK {
|
|
|
1746
4244
|
*/
|
|
1747
4245
|
private handleMessage;
|
|
1748
4246
|
/**
|
|
1749
|
-
* Send a message to the Superatom service
|
|
4247
|
+
* Send a message to the Superatom service.
|
|
4248
|
+
* Returns true if the message was sent, false if the WebSocket is not connected.
|
|
4249
|
+
* Does NOT throw on closed connections — callers can check the return value if needed.
|
|
4250
|
+
*/
|
|
4251
|
+
send(message: Message): boolean;
|
|
4252
|
+
/**
|
|
4253
|
+
* Queue a message that couldn't be delivered because the socket was down,
|
|
4254
|
+
* to be resent once it reconnects. Drops the oldest entry once the bound is
|
|
4255
|
+
* hit — an outage long enough to fill this queue means the oldest queued
|
|
4256
|
+
* responses are for requests the caller has likely already given up on.
|
|
1750
4257
|
*/
|
|
1751
|
-
|
|
4258
|
+
private queuePendingMessage;
|
|
4259
|
+
/**
|
|
4260
|
+
* Resend everything queued while the socket was down, now that it's back
|
|
4261
|
+
* up. Uses this.ws.send() directly (not send()) so a message that fails
|
|
4262
|
+
* again goes back through queuePendingMessage() rather than being silently
|
|
4263
|
+
* dropped a second time.
|
|
4264
|
+
*/
|
|
4265
|
+
private flushPendingOutbox;
|
|
1752
4266
|
/**
|
|
1753
4267
|
* Register a message handler to receive all messages
|
|
1754
4268
|
*/
|
|
@@ -1788,6 +4302,14 @@ declare class SuperatomSDK {
|
|
|
1788
4302
|
*/
|
|
1789
4303
|
private handlePong;
|
|
1790
4304
|
private storeComponents;
|
|
4305
|
+
/**
|
|
4306
|
+
* The live, frontend-registered component catalog (name, type, description,
|
|
4307
|
+
* and full prop schema per component) — the same authoritative source
|
|
4308
|
+
* DASH_COMP_REQ's LLM prompt is built from. Exposed so other integrations
|
|
4309
|
+
* (e.g. the dashboard-agent script bridge) can read real component
|
|
4310
|
+
* contracts instead of maintaining a separate, driftable hand-written copy.
|
|
4311
|
+
*/
|
|
4312
|
+
getComponents(): Component[];
|
|
1791
4313
|
/**
|
|
1792
4314
|
* Set tools for the SDK instance
|
|
1793
4315
|
*/
|
|
@@ -1796,6 +4318,57 @@ declare class SuperatomSDK {
|
|
|
1796
4318
|
* Get the stored tools
|
|
1797
4319
|
*/
|
|
1798
4320
|
getTools(): Tool$1[];
|
|
4321
|
+
/**
|
|
4322
|
+
* Call a registered collection operation in-process — no WebSocket
|
|
4323
|
+
* round-trip, since the caller is already running inside this same SDK
|
|
4324
|
+
* instance. Lets SDK-internal features (e.g. the dashboard agent) reuse
|
|
4325
|
+
* whatever collection a deployment has already registered (e.g.
|
|
4326
|
+
* 'dashboards'.'query') by name/convention, instead of requiring a
|
|
4327
|
+
* separate callback purely to re-expose data a collection already serves.
|
|
4328
|
+
* Throws if the collection or operation isn't registered.
|
|
4329
|
+
*/
|
|
4330
|
+
callCollection<TResult = any>(collectionName: string, operation: string, params?: any): Promise<TResult>;
|
|
4331
|
+
/**
|
|
4332
|
+
* Register workflow components for the SDK instance.
|
|
4333
|
+
*
|
|
4334
|
+
* Workflows are pre-built multi-step UI flows the main agent can pick when
|
|
4335
|
+
* the user's prompt matches a workflow's `whenToUse` trigger. Picking a
|
|
4336
|
+
* workflow short-circuits analysis text + dashboard component generation —
|
|
4337
|
+
* the workflow component is returned directly, with the LLM-extracted props.
|
|
4338
|
+
*/
|
|
4339
|
+
setWorkflows(workflows: WorkflowDescriptor[]): void;
|
|
4340
|
+
/**
|
|
4341
|
+
* Get the registered workflow components.
|
|
4342
|
+
*/
|
|
4343
|
+
getWorkflows(): WorkflowDescriptor[];
|
|
4344
|
+
/**
|
|
4345
|
+
* Apply model strategy to all LLM provider singletons
|
|
4346
|
+
* @param strategy - 'best', 'fast', or 'balanced'
|
|
4347
|
+
*/
|
|
4348
|
+
private applyModelStrategy;
|
|
4349
|
+
/**
|
|
4350
|
+
* Set model strategy at runtime
|
|
4351
|
+
* @param strategy - 'best', 'fast', or 'balanced'
|
|
4352
|
+
*/
|
|
4353
|
+
setModelStrategy(strategy: ModelStrategy): void;
|
|
4354
|
+
/**
|
|
4355
|
+
* Get current model strategy
|
|
4356
|
+
*/
|
|
4357
|
+
getModelStrategy(): ModelStrategy;
|
|
4358
|
+
/**
|
|
4359
|
+
* Apply conversation similarity threshold to all LLM provider singletons
|
|
4360
|
+
* @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
|
|
4361
|
+
*/
|
|
4362
|
+
private applyConversationSimilarityThreshold;
|
|
4363
|
+
/**
|
|
4364
|
+
* Set conversation similarity threshold at runtime
|
|
4365
|
+
* @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
|
|
4366
|
+
*/
|
|
4367
|
+
setConversationSimilarityThreshold(threshold: number): void;
|
|
4368
|
+
/**
|
|
4369
|
+
* Get current conversation similarity threshold
|
|
4370
|
+
*/
|
|
4371
|
+
getConversationSimilarityThreshold(): number;
|
|
1799
4372
|
}
|
|
1800
4373
|
|
|
1801
|
-
export { type Action, BM25L, type BM25LOptions, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LogLevel, type Message, type
|
|
4374
|
+
export { type Action, type AgentConfig, type AgentResponse, BM25L, type BM25LOptions, type BaseLLMConfig, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, DEFAULT_AGENT_CONFIG, type DashboardAgentCollectionConfig, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, MainAgent, type Message, type ModelStrategy, type OutputField, type RerankedResult, 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, UIBlock, UILogCollector, type User, UserManager, type UsersData, type WorkflowDescriptor, anthropicLLM, dashboardConversationHistory, geminiLLM, groqLLM, hybridRerank, llmUsageLogger, logger, normalizeScriptBody, openaiLLM, queryCache, registerDashboardAgentCollection, rerankChromaResults, rerankConversationResults, resolveScriptRecipeStore, runScript, userPromptErrorLogger };
|