@superatomai/sdk-node 0.0.43 → 0.0.44-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 +2455 -126
- package/dist/index.d.ts +2455 -126
- package/dist/index.js +23242 -8986
- package/dist/index.mjs +23311 -9064
- 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 +532 -0
- package/dist/userResponse/scripts/script-bootstrap.mjs +530 -0
- package/package.json +52 -49
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,15 +1,981 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import Anthropic from '@anthropic-ai/sdk';
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* Script Flow Types
|
|
6
|
+
*
|
|
7
|
+
* Defines interfaces for the script-based query architecture:
|
|
8
|
+
* - ScriptRecipe: metadata for matching, validation, and quality tracking
|
|
9
|
+
* - ScriptResult: output from executing a script
|
|
10
|
+
* - ScriptMatch: result from the LLM-based script matcher
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Recipe metadata stored alongside each script.
|
|
15
|
+
* Used for matching, validation, and quality tracking.
|
|
16
|
+
*/
|
|
17
|
+
interface ScriptRecipe {
|
|
18
|
+
/** Unique script identifier */
|
|
19
|
+
id: string;
|
|
20
|
+
/** Version number (incremented on regeneration) */
|
|
21
|
+
version: number;
|
|
22
|
+
/** Human-readable name (e.g., "Revenue by Dimension") */
|
|
23
|
+
name: string;
|
|
24
|
+
/** Natural language description of what this script does */
|
|
25
|
+
intentDescription: string;
|
|
26
|
+
/** Keyword tags for quick filtering */
|
|
27
|
+
tags: string[];
|
|
28
|
+
/** Source tool IDs this script queries (e.g., ["mssql-abc123_query"]) */
|
|
29
|
+
sourceIds: string[];
|
|
30
|
+
/** Table names used (for future schema drift detection) */
|
|
31
|
+
tables: string[];
|
|
32
|
+
/** Parameter definitions — what can vary */
|
|
33
|
+
parameters: ScriptParameter[];
|
|
34
|
+
/** The script function body as a string. Loaded from disk (scripts-store/<fileBase>.ts). */
|
|
35
|
+
scriptBody: string;
|
|
36
|
+
/**
|
|
37
|
+
* On-disk filename stem for the body: scripts-store/<fileBase>.ts.
|
|
38
|
+
* Editable in the IDE. Decided at authoring time (slug of `name`, with a
|
|
39
|
+
* short id suffix on collision) and stable across promotion.
|
|
40
|
+
*/
|
|
41
|
+
fileBase?: string;
|
|
42
|
+
/** sha256 of the on-disk body — lets the runtime detect manual edits. */
|
|
43
|
+
bodyHash?: string;
|
|
44
|
+
/** Project scope (single-VM deployments may leave this undefined). */
|
|
45
|
+
projectId?: string;
|
|
46
|
+
/** Times this script was used successfully */
|
|
47
|
+
successCount: number;
|
|
48
|
+
/** Times this script failed */
|
|
49
|
+
failureCount: number;
|
|
50
|
+
/** ISO timestamp of last usage */
|
|
51
|
+
lastUsed: string;
|
|
52
|
+
/** Original user question that created this script */
|
|
53
|
+
createdFrom: string;
|
|
54
|
+
/** ISO timestamp */
|
|
55
|
+
createdAt: string;
|
|
56
|
+
/** ISO timestamp */
|
|
57
|
+
updatedAt: string;
|
|
58
|
+
/**
|
|
59
|
+
* `recipe.id` of the parent this script was forked from.
|
|
60
|
+
* Undefined for root scripts (those written from scratch by MainAgent).
|
|
61
|
+
* See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md.
|
|
62
|
+
*/
|
|
63
|
+
parentId?: string;
|
|
64
|
+
/** 0 for root scripts; `parent.forkDepth + 1` for forks. Capped at 3. */
|
|
65
|
+
forkDepth?: number;
|
|
66
|
+
/**
|
|
67
|
+
* Brief description of what this fork changed vs its parent
|
|
68
|
+
* (sourced from the matcher's `modificationHint`).
|
|
69
|
+
*/
|
|
70
|
+
forkReason?: string;
|
|
71
|
+
/**
|
|
72
|
+
* Validated component specs captured at authoring time. On a tier-high
|
|
73
|
+
* replay these are rebound to fresh queryIds deterministically — no
|
|
74
|
+
* component-generation LLM call, and the rendered columns can't drift from
|
|
75
|
+
* what was validated when the script was authored. Absent on recipes
|
|
76
|
+
* authored before this landed; those fall back to LLM component generation.
|
|
77
|
+
* See backend/docs/SCRIPT-COMPONENT-CONSISTENCY.md.
|
|
78
|
+
*/
|
|
79
|
+
components?: ScriptComponentSpec[];
|
|
80
|
+
/**
|
|
81
|
+
* What the user explicitly asked the output to LOOK like, set by a display
|
|
82
|
+
* edit ("show that as a bar chart", "make the bars horizontal").
|
|
83
|
+
*
|
|
84
|
+
* Deliberately SEPARATE from `components`. Those are validated bindings that
|
|
85
|
+
* must be cleared on a data edit — after "break it down by brand" the axis
|
|
86
|
+
* keys are wrong, and after "use the mode" the stored title still says
|
|
87
|
+
* "Average…". A rendering CHOICE, by contrast, is still valid afterwards.
|
|
88
|
+
* Keeping them in one field meant every data edit silently discarded the
|
|
89
|
+
* user's chart type.
|
|
90
|
+
*
|
|
91
|
+
* Fed to the component generator as a hint whenever specs are (re)generated,
|
|
92
|
+
* so the chosen rendering comes back even after the SQL changes.
|
|
93
|
+
*/
|
|
94
|
+
displayPreference?: ScriptDisplayPreference;
|
|
95
|
+
/**
|
|
96
|
+
* Lifecycle stage of this recipe on disk.
|
|
97
|
+
* - 'draft': written by MainAgent's write_script during a turn; filtered out
|
|
98
|
+
* of FTS results (status='verified' only) so the matcher never picks it.
|
|
99
|
+
* Filename is suffixed with `turnId` to keep concurrent turns
|
|
100
|
+
* from clobbering each other's drafts.
|
|
101
|
+
* - 'verified': promoted after `execute_script` succeeded; the matcher sees it.
|
|
102
|
+
* Filename drops the turn suffix unless a verified file with
|
|
103
|
+
* the same slug already exists (collision case keeps the suffix).
|
|
104
|
+
*
|
|
105
|
+
* Recipes loaded from disk without this field default to 'verified' so
|
|
106
|
+
* existing scripts keep working unchanged.
|
|
107
|
+
*/
|
|
108
|
+
status?: 'draft' | 'verified';
|
|
109
|
+
/**
|
|
110
|
+
* Per-turn unique suffix used for draft filenames (e.g. `1714745623-x9k2`).
|
|
111
|
+
* Set when the draft is saved; carried until the recipe is promoted.
|
|
112
|
+
*/
|
|
113
|
+
turnId?: string;
|
|
114
|
+
/**
|
|
115
|
+
* Last execution error captured by `recordDraftError` while the recipe was
|
|
116
|
+
* still a draft. Lets users open the draft .json file and see why it failed
|
|
117
|
+
* without grepping logs. Cleared on promotion to 'verified'.
|
|
118
|
+
*/
|
|
119
|
+
lastError?: {
|
|
120
|
+
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
121
|
+
message: string;
|
|
122
|
+
at: string;
|
|
123
|
+
attempt: number;
|
|
124
|
+
};
|
|
125
|
+
/** userId who committed the most recent edit (audit trail — recipes are project-scoped). */
|
|
126
|
+
editedBy?: string;
|
|
127
|
+
/** The instruction that produced the current version. */
|
|
128
|
+
editedFrom?: string;
|
|
129
|
+
/**
|
|
130
|
+
* Prior versions, newest last. The body itself is archived on disk as
|
|
131
|
+
* `<fileBase>.v<version>.ts`; this records what changed and who did it.
|
|
132
|
+
*/
|
|
133
|
+
history?: ScriptVersionRecord[];
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* A durable, user-stated rendering choice for a recipe. Survives data edits.
|
|
137
|
+
*/
|
|
138
|
+
interface ScriptDisplayPreference {
|
|
139
|
+
/** Component types the user's chosen rendering resolved to, e.g. ["DynamicBarChart"]. */
|
|
140
|
+
componentTypes: string[];
|
|
141
|
+
/** The instruction itself — carries nuance the types can't ("horizontal", "sorted descending"). */
|
|
142
|
+
instruction: string;
|
|
143
|
+
/** ISO timestamp of the display edit that set this. */
|
|
144
|
+
at: string;
|
|
145
|
+
}
|
|
146
|
+
/** One superseded version of a recipe body (see ScriptStore.commitEdit). */
|
|
147
|
+
interface ScriptVersionRecord {
|
|
148
|
+
/** Version number this record superseded (i.e. the OLD version). */
|
|
149
|
+
version: number;
|
|
150
|
+
/** ISO timestamp of the edit that superseded it. */
|
|
151
|
+
at: string;
|
|
152
|
+
/** userId who made the edit, when known. */
|
|
153
|
+
by?: string;
|
|
154
|
+
/** The edit instruction that caused the supersede. */
|
|
155
|
+
instruction?: string;
|
|
156
|
+
/** One-line summary of what changed, for the version picker. */
|
|
157
|
+
changeSummary?: string;
|
|
158
|
+
/** sha256 of the superseded body — pairs with `<fileBase>.v<version>.ts`. */
|
|
159
|
+
bodyHash?: string;
|
|
160
|
+
}
|
|
161
|
+
interface ScriptParameter {
|
|
162
|
+
/** Parameter name (used in script body as params.name) */
|
|
163
|
+
name: string;
|
|
164
|
+
/** Parameter type */
|
|
165
|
+
type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
|
|
166
|
+
/** Whether this parameter is required */
|
|
167
|
+
required: boolean;
|
|
168
|
+
/** Default value if not provided */
|
|
169
|
+
default?: any;
|
|
170
|
+
/** For enum type — maps user-facing values to internal values */
|
|
171
|
+
enumValues?: Record<string, string>;
|
|
172
|
+
/** Human-readable description (used in the matcher LLM prompt) */
|
|
173
|
+
description: string;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* A reusable component binding captured when a script is authored. Stored on
|
|
177
|
+
* the recipe so tier-high replays rebuild components deterministically (rebind
|
|
178
|
+
* to fresh queryIds) instead of re-running the component-picker LLM.
|
|
179
|
+
*/
|
|
180
|
+
interface ScriptComponentSpec {
|
|
181
|
+
/** Registered component name (e.g. "DynamicBarChart") — matched against the available component library. */
|
|
182
|
+
componentType: string;
|
|
183
|
+
/** `executedQuery.sourceId` to bind to (e.g. a tool id or 'computed:_final'), 'federation' for a cross-source component, or 'markdown' for a content-only narrative block (no data source). */
|
|
184
|
+
sourceRef: string;
|
|
185
|
+
/** Present only when sourceRef === 'federation' — the DuckDB SQL to re-execute on replay. */
|
|
186
|
+
federationSql?: string;
|
|
187
|
+
/** Present only when sourceRef === 'markdown' — the narrative text to render on replay (markdown has no data source, so its content must be persisted). */
|
|
188
|
+
content?: string;
|
|
189
|
+
title?: string;
|
|
190
|
+
description?: string;
|
|
191
|
+
/** Validated axis/value keys + aggregation — all referencing real columns of the bound source. */
|
|
192
|
+
config: Record<string, any>;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Result from executing a script via ScriptRunner.
|
|
196
|
+
*/
|
|
197
|
+
interface ScriptResult {
|
|
198
|
+
/** Whether the script executed successfully */
|
|
199
|
+
success: boolean;
|
|
200
|
+
/** Combined data from all queries */
|
|
201
|
+
data: any[];
|
|
202
|
+
/** Program-generated narrative, when the script exports getAnalysis. */
|
|
203
|
+
analysis?: AnalysisOutput;
|
|
204
|
+
/**
|
|
205
|
+
* getAnalysis threw. `success` stays true — the data is valid, so the caller
|
|
206
|
+
* falls back to LLM prose rather than losing the answer.
|
|
207
|
+
*/
|
|
208
|
+
analysisError?: string;
|
|
209
|
+
/** Program-generated component specs, when the script exports getComponents. */
|
|
210
|
+
components?: ScriptComponentSpec[];
|
|
211
|
+
/**
|
|
212
|
+
* getComponents threw or returned a non-array. `success` stays true — the data
|
|
213
|
+
* is valid, so the caller falls back to the recipe's stored specs and then to
|
|
214
|
+
* LLM generation rather than losing the dashboard.
|
|
215
|
+
*/
|
|
216
|
+
componentsError?: string;
|
|
217
|
+
/** Individual query results tracked during execution */
|
|
218
|
+
executedQueries: ScriptQueryResult[];
|
|
219
|
+
/** Error message if failed */
|
|
220
|
+
error?: string;
|
|
221
|
+
/**
|
|
222
|
+
* Where in the lifecycle the error occurred. Lets MainAgent's fix-loop
|
|
223
|
+
* decide between "rewrite the whole draft" (compile) and "patch the
|
|
224
|
+
* specific line" (runtime).
|
|
225
|
+
*/
|
|
226
|
+
errorPhase?: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
227
|
+
/** Total execution time in milliseconds */
|
|
228
|
+
executionTimeMs: number;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* A single query executed during script runtime.
|
|
232
|
+
* Tracked by ScriptContext for component generation and debugging.
|
|
233
|
+
*/
|
|
234
|
+
interface ScriptQueryResult {
|
|
235
|
+
/** Source tool ID */
|
|
236
|
+
sourceId: string;
|
|
237
|
+
/** Human-readable source name */
|
|
238
|
+
sourceName: string;
|
|
239
|
+
/** The SQL that was executed */
|
|
240
|
+
sql: string;
|
|
241
|
+
/** Result data rows */
|
|
242
|
+
data: any[];
|
|
243
|
+
/** Number of rows returned */
|
|
244
|
+
count: number;
|
|
245
|
+
/** Total rows that matched before limit (if available) */
|
|
246
|
+
totalCount?: number;
|
|
247
|
+
/** Query execution time in milliseconds */
|
|
248
|
+
executionTimeMs: number;
|
|
249
|
+
/**
|
|
250
|
+
* True for rows that did NOT come from a real SQL execution — either a
|
|
251
|
+
* ctx.emit() dataset or the synthesized "computed:_final" entry that
|
|
252
|
+
* carries the script's post-JS returned data. The component generator
|
|
253
|
+
* uses this to route the resulting component through the script_dataset
|
|
254
|
+
* sentinel toolId so the frontend resolves it via the queryCache short-circuit.
|
|
255
|
+
*/
|
|
256
|
+
virtual?: boolean;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Match tier returned by the LLM script matcher.
|
|
260
|
+
*
|
|
261
|
+
* - 'high': the script answers the question directly; only parameter values
|
|
262
|
+
* may differ. The runtime replays it with extracted params (cheapest path).
|
|
263
|
+
* - 'near': the script answers a STRUCTURALLY similar question but needs
|
|
264
|
+
* body modification (different metric, dimension, table, filter shape).
|
|
265
|
+
* The runtime forks the parent and adapts the body via MainAgent's normal
|
|
266
|
+
* write_script + execute_script loop — no SourceAgent dispatch needed.
|
|
267
|
+
* See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md for the full design.
|
|
268
|
+
* - 'edit': the user is INSTRUCTING a change to the script that produced the
|
|
269
|
+
* previous answer (not asking a new question). Only reachable when the turn
|
|
270
|
+
* carries a ScriptBinding — without one the matcher coerces it to 'none', so
|
|
271
|
+
* a prompt regression can't turn this into a loose similarity path. The
|
|
272
|
+
* runtime runs MainAgent in edit mode and commits the result in place.
|
|
273
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md.
|
|
274
|
+
* - 'none': no script is relevant; full agent flow runs.
|
|
275
|
+
*/
|
|
276
|
+
type MatchTier = 'high' | 'near' | 'edit' | 'none';
|
|
277
|
+
/**
|
|
278
|
+
* Which recipe produced the answer the user is currently looking at.
|
|
279
|
+
*
|
|
280
|
+
* Set whenever a turn's answer came from a script (replay, fresh authoring, or
|
|
281
|
+
* a committed edit) and carried on the UIBlock + saved conversation row. Two
|
|
282
|
+
* consumers:
|
|
283
|
+
* 1. The matcher — the 'edit' tier is ONLY reachable when a binding exists, so
|
|
284
|
+
* "use mode instead of mean" resolves to a concrete script instead of being
|
|
285
|
+
* matched on keywords it shares with no script name.
|
|
286
|
+
* 2. Cache invalidation — after an edit commits, conversations bound to that
|
|
287
|
+
* recipeId must be dropped, or the exact-match cache replays the pre-edit
|
|
288
|
+
* answer and the edit looks like a no-op.
|
|
289
|
+
*
|
|
290
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
291
|
+
*/
|
|
292
|
+
interface ScriptBinding {
|
|
293
|
+
recipeId: string;
|
|
294
|
+
/** Params the script ran with — the edit's starting point. */
|
|
295
|
+
params: Record<string, any>;
|
|
296
|
+
/** Recipe name at bind time (matcher catalog + user-facing confirmation). */
|
|
297
|
+
name: string;
|
|
298
|
+
/** Columns the last run returned — grounds the editor without a re-query. */
|
|
299
|
+
columns?: string[];
|
|
300
|
+
/**
|
|
301
|
+
* The question that produced this answer. Required for disambiguation when a
|
|
302
|
+
* thread ran several scripts — without it the candidates are just names and
|
|
303
|
+
* the matcher cannot resolve "use the mode for the WSP one".
|
|
304
|
+
*/
|
|
305
|
+
userPrompt?: string;
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Result from the LLM-based script matcher.
|
|
309
|
+
*
|
|
310
|
+
* For `tier: 'high'`, `extractedParams` carries the values to pass to the
|
|
311
|
+
* existing script. For `tier: 'near'`, `gaps` and `modificationHint` describe
|
|
312
|
+
* what the fork-author needs to change in the parent body.
|
|
313
|
+
*/
|
|
314
|
+
interface ScriptMatch {
|
|
315
|
+
/** The matched script recipe */
|
|
316
|
+
recipe: ScriptRecipe;
|
|
317
|
+
/** Match tier — see MatchTier docs */
|
|
318
|
+
tier: MatchTier;
|
|
319
|
+
/** Similarity score (0-1, derived from LLM tier) */
|
|
320
|
+
similarity: number;
|
|
321
|
+
/**
|
|
322
|
+
* Legacy confidence level. Mirrors `tier === 'high'`/`'near'` for now;
|
|
323
|
+
* kept so existing callers compile while we migrate to tier-based logic.
|
|
324
|
+
*/
|
|
325
|
+
confidence: 'high' | 'medium';
|
|
326
|
+
/** Parameters extracted from the user question by the LLM (tier='high') */
|
|
327
|
+
extractedParams?: Record<string, any>;
|
|
328
|
+
/**
|
|
329
|
+
* Proper nouns the question named, VERBATIM, with the parameter each fills.
|
|
330
|
+
*
|
|
331
|
+
* The matcher must NOT resolve these itself. Observed live: it substituted the
|
|
332
|
+
* customer name "PREMER ENRGES PHOTOOTAIC" into an id parameter believing that
|
|
333
|
+
* "the runtime will resolve the customer name to its PartyId(s)" — nothing on
|
|
334
|
+
* the replay path does, and `WHERE BillingPartyId IN (PREMER ENRGES
|
|
335
|
+
* PHOTOOTAIC)` reached SQL. Reported here, the runtime resolves them before
|
|
336
|
+
* replay and rejects the match when one cannot be resolved.
|
|
337
|
+
*/
|
|
338
|
+
mentions?: Array<{
|
|
339
|
+
text: string;
|
|
340
|
+
param?: string;
|
|
341
|
+
}>;
|
|
342
|
+
/** Business concepts the question relies on (e.g. "outstanding balance"). */
|
|
343
|
+
entityTypes?: string[];
|
|
344
|
+
/** What the user question needs that the parent doesn't cover (tier='near') */
|
|
345
|
+
gaps?: string[];
|
|
346
|
+
/** One-sentence description of the change the fork-author should make (tier='near') */
|
|
347
|
+
modificationHint?: string;
|
|
348
|
+
/**
|
|
349
|
+
* Which HALF of the recipe the edit targets (tier='edit'). A recipe has two
|
|
350
|
+
* independently editable halves:
|
|
351
|
+
* - 'data' — the scriptBody: how the rows are produced (aggregation,
|
|
352
|
+
* filters, joins, grouping). Runs MainAgent in edit mode.
|
|
353
|
+
* - 'display' — the component specs: how those SAME rows are shown (chart
|
|
354
|
+
* type, orientation, columns, labels). Replays the proven SQL
|
|
355
|
+
* and regenerates the specs — never authors a script.
|
|
356
|
+
* Defaults to 'data' when the matcher omits it.
|
|
357
|
+
*/
|
|
358
|
+
editTarget?: 'data' | 'display';
|
|
359
|
+
/**
|
|
360
|
+
* Self-contained restatement of the change the user asked for (tier='edit').
|
|
361
|
+
* MUST have pronouns/deixis resolved ("this", "it", "that column") — the edit
|
|
362
|
+
* prompt never sees the conversation history, so an unresolved instruction is
|
|
363
|
+
* unusable downstream.
|
|
364
|
+
*/
|
|
365
|
+
editInstruction?: string;
|
|
366
|
+
/** Why the matcher made this choice (for logs and telemetry) */
|
|
367
|
+
reasoning?: string;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* script-ipc.ts — Protocol definitions for parent/child IPC.
|
|
372
|
+
*
|
|
373
|
+
* Transport: newline-delimited JSON over the child's stdin/stdout.
|
|
374
|
+
* stderr is passed through for uncaught exceptions and compile errors.
|
|
375
|
+
*
|
|
376
|
+
* See backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md § IPC Bridge.
|
|
377
|
+
*/
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* What getAnalysis returns. `analysis` is the narrative and `summary` the short
|
|
381
|
+
* bullets the markdown block binds to — siblings over one dataset, never a
|
|
382
|
+
* summary OF the narrative. See backend/docs/ANALYSIS-AS-PROGRAM-DESIGN.md § 4.3.
|
|
383
|
+
*/
|
|
384
|
+
interface AnalysisOutput {
|
|
385
|
+
analysis?: string;
|
|
386
|
+
summary?: string[];
|
|
387
|
+
method?: string;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* StreamBuffer - Buffered streaming utility for smoother text delivery
|
|
392
|
+
* Batches small chunks together and flushes at regular intervals
|
|
393
|
+
*/
|
|
394
|
+
type StreamCallback = (chunk: string) => void;
|
|
395
|
+
/**
|
|
396
|
+
* StreamBuffer class for managing buffered streaming output
|
|
397
|
+
* Provides smooth text delivery by batching small chunks
|
|
398
|
+
*/
|
|
399
|
+
declare class StreamBuffer {
|
|
400
|
+
private buffer;
|
|
401
|
+
private flushTimer;
|
|
402
|
+
private callback;
|
|
403
|
+
private fullText;
|
|
404
|
+
constructor(callback?: StreamCallback);
|
|
405
|
+
/**
|
|
406
|
+
* Check if the buffer has a callback configured
|
|
407
|
+
*/
|
|
408
|
+
hasCallback(): boolean;
|
|
409
|
+
/**
|
|
410
|
+
* Get all text that has been written (including already flushed)
|
|
411
|
+
*/
|
|
412
|
+
getFullText(): string;
|
|
413
|
+
/**
|
|
414
|
+
* Write a chunk to the buffer
|
|
415
|
+
* Large chunks or chunks with newlines are flushed immediately
|
|
416
|
+
* Small chunks are batched and flushed after a short interval
|
|
417
|
+
*
|
|
418
|
+
* @param chunk - Text chunk to write
|
|
419
|
+
*/
|
|
420
|
+
write(chunk: string): void;
|
|
421
|
+
/**
|
|
422
|
+
* Flush the buffer immediately
|
|
423
|
+
* Call this before tool execution or other operations that need clean output
|
|
424
|
+
*/
|
|
425
|
+
flush(): void;
|
|
426
|
+
/**
|
|
427
|
+
* Internal flush implementation
|
|
428
|
+
*/
|
|
429
|
+
private flushNow;
|
|
430
|
+
/**
|
|
431
|
+
* Clean up resources
|
|
432
|
+
* Call this when done with the buffer
|
|
433
|
+
*/
|
|
434
|
+
dispose(): void;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* ToolExecutorService - Handles execution of SQL queries and external tools
|
|
439
|
+
* Extracted from BaseLLM.generateTextResponse for better separation of concerns
|
|
440
|
+
*/
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* External tool definition
|
|
444
|
+
*/
|
|
445
|
+
interface ExternalTool {
|
|
446
|
+
id: string;
|
|
447
|
+
name: string;
|
|
448
|
+
description?: string;
|
|
449
|
+
/** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
|
|
450
|
+
toolType?: 'source' | 'direct';
|
|
451
|
+
/** Full untruncated schema for source agent (all columns visible) */
|
|
452
|
+
fullSchema?: string;
|
|
453
|
+
/** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
|
|
454
|
+
schemaTier?: string;
|
|
455
|
+
/** Schema search function for very_large tier — keyword search over entities */
|
|
456
|
+
schemaSearchFn?: (keywords: string[]) => string;
|
|
457
|
+
/** `signal` fires when the user hits Stop mid-query — passed through to the backend's SourceTool.fn. */
|
|
458
|
+
fn: (input: any, signal?: AbortSignal) => Promise<any>;
|
|
459
|
+
limit?: number;
|
|
460
|
+
outputSchema?: any;
|
|
461
|
+
executionType?: 'immediate' | 'deferred';
|
|
462
|
+
userProvidedData?: any;
|
|
463
|
+
params?: Record<string, any>;
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Executed tool tracking info
|
|
467
|
+
*/
|
|
468
|
+
interface ExecutedToolInfo {
|
|
469
|
+
id: string;
|
|
470
|
+
name: string;
|
|
471
|
+
params: any;
|
|
472
|
+
result: {
|
|
473
|
+
_totalRecords: number;
|
|
474
|
+
_recordsShown: number;
|
|
475
|
+
_metadata?: any;
|
|
476
|
+
_sampleData: any[];
|
|
477
|
+
/** Bounded summary over the FULL fetched result (complete structure). */
|
|
478
|
+
_summary?: any;
|
|
479
|
+
/** Up to MAIN_AGENT_COMPLETE_ROWS rows — the complete result when small. */
|
|
480
|
+
_mainAgentRows?: any[];
|
|
481
|
+
};
|
|
482
|
+
outputSchema?: any;
|
|
483
|
+
sourceSchema?: string;
|
|
484
|
+
sourceType?: string;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* Multi-Agent Architecture Types
|
|
489
|
+
*
|
|
490
|
+
* Defines interfaces for the hierarchical agent system:
|
|
491
|
+
* - Main Agent: ONE LLM.streamWithTools() call with source agent tools
|
|
492
|
+
* - Source Agents: independent agents that query individual data sources
|
|
493
|
+
*
|
|
494
|
+
* The main agent sees only source summaries. When it calls a source tool,
|
|
495
|
+
* the SourceAgent runs independently (own LLM, own retries) and returns clean data.
|
|
496
|
+
*/
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* Per-entity detail: name, row count, and column names.
|
|
500
|
+
* Gives the main agent enough context to route to the right source.
|
|
501
|
+
*/
|
|
502
|
+
interface EntityDetail {
|
|
503
|
+
/** Entity name (table, sheet, endpoint) */
|
|
504
|
+
name: string;
|
|
505
|
+
/** Approximate row count */
|
|
506
|
+
rowCount?: number;
|
|
507
|
+
/** Column/field names */
|
|
508
|
+
columns: string[];
|
|
509
|
+
/** Entity-level semantic summary (what the table means) — for main-agent routing. */
|
|
510
|
+
summary?: string;
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Representation of a data source for the main agent.
|
|
514
|
+
* Contains entity names WITH column names so the LLM can route accurately.
|
|
515
|
+
*/
|
|
516
|
+
interface SourceSummary {
|
|
517
|
+
/** Source ID (matches tool ID prefix) */
|
|
518
|
+
id: string;
|
|
519
|
+
/** Human-readable source name */
|
|
520
|
+
name: string;
|
|
521
|
+
/** Source type: postgres, excel, rest_api, etc. */
|
|
522
|
+
type: string;
|
|
523
|
+
/** Brief description of what data this source contains */
|
|
524
|
+
description: string;
|
|
525
|
+
/** Detailed entity info with column names for routing */
|
|
526
|
+
entityDetails: EntityDetail[];
|
|
527
|
+
/** The tool ID associated with this source */
|
|
528
|
+
toolId: string;
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* What a source agent returns after querying its data source.
|
|
532
|
+
* The main agent uses this to analyze and compose the final response.
|
|
533
|
+
*/
|
|
534
|
+
interface SourceAgentResult {
|
|
535
|
+
/** Source ID */
|
|
536
|
+
sourceId: string;
|
|
537
|
+
/** Source name */
|
|
538
|
+
sourceName: string;
|
|
539
|
+
/** Whether the query succeeded */
|
|
540
|
+
success: boolean;
|
|
541
|
+
/** Result data rows */
|
|
542
|
+
data: any[];
|
|
543
|
+
/** Metadata about the query execution */
|
|
544
|
+
metadata: SourceAgentMetadata;
|
|
545
|
+
/** Tool execution info for the last successful query (backward compat) */
|
|
546
|
+
executedTool: ExecutedToolInfo;
|
|
547
|
+
/** All successful tool executions (primary + follow-up queries) */
|
|
548
|
+
allExecutedTools?: ExecutedToolInfo[];
|
|
549
|
+
/** Error message if failed */
|
|
550
|
+
error?: string;
|
|
551
|
+
}
|
|
552
|
+
interface SourceAgentMetadata {
|
|
553
|
+
/** Total rows that matched the query (before limit) */
|
|
554
|
+
totalRowsMatched: number;
|
|
555
|
+
/** Rows actually returned (after limit) */
|
|
556
|
+
rowsReturned: number;
|
|
557
|
+
/** Whether the result was truncated by the row limit */
|
|
558
|
+
isLimited: boolean;
|
|
559
|
+
/** The query/params that were executed */
|
|
560
|
+
queryExecuted?: string;
|
|
561
|
+
/** Execution time in milliseconds */
|
|
562
|
+
executionTimeMs: number;
|
|
563
|
+
}
|
|
564
|
+
/**
|
|
565
|
+
* A pre-built, multi-step UI flow registered with the SDK.
|
|
566
|
+
*
|
|
567
|
+
* When the main agent decides a user's question matches a workflow's whenToUse
|
|
568
|
+
* trigger, it picks the workflow instead of running source agents / generating
|
|
569
|
+
* dashboard components. The LLM extracts the workflow's required props from the
|
|
570
|
+
* prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
|
|
571
|
+
* workflow component directly — no analysis text, no chart generation. The
|
|
572
|
+
* frontend renders the registered workflow component with the LLM-extracted
|
|
573
|
+
* props.
|
|
574
|
+
*/
|
|
575
|
+
interface WorkflowDescriptor {
|
|
576
|
+
/** Unique workflow id (used as the LLM tool name) */
|
|
577
|
+
id: string;
|
|
578
|
+
/** Component name on the frontend (matches the registered React component) */
|
|
579
|
+
name: string;
|
|
580
|
+
/** Short human-readable description of what this workflow does */
|
|
581
|
+
description: string;
|
|
582
|
+
/**
|
|
583
|
+
* 1–2 sentence trigger condition. The LLM uses this to decide if the
|
|
584
|
+
* user's prompt matches this workflow. Be specific — e.g.
|
|
585
|
+
* "User wants to *initiate* an inventory transfer (review + submit POs),
|
|
586
|
+
* not just see analysis or charts."
|
|
587
|
+
*/
|
|
588
|
+
whenToUse: string;
|
|
589
|
+
/**
|
|
590
|
+
* JSON-schema-style description of the props the workflow needs. Becomes
|
|
591
|
+
* the LLM tool's input_schema, so the model fills these from the prompt.
|
|
592
|
+
* Use the same shape as `params` on direct tools — string descriptors with
|
|
593
|
+
* an optional "(optional)" suffix.
|
|
594
|
+
*
|
|
595
|
+
* Example:
|
|
596
|
+
* ```
|
|
597
|
+
* {
|
|
598
|
+
* selectedStore: 'object — { id, name } of the source branch',
|
|
599
|
+
* minROI: 'number (optional) — only show transfers with ROI ≥ this',
|
|
600
|
+
* }
|
|
601
|
+
* ```
|
|
602
|
+
*/
|
|
603
|
+
propsSchema: Record<string, string>;
|
|
604
|
+
/**
|
|
605
|
+
* Optional: static prop defaults merged with LLM-extracted props before
|
|
606
|
+
* the component is returned. Useful for things like the embedded
|
|
607
|
+
* `externalTool` config that the workflow uses to fetch its own data.
|
|
608
|
+
*/
|
|
609
|
+
defaultProps?: Record<string, any>;
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* The workflow selection captured during a routing call.
|
|
613
|
+
* Set on AgentResponse when the LLM picks a workflow tool.
|
|
614
|
+
*/
|
|
615
|
+
interface SelectedWorkflow {
|
|
616
|
+
/** Component name (matches WorkflowDescriptor.name) */
|
|
617
|
+
name: string;
|
|
618
|
+
/** Props extracted from the prompt + merged with workflow.defaultProps */
|
|
619
|
+
props: Record<string, any>;
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Set when this turn applies a user-directed edit to an existing script instead
|
|
623
|
+
* of authoring a new one. MainAgent keeps the SAME harness (tools, loop,
|
|
624
|
+
* write_script/execute_script verification) and swaps only the system prompt —
|
|
625
|
+
* `agent-main-edit` instead of `agent-main`.
|
|
626
|
+
*
|
|
627
|
+
* The two framings contradict each other on whether to query a source first, so
|
|
628
|
+
* they must never be resident in one rendered prompt.
|
|
629
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § D3.
|
|
630
|
+
*/
|
|
631
|
+
interface EditContext {
|
|
632
|
+
/** Recipe being edited — the shadow draft records it as parentId. */
|
|
633
|
+
recipeId: string;
|
|
634
|
+
parentName: string;
|
|
635
|
+
parentBody: string;
|
|
636
|
+
/** Self-contained restatement of the change (from the matcher). */
|
|
637
|
+
instruction: string;
|
|
638
|
+
/** Columns the last run returned — grounds the edit without a re-query. */
|
|
639
|
+
lastResultColumns?: string[];
|
|
640
|
+
/** Rendered parameter list of the parent, for the prompt. */
|
|
641
|
+
parentParams?: string;
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* The complete response from the multi-agent system.
|
|
645
|
+
* Contains everything needed for text display + component generation.
|
|
646
|
+
*/
|
|
647
|
+
interface AgentResponse {
|
|
648
|
+
/** Generated text response (analysis of the data) */
|
|
649
|
+
text: string;
|
|
650
|
+
/**
|
|
651
|
+
* Program-generated narrative when the script exported getAnalysis. `text`
|
|
652
|
+
* already carries `analysis.analysis`; this also exposes `summary`, which
|
|
653
|
+
* the markdown block binds to instead of being an LLM summary of the prose.
|
|
654
|
+
*/
|
|
655
|
+
analysis?: AnalysisOutput;
|
|
656
|
+
/** All executed tools across all source agents (for component generation) */
|
|
657
|
+
executedTools: ExecutedToolInfo[];
|
|
658
|
+
/** Individual results from each source agent */
|
|
659
|
+
sourceResults: SourceAgentResult[];
|
|
660
|
+
/**
|
|
661
|
+
* Populated when MainAgent wrote AND successfully executed a script during its turn.
|
|
662
|
+
* Caller (agent-user-response.ts) persists it via ScriptStore.save().
|
|
663
|
+
* Absent when MainAgent didn't write one (trivial question / all attempts failed).
|
|
664
|
+
*/
|
|
665
|
+
savedScript?: AgentWrittenScript;
|
|
666
|
+
/** Failed execute_script tool_result texts this turn, in order — see RunTrace.script.failedAttempts. */
|
|
667
|
+
failedScriptAttempts?: string[];
|
|
668
|
+
/**
|
|
669
|
+
* Set when the LLM routed the question to a registered workflow component.
|
|
670
|
+
* When present, the upstream caller should skip component generation and
|
|
671
|
+
* return this workflow as the response.
|
|
672
|
+
*/
|
|
673
|
+
workflow?: SelectedWorkflow;
|
|
674
|
+
/**
|
|
675
|
+
* Validated component specs the agent authored via `write_components`.
|
|
676
|
+
* When present the caller assembles the dashboard from these instead of
|
|
677
|
+
* running the component-generation LLM. Absent when the agent didn't call
|
|
678
|
+
* the tool — the caller then falls back to `generateScriptComponents`.
|
|
679
|
+
* See backend/docs/COMPONENT-GENERATION-V2.md §2.2.
|
|
680
|
+
*/
|
|
681
|
+
componentSpecs?: ScriptComponentSpec[];
|
|
682
|
+
/** Layout title/description from the same `write_components` call. */
|
|
683
|
+
componentLayout?: {
|
|
684
|
+
title: string;
|
|
685
|
+
description?: string;
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* A script MainAgent authored + verified during its turn. Shape aligns with
|
|
690
|
+
* what ScriptStore.save() needs — minus store-assigned fields (id, timestamps, counts).
|
|
691
|
+
*/
|
|
692
|
+
interface AgentWrittenScript {
|
|
693
|
+
/**
|
|
694
|
+
* `ScriptRecipe.id` of the draft that was authored + verified during this turn.
|
|
695
|
+
* The caller passes this to `ScriptStore.promoteToVerified(recipeId, …)` to
|
|
696
|
+
* flip the draft to verified status and (when possible) drop the turn-suffix
|
|
697
|
+
* from its filename.
|
|
698
|
+
*/
|
|
699
|
+
recipeId: string;
|
|
700
|
+
name: string;
|
|
701
|
+
intentDescription: string;
|
|
702
|
+
tags: string[];
|
|
703
|
+
parameters: Array<{
|
|
704
|
+
name: string;
|
|
705
|
+
type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
|
|
706
|
+
required: boolean;
|
|
707
|
+
default?: any;
|
|
708
|
+
enumValues?: Record<string, string>;
|
|
709
|
+
description: string;
|
|
710
|
+
}>;
|
|
711
|
+
scriptBody: string;
|
|
712
|
+
/** Source IDs referenced by the script (extracted from ctx.query calls) */
|
|
713
|
+
sourceIds: string[];
|
|
714
|
+
/** Tables referenced in the script's SQL (regex-extracted) */
|
|
715
|
+
tables: string[];
|
|
716
|
+
/** Executed queries from the verified run — fed to component generation */
|
|
717
|
+
executedQueries: Array<{
|
|
718
|
+
sourceId: string;
|
|
719
|
+
sourceName: string;
|
|
720
|
+
sql: string;
|
|
721
|
+
data: any[];
|
|
722
|
+
count: number;
|
|
723
|
+
totalCount?: number;
|
|
724
|
+
executionTimeMs: number;
|
|
725
|
+
/**
|
|
726
|
+
* True for synthetic entries (ctx.emit datasets, the computed:_final
|
|
727
|
+
* post-JS data). The component generator routes virtual sources through
|
|
728
|
+
* the script_dataset sentinel toolId so the frontend resolves them via
|
|
729
|
+
* queryCache instead of attempting to re-execute SQL.
|
|
730
|
+
*/
|
|
731
|
+
virtual?: boolean;
|
|
732
|
+
}>;
|
|
733
|
+
/** The tool_result JSON MainAgent's LLM got back from execute_script — see RunTrace.script.executionResult. */
|
|
734
|
+
executionResult?: string;
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* Debug trace for a single chat_agent turn — which KB/schema nodes were
|
|
738
|
+
* retrieved and considered, and which script (if any) produced the answer.
|
|
739
|
+
* Persisted separately from the answer itself (fusion-5's
|
|
740
|
+
* `conversation_traces` table, written via `saveTrace`), never sent through
|
|
741
|
+
* `analyticsClient` (data-residency — see design doc §5).
|
|
742
|
+
*/
|
|
743
|
+
interface RunTrace {
|
|
744
|
+
version: 1;
|
|
745
|
+
kbNodes: {
|
|
746
|
+
/**
|
|
747
|
+
* Always-on nodes included regardless of the question (getGlobalKnowledgeBase).
|
|
748
|
+
* `content` is the node's full text AS IT WAS at retrieval time — captured so a
|
|
749
|
+
* later edit/delete of the KB node doesn't erase what the LLM actually saw.
|
|
750
|
+
*/
|
|
751
|
+
global: Array<{
|
|
752
|
+
kbId: string;
|
|
753
|
+
title: string;
|
|
754
|
+
content?: string;
|
|
755
|
+
}>;
|
|
756
|
+
/** Semantically matched for this specific question (getKnowledgeBase). Same `content` reasoning as above. */
|
|
757
|
+
query: Array<{
|
|
758
|
+
kbId: string;
|
|
759
|
+
title: string;
|
|
760
|
+
similarity?: number;
|
|
761
|
+
content?: string;
|
|
762
|
+
}>;
|
|
763
|
+
};
|
|
764
|
+
schemaNodes: {
|
|
765
|
+
/** MainAgent's cross-source prefilter — which sources were even considered. */
|
|
766
|
+
routing: Array<{
|
|
767
|
+
sourceId: string;
|
|
768
|
+
sourceName?: string;
|
|
769
|
+
similarity: number;
|
|
770
|
+
}>;
|
|
771
|
+
/** SourceAgent-scope per-source table resolution (MainAgent.preResolveSchema). */
|
|
772
|
+
preResolve: Array<{
|
|
773
|
+
sourceId: string;
|
|
774
|
+
table?: string;
|
|
775
|
+
description?: string;
|
|
776
|
+
similarity: number;
|
|
777
|
+
}>;
|
|
778
|
+
/**
|
|
779
|
+
* The exact {{SOURCE_SUMMARIES}} text injected into MainAgent's system prompt
|
|
780
|
+
* (agent-prompt-builder.ts's formatSummariesForPrompt output) — every
|
|
781
|
+
* registered source's catalog entry, not retrieval-specific, captured once per
|
|
782
|
+
* turn. This is what the main agent actually saw when deciding which source(s)
|
|
783
|
+
* to call.
|
|
784
|
+
*/
|
|
785
|
+
mainAgentCatalog?: string;
|
|
786
|
+
/**
|
|
787
|
+
* One entry per SourceAgent dispatch (a source called twice in one turn gets
|
|
788
|
+
* two entries) — the exact {{FULL_SCHEMA}} text injected into that
|
|
789
|
+
* SourceAgent's own system prompt, however it was sourced, plus any
|
|
790
|
+
* search_schema follow-up lookups it made mid-conversation when the schema
|
|
791
|
+
* shown wasn't enough.
|
|
792
|
+
*/
|
|
793
|
+
sourceAgentSchemas: Array<{
|
|
794
|
+
sourceId: string;
|
|
795
|
+
sourceName?: string;
|
|
796
|
+
/**
|
|
797
|
+
* The exact intent text MainAgent wrote for this dispatch (before the
|
|
798
|
+
* resolved-entities block gets appended by code — see
|
|
799
|
+
* buildResolvedEntitiesBlock) — what MainAgent actually asked this
|
|
800
|
+
* source agent to go find.
|
|
801
|
+
*/
|
|
802
|
+
intent: string;
|
|
803
|
+
/** How `schemaText` was sourced — see SourceAgent.buildPrompt's fullSchema fallback chain. */
|
|
804
|
+
method: 'preresolved-embedding' | 'tool-full-schema' | 'tool-description' | 'none';
|
|
805
|
+
schemaText: string;
|
|
806
|
+
/** In call order — each search_schema tool call this SourceAgent made, and the exact result text handed back to its own LLM. */
|
|
807
|
+
searchSchemaLookups: Array<{
|
|
808
|
+
keywords: string[];
|
|
809
|
+
result: string;
|
|
810
|
+
}>;
|
|
811
|
+
/** The tool_result text MainAgent's LLM read back for this dispatch (formatResultForMainAgent output). */
|
|
812
|
+
result?: string;
|
|
813
|
+
}>;
|
|
814
|
+
};
|
|
815
|
+
/** The script that produced this answer, if any. Null for a general (no-tool) answer. */
|
|
816
|
+
script: {
|
|
817
|
+
/** True when an existing recipe was replayed unchanged (ScriptMatcher tier='high'). */
|
|
818
|
+
reused: boolean;
|
|
819
|
+
recipeId?: string | null;
|
|
820
|
+
body?: string | null;
|
|
821
|
+
/** Set when reused — the matcher's reasoning for picking this recipe. */
|
|
822
|
+
reasoning?: string | null;
|
|
823
|
+
/** The winning execute_script tool_result text. Only set when reused=false — a replay never re-runs execute_script. Failed attempts aren't kept. */
|
|
824
|
+
executionResult?: string | null;
|
|
825
|
+
/** Failed execute_script tool_result texts this turn, in order (before the winning one, if any). */
|
|
826
|
+
failedAttempts?: string[];
|
|
827
|
+
} | null;
|
|
828
|
+
/**
|
|
829
|
+
* `resolve_entities` tool activity this turn (see main-agent.ts's
|
|
830
|
+
* RESOLVE_ENTITIES_TOOL_DEF / handleResolveEntities) — names/identifiers the
|
|
831
|
+
* user mentioned, resolved to database ids before any SQL was written.
|
|
832
|
+
* Absent/empty entirely for a project with no entity-search collection
|
|
833
|
+
* registered, or a turn that named nothing.
|
|
834
|
+
*/
|
|
835
|
+
entityResolution: {
|
|
836
|
+
/**
|
|
837
|
+
* The entity-type catalog text injected into MainAgent's system prompt
|
|
838
|
+
* (loadEntityCatalog's output) — what let the LLM name a concept instead
|
|
839
|
+
* of guessing the project's vocabulary. Captured once per turn.
|
|
840
|
+
*/
|
|
841
|
+
catalogText?: string;
|
|
842
|
+
/**
|
|
843
|
+
* One entry per `resolve_entities` tool call this turn (a turn can call it
|
|
844
|
+
* more than once) — the FULL raw response from the entity-search
|
|
845
|
+
* collection, not just the trimmed {mention,entityType,instanceId,
|
|
846
|
+
* displayName} MainAgent keeps for itself to build the dispatch block.
|
|
847
|
+
* `score`/`ambiguous`/`alternatives` only exist here, nowhere else.
|
|
848
|
+
*/
|
|
849
|
+
calls: Array<{
|
|
850
|
+
mentions: Array<{
|
|
851
|
+
text: string;
|
|
852
|
+
entityType?: string;
|
|
853
|
+
}>;
|
|
854
|
+
entityTypes: string[];
|
|
855
|
+
resolved: Array<{
|
|
856
|
+
mention: string;
|
|
857
|
+
entityType: string;
|
|
858
|
+
instanceId: string;
|
|
859
|
+
displayName: string;
|
|
860
|
+
attrs?: Record<string, any>;
|
|
861
|
+
score?: number;
|
|
862
|
+
ambiguous?: boolean;
|
|
863
|
+
alternatives?: Array<{
|
|
864
|
+
instanceId: string;
|
|
865
|
+
displayName: string;
|
|
866
|
+
score: number;
|
|
867
|
+
}>;
|
|
868
|
+
}>;
|
|
869
|
+
unresolved: string[];
|
|
870
|
+
entityMap: Record<string, any>;
|
|
871
|
+
unmatchedEntityTypes?: Array<{
|
|
872
|
+
requested: string;
|
|
873
|
+
candidates?: string[];
|
|
874
|
+
}>;
|
|
875
|
+
/** Set when the collection call itself failed (fails open — see handleResolveEntities). */
|
|
876
|
+
error?: string;
|
|
877
|
+
}>;
|
|
878
|
+
};
|
|
879
|
+
/**
|
|
880
|
+
* The prior-turn conversation context injected into this turn's prompt as
|
|
881
|
+
* CONVERSATION_HISTORY — exactly what each flow already builds for itself
|
|
882
|
+
* (chat: thread.getConversationContext(); report/dashboard: their own
|
|
883
|
+
* equivalents), captured as-is. Every call site sets this unconditionally
|
|
884
|
+
* (empty string '' when there's no prior context — new thread, or history
|
|
885
|
+
* trimmed to nothing), so an empty turn is visibly "no history" in the
|
|
886
|
+
* saved trace rather than a silently missing key. Optional only because
|
|
887
|
+
* traces saved before this field existed won't have it at all.
|
|
888
|
+
*/
|
|
889
|
+
conversationHistory?: string;
|
|
890
|
+
/**
|
|
891
|
+
* The exact {{USER_ACCESS_CONTEXT}} text injected into MainAgent's system
|
|
892
|
+
* prompt — the per-user authorization config (sa-api users.config)
|
|
893
|
+
* rendered by buildUserAccessContext, as-is. Captured once (MainAgent's
|
|
894
|
+
* prompt is what SourceAgent's identical value is derived from — no need
|
|
895
|
+
* to duplicate it per source dispatch). Set unconditionally (empty string
|
|
896
|
+
* '' when there's no config for this user), so "no restrictions" is
|
|
897
|
+
* visible in the saved trace rather than a silently missing key. Optional
|
|
898
|
+
* only because traces saved before this field existed won't have it.
|
|
899
|
+
*/
|
|
900
|
+
userAccessContext?: string;
|
|
901
|
+
}
|
|
902
|
+
/**
|
|
903
|
+
* Configuration for the multi-agent system.
|
|
904
|
+
* Controls limits, models, and behavior.
|
|
905
|
+
*/
|
|
906
|
+
interface AgentConfig {
|
|
907
|
+
/** Max rows shown to the UI preview / inlined per source (default: 10) */
|
|
908
|
+
maxRowsPerSource: number;
|
|
909
|
+
/**
|
|
910
|
+
* Max rows a source query may FETCH from the DB server-side (default: 2000).
|
|
911
|
+
* Decoupled from what the main agent is shown: the full result is fetched and
|
|
912
|
+
* summarized (bounded), but only a small/complete slice enters LLM context.
|
|
913
|
+
* This lets small lookups (benchmark maps) arrive COMPLETE without letting
|
|
914
|
+
* large results blow up context.
|
|
915
|
+
*/
|
|
916
|
+
maxRowsFetched: number;
|
|
917
|
+
/** Model for the main agent (routing + analysis in one LLM call) */
|
|
918
|
+
mainAgentModel: string;
|
|
919
|
+
/** Model for source agent query generation */
|
|
920
|
+
sourceAgentModel: string;
|
|
921
|
+
/** API key for LLM calls */
|
|
922
|
+
apiKey?: string;
|
|
923
|
+
/** Max retry attempts per source agent */
|
|
924
|
+
maxRetries: number;
|
|
925
|
+
/** Max tool calling iterations for the main agent loop */
|
|
926
|
+
maxIterations: number;
|
|
927
|
+
/** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
|
|
928
|
+
globalKnowledgeBase?: string;
|
|
929
|
+
/** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
|
|
930
|
+
knowledgeBaseContext?: string;
|
|
931
|
+
/** Per-user authorization config (sa-api users.config), rendered to text — see buildUserAccessContext */
|
|
932
|
+
userAccessContext?: string;
|
|
933
|
+
/** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
|
|
934
|
+
collections?: any;
|
|
935
|
+
/** Optional project ID for scoping embedding searches */
|
|
936
|
+
projectId?: string;
|
|
937
|
+
/**
|
|
938
|
+
* Optional debug-trace accumulator for this turn (Phase 1, chat_agent only).
|
|
939
|
+
* When present, MainAgent-scope retrieval call sites (e.g. preResolveSchema)
|
|
940
|
+
* push their structured results into it. Absent for callers that don't care
|
|
941
|
+
* about trace capture (e.g. headless flows) — every push site must treat
|
|
942
|
+
* this as optional and never let a capture failure affect the real answer.
|
|
943
|
+
*/
|
|
944
|
+
trace?: RunTrace;
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Default agent configuration
|
|
948
|
+
*/
|
|
949
|
+
declare const DEFAULT_AGENT_CONFIG: AgentConfig;
|
|
950
|
+
|
|
4
951
|
/**
|
|
5
952
|
* Unified UIBlock structure for database storage
|
|
6
|
-
* Used in both bookmarks and user-conversations tables
|
|
953
|
+
* Used in both bookmarks and user-conversations tables.
|
|
954
|
+
*
|
|
955
|
+
* `analysis` always holds whatever real narration exists — the full answer on
|
|
956
|
+
* success, or whatever was actually streamed before a failure (may be empty).
|
|
957
|
+
* `error` is a dedicated field, null on success — it can be a plain string OR
|
|
958
|
+
* a structured object/array (e.g. the agent's raw `errors` list), whatever
|
|
959
|
+
* shape the failure naturally has; it's never coerced into `analysis`.
|
|
7
960
|
*/
|
|
8
961
|
interface DBUIBlock {
|
|
9
962
|
id: string;
|
|
10
963
|
component: Record<string, any> | null;
|
|
11
964
|
analysis: string | null;
|
|
12
965
|
user_prompt: string;
|
|
966
|
+
error?: unknown | null;
|
|
967
|
+
/**
|
|
968
|
+
* The script recipe that produced this answer, when one did. Read back via
|
|
969
|
+
* `conversation-history.exactMatch` so an edit follow-up still has a target
|
|
970
|
+
* after a reload (the in-memory thread is gone by then), and indexed so
|
|
971
|
+
* committing an edit can purge every cached answer bound to the recipe.
|
|
972
|
+
*/
|
|
973
|
+
scriptBinding?: {
|
|
974
|
+
recipeId: string;
|
|
975
|
+
params?: Record<string, any>;
|
|
976
|
+
name?: string;
|
|
977
|
+
columns?: string[];
|
|
978
|
+
};
|
|
13
979
|
}
|
|
14
980
|
|
|
15
981
|
/**
|
|
@@ -59,7 +1025,18 @@ declare class Logger {
|
|
|
59
1025
|
* Log debug message (only shown for verbose level)
|
|
60
1026
|
*/
|
|
61
1027
|
debug(...args: any[]): void;
|
|
1028
|
+
/**
|
|
1029
|
+
* Write to log file
|
|
1030
|
+
*/
|
|
62
1031
|
file(...args: any[]): void;
|
|
1032
|
+
/**
|
|
1033
|
+
* Clear the log file (call at start of new user request)
|
|
1034
|
+
*/
|
|
1035
|
+
clearFile(): void;
|
|
1036
|
+
/**
|
|
1037
|
+
* Log LLM method prompts with clear labeling
|
|
1038
|
+
*/
|
|
1039
|
+
logLLMPrompt(methodName: string, promptType: 'system' | 'user', content: string | object | any[]): void;
|
|
63
1040
|
}
|
|
64
1041
|
declare const logger: Logger;
|
|
65
1042
|
|
|
@@ -149,6 +1126,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
149
1126
|
dependencies?: string[] | undefined;
|
|
150
1127
|
} | undefined;
|
|
151
1128
|
props?: Record<string, any> | undefined;
|
|
1129
|
+
data?: Record<string, any> | undefined;
|
|
152
1130
|
render?: any;
|
|
153
1131
|
states?: Record<string, any> | undefined;
|
|
154
1132
|
methods?: Record<string, {
|
|
@@ -159,7 +1137,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
159
1137
|
fn: string;
|
|
160
1138
|
deps?: string[] | undefined;
|
|
161
1139
|
}[] | undefined;
|
|
162
|
-
data?: Record<string, any> | undefined;
|
|
163
1140
|
pages?: {
|
|
164
1141
|
id: string;
|
|
165
1142
|
name: string;
|
|
@@ -181,6 +1158,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
181
1158
|
dependencies?: string[] | undefined;
|
|
182
1159
|
} | undefined;
|
|
183
1160
|
props?: Record<string, any> | undefined;
|
|
1161
|
+
data?: Record<string, any> | undefined;
|
|
184
1162
|
render?: any;
|
|
185
1163
|
states?: Record<string, any> | undefined;
|
|
186
1164
|
methods?: Record<string, {
|
|
@@ -191,7 +1169,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
191
1169
|
fn: string;
|
|
192
1170
|
deps?: string[] | undefined;
|
|
193
1171
|
}[] | undefined;
|
|
194
|
-
data?: Record<string, any> | undefined;
|
|
195
1172
|
pages?: {
|
|
196
1173
|
id: string;
|
|
197
1174
|
name: string;
|
|
@@ -217,6 +1194,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
217
1194
|
dependencies?: string[] | undefined;
|
|
218
1195
|
} | undefined;
|
|
219
1196
|
props?: Record<string, any> | undefined;
|
|
1197
|
+
data?: Record<string, any> | undefined;
|
|
220
1198
|
render?: any;
|
|
221
1199
|
states?: Record<string, any> | undefined;
|
|
222
1200
|
methods?: Record<string, {
|
|
@@ -227,7 +1205,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
227
1205
|
fn: string;
|
|
228
1206
|
deps?: string[] | undefined;
|
|
229
1207
|
}[] | undefined;
|
|
230
|
-
data?: Record<string, any> | undefined;
|
|
231
1208
|
pages?: {
|
|
232
1209
|
id: string;
|
|
233
1210
|
name: string;
|
|
@@ -253,6 +1230,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
253
1230
|
dependencies?: string[] | undefined;
|
|
254
1231
|
} | undefined;
|
|
255
1232
|
props?: Record<string, any> | undefined;
|
|
1233
|
+
data?: Record<string, any> | undefined;
|
|
256
1234
|
render?: any;
|
|
257
1235
|
states?: Record<string, any> | undefined;
|
|
258
1236
|
methods?: Record<string, {
|
|
@@ -263,7 +1241,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
263
1241
|
fn: string;
|
|
264
1242
|
deps?: string[] | undefined;
|
|
265
1243
|
}[] | undefined;
|
|
266
|
-
data?: Record<string, any> | undefined;
|
|
267
1244
|
pages?: {
|
|
268
1245
|
id: string;
|
|
269
1246
|
name: string;
|
|
@@ -344,6 +1321,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
344
1321
|
dependencies?: string[] | undefined;
|
|
345
1322
|
} | undefined;
|
|
346
1323
|
props?: Record<string, any> | undefined;
|
|
1324
|
+
data?: Record<string, any> | undefined;
|
|
347
1325
|
render?: any;
|
|
348
1326
|
states?: Record<string, any> | undefined;
|
|
349
1327
|
methods?: Record<string, {
|
|
@@ -354,7 +1332,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
354
1332
|
fn: string;
|
|
355
1333
|
deps?: string[] | undefined;
|
|
356
1334
|
}[] | undefined;
|
|
357
|
-
data?: Record<string, any> | undefined;
|
|
358
1335
|
}, {
|
|
359
1336
|
id: string;
|
|
360
1337
|
name?: string | undefined;
|
|
@@ -368,6 +1345,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
368
1345
|
dependencies?: string[] | undefined;
|
|
369
1346
|
} | undefined;
|
|
370
1347
|
props?: Record<string, any> | undefined;
|
|
1348
|
+
data?: Record<string, any> | undefined;
|
|
371
1349
|
render?: any;
|
|
372
1350
|
states?: Record<string, any> | undefined;
|
|
373
1351
|
methods?: Record<string, {
|
|
@@ -378,7 +1356,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
378
1356
|
fn: string;
|
|
379
1357
|
deps?: string[] | undefined;
|
|
380
1358
|
}[] | undefined;
|
|
381
|
-
data?: Record<string, any> | undefined;
|
|
382
1359
|
}>;
|
|
383
1360
|
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
384
1361
|
context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
@@ -396,6 +1373,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
396
1373
|
dependencies?: string[] | undefined;
|
|
397
1374
|
} | undefined;
|
|
398
1375
|
props?: Record<string, any> | undefined;
|
|
1376
|
+
data?: Record<string, any> | undefined;
|
|
399
1377
|
render?: any;
|
|
400
1378
|
states?: Record<string, any> | undefined;
|
|
401
1379
|
methods?: Record<string, {
|
|
@@ -406,7 +1384,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
406
1384
|
fn: string;
|
|
407
1385
|
deps?: string[] | undefined;
|
|
408
1386
|
}[] | undefined;
|
|
409
|
-
data?: Record<string, any> | undefined;
|
|
410
1387
|
};
|
|
411
1388
|
data?: Record<string, any> | undefined;
|
|
412
1389
|
context?: Record<string, any> | undefined;
|
|
@@ -424,6 +1401,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
424
1401
|
dependencies?: string[] | undefined;
|
|
425
1402
|
} | undefined;
|
|
426
1403
|
props?: Record<string, any> | undefined;
|
|
1404
|
+
data?: Record<string, any> | undefined;
|
|
427
1405
|
render?: any;
|
|
428
1406
|
states?: Record<string, any> | undefined;
|
|
429
1407
|
methods?: Record<string, {
|
|
@@ -434,7 +1412,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
434
1412
|
fn: string;
|
|
435
1413
|
deps?: string[] | undefined;
|
|
436
1414
|
}[] | undefined;
|
|
437
|
-
data?: Record<string, any> | undefined;
|
|
438
1415
|
};
|
|
439
1416
|
data?: Record<string, any> | undefined;
|
|
440
1417
|
context?: Record<string, any> | undefined;
|
|
@@ -623,19 +1600,19 @@ declare const ComponentSchema: z.ZodObject<{
|
|
|
623
1600
|
type: z.ZodString;
|
|
624
1601
|
description: z.ZodString;
|
|
625
1602
|
props: z.ZodObject<{
|
|
626
|
-
query: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]
|
|
1603
|
+
query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
|
|
627
1604
|
title: z.ZodOptional<z.ZodString>;
|
|
628
1605
|
description: z.ZodOptional<z.ZodString>;
|
|
629
1606
|
config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
630
1607
|
actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
|
|
631
1608
|
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
632
|
-
query: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]
|
|
1609
|
+
query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
|
|
633
1610
|
title: z.ZodOptional<z.ZodString>;
|
|
634
1611
|
description: z.ZodOptional<z.ZodString>;
|
|
635
1612
|
config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
636
1613
|
actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
|
|
637
1614
|
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
638
|
-
query: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]
|
|
1615
|
+
query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
|
|
639
1616
|
title: z.ZodOptional<z.ZodString>;
|
|
640
1617
|
description: z.ZodOptional<z.ZodString>;
|
|
641
1618
|
config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
@@ -650,7 +1627,7 @@ declare const ComponentSchema: z.ZodObject<{
|
|
|
650
1627
|
description: string;
|
|
651
1628
|
props: {
|
|
652
1629
|
description?: string | undefined;
|
|
653
|
-
query?: string | {} | undefined;
|
|
1630
|
+
query?: string | {} | null | undefined;
|
|
654
1631
|
title?: string | undefined;
|
|
655
1632
|
config?: Record<string, unknown> | undefined;
|
|
656
1633
|
actions?: any[] | undefined;
|
|
@@ -668,7 +1645,7 @@ declare const ComponentSchema: z.ZodObject<{
|
|
|
668
1645
|
description: string;
|
|
669
1646
|
props: {
|
|
670
1647
|
description?: string | undefined;
|
|
671
|
-
query?: string | {} | undefined;
|
|
1648
|
+
query?: string | {} | null | undefined;
|
|
672
1649
|
title?: string | undefined;
|
|
673
1650
|
config?: Record<string, unknown> | undefined;
|
|
674
1651
|
actions?: any[] | undefined;
|
|
@@ -681,24 +1658,137 @@ declare const ComponentSchema: z.ZodObject<{
|
|
|
681
1658
|
keywords?: string[] | undefined;
|
|
682
1659
|
}>;
|
|
683
1660
|
type Component = z.infer<typeof ComponentSchema>;
|
|
1661
|
+
declare const OutputFieldSchema: z.ZodObject<{
|
|
1662
|
+
name: z.ZodString;
|
|
1663
|
+
type: z.ZodEnum<["string", "number", "boolean", "date"]>;
|
|
1664
|
+
description: z.ZodString;
|
|
1665
|
+
}, "strip", z.ZodTypeAny, {
|
|
1666
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1667
|
+
name: string;
|
|
1668
|
+
description: string;
|
|
1669
|
+
}, {
|
|
1670
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1671
|
+
name: string;
|
|
1672
|
+
description: string;
|
|
1673
|
+
}>;
|
|
1674
|
+
type OutputField = z.infer<typeof OutputFieldSchema>;
|
|
1675
|
+
declare const OutputSchema: z.ZodObject<{
|
|
1676
|
+
description: z.ZodString;
|
|
1677
|
+
fields: z.ZodArray<z.ZodObject<{
|
|
1678
|
+
name: z.ZodString;
|
|
1679
|
+
type: z.ZodEnum<["string", "number", "boolean", "date"]>;
|
|
1680
|
+
description: z.ZodString;
|
|
1681
|
+
}, "strip", z.ZodTypeAny, {
|
|
1682
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1683
|
+
name: string;
|
|
1684
|
+
description: string;
|
|
1685
|
+
}, {
|
|
1686
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1687
|
+
name: string;
|
|
1688
|
+
description: string;
|
|
1689
|
+
}>, "many">;
|
|
1690
|
+
}, "strip", z.ZodTypeAny, {
|
|
1691
|
+
description: string;
|
|
1692
|
+
fields: {
|
|
1693
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1694
|
+
name: string;
|
|
1695
|
+
description: string;
|
|
1696
|
+
}[];
|
|
1697
|
+
}, {
|
|
1698
|
+
description: string;
|
|
1699
|
+
fields: {
|
|
1700
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1701
|
+
name: string;
|
|
1702
|
+
description: string;
|
|
1703
|
+
}[];
|
|
1704
|
+
}>;
|
|
1705
|
+
type ToolOutputSchema = z.infer<typeof OutputSchema>;
|
|
684
1706
|
declare const ToolSchema: z.ZodObject<{
|
|
685
1707
|
id: z.ZodString;
|
|
686
1708
|
name: z.ZodString;
|
|
687
1709
|
description: z.ZodString;
|
|
1710
|
+
/** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
|
|
1711
|
+
toolType: z.ZodOptional<z.ZodEnum<["source", "direct"]>>;
|
|
1712
|
+
/** Full untruncated schema for source agent (all columns visible) */
|
|
1713
|
+
fullSchema: z.ZodOptional<z.ZodString>;
|
|
688
1714
|
params: z.ZodRecord<z.ZodString, z.ZodString>;
|
|
689
1715
|
fn: z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodAny>;
|
|
1716
|
+
outputSchema: z.ZodOptional<z.ZodObject<{
|
|
1717
|
+
description: z.ZodString;
|
|
1718
|
+
fields: z.ZodArray<z.ZodObject<{
|
|
1719
|
+
name: z.ZodString;
|
|
1720
|
+
type: z.ZodEnum<["string", "number", "boolean", "date"]>;
|
|
1721
|
+
description: z.ZodString;
|
|
1722
|
+
}, "strip", z.ZodTypeAny, {
|
|
1723
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1724
|
+
name: string;
|
|
1725
|
+
description: string;
|
|
1726
|
+
}, {
|
|
1727
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1728
|
+
name: string;
|
|
1729
|
+
description: string;
|
|
1730
|
+
}>, "many">;
|
|
1731
|
+
}, "strip", z.ZodTypeAny, {
|
|
1732
|
+
description: string;
|
|
1733
|
+
fields: {
|
|
1734
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1735
|
+
name: string;
|
|
1736
|
+
description: string;
|
|
1737
|
+
}[];
|
|
1738
|
+
}, {
|
|
1739
|
+
description: string;
|
|
1740
|
+
fields: {
|
|
1741
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1742
|
+
name: string;
|
|
1743
|
+
description: string;
|
|
1744
|
+
}[];
|
|
1745
|
+
}>>;
|
|
1746
|
+
/** Cache policy. `false` = never cache (live data, write ops). Mirrors HTTP `Cache-Control: no-store`. */
|
|
1747
|
+
cache: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<false>, z.ZodObject<{
|
|
1748
|
+
ttlMs: z.ZodOptional<z.ZodNumber>;
|
|
1749
|
+
}, "strip", z.ZodTypeAny, {
|
|
1750
|
+
ttlMs?: number | undefined;
|
|
1751
|
+
}, {
|
|
1752
|
+
ttlMs?: number | undefined;
|
|
1753
|
+
}>]>>;
|
|
690
1754
|
}, "strip", z.ZodTypeAny, {
|
|
691
1755
|
id: string;
|
|
692
1756
|
params: Record<string, string>;
|
|
693
1757
|
name: string;
|
|
694
1758
|
description: string;
|
|
695
1759
|
fn: (args_0: any, ...args: unknown[]) => any;
|
|
1760
|
+
toolType?: "source" | "direct" | undefined;
|
|
1761
|
+
fullSchema?: string | undefined;
|
|
1762
|
+
outputSchema?: {
|
|
1763
|
+
description: string;
|
|
1764
|
+
fields: {
|
|
1765
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1766
|
+
name: string;
|
|
1767
|
+
description: string;
|
|
1768
|
+
}[];
|
|
1769
|
+
} | undefined;
|
|
1770
|
+
cache?: false | {
|
|
1771
|
+
ttlMs?: number | undefined;
|
|
1772
|
+
} | undefined;
|
|
696
1773
|
}, {
|
|
697
1774
|
id: string;
|
|
698
1775
|
params: Record<string, string>;
|
|
699
1776
|
name: string;
|
|
700
1777
|
description: string;
|
|
701
1778
|
fn: (args_0: any, ...args: unknown[]) => any;
|
|
1779
|
+
toolType?: "source" | "direct" | undefined;
|
|
1780
|
+
fullSchema?: string | undefined;
|
|
1781
|
+
outputSchema?: {
|
|
1782
|
+
description: string;
|
|
1783
|
+
fields: {
|
|
1784
|
+
type: "string" | "number" | "boolean" | "date";
|
|
1785
|
+
name: string;
|
|
1786
|
+
description: string;
|
|
1787
|
+
}[];
|
|
1788
|
+
} | undefined;
|
|
1789
|
+
cache?: false | {
|
|
1790
|
+
ttlMs?: number | undefined;
|
|
1791
|
+
} | undefined;
|
|
702
1792
|
}>;
|
|
703
1793
|
type Tool$1 = z.infer<typeof ToolSchema>;
|
|
704
1794
|
type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
|
|
@@ -737,6 +1827,10 @@ interface SuperatomSDKConfig {
|
|
|
737
1827
|
bundleDir?: string;
|
|
738
1828
|
promptsDir?: string;
|
|
739
1829
|
databaseType?: DatabaseType;
|
|
1830
|
+
/** BCP-47 locale for `fmt` in generated analyses, e.g. 'en-IN', 'en-US'. Defaults to 'en-IN'. */
|
|
1831
|
+
locale?: string;
|
|
1832
|
+
/** ISO-4217 currency for `fmt`, e.g. 'INR', 'USD'. Defaults to 'INR'. */
|
|
1833
|
+
currency?: string;
|
|
740
1834
|
ANTHROPIC_API_KEY?: string;
|
|
741
1835
|
GROQ_API_KEY?: string;
|
|
742
1836
|
GEMINI_API_KEY?: string;
|
|
@@ -750,27 +1844,61 @@ interface SuperatomSDKConfig {
|
|
|
750
1844
|
* - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
|
|
751
1845
|
*/
|
|
752
1846
|
modelStrategy?: ModelStrategy;
|
|
1847
|
+
/**
|
|
1848
|
+
* Model for the main agent (routing + analysis).
|
|
1849
|
+
* Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
|
|
1850
|
+
* If not set, uses the provider's default model.
|
|
1851
|
+
*/
|
|
1852
|
+
mainAgentModel?: string;
|
|
1853
|
+
/**
|
|
1854
|
+
* Model for source agents (per-source query generation).
|
|
1855
|
+
* Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
|
|
1856
|
+
* If not set, uses the provider's default model.
|
|
1857
|
+
*/
|
|
1858
|
+
sourceAgentModel?: string;
|
|
753
1859
|
/**
|
|
754
1860
|
* Separate model configuration for DASH_COMP flow (dashboard component picking)
|
|
755
1861
|
* If not provided, falls back to provider-based model selection
|
|
756
1862
|
*/
|
|
757
1863
|
dashCompModels?: DashCompModelConfig;
|
|
1864
|
+
/**
|
|
1865
|
+
* Similarity threshold for conversation search (semantic matching)
|
|
1866
|
+
* Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
|
|
1867
|
+
* Higher values require closer matches, lower values allow more distant matches
|
|
1868
|
+
* Default: 0.8
|
|
1869
|
+
*/
|
|
1870
|
+
conversationSimilarityThreshold?: number;
|
|
1871
|
+
/**
|
|
1872
|
+
* Query cache TTL (Time To Live) in minutes
|
|
1873
|
+
* Cached query results expire after this duration
|
|
1874
|
+
* Default: 5 minutes
|
|
1875
|
+
*/
|
|
1876
|
+
queryCacheTTL?: number;
|
|
1877
|
+
/**
|
|
1878
|
+
* Dashboard conversation history TTL (Time To Live) in minutes
|
|
1879
|
+
* Per-dashboard conversation histories expire after this duration
|
|
1880
|
+
* Default: 30 minutes
|
|
1881
|
+
*/
|
|
1882
|
+
dashboardHistoryTTL?: number;
|
|
758
1883
|
}
|
|
759
1884
|
|
|
760
1885
|
declare const KbNodesQueryFiltersSchema: z.ZodObject<{
|
|
761
1886
|
query: z.ZodOptional<z.ZodString>;
|
|
762
1887
|
category: z.ZodOptional<z.ZodString>;
|
|
763
1888
|
tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
764
|
-
|
|
1889
|
+
type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
|
|
1890
|
+
createdBy: z.ZodOptional<z.ZodString>;
|
|
765
1891
|
}, "strip", z.ZodTypeAny, {
|
|
1892
|
+
type?: "query" | "user" | "global" | undefined;
|
|
766
1893
|
query?: string | undefined;
|
|
767
1894
|
category?: string | undefined;
|
|
768
|
-
createdBy?:
|
|
1895
|
+
createdBy?: string | undefined;
|
|
769
1896
|
tags?: string[] | undefined;
|
|
770
1897
|
}, {
|
|
1898
|
+
type?: "query" | "user" | "global" | undefined;
|
|
771
1899
|
query?: string | undefined;
|
|
772
1900
|
category?: string | undefined;
|
|
773
|
-
createdBy?:
|
|
1901
|
+
createdBy?: string | undefined;
|
|
774
1902
|
tags?: string[] | undefined;
|
|
775
1903
|
}>;
|
|
776
1904
|
type KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
|
|
@@ -782,106 +1910,118 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
|
|
|
782
1910
|
content: z.ZodOptional<z.ZodString>;
|
|
783
1911
|
category: z.ZodOptional<z.ZodString>;
|
|
784
1912
|
tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
1913
|
+
type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
|
|
1914
|
+
createdBy: z.ZodOptional<z.ZodString>;
|
|
1915
|
+
updatedBy: z.ZodOptional<z.ZodString>;
|
|
1916
|
+
userId: z.ZodOptional<z.ZodString>;
|
|
788
1917
|
query: z.ZodOptional<z.ZodString>;
|
|
789
1918
|
filters: z.ZodOptional<z.ZodObject<{
|
|
790
1919
|
query: z.ZodOptional<z.ZodString>;
|
|
791
1920
|
category: z.ZodOptional<z.ZodString>;
|
|
792
1921
|
tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
793
|
-
|
|
1922
|
+
type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
|
|
1923
|
+
createdBy: z.ZodOptional<z.ZodString>;
|
|
794
1924
|
}, "strip", z.ZodTypeAny, {
|
|
1925
|
+
type?: "query" | "user" | "global" | undefined;
|
|
795
1926
|
query?: string | undefined;
|
|
796
1927
|
category?: string | undefined;
|
|
797
|
-
createdBy?:
|
|
1928
|
+
createdBy?: string | undefined;
|
|
798
1929
|
tags?: string[] | undefined;
|
|
799
1930
|
}, {
|
|
1931
|
+
type?: "query" | "user" | "global" | undefined;
|
|
800
1932
|
query?: string | undefined;
|
|
801
1933
|
category?: string | undefined;
|
|
802
|
-
createdBy?:
|
|
1934
|
+
createdBy?: string | undefined;
|
|
803
1935
|
tags?: string[] | undefined;
|
|
804
1936
|
}>>;
|
|
805
1937
|
limit: z.ZodOptional<z.ZodNumber>;
|
|
806
1938
|
offset: z.ZodOptional<z.ZodNumber>;
|
|
807
1939
|
}, "strip", z.ZodTypeAny, {
|
|
808
1940
|
id?: number | undefined;
|
|
1941
|
+
type?: "query" | "user" | "global" | undefined;
|
|
809
1942
|
query?: string | undefined;
|
|
810
1943
|
title?: string | undefined;
|
|
811
1944
|
category?: string | undefined;
|
|
812
|
-
userId?:
|
|
1945
|
+
userId?: string | undefined;
|
|
813
1946
|
limit?: number | undefined;
|
|
814
1947
|
filters?: {
|
|
1948
|
+
type?: "query" | "user" | "global" | undefined;
|
|
815
1949
|
query?: string | undefined;
|
|
816
1950
|
category?: string | undefined;
|
|
817
|
-
createdBy?:
|
|
1951
|
+
createdBy?: string | undefined;
|
|
818
1952
|
tags?: string[] | undefined;
|
|
819
1953
|
} | undefined;
|
|
820
|
-
createdBy?:
|
|
821
|
-
updatedBy?:
|
|
1954
|
+
createdBy?: string | undefined;
|
|
1955
|
+
updatedBy?: string | undefined;
|
|
1956
|
+
offset?: number | undefined;
|
|
822
1957
|
tags?: string[] | undefined;
|
|
823
1958
|
content?: string | undefined;
|
|
824
|
-
offset?: number | undefined;
|
|
825
1959
|
}, {
|
|
826
1960
|
id?: number | undefined;
|
|
1961
|
+
type?: "query" | "user" | "global" | undefined;
|
|
827
1962
|
query?: string | undefined;
|
|
828
1963
|
title?: string | undefined;
|
|
829
1964
|
category?: string | undefined;
|
|
830
|
-
userId?:
|
|
1965
|
+
userId?: string | undefined;
|
|
831
1966
|
limit?: number | undefined;
|
|
832
1967
|
filters?: {
|
|
1968
|
+
type?: "query" | "user" | "global" | undefined;
|
|
833
1969
|
query?: string | undefined;
|
|
834
1970
|
category?: string | undefined;
|
|
835
|
-
createdBy?:
|
|
1971
|
+
createdBy?: string | undefined;
|
|
836
1972
|
tags?: string[] | undefined;
|
|
837
1973
|
} | undefined;
|
|
838
|
-
createdBy?:
|
|
839
|
-
updatedBy?:
|
|
1974
|
+
createdBy?: string | undefined;
|
|
1975
|
+
updatedBy?: string | undefined;
|
|
1976
|
+
offset?: number | undefined;
|
|
840
1977
|
tags?: string[] | undefined;
|
|
841
1978
|
content?: string | undefined;
|
|
842
|
-
offset?: number | undefined;
|
|
843
1979
|
}>>;
|
|
844
1980
|
}, "strip", z.ZodTypeAny, {
|
|
845
|
-
operation: "create" | "getOne" | "
|
|
1981
|
+
operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
|
|
846
1982
|
data?: {
|
|
847
1983
|
id?: number | undefined;
|
|
1984
|
+
type?: "query" | "user" | "global" | undefined;
|
|
848
1985
|
query?: string | undefined;
|
|
849
1986
|
title?: string | undefined;
|
|
850
1987
|
category?: string | undefined;
|
|
851
|
-
userId?:
|
|
1988
|
+
userId?: string | undefined;
|
|
852
1989
|
limit?: number | undefined;
|
|
853
1990
|
filters?: {
|
|
1991
|
+
type?: "query" | "user" | "global" | undefined;
|
|
854
1992
|
query?: string | undefined;
|
|
855
1993
|
category?: string | undefined;
|
|
856
|
-
createdBy?:
|
|
1994
|
+
createdBy?: string | undefined;
|
|
857
1995
|
tags?: string[] | undefined;
|
|
858
1996
|
} | undefined;
|
|
859
|
-
createdBy?:
|
|
860
|
-
updatedBy?:
|
|
1997
|
+
createdBy?: string | undefined;
|
|
1998
|
+
updatedBy?: string | undefined;
|
|
1999
|
+
offset?: number | undefined;
|
|
861
2000
|
tags?: string[] | undefined;
|
|
862
2001
|
content?: string | undefined;
|
|
863
|
-
offset?: number | undefined;
|
|
864
2002
|
} | undefined;
|
|
865
2003
|
}, {
|
|
866
|
-
operation: "create" | "getOne" | "
|
|
2004
|
+
operation: "create" | "getOne" | "search" | "update" | "delete" | "getAll" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
|
|
867
2005
|
data?: {
|
|
868
2006
|
id?: number | undefined;
|
|
2007
|
+
type?: "query" | "user" | "global" | undefined;
|
|
869
2008
|
query?: string | undefined;
|
|
870
2009
|
title?: string | undefined;
|
|
871
2010
|
category?: string | undefined;
|
|
872
|
-
userId?:
|
|
2011
|
+
userId?: string | undefined;
|
|
873
2012
|
limit?: number | undefined;
|
|
874
2013
|
filters?: {
|
|
2014
|
+
type?: "query" | "user" | "global" | undefined;
|
|
875
2015
|
query?: string | undefined;
|
|
876
2016
|
category?: string | undefined;
|
|
877
|
-
createdBy?:
|
|
2017
|
+
createdBy?: string | undefined;
|
|
878
2018
|
tags?: string[] | undefined;
|
|
879
2019
|
} | undefined;
|
|
880
|
-
createdBy?:
|
|
881
|
-
updatedBy?:
|
|
2020
|
+
createdBy?: string | undefined;
|
|
2021
|
+
updatedBy?: string | undefined;
|
|
2022
|
+
offset?: number | undefined;
|
|
882
2023
|
tags?: string[] | undefined;
|
|
883
2024
|
content?: string | undefined;
|
|
884
|
-
offset?: number | undefined;
|
|
885
2025
|
} | undefined;
|
|
886
2026
|
}>;
|
|
887
2027
|
type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
|
|
@@ -1082,72 +2222,624 @@ declare class DashboardManager {
|
|
|
1082
2222
|
* Get dashboard count
|
|
1083
2223
|
* @returns Number of dashboards
|
|
1084
2224
|
*/
|
|
1085
|
-
getDashboardCount(): number;
|
|
1086
|
-
}
|
|
1087
|
-
|
|
1088
|
-
/**
|
|
1089
|
-
* ReportManager class to handle CRUD operations on reports
|
|
1090
|
-
* All operations read/write directly to files (no in-memory caching)
|
|
1091
|
-
*/
|
|
1092
|
-
declare class ReportManager {
|
|
1093
|
-
private reportsBasePath;
|
|
1094
|
-
private projectId;
|
|
2225
|
+
getDashboardCount(): number;
|
|
2226
|
+
}
|
|
2227
|
+
|
|
2228
|
+
/**
|
|
2229
|
+
* ReportManager class to handle CRUD operations on reports
|
|
2230
|
+
* All operations read/write directly to files (no in-memory caching)
|
|
2231
|
+
*/
|
|
2232
|
+
declare class ReportManager {
|
|
2233
|
+
private reportsBasePath;
|
|
2234
|
+
private projectId;
|
|
2235
|
+
/**
|
|
2236
|
+
* Initialize ReportManager with project ID
|
|
2237
|
+
* @param projectId - Project ID to use in file path
|
|
2238
|
+
*/
|
|
2239
|
+
constructor(projectId?: string);
|
|
2240
|
+
/**
|
|
2241
|
+
* Get the file path for a specific report
|
|
2242
|
+
* @param reportId - Report ID
|
|
2243
|
+
* @returns Full path to report data.json file
|
|
2244
|
+
*/
|
|
2245
|
+
private getReportPath;
|
|
2246
|
+
/**
|
|
2247
|
+
* Create a new report
|
|
2248
|
+
* @param reportId - Unique report ID
|
|
2249
|
+
* @param report - Report data
|
|
2250
|
+
* @returns Created report with metadata
|
|
2251
|
+
*/
|
|
2252
|
+
createReport(reportId: string, report: DSLRendererProps): DSLRendererProps;
|
|
2253
|
+
/**
|
|
2254
|
+
* Get a specific report by ID
|
|
2255
|
+
* @param reportId - Report ID
|
|
2256
|
+
* @returns Report data or null if not found
|
|
2257
|
+
*/
|
|
2258
|
+
getReport(reportId: string): DSLRendererProps | null;
|
|
2259
|
+
/**
|
|
2260
|
+
* Get all reports
|
|
2261
|
+
* @returns Array of report objects with their IDs
|
|
2262
|
+
*/
|
|
2263
|
+
getAllReports(): Array<{
|
|
2264
|
+
reportId: string;
|
|
2265
|
+
report: DSLRendererProps;
|
|
2266
|
+
}>;
|
|
2267
|
+
/**
|
|
2268
|
+
* Update an existing report
|
|
2269
|
+
* @param reportId - Report ID
|
|
2270
|
+
* @param report - Updated report data
|
|
2271
|
+
* @returns Updated report or null if not found
|
|
2272
|
+
*/
|
|
2273
|
+
updateReport(reportId: string, report: DSLRendererProps): DSLRendererProps | null;
|
|
2274
|
+
/**
|
|
2275
|
+
* Delete a report
|
|
2276
|
+
* @param reportId - Report ID
|
|
2277
|
+
* @returns True if deleted, false if not found
|
|
2278
|
+
*/
|
|
2279
|
+
deleteReport(reportId: string): boolean;
|
|
2280
|
+
/**
|
|
2281
|
+
* Check if a report exists
|
|
2282
|
+
* @param reportId - Report ID
|
|
2283
|
+
* @returns True if report exists, false otherwise
|
|
2284
|
+
*/
|
|
2285
|
+
reportExists(reportId: string): boolean;
|
|
2286
|
+
/**
|
|
2287
|
+
* Get report count
|
|
2288
|
+
* @returns Number of reports
|
|
2289
|
+
*/
|
|
2290
|
+
getReportCount(): number;
|
|
2291
|
+
}
|
|
2292
|
+
|
|
2293
|
+
/**
|
|
2294
|
+
* ScriptRecipeStore — injected metadata backend for the script flow.
|
|
2295
|
+
*
|
|
2296
|
+
* The SDK is standalone (no DB dependency). The backend implements this
|
|
2297
|
+
* interface over Postgres (full-text search + atomic counters) and injects it
|
|
2298
|
+
* via `collections['script-recipes']`, exactly like `collections['source-embeddings']`.
|
|
2299
|
+
* `ScriptStore` consumes it for all METADATA operations while keeping the
|
|
2300
|
+
* executable body on disk as scripts-store/<fileBase>.ts.
|
|
2301
|
+
*
|
|
2302
|
+
* All metadata rows are plain JSON (no scriptBody — that lives on disk).
|
|
2303
|
+
* See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md (#1, #3, #7).
|
|
2304
|
+
*/
|
|
2305
|
+
|
|
2306
|
+
/** One recipe's metadata as stored in Postgres (mirrors the script_recipes table). */
|
|
2307
|
+
interface ScriptRecipeMetaRow {
|
|
2308
|
+
id: string;
|
|
2309
|
+
projectId?: string | null;
|
|
2310
|
+
version: number;
|
|
2311
|
+
name: string;
|
|
2312
|
+
intentDescription: string;
|
|
2313
|
+
tags: string[] | null;
|
|
2314
|
+
createdFrom: string | null;
|
|
2315
|
+
sourceIds: string[] | null;
|
|
2316
|
+
tables: string[] | null;
|
|
2317
|
+
parameters: ScriptParameter[] | null;
|
|
2318
|
+
components?: ScriptComponentSpec[] | null;
|
|
2319
|
+
displayPreference?: ScriptDisplayPreference | null;
|
|
2320
|
+
fileBase: string;
|
|
2321
|
+
bodyHash?: string | null;
|
|
2322
|
+
successCount: number;
|
|
2323
|
+
failureCount: number;
|
|
2324
|
+
lastUsed: string | null;
|
|
2325
|
+
parentId?: string | null;
|
|
2326
|
+
forkDepth?: number | null;
|
|
2327
|
+
forkReason?: string | null;
|
|
2328
|
+
status: 'draft' | 'verified' | string;
|
|
2329
|
+
turnId?: string | null;
|
|
2330
|
+
editedBy?: string | null;
|
|
2331
|
+
editedFrom?: string | null;
|
|
2332
|
+
history?: ScriptVersionRecord[] | null;
|
|
2333
|
+
lastError?: {
|
|
2334
|
+
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
2335
|
+
message: string;
|
|
2336
|
+
at: string;
|
|
2337
|
+
attempt: number;
|
|
2338
|
+
} | null;
|
|
2339
|
+
createdAt?: string | null;
|
|
2340
|
+
updatedAt?: string | null;
|
|
2341
|
+
}
|
|
2342
|
+
interface ScriptRecipeStore {
|
|
2343
|
+
/** FTS shortlist of healthy verified recipes for the matcher (metadata only). */
|
|
2344
|
+
search(params: {
|
|
2345
|
+
prompt: string;
|
|
2346
|
+
projectId?: string;
|
|
2347
|
+
limit?: number;
|
|
2348
|
+
}): Promise<ScriptRecipeMetaRow[]>;
|
|
2349
|
+
/** Fetch one recipe by id (any status). */
|
|
2350
|
+
getById(id: string): Promise<ScriptRecipeMetaRow | null>;
|
|
2351
|
+
/** Count healthy verified recipes (drives the "any scripts?" gate). */
|
|
2352
|
+
count(params?: {
|
|
2353
|
+
projectId?: string;
|
|
2354
|
+
}): Promise<number>;
|
|
2355
|
+
/** Insert or update a recipe row (keyed by id). */
|
|
2356
|
+
upsert(row: ScriptRecipeMetaRow): Promise<void>;
|
|
2357
|
+
/** Atomically bump counters / last-used. */
|
|
2358
|
+
updateStats(id: string, patch: {
|
|
2359
|
+
successDelta?: number;
|
|
2360
|
+
failureDelta?: number;
|
|
2361
|
+
lastUsed?: string;
|
|
2362
|
+
}): Promise<void>;
|
|
2363
|
+
/** Flip a draft to verified, applying provenance + optional fork lineage. */
|
|
2364
|
+
promote(id: string, patch: {
|
|
2365
|
+
sourceIds: string[];
|
|
2366
|
+
tables: string[];
|
|
2367
|
+
fileBase?: string;
|
|
2368
|
+
parentId?: string;
|
|
2369
|
+
forkDepth?: number;
|
|
2370
|
+
forkReason?: string;
|
|
2371
|
+
components?: ScriptComponentSpec[];
|
|
2372
|
+
}): Promise<ScriptRecipeMetaRow | null>;
|
|
2373
|
+
/**
|
|
2374
|
+
* Commit a verified edit onto an EXISTING recipe: bump `version`, replace the
|
|
2375
|
+
* body-bearing metadata, append a history record, reset health counters, and
|
|
2376
|
+
* clear the component specs (they were validated against the old shape).
|
|
2377
|
+
* Returns the updated row, or null when the target is gone.
|
|
2378
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5.
|
|
2379
|
+
*/
|
|
2380
|
+
commitEdit?(id: string, patch: {
|
|
2381
|
+
name?: string;
|
|
2382
|
+
intentDescription?: string;
|
|
2383
|
+
tags?: string[];
|
|
2384
|
+
parameters?: ScriptParameter[];
|
|
2385
|
+
bodyHash: string;
|
|
2386
|
+
/** New on-disk stem when the edit renamed the script; omitted otherwise. */
|
|
2387
|
+
fileBase?: string;
|
|
2388
|
+
sourceIds?: string[];
|
|
2389
|
+
tables?: string[];
|
|
2390
|
+
editedBy?: string;
|
|
2391
|
+
editedFrom?: string;
|
|
2392
|
+
historyEntry: {
|
|
2393
|
+
version: number;
|
|
2394
|
+
at: string;
|
|
2395
|
+
by?: string;
|
|
2396
|
+
instruction?: string;
|
|
2397
|
+
changeSummary?: string;
|
|
2398
|
+
bodyHash?: string;
|
|
2399
|
+
};
|
|
2400
|
+
}): Promise<ScriptRecipeMetaRow | null>;
|
|
2401
|
+
/** Stamp a draft's last execution error. */
|
|
2402
|
+
recordDraftError(id: string, err: {
|
|
2403
|
+
phase: string;
|
|
2404
|
+
message: string;
|
|
2405
|
+
attempt: number;
|
|
2406
|
+
at: string;
|
|
2407
|
+
}): Promise<void>;
|
|
2408
|
+
/** Delete a recipe row (body file removed separately). */
|
|
2409
|
+
remove(id: string): Promise<void>;
|
|
2410
|
+
/** True if `fileBase` is taken by a different recipe in this project. */
|
|
2411
|
+
fileBaseTaken(fileBase: string, excludeId: string, projectId?: string): Promise<boolean>;
|
|
2412
|
+
}
|
|
2413
|
+
/** Pull the injected store off the collections bag (or null if not wired). */
|
|
2414
|
+
declare function resolveScriptRecipeStore(collections: any): ScriptRecipeStore | null;
|
|
2415
|
+
|
|
2416
|
+
/**
|
|
2417
|
+
* ScriptStore — Postgres metadata + on-disk body for script recipes.
|
|
2418
|
+
*
|
|
2419
|
+
* Split of responsibilities:
|
|
2420
|
+
* - METADATA → injected `ScriptRecipeStore` (Postgres FTS + atomic counters),
|
|
2421
|
+
* resolved from `collections['script-recipes']`.
|
|
2422
|
+
* - BODY → scripts-store/<fileBase>.ts, editable in your IDE. Written
|
|
2423
|
+
* atomically (temp + rename); `bodyHash` (sha256) detects edits.
|
|
2424
|
+
*
|
|
2425
|
+
* The old "read every file every turn + send the whole catalog to the LLM"
|
|
2426
|
+
* matcher is gone — matching is `store.search(prompt)` (FTS shortlist). The
|
|
2427
|
+
* draft/verified filename dance is gone too: `status` is a DB column and the
|
|
2428
|
+
* file keeps a stable `<fileBase>.ts` name across promotion.
|
|
2429
|
+
*
|
|
2430
|
+
* When no metadata store is injected, the store degrades to a safe no-op
|
|
2431
|
+
* (count 0 → script flow disabled) instead of crashing.
|
|
2432
|
+
*
|
|
2433
|
+
* See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md.
|
|
2434
|
+
*/
|
|
2435
|
+
|
|
2436
|
+
interface SaveDraftInput {
|
|
2437
|
+
/** Reuse an existing draft (retry); omit to mint a new one. */
|
|
2438
|
+
recipeId?: string;
|
|
2439
|
+
/** Per-turn unique suffix, stable across retries within the turn. */
|
|
2440
|
+
turnId: string;
|
|
2441
|
+
name: string;
|
|
2442
|
+
intentDescription: string;
|
|
2443
|
+
tags: string[];
|
|
2444
|
+
parameters: ScriptParameter[];
|
|
2445
|
+
scriptBody: string;
|
|
2446
|
+
createdFrom: string;
|
|
2447
|
+
/**
|
|
2448
|
+
* Set when this draft is a SHADOW of an existing recipe being edited. The
|
|
2449
|
+
* draft is verified independently and merged back onto the parent via
|
|
2450
|
+
* `commitEdit`, so the working script is never clobbered by an edit that
|
|
2451
|
+
* turns out not to run. See backend/docs/SCRIPT-EDIT-DESIGN.md § D5.
|
|
2452
|
+
*/
|
|
2453
|
+
parentId?: string;
|
|
2454
|
+
}
|
|
2455
|
+
interface PromoteToVerifiedInput {
|
|
2456
|
+
sourceIds: string[];
|
|
2457
|
+
tables: string[];
|
|
2458
|
+
parentId?: string;
|
|
2459
|
+
forkDepth?: number;
|
|
2460
|
+
forkReason?: string;
|
|
2461
|
+
components?: ScriptComponentSpec[];
|
|
2462
|
+
}
|
|
2463
|
+
interface ScriptStoreOptions {
|
|
2464
|
+
/** Explicit metadata store, or resolved from `collections['script-recipes']`. */
|
|
2465
|
+
store?: ScriptRecipeStore | null;
|
|
2466
|
+
collections?: any;
|
|
2467
|
+
/** Body directory (defaults to <cwd>/scripts-store). */
|
|
2468
|
+
baseDir?: string;
|
|
2469
|
+
/** Project scope stamped on every row. */
|
|
2470
|
+
projectId?: string;
|
|
2471
|
+
}
|
|
2472
|
+
declare function normalizeScriptBody(scriptBody: string): string;
|
|
2473
|
+
declare class ScriptStore {
|
|
2474
|
+
private store;
|
|
2475
|
+
private storeDir;
|
|
2476
|
+
private projectId?;
|
|
2477
|
+
constructor(opts?: ScriptStoreOptions);
|
|
2478
|
+
/** Whether a metadata store is wired (matcher / authoring are gated on this). */
|
|
2479
|
+
hasStore(): boolean;
|
|
2480
|
+
/** Number of healthy verified recipes (gates the script-matching path). */
|
|
2481
|
+
count(): Promise<number>;
|
|
2482
|
+
/**
|
|
2483
|
+
* FTS shortlist for the matcher (metadata only — bodies are loaded lazily by
|
|
2484
|
+
* `get()` once the LLM picks one). Returns verified, healthy recipes ranked
|
|
2485
|
+
* by relevance.
|
|
2486
|
+
*/
|
|
2487
|
+
search(prompt: string, limit?: number): Promise<ScriptRecipe[]>;
|
|
2488
|
+
/** Fetch one recipe by id with its body loaded from disk. */
|
|
2489
|
+
get(id: string): Promise<ScriptRecipe | null>;
|
|
2490
|
+
/** Create or update a recipe (metadata upsert + body write when changed). */
|
|
2491
|
+
save(recipe: ScriptRecipe): Promise<void>;
|
|
2492
|
+
/**
|
|
2493
|
+
* Persist (or update) a draft. Within a turn, retries that pass the same
|
|
2494
|
+
* `recipeId` overwrite the same row + file; a fresh `recipeId` mints a new
|
|
2495
|
+
* draft. The body is visible at scripts-store/<fileBase>.ts immediately.
|
|
2496
|
+
*/
|
|
2497
|
+
saveDraft(input: SaveDraftInput): Promise<ScriptRecipe>;
|
|
2498
|
+
/** Stamp a draft's last execution error (metadata only). */
|
|
2499
|
+
recordDraftError(recipeId: string, err: {
|
|
2500
|
+
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
2501
|
+
message: string;
|
|
2502
|
+
attempt: number;
|
|
2503
|
+
}): Promise<void>;
|
|
2504
|
+
/**
|
|
2505
|
+
* Promote a successfully-executed draft into a verified script.
|
|
2506
|
+
* The on-disk body already exists at <fileBase>.ts (written at write_script
|
|
2507
|
+
* time) and keeps its name — only the DB row flips status + provenance.
|
|
2508
|
+
*/
|
|
2509
|
+
promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): Promise<ScriptRecipe | null>;
|
|
2510
|
+
/**
|
|
2511
|
+
* Commit a user-directed edit: merge a VERIFIED shadow draft back onto the
|
|
2512
|
+
* recipe it was editing, as version N+1 under the SAME recipe id.
|
|
2513
|
+
*
|
|
2514
|
+
* Keeping the id stable is the point of the whole feature — every cached
|
|
2515
|
+
* conversation, `script_dataset` regeneration descriptor and persisted
|
|
2516
|
+
* component spec already points at it, so the correction applies retroactively
|
|
2517
|
+
* to replays instead of stranding them on the old body.
|
|
2518
|
+
*
|
|
2519
|
+
* Steps (see backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5):
|
|
2520
|
+
* 1. archive the current body as `<fileBase>.v<version>.ts`
|
|
2521
|
+
* 2. write the edited body to the original fileBase (atomic)
|
|
2522
|
+
* 3. version++, copy name/description/params, append a history record
|
|
2523
|
+
* 4. reset health counters — the pre-edit failure history is stale
|
|
2524
|
+
* 5. clear component specs — they were validated against the OLD shape
|
|
2525
|
+
* 6. delete the shadow draft (row + file)
|
|
2526
|
+
*
|
|
2527
|
+
* Returns the updated recipe, or null when the commit could not be applied
|
|
2528
|
+
* (caller should then fall back to treating the draft as a new script).
|
|
2529
|
+
*/
|
|
2530
|
+
commitEdit(targetId: string, draft: {
|
|
2531
|
+
recipeId: string;
|
|
2532
|
+
name?: string;
|
|
2533
|
+
intentDescription?: string;
|
|
2534
|
+
tags?: string[];
|
|
2535
|
+
parameters?: ScriptParameter[];
|
|
2536
|
+
scriptBody: string;
|
|
2537
|
+
sourceIds?: string[];
|
|
2538
|
+
tables?: string[];
|
|
2539
|
+
}, meta: {
|
|
2540
|
+
instruction?: string;
|
|
2541
|
+
changeSummary?: string;
|
|
2542
|
+
editedBy?: string;
|
|
2543
|
+
}): Promise<ScriptRecipe | null>;
|
|
2544
|
+
/**
|
|
2545
|
+
* Drop a draft (row + body file). MainAgent calls this at end-of-turn when a
|
|
2546
|
+
* draft was authored but never verified — failed drafts are never matched, so
|
|
2547
|
+
* deleting them immediately avoids unbounded accumulation (#5). No-op if the
|
|
2548
|
+
* recipe isn't a draft (so a promoted/verified script is never removed here).
|
|
2549
|
+
*/
|
|
2550
|
+
discardDraft(recipeId: string): Promise<void>;
|
|
2551
|
+
/** Delete a recipe (row + body file). */
|
|
2552
|
+
delete(id: string): Promise<void>;
|
|
2553
|
+
/** Record a successful execution (atomic counter bump). */
|
|
2554
|
+
recordSuccess(id: string): Promise<void>;
|
|
2555
|
+
/** Record a failed execution (atomic counter bump). */
|
|
2556
|
+
recordFailure(id: string): Promise<void>;
|
|
2557
|
+
/** Absolute path to the .ts body for a recipe (used by the runner/MainAgent). */
|
|
2558
|
+
getScriptPath(recipe: ScriptRecipe): string;
|
|
2559
|
+
private removeById;
|
|
2560
|
+
private rowToRecipe;
|
|
2561
|
+
private recipeToRow;
|
|
2562
|
+
/** slug of name, with a short id suffix when the bare slug is already taken. */
|
|
2563
|
+
private computeFileBase;
|
|
2564
|
+
private toSlug;
|
|
2565
|
+
private hash;
|
|
2566
|
+
/**
|
|
2567
|
+
* Attach getComponents to the recipe body. The stored `components` column is
|
|
2568
|
+
* cleared at promotion (see promoteToVerified): once the body computes its own
|
|
2569
|
+
* specs, a stale spec array beside a live program is how the wrong one gets
|
|
2570
|
+
* read later. See backend/docs/COMPONENTS-AS-PROGRAM-DESIGN.md § 4.4.
|
|
2571
|
+
*/
|
|
2572
|
+
attachComponents(recipeId: string, componentsBody: string): Promise<boolean>;
|
|
2573
|
+
/**
|
|
2574
|
+
* Append (or replace) the `getAnalysis` export on an existing draft body.
|
|
2575
|
+
*
|
|
2576
|
+
* The narrative is authored AFTER execution, so it lands on a file that
|
|
2577
|
+
* already holds a working getData — rewriting the whole body would risk
|
|
2578
|
+
* losing the query that just succeeded. Replaces any earlier getAnalysis so
|
|
2579
|
+
* a retry does not stack duplicate exports.
|
|
2580
|
+
*/
|
|
2581
|
+
attachAnalysis(recipeId: string, analysisBody: string): Promise<boolean>;
|
|
2582
|
+
private bodyPath;
|
|
2583
|
+
private readBody;
|
|
2584
|
+
/** Directory holding superseded bodies. Dot-prefixed so IDEs/`ls` hide it. */
|
|
2585
|
+
private get archiveDir();
|
|
2586
|
+
/**
|
|
2587
|
+
* Archive a superseded body as `.versions/<fileBase>.v<n>.ts`.
|
|
2588
|
+
*
|
|
2589
|
+
* Kept out of the main store directory on purpose — see commitEdit step 1.
|
|
2590
|
+
* To roll back: copy the file back over `scripts-store/<fileBase>.ts`.
|
|
2591
|
+
*/
|
|
2592
|
+
private writeArchive;
|
|
2593
|
+
/**
|
|
2594
|
+
* Move a recipe's archived versions to a new prefix when its fileBase changes,
|
|
2595
|
+
* so all versions of one recipe stay grouped. Without this, two renames would
|
|
2596
|
+
* scatter a single recipe's history across three prefixes in `.versions/` with
|
|
2597
|
+
* nothing linking them back to the live script.
|
|
2598
|
+
*/
|
|
2599
|
+
private renameArchives;
|
|
2600
|
+
/** Atomic body write (temp + rename) so concurrent reads never see a partial file. */
|
|
2601
|
+
private writeBody;
|
|
2602
|
+
private unlinkBody;
|
|
2603
|
+
}
|
|
2604
|
+
|
|
2605
|
+
/**
|
|
2606
|
+
* Main Agent (Orchestrator)
|
|
2607
|
+
*
|
|
2608
|
+
* A single LLM.streamWithTools() call that handles everything:
|
|
2609
|
+
* - Routing: decides which source(s) to query based on summaries
|
|
2610
|
+
* - Querying: calls source tools (each wraps an independent SourceAgent)
|
|
2611
|
+
* - Direct tools: calls pre-built function tools directly with LLM-provided params
|
|
2612
|
+
* - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
|
|
2613
|
+
* - Analysis: generates final text response from the data
|
|
2614
|
+
*
|
|
2615
|
+
* Two tool types:
|
|
2616
|
+
* - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
|
|
2617
|
+
* - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
|
|
2618
|
+
*/
|
|
2619
|
+
|
|
2620
|
+
declare class MainAgent {
|
|
2621
|
+
private externalTools;
|
|
2622
|
+
private workflows;
|
|
2623
|
+
private config;
|
|
2624
|
+
private streamBuffer;
|
|
2625
|
+
/**
|
|
2626
|
+
* Optional: when provided, MainAgent exposes the `write_script` /
|
|
2627
|
+
* `execute_script` tools to the LLM and persists drafts to disk via the
|
|
2628
|
+
* store. Headless callers (alert analyzer, metric resolver) omit these to
|
|
2629
|
+
* suppress script authoring entirely — drafts would otherwise leak onto
|
|
2630
|
+
* disk with no caller to promote or clean them up.
|
|
2631
|
+
*/
|
|
2632
|
+
private scriptStore;
|
|
2633
|
+
private turnId;
|
|
2634
|
+
private createdFromPrompt;
|
|
2635
|
+
private scriptState;
|
|
2636
|
+
/** Answer-flow component catalog (filtered + projected by the caller). */
|
|
2637
|
+
private componentCatalog;
|
|
2638
|
+
/** Specs accepted by `write_components` this turn; empty until it succeeds. */
|
|
2639
|
+
/**
|
|
2640
|
+
* Entities resolved this turn, appended verbatim to every source dispatch.
|
|
2641
|
+
*
|
|
2642
|
+
* Not left to the model to copy into its intent prose: observed live, the
|
|
2643
|
+
* MainAgent wrote names instead of ids on the first dispatch AND re-spelled
|
|
2644
|
+
* 'F D C LIMITED' as 'FDC Limited', so the source agent fell back to
|
|
2645
|
+
* `PartyName LIKE '%FDC%'` and found 2 of 3 customers. Carrying the ids
|
|
2646
|
+
* structurally makes that impossible rather than instruction-dependent.
|
|
2647
|
+
*/
|
|
2648
|
+
private resolvedEntities;
|
|
2649
|
+
private componentSpecs;
|
|
2650
|
+
private componentLayout;
|
|
2651
|
+
private renderComponentAttempts;
|
|
2652
|
+
/**
|
|
2653
|
+
* Fork mode — set when this turn is adapting a near-matching parent script.
|
|
2654
|
+
* In fork mode there is no legitimate "answer with bare text" outcome: the
|
|
2655
|
+
* only correct first move is a tool call (write_script, or a source tool for
|
|
2656
|
+
* schema discovery). We therefore force tool use on the first LLM iteration
|
|
2657
|
+
* so the model can't end its turn with a bare "I'll adapt…" preamble and zero
|
|
2658
|
+
* tool calls. Never set on the fresh-authoring / general-question path.
|
|
2659
|
+
*/
|
|
2660
|
+
private forkMode;
|
|
2661
|
+
/**
|
|
2662
|
+
* Edit mode — set when this turn applies a user-directed change to an
|
|
2663
|
+
* existing script. Swaps the system prompt to `agent-main-edit` and stamps
|
|
2664
|
+
* the shadow draft's parentId. Like fork mode there is no legitimate
|
|
2665
|
+
* "answer with bare text" outcome, so tool use is forced on iteration 1.
|
|
2666
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 4.
|
|
2667
|
+
*/
|
|
2668
|
+
private editContext;
|
|
2669
|
+
/** The recipe's durable rendering choice — see the constructor. */
|
|
2670
|
+
private displayPreference;
|
|
2671
|
+
/**
|
|
2672
|
+
* Per-turn cancellation signal (user hit "Stop"). Set at the top of
|
|
2673
|
+
* handleQuestion and read by the tool handler, the SourceAgent dispatch, and
|
|
2674
|
+
* the script subprocess so an abort tears down every layer of the turn.
|
|
2675
|
+
*/
|
|
2676
|
+
private abortSignal?;
|
|
2677
|
+
constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[], forkMode?: boolean, editContext?: EditContext, componentCatalog?: Component[],
|
|
2678
|
+
/**
|
|
2679
|
+
* The recipe's durable rendering choice, when it has one. A DATA edit
|
|
2680
|
+
* re-authors getComponents from scratch, so without this the user's chart
|
|
2681
|
+
* type is silently dropped whenever anyone changes the SQL.
|
|
2682
|
+
*/
|
|
2683
|
+
displayPreference?: {
|
|
2684
|
+
componentTypes: string[];
|
|
2685
|
+
instruction: string;
|
|
2686
|
+
});
|
|
2687
|
+
/** True when the turn is applying a user-directed script edit. */
|
|
2688
|
+
private get editMode();
|
|
2689
|
+
private get scriptingEnabled();
|
|
2690
|
+
/**
|
|
2691
|
+
* Handle a user question using the multi-agent system.
|
|
2692
|
+
*
|
|
2693
|
+
* This is ONE LLM.streamWithTools() call. The LLM:
|
|
2694
|
+
* 1. Sees source summaries + direct tool descriptions in system prompt
|
|
2695
|
+
* 2. Decides which tool(s) to call (routing)
|
|
2696
|
+
* 3. Source tools → SourceAgent runs independently → returns data
|
|
2697
|
+
* 4. Direct tools → fn() called directly with LLM params → returns data
|
|
2698
|
+
* 5. Generates final analysis text
|
|
2699
|
+
*/
|
|
2700
|
+
handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, signal?: AbortSignal): Promise<AgentResponse>;
|
|
2701
|
+
/**
|
|
2702
|
+
* Tool definition, with the catalog rendered from the registered `Metadata`
|
|
2703
|
+
* the caller passed in. Generated rather than hand-written so it cannot drift
|
|
2704
|
+
* from what the frontend actually ships.
|
|
2705
|
+
*/
|
|
2706
|
+
private buildWriteComponentsToolDef;
|
|
2707
|
+
/**
|
|
2708
|
+
* Validate the agent's component picks against the REAL columns of each bound
|
|
2709
|
+
* dataset. All-or-nothing: any error rejects the whole call and returns the
|
|
2710
|
+
* findings, because a partially-accepted dashboard makes the retry ambiguous.
|
|
2711
|
+
*/
|
|
2712
|
+
private validateSpecs;
|
|
2713
|
+
/**
|
|
2714
|
+
* Author the dashboard as a program. Attaches getComponents to the draft, runs
|
|
2715
|
+
* it over the verified rows, then validates the specs it RETURNED — the program
|
|
2716
|
+
* is never trusted because it is a program, exactly as an authored spec is not.
|
|
2717
|
+
*/
|
|
2718
|
+
private handleWriteComponents;
|
|
2719
|
+
/**
|
|
2720
|
+
* Author the answer as a program. Runs after execute_script, so the body is
|
|
2721
|
+
* written with the result already known and can react to what it found.
|
|
2722
|
+
*
|
|
2723
|
+
* Rejects a body that types numbers rather than computing them — see
|
|
2724
|
+
* analysis-lint. A hardcoded figure is worse than prose: it freezes into the
|
|
2725
|
+
* recipe and replays unchanged while the data moves underneath it.
|
|
2726
|
+
*/
|
|
2727
|
+
private handleWriteAnalysis;
|
|
2728
|
+
private handleWriteScript;
|
|
2729
|
+
private handleExecuteScript;
|
|
2730
|
+
/**
|
|
2731
|
+
* Build the AgentWrittenScript payload the caller will hand to
|
|
2732
|
+
* `ScriptStore.promoteToVerified()`. Only returned when a verified
|
|
2733
|
+
* successful execution is on record.
|
|
2734
|
+
*/
|
|
2735
|
+
private buildSavedScript;
|
|
2736
|
+
private normalizeParameterList;
|
|
2737
|
+
/**
|
|
2738
|
+
* Use the schema embedding collection to pre-select relevant tables for
|
|
2739
|
+
* this source + intent. Returns a formatted schema block if confidence is
|
|
2740
|
+
* high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
|
|
2741
|
+
*
|
|
2742
|
+
* When this returns a block, we can skip the SourceAgent's `search_schema`
|
|
2743
|
+
* loop and reduce iteration budget. When it returns null, the SourceAgent
|
|
2744
|
+
* falls back to the existing LLM-driven keyword search (same as today).
|
|
2745
|
+
*/
|
|
2746
|
+
/**
|
|
2747
|
+
* Ids + verbatim names for everything resolved this turn, appended by CODE to
|
|
2748
|
+
* each source dispatch so neither omission nor re-spelling by the model can
|
|
2749
|
+
* lose them. Empty string when nothing was resolved, so intents are untouched
|
|
2750
|
+
* for questions that name no entities.
|
|
2751
|
+
*
|
|
2752
|
+
* Also appends `attrs.scopeSql` when the resolved instance carries one —
|
|
2753
|
+
* same "guaranteed by code" reasoning as the ids/names above, extended to
|
|
2754
|
+
* the one attrs field with a documented, cross-entity-type meaning: a
|
|
2755
|
+
* ready-made SQL predicate an entity's index precomputed (see
|
|
2756
|
+
* ENTITY-SEARCH-DESIGN.md's hierarchy-broadening pattern — branch/region/
|
|
2757
|
+
* state entity types attach it so a lane/route question never needs its
|
|
2758
|
+
* own city-matching join). Confirmed real cost of not doing this: a
|
|
2759
|
+
* branch/state resolved with scopeSql sat unused while the source agent
|
|
2760
|
+
* spent 4 failed exploratory queries rediscovering the exact same
|
|
2761
|
+
* branch-id list by hand (Invalid column name 'StateName'/'CityId'/
|
|
2762
|
+
* 'OrganizationLocationId', in that order, ~144s, before landing on ids
|
|
2763
|
+
* that were sitting in scopeSql from the very first resolve_entities
|
|
2764
|
+
* call). Other attrs (code, counts, etc.) are not dumped here — they are
|
|
2765
|
+
* descriptive, not actionable the way a precomputed predicate is, and
|
|
2766
|
+
* bloating every dispatch with all of them for no clear gain isn't worth
|
|
2767
|
+
* it; scopeSql is the one thing worth this guarantee today.
|
|
2768
|
+
*/
|
|
2769
|
+
private buildResolvedEntitiesBlock;
|
|
2770
|
+
/** True when the backend registered the entity-search collection. */
|
|
2771
|
+
private get entitySearchEnabled();
|
|
2772
|
+
/**
|
|
2773
|
+
* Compact catalog (type + gloss) for the system prompt. This is what lets the
|
|
2774
|
+
* LLM NAME a concept instead of guessing at our vocabulary — it can infer
|
|
2775
|
+
* that a question is about unpaid money, but not that we call that
|
|
2776
|
+
* `outstanding-balance`. Full `resolution` detail is fetched by the tool.
|
|
2777
|
+
*
|
|
2778
|
+
* Deliberately NOT cached in-process. The token cost is already handled by
|
|
2779
|
+
* prompt caching (the system prompt carries a cache_control breakpoint), and
|
|
2780
|
+
* re-reading a tiny PK-ordered table costs ~nothing. Fetching fresh does not
|
|
2781
|
+
* weaken the prompt cache either: unchanged data renders byte-identical text,
|
|
2782
|
+
* so the prefix still hits. A process cache would only buy a staleness window
|
|
2783
|
+
* in which a newly indexed entity is invisible to the agent.
|
|
2784
|
+
*/
|
|
2785
|
+
private loadEntityCatalog;
|
|
1095
2786
|
/**
|
|
1096
|
-
*
|
|
1097
|
-
*
|
|
2787
|
+
* Never throws: a resolver outage must degrade to "nothing resolved" and
|
|
2788
|
+
* leave the agent exactly as it was, not take the whole answer down.
|
|
1098
2789
|
*/
|
|
1099
|
-
|
|
2790
|
+
private handleResolveEntities;
|
|
2791
|
+
private preResolveSchema;
|
|
1100
2792
|
/**
|
|
1101
|
-
*
|
|
1102
|
-
* @param reportId - Report ID
|
|
1103
|
-
* @returns Full path to report data.json file
|
|
2793
|
+
* Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
|
|
1104
2794
|
*/
|
|
1105
|
-
private
|
|
2795
|
+
private handleDirectTool;
|
|
1106
2796
|
/**
|
|
1107
|
-
*
|
|
1108
|
-
*
|
|
1109
|
-
* @param report - Report data
|
|
1110
|
-
* @returns Created report with metadata
|
|
2797
|
+
* Build the main agent's system prompt with source summaries, direct tool descriptions,
|
|
2798
|
+
* and workflow component descriptions.
|
|
1111
2799
|
*/
|
|
1112
|
-
|
|
2800
|
+
private buildSystemPrompt;
|
|
1113
2801
|
/**
|
|
1114
|
-
*
|
|
1115
|
-
*
|
|
1116
|
-
* @returns Report data or null if not found
|
|
2802
|
+
* Build tool definitions for source tools — summary-only descriptions.
|
|
2803
|
+
* The full schema is inside the SourceAgent which runs independently.
|
|
1117
2804
|
*/
|
|
1118
|
-
|
|
2805
|
+
private buildSourceToolDefinitions;
|
|
1119
2806
|
/**
|
|
1120
|
-
*
|
|
1121
|
-
*
|
|
2807
|
+
* Build tool definitions for direct tools — expose their actual params.
|
|
2808
|
+
* These are called directly by the main agent LLM, no SourceAgent.
|
|
1122
2809
|
*/
|
|
1123
|
-
|
|
1124
|
-
reportId: string;
|
|
1125
|
-
report: DSLRendererProps;
|
|
1126
|
-
}>;
|
|
2810
|
+
private buildDirectToolDefinitions;
|
|
1127
2811
|
/**
|
|
1128
|
-
*
|
|
1129
|
-
*
|
|
1130
|
-
*
|
|
1131
|
-
*
|
|
2812
|
+
* Capture a workflow selection. We do NOT execute anything — the LLM has
|
|
2813
|
+
* already extracted the props it wants the workflow rendered with. We
|
|
2814
|
+
* record the selection (via the capture callback) and return a short
|
|
2815
|
+
* acknowledgement so the LLM ends its turn cleanly without writing
|
|
2816
|
+
* analysis text or calling more tools.
|
|
1132
2817
|
*/
|
|
1133
|
-
|
|
2818
|
+
private handleWorkflow;
|
|
1134
2819
|
/**
|
|
1135
|
-
*
|
|
1136
|
-
*
|
|
1137
|
-
*
|
|
2820
|
+
* Build LLM tool definitions for workflow components. The workflow's
|
|
2821
|
+
* propsSchema becomes the tool's input_schema so the LLM extracts props
|
|
2822
|
+
* directly from the prompt — same mechanic as direct tools.
|
|
1138
2823
|
*/
|
|
1139
|
-
|
|
2824
|
+
private buildWorkflowToolDefinitions;
|
|
1140
2825
|
/**
|
|
1141
|
-
*
|
|
1142
|
-
* @param reportId - Report ID
|
|
1143
|
-
* @returns True if report exists, false otherwise
|
|
2826
|
+
* Format a source agent's result as a clean string for the main agent LLM.
|
|
1144
2827
|
*/
|
|
1145
|
-
|
|
2828
|
+
private formatResultForMainAgent;
|
|
1146
2829
|
/**
|
|
1147
|
-
* Get
|
|
1148
|
-
* @returns Number of reports
|
|
2830
|
+
* Get source summaries (for external inspection/debugging).
|
|
1149
2831
|
*/
|
|
1150
|
-
|
|
2832
|
+
getSourceSummaries(): SourceSummary[];
|
|
2833
|
+
}
|
|
2834
|
+
|
|
2835
|
+
/**
|
|
2836
|
+
* Represents an action that can be performed on a UIBlock
|
|
2837
|
+
*/
|
|
2838
|
+
interface Action {
|
|
2839
|
+
id: string;
|
|
2840
|
+
name: string;
|
|
2841
|
+
type: string;
|
|
2842
|
+
[key: string]: any;
|
|
1151
2843
|
}
|
|
1152
2844
|
|
|
1153
2845
|
type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
|
|
@@ -1162,7 +2854,45 @@ interface LLMOptions {
|
|
|
1162
2854
|
temperature?: number;
|
|
1163
2855
|
topP?: number;
|
|
1164
2856
|
apiKey?: string;
|
|
2857
|
+
baseURL?: string;
|
|
1165
2858
|
partial?: (chunk: string) => void;
|
|
2859
|
+
/**
|
|
2860
|
+
* Per-request cancellation. When the caller aborts this signal (user hit
|
|
2861
|
+
* "Stop"), the underlying provider request is cancelled and the call throws
|
|
2862
|
+
* a RequestAbortedError. Threaded into the provider `messages.create` request
|
|
2863
|
+
* options and checked between tool-loop iterations. Currently honored on the
|
|
2864
|
+
* Anthropic path (the agent flow's default provider).
|
|
2865
|
+
*/
|
|
2866
|
+
signal?: AbortSignal;
|
|
2867
|
+
/**
|
|
2868
|
+
* Forces a tool call on the FIRST iteration of streamWithTools only
|
|
2869
|
+
* (subsequent iterations revert to auto). Used by fork mode to stop the
|
|
2870
|
+
* model from ending its turn with a bare "I'll adapt the script…" preamble
|
|
2871
|
+
* and zero tool calls. `{ type: 'any' }` lets the model pick which tool
|
|
2872
|
+
* (write_script in the common case, a source tool for schema discovery);
|
|
2873
|
+
* `{ type: 'tool', name }` pins a specific tool. Honored on both the
|
|
2874
|
+
* Anthropic path and the OpenAI/OpenRouter path (mapped to OpenAI's
|
|
2875
|
+
* tool_choice: 'required' / a named function).
|
|
2876
|
+
*/
|
|
2877
|
+
firstIterationToolChoice?: {
|
|
2878
|
+
type: 'any';
|
|
2879
|
+
} | {
|
|
2880
|
+
type: 'tool';
|
|
2881
|
+
name: string;
|
|
2882
|
+
};
|
|
2883
|
+
/**
|
|
2884
|
+
* Internal — set only by the OpenRouter wrappers when the target is a Claude
|
|
2885
|
+
* model. Tells the OpenAI-wire path to emit Anthropic `cache_control`
|
|
2886
|
+
* breakpoints (OpenRouter forwards them to Anthropic for prompt caching).
|
|
2887
|
+
* Never set for direct OpenAI/Groq calls, so their requests are unchanged.
|
|
2888
|
+
*/
|
|
2889
|
+
_openrouterClaudeCaching?: boolean;
|
|
2890
|
+
/**
|
|
2891
|
+
* Internal — OpenRouter provider-routing preferences (forwarded as the
|
|
2892
|
+
* `provider` body field). Set by the OpenRouter wrappers to steer routing to
|
|
2893
|
+
* a fast backend (e.g. {sort:'throughput'}). Never set for direct OpenAI/Groq.
|
|
2894
|
+
*/
|
|
2895
|
+
_openrouterProvider?: Record<string, unknown>;
|
|
1166
2896
|
}
|
|
1167
2897
|
interface Tool {
|
|
1168
2898
|
name: string;
|
|
@@ -1184,6 +2914,16 @@ declare class LLM {
|
|
|
1184
2914
|
* @returns Normalized system prompt for Anthropic API
|
|
1185
2915
|
*/
|
|
1186
2916
|
private static _normalizeSystemPrompt;
|
|
2917
|
+
/**
|
|
2918
|
+
* Strip unpaired UTF-16 surrogates from every text field of a message set.
|
|
2919
|
+
*
|
|
2920
|
+
* A lone surrogate (from mid-pair string slicing or corrupt source data)
|
|
2921
|
+
* serializes to a bare `\udXXX` escape that strict JSON parsers — including
|
|
2922
|
+
* the one on Anthropic's API — reject with "no low surrogate in string",
|
|
2923
|
+
* failing the whole request. Sanitizing here, at the single boundary every
|
|
2924
|
+
* provider call flows through, guarantees no request can carry one.
|
|
2925
|
+
*/
|
|
2926
|
+
private static _sanitizeMessages;
|
|
1187
2927
|
/**
|
|
1188
2928
|
* Log cache usage metrics from Anthropic API response
|
|
1189
2929
|
* Shows cache hits, costs, and savings
|
|
@@ -1200,16 +2940,76 @@ declare class LLM {
|
|
|
1200
2940
|
* "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
|
|
1201
2941
|
*/
|
|
1202
2942
|
private static _parseModel;
|
|
2943
|
+
/**
|
|
2944
|
+
* Map an Anthropic model id (e.g. "claude-sonnet-4-5-20250929") to the OpenRouter slug
|
|
2945
|
+
* (e.g. "claude-sonnet-4.5"). OpenRouter slugs drop the date suffix and use dotted versions.
|
|
2946
|
+
*/
|
|
2947
|
+
private static _toOpenRouterSlug;
|
|
2948
|
+
/**
|
|
2949
|
+
* Per-provider proxy base URL. Returns `${SUPERATOM_LLM_PROXY_URL}/<provider>`
|
|
2950
|
+
* when our Cloudflare LLM proxy is configured, else undefined (→ talk to the
|
|
2951
|
+
* provider directly, legacy behaviour). An explicit options.baseURL (e.g.
|
|
2952
|
+
* OpenRouter) always wins and is never overridden. See backend/docs/llm-proxy.md.
|
|
2953
|
+
*/
|
|
2954
|
+
private static _proxyBaseURL;
|
|
2955
|
+
private static _openrouterOptions;
|
|
2956
|
+
private static _isRetryableProviderError;
|
|
2957
|
+
private static _withOpenrouterRetry;
|
|
2958
|
+
private static _openrouterText;
|
|
2959
|
+
private static _openrouterStream;
|
|
2960
|
+
private static _openrouterStreamWithTools;
|
|
2961
|
+
/**
|
|
2962
|
+
* Build an Anthropic client. Routes through our Cloudflare LLM proxy when
|
|
2963
|
+
* SUPERATOM_LLM_PROXY_URL is set (each client ships a per-client proxy key as
|
|
2964
|
+
* ANTHROPIC_API_KEY and never holds the real key); otherwise talks to
|
|
2965
|
+
* api.anthropic.com directly. See backend/docs/llm-proxy.md.
|
|
2966
|
+
*/
|
|
2967
|
+
private static _anthropicClient;
|
|
2968
|
+
/** True when OpenRouter is configured as a fail-open fallback for Claude. */
|
|
2969
|
+
private static _openrouterAvailable;
|
|
2970
|
+
/** Remap an Anthropic model id to the OpenRouter model path for fail-open. */
|
|
2971
|
+
private static _anthropicFallbackModel;
|
|
1203
2972
|
private static _anthropicText;
|
|
1204
2973
|
private static _anthropicStream;
|
|
1205
2974
|
private static _anthropicStreamWithTools;
|
|
1206
2975
|
private static _groqText;
|
|
1207
2976
|
private static _groqStream;
|
|
2977
|
+
/**
|
|
2978
|
+
* Gemini request options carrying the proxy base URL, or undefined → talk to
|
|
2979
|
+
* generativelanguage.googleapis.com directly. The Google SDK takes baseUrl as a
|
|
2980
|
+
* per-model request option, not a constructor arg. See backend/docs/llm-proxy.md.
|
|
2981
|
+
*/
|
|
2982
|
+
private static _geminiRequestOptions;
|
|
1208
2983
|
private static _geminiText;
|
|
1209
2984
|
private static _geminiStream;
|
|
2985
|
+
/**
|
|
2986
|
+
* Recursively strip unsupported JSON Schema properties for Gemini
|
|
2987
|
+
* Gemini doesn't support: additionalProperties, $schema, etc.
|
|
2988
|
+
*/
|
|
2989
|
+
private static _cleanSchemaForGemini;
|
|
1210
2990
|
private static _geminiStreamWithTools;
|
|
2991
|
+
/** True for Anthropic/Claude model ids — gates OpenRouter prompt caching. */
|
|
2992
|
+
private static _isClaudeModel;
|
|
2993
|
+
/**
|
|
2994
|
+
* Build the OpenAI-wire system message. For OpenRouter + Claude
|
|
2995
|
+
* (cacheClaude=true) it emits content parts carrying Anthropic
|
|
2996
|
+
* `cache_control` breakpoints (preserving any the caller set, else marking
|
|
2997
|
+
* the last block), so OpenRouter forwards them to Anthropic for prompt
|
|
2998
|
+
* caching. Otherwise it returns a plain flattened string — unchanged for
|
|
2999
|
+
* direct OpenAI/Groq.
|
|
3000
|
+
*/
|
|
3001
|
+
private static _openaiSystemMessage;
|
|
3002
|
+
/**
|
|
3003
|
+
* Split an OpenAI-wire usage object. `prompt_tokens` INCLUDES cached tokens,
|
|
3004
|
+
* so we subtract them out (Anthropic-style: input excludes cache reads) and
|
|
3005
|
+
* report cached separately — this makes calculateCost price cache reads at
|
|
3006
|
+
* the discounted rate and reflects OpenRouter prompt-cache savings in logs.
|
|
3007
|
+
*/
|
|
3008
|
+
private static _openaiUsage;
|
|
1211
3009
|
private static _openaiText;
|
|
1212
3010
|
private static _openaiStream;
|
|
3011
|
+
/** Map the Anthropic-style firstIterationToolChoice to OpenAI's tool_choice. */
|
|
3012
|
+
private static _openaiToolChoice;
|
|
1213
3013
|
private static _openaiStreamWithTools;
|
|
1214
3014
|
/**
|
|
1215
3015
|
* Parse JSON string, handling markdown code blocks and surrounding text
|
|
@@ -1299,16 +3099,6 @@ declare class UILogCollector {
|
|
|
1299
3099
|
setUIBlockId(uiBlockId: string): void;
|
|
1300
3100
|
}
|
|
1301
3101
|
|
|
1302
|
-
/**
|
|
1303
|
-
* Represents an action that can be performed on a UIBlock
|
|
1304
|
-
*/
|
|
1305
|
-
interface Action {
|
|
1306
|
-
id: string;
|
|
1307
|
-
name: string;
|
|
1308
|
-
type: string;
|
|
1309
|
-
[key: string]: any;
|
|
1310
|
-
}
|
|
1311
|
-
|
|
1312
3102
|
/**
|
|
1313
3103
|
* UIBlock represents a single user and assistant message block in a thread
|
|
1314
3104
|
* Contains user question, component metadata, component data, text response, and available actions
|
|
@@ -1321,6 +3111,13 @@ declare class UIBlock {
|
|
|
1321
3111
|
private textResponse;
|
|
1322
3112
|
private actions;
|
|
1323
3113
|
private createdAt;
|
|
3114
|
+
/**
|
|
3115
|
+
* Which script recipe produced this answer, when a script did. Read on the
|
|
3116
|
+
* NEXT turn so the user can say "use mode instead" and have the matcher
|
|
3117
|
+
* resolve it to a concrete script (the `edit` tier is unreachable without it).
|
|
3118
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
3119
|
+
*/
|
|
3120
|
+
private scriptBinding;
|
|
1324
3121
|
/**
|
|
1325
3122
|
* Creates a new UIBlock instance
|
|
1326
3123
|
* @param userQuestion - The user's question or input
|
|
@@ -1412,9 +3209,22 @@ declare class UIBlock {
|
|
|
1412
3209
|
* Clear all actions
|
|
1413
3210
|
*/
|
|
1414
3211
|
clearActions(): void;
|
|
3212
|
+
/** The program-generated half of the answer — see setProgramAnswer. */
|
|
3213
|
+
programAnswer?: string | null;
|
|
1415
3214
|
/**
|
|
1416
|
-
*
|
|
3215
|
+
* Bind this block to the script recipe that produced its answer.
|
|
3216
|
+
*/
|
|
3217
|
+
setScriptBinding(binding: Record<string, any> | null): void;
|
|
3218
|
+
/**
|
|
3219
|
+
* The program-generated half of the answer, kept verbatim so a reload can
|
|
3220
|
+
* replace exactly that text without disturbing the streamed narration.
|
|
3221
|
+
*/
|
|
3222
|
+
setProgramAnswer(text: string | null): void;
|
|
3223
|
+
getProgramAnswer(): string | null;
|
|
3224
|
+
/**
|
|
3225
|
+
* The script recipe bound to this block, if any.
|
|
1417
3226
|
*/
|
|
3227
|
+
getScriptBinding(): Record<string, any> | null;
|
|
1418
3228
|
getCreatedAt(): Date;
|
|
1419
3229
|
/**
|
|
1420
3230
|
* Convert UIBlock to JSON-serializable object
|
|
@@ -1482,6 +3292,32 @@ declare class Thread {
|
|
|
1482
3292
|
* @param currentUIBlockId - ID of current UIBlock to exclude from context (optional)
|
|
1483
3293
|
* @returns Formatted conversation history string
|
|
1484
3294
|
*/
|
|
3295
|
+
/**
|
|
3296
|
+
* The script recipe bound to the most recent completed UIBlock — i.e. the
|
|
3297
|
+
* script behind the answer the user is currently looking at. Drives the
|
|
3298
|
+
* matcher's `edit` tier: without it, "use mode instead" has no target and
|
|
3299
|
+
* falls through to regeneration.
|
|
3300
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
3301
|
+
*/
|
|
3302
|
+
getActiveScriptBinding(currentUIBlockId?: string): Record<string, any> | null;
|
|
3303
|
+
/**
|
|
3304
|
+
* The recent script-backed answers in this thread, newest first — the
|
|
3305
|
+
* candidate set a user-directed edit can target.
|
|
3306
|
+
*
|
|
3307
|
+
* Returning several rather than only the newest is what lets an instruction
|
|
3308
|
+
* name its own target ("use the mode for the WSP one"). With a single
|
|
3309
|
+
* candidate every edit lands on the most recent script, which silently edits
|
|
3310
|
+
* the wrong recipe whenever the user meant an earlier one.
|
|
3311
|
+
*
|
|
3312
|
+
* Deduped by recipeId (newest occurrence wins) so a long editing session on
|
|
3313
|
+
* one script doesn't crowd out the others. Each entry carries the question
|
|
3314
|
+
* that produced it — without that the candidates are indistinguishable.
|
|
3315
|
+
*
|
|
3316
|
+
* In-memory only: dies with the process. The caller falls back to the
|
|
3317
|
+
* persisted bindings when this comes back empty.
|
|
3318
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
3319
|
+
*/
|
|
3320
|
+
getScriptBindings(limit?: number, currentUIBlockId?: string): Record<string, any>[];
|
|
1485
3321
|
getConversationContext(limit?: number, currentUIBlockId?: string): string;
|
|
1486
3322
|
/**
|
|
1487
3323
|
* Convert Thread to JSON-serializable object
|
|
@@ -1491,12 +3327,20 @@ declare class Thread {
|
|
|
1491
3327
|
|
|
1492
3328
|
/**
|
|
1493
3329
|
* ThreadManager manages all threads globally
|
|
1494
|
-
* Provides methods to create, retrieve, and delete threads
|
|
3330
|
+
* Provides methods to create, retrieve, and delete threads.
|
|
3331
|
+
* Includes automatic cleanup to prevent unbounded memory growth.
|
|
1495
3332
|
*/
|
|
1496
3333
|
declare class ThreadManager {
|
|
1497
3334
|
private static instance;
|
|
1498
3335
|
private threads;
|
|
3336
|
+
private cleanupInterval;
|
|
3337
|
+
private readonly threadTtlMs;
|
|
1499
3338
|
private constructor();
|
|
3339
|
+
/**
|
|
3340
|
+
* Periodically remove threads older than 7 days.
|
|
3341
|
+
* Runs every hour to avoid frequent iteration over the map.
|
|
3342
|
+
*/
|
|
3343
|
+
private startCleanup;
|
|
1500
3344
|
/**
|
|
1501
3345
|
* Get singleton instance of ThreadManager
|
|
1502
3346
|
*/
|
|
@@ -1895,6 +3739,92 @@ declare function rerankConversationResults<T extends {
|
|
|
1895
3739
|
bm25Score: number;
|
|
1896
3740
|
}>;
|
|
1897
3741
|
|
|
3742
|
+
/**
|
|
3743
|
+
* QueryExecutionService - Handles all query execution, validation, and retry logic
|
|
3744
|
+
* Extracted from BaseLLM for better separation of concerns
|
|
3745
|
+
*/
|
|
3746
|
+
|
|
3747
|
+
/**
|
|
3748
|
+
* Context for component when requesting query fix
|
|
3749
|
+
*/
|
|
3750
|
+
interface ComponentContext {
|
|
3751
|
+
name: string;
|
|
3752
|
+
type: string;
|
|
3753
|
+
title?: string;
|
|
3754
|
+
}
|
|
3755
|
+
/**
|
|
3756
|
+
* Result of query validation
|
|
3757
|
+
*/
|
|
3758
|
+
interface QueryValidationResult {
|
|
3759
|
+
component: Component | null;
|
|
3760
|
+
queryKey: string;
|
|
3761
|
+
result: any;
|
|
3762
|
+
validated: boolean;
|
|
3763
|
+
}
|
|
3764
|
+
/**
|
|
3765
|
+
* Result of batch query validation
|
|
3766
|
+
*/
|
|
3767
|
+
interface BatchValidationResult {
|
|
3768
|
+
components: Component[];
|
|
3769
|
+
queryResults: Map<string, any>;
|
|
3770
|
+
}
|
|
3771
|
+
/**
|
|
3772
|
+
* Configuration for QueryExecutionService
|
|
3773
|
+
*/
|
|
3774
|
+
interface QueryExecutionServiceConfig {
|
|
3775
|
+
defaultLimit: number;
|
|
3776
|
+
getModelForTask: (taskType: 'simple' | 'complex') => string;
|
|
3777
|
+
getApiKey: (apiKey?: string) => string | undefined;
|
|
3778
|
+
providerName: string;
|
|
3779
|
+
}
|
|
3780
|
+
/**
|
|
3781
|
+
* QueryExecutionService handles all query-related operations
|
|
3782
|
+
*/
|
|
3783
|
+
declare class QueryExecutionService {
|
|
3784
|
+
private config;
|
|
3785
|
+
constructor(config: QueryExecutionServiceConfig);
|
|
3786
|
+
/**
|
|
3787
|
+
* Get the cache key for a query
|
|
3788
|
+
* This ensures the cache key matches what the frontend will send
|
|
3789
|
+
*/
|
|
3790
|
+
getQueryCacheKey(query: any): string;
|
|
3791
|
+
/**
|
|
3792
|
+
* Execute a query against the database
|
|
3793
|
+
* @param query - The SQL query to execute (string or object with sql/values)
|
|
3794
|
+
* @param collections - Collections object containing database execute function
|
|
3795
|
+
* @returns Object with result data and cache key
|
|
3796
|
+
*/
|
|
3797
|
+
executeQuery(query: any, collections: any): Promise<{
|
|
3798
|
+
result: any;
|
|
3799
|
+
cacheKey: string;
|
|
3800
|
+
}>;
|
|
3801
|
+
/**
|
|
3802
|
+
* Request the LLM to fix a failed SQL query
|
|
3803
|
+
* @param failedQuery - The query that failed execution
|
|
3804
|
+
* @param errorMessage - The error message from the failed execution
|
|
3805
|
+
* @param componentContext - Context about the component
|
|
3806
|
+
* @param apiKey - Optional API key
|
|
3807
|
+
* @returns Fixed query string
|
|
3808
|
+
*/
|
|
3809
|
+
requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
|
|
3810
|
+
/**
|
|
3811
|
+
* Validate a single component's query with retry logic
|
|
3812
|
+
* @param component - The component to validate
|
|
3813
|
+
* @param collections - Collections object containing database execute function
|
|
3814
|
+
* @param apiKey - Optional API key for LLM calls
|
|
3815
|
+
* @returns Validation result with component, query key, and result
|
|
3816
|
+
*/
|
|
3817
|
+
validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
|
|
3818
|
+
/**
|
|
3819
|
+
* Validate multiple component queries in parallel
|
|
3820
|
+
* @param components - Array of components with potential queries
|
|
3821
|
+
* @param collections - Collections object containing database execute function
|
|
3822
|
+
* @param apiKey - Optional API key for LLM calls
|
|
3823
|
+
* @returns Object with validated components and query results map
|
|
3824
|
+
*/
|
|
3825
|
+
validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
|
|
3826
|
+
}
|
|
3827
|
+
|
|
1898
3828
|
/**
|
|
1899
3829
|
* Task types for model selection
|
|
1900
3830
|
* - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
|
|
@@ -1913,6 +3843,7 @@ interface BaseLLMConfig {
|
|
|
1913
3843
|
* - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
|
|
1914
3844
|
*/
|
|
1915
3845
|
modelStrategy?: ModelStrategy;
|
|
3846
|
+
conversationSimilarityThreshold?: number;
|
|
1916
3847
|
}
|
|
1917
3848
|
/**
|
|
1918
3849
|
* BaseLLM abstract class for AI-powered component generation and matching
|
|
@@ -1924,6 +3855,8 @@ declare abstract class BaseLLM {
|
|
|
1924
3855
|
protected defaultLimit: number;
|
|
1925
3856
|
protected apiKey?: string;
|
|
1926
3857
|
protected modelStrategy: ModelStrategy;
|
|
3858
|
+
protected conversationSimilarityThreshold: number;
|
|
3859
|
+
protected queryService: QueryExecutionService;
|
|
1927
3860
|
constructor(config?: BaseLLMConfig);
|
|
1928
3861
|
/**
|
|
1929
3862
|
* Get the appropriate model based on task type and model strategy
|
|
@@ -1941,6 +3874,16 @@ declare abstract class BaseLLM {
|
|
|
1941
3874
|
* @returns The current model strategy
|
|
1942
3875
|
*/
|
|
1943
3876
|
getModelStrategy(): ModelStrategy;
|
|
3877
|
+
/**
|
|
3878
|
+
* Set the conversation similarity threshold at runtime
|
|
3879
|
+
* @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
|
|
3880
|
+
*/
|
|
3881
|
+
setConversationSimilarityThreshold(threshold: number): void;
|
|
3882
|
+
/**
|
|
3883
|
+
* Get the current conversation similarity threshold
|
|
3884
|
+
* @returns The current threshold value
|
|
3885
|
+
*/
|
|
3886
|
+
getConversationSimilarityThreshold(): number;
|
|
1944
3887
|
/**
|
|
1945
3888
|
* Get the default model for this provider (used for complex tasks like text generation)
|
|
1946
3889
|
*/
|
|
@@ -1976,11 +3919,10 @@ declare abstract class BaseLLM {
|
|
|
1976
3919
|
* @param analysisContent - The text response containing component suggestions
|
|
1977
3920
|
* @param components - List of available components
|
|
1978
3921
|
* @param apiKey - Optional API key
|
|
1979
|
-
* @param logCollector - Optional log collector
|
|
1980
3922
|
* @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
|
|
1981
3923
|
* @returns Object containing matched components, layout title/description, and follow-up actions
|
|
1982
3924
|
*/
|
|
1983
|
-
matchComponentsFromAnalysis(analysisContent: string, components: Component[],
|
|
3925
|
+
matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
|
|
1984
3926
|
components: Component[];
|
|
1985
3927
|
layoutTitle: string;
|
|
1986
3928
|
layoutDescription: string;
|
|
@@ -1990,7 +3932,7 @@ declare abstract class BaseLLM {
|
|
|
1990
3932
|
* Classify user question into category and detect external tools needed
|
|
1991
3933
|
* Determines if question is for data analysis, requires external tools, or needs text response
|
|
1992
3934
|
*/
|
|
1993
|
-
classifyQuestionCategory(userPrompt: string, apiKey?: string,
|
|
3935
|
+
classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
|
|
1994
3936
|
category: 'data_analysis' | 'data_modification' | 'general';
|
|
1995
3937
|
externalTools: Array<{
|
|
1996
3938
|
type: string;
|
|
@@ -2005,10 +3947,12 @@ declare abstract class BaseLLM {
|
|
|
2005
3947
|
/**
|
|
2006
3948
|
* Adapt UI block parameters based on current user question
|
|
2007
3949
|
* Takes a matched UI block from semantic search and modifies its props to answer the new question
|
|
3950
|
+
* Also adapts the cached text response to match the new question
|
|
2008
3951
|
*/
|
|
2009
|
-
adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string,
|
|
3952
|
+
adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
|
|
2010
3953
|
success: boolean;
|
|
2011
3954
|
adaptedComponent?: Component;
|
|
3955
|
+
adaptedTextResponse?: string;
|
|
2012
3956
|
parametersChanged?: Array<{
|
|
2013
3957
|
field: string;
|
|
2014
3958
|
reason: string;
|
|
@@ -2020,13 +3964,8 @@ declare abstract class BaseLLM {
|
|
|
2020
3964
|
* This provides conversational text responses instead of component generation
|
|
2021
3965
|
* Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
|
|
2022
3966
|
* After generating text response, if components are provided, matches suggested components
|
|
2023
|
-
* @param streamCallback - Optional callback function to receive text chunks as they stream
|
|
2024
|
-
* @param collections - Collection registry for executing database queries via database.execute
|
|
2025
|
-
* @param components - Optional list of available components for matching suggestions
|
|
2026
|
-
* @param externalTools - Optional array of external tools (email, calendar, etc.) that can be called
|
|
2027
|
-
* @param category - Question category ('data_analysis' | 'data_modification' | 'general'). For data_modification, answer component streaming is skipped. For general, component generation is skipped entirely.
|
|
2028
3967
|
*/
|
|
2029
|
-
generateTextResponse(userPrompt: string, apiKey?: string,
|
|
3968
|
+
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>;
|
|
2030
3969
|
/**
|
|
2031
3970
|
* Main orchestration function with semantic search and multi-step classification
|
|
2032
3971
|
* NEW FLOW (Recommended):
|
|
@@ -2034,19 +3973,14 @@ declare abstract class BaseLLM {
|
|
|
2034
3973
|
* - If match found → Adapt UI block parameters and return
|
|
2035
3974
|
* 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
|
|
2036
3975
|
* 3. Route appropriately based on category and response mode
|
|
2037
|
-
*
|
|
2038
|
-
* @param responseMode - 'component' for component generation (default), 'text' for text responses
|
|
2039
|
-
* @param streamCallback - Optional callback function to receive text chunks as they stream (only for text mode)
|
|
2040
|
-
* @param collections - Collection registry for executing database queries (required for text mode)
|
|
2041
|
-
* @param externalTools - Optional array of external tools (email, calendar, etc.) that can be called (only for text mode)
|
|
2042
3976
|
*/
|
|
2043
|
-
handleUserRequest(userPrompt: string, components: Component[], apiKey?: string,
|
|
3977
|
+
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>;
|
|
2044
3978
|
/**
|
|
2045
3979
|
* Generate next questions that the user might ask based on the original prompt and generated component
|
|
2046
3980
|
* This helps provide intelligent suggestions for follow-up queries
|
|
2047
3981
|
* For general/conversational questions without components, pass textResponse instead
|
|
2048
3982
|
*/
|
|
2049
|
-
generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string,
|
|
3983
|
+
generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string, signal?: AbortSignal): Promise<string[]>;
|
|
2050
3984
|
}
|
|
2051
3985
|
|
|
2052
3986
|
interface AnthropicLLMConfig extends BaseLLMConfig {
|
|
@@ -2105,7 +4039,334 @@ declare class OpenAILLM extends BaseLLM {
|
|
|
2105
4039
|
}
|
|
2106
4040
|
declare const openaiLLM: OpenAILLM;
|
|
2107
4041
|
|
|
2108
|
-
|
|
4042
|
+
/**
|
|
4043
|
+
* Query Cache — Two mechanisms:
|
|
4044
|
+
*
|
|
4045
|
+
* 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
|
|
4046
|
+
* of recently validated queries. True LRU eviction: reads bubble entries to the back via
|
|
4047
|
+
* delete+re-set so the oldest *unused* entry is evicted, not the oldest *inserted*.
|
|
4048
|
+
*
|
|
4049
|
+
* 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
|
|
4050
|
+
* No server-side storage needed for SQL mappings. The token is decrypted on each request.
|
|
4051
|
+
* This eliminates the unbounded queryIdCache that previously grew forever and caused
|
|
4052
|
+
* memory bloat (hundreds of MBs after thousands of queries).
|
|
4053
|
+
*
|
|
4054
|
+
* Result data can still be cached temporarily via the data cache (mechanism 1).
|
|
4055
|
+
*/
|
|
4056
|
+
declare class QueryCache {
|
|
4057
|
+
private cache;
|
|
4058
|
+
private ttlMs;
|
|
4059
|
+
private maxCacheSize;
|
|
4060
|
+
private cleanupInterval;
|
|
4061
|
+
private readonly algorithm;
|
|
4062
|
+
private encryptionKey;
|
|
4063
|
+
constructor();
|
|
4064
|
+
/**
|
|
4065
|
+
* Set the cache TTL (Time To Live)
|
|
4066
|
+
* @param minutes - TTL in minutes (default: 10)
|
|
4067
|
+
*/
|
|
4068
|
+
setTTL(minutes: number): void;
|
|
4069
|
+
/**
|
|
4070
|
+
* Get the current TTL in minutes
|
|
4071
|
+
*/
|
|
4072
|
+
getTTL(): number;
|
|
4073
|
+
/**
|
|
4074
|
+
* Store query result in data cache.
|
|
4075
|
+
* If the key already exists, it's removed first so the re-insert places it
|
|
4076
|
+
* at the back of the iteration order (LRU). Eviction only fires when adding
|
|
4077
|
+
* a genuinely new key past the size limit.
|
|
4078
|
+
*/
|
|
4079
|
+
set(query: string, data: any): void;
|
|
4080
|
+
/**
|
|
4081
|
+
* Get cached result if exists and not expired.
|
|
4082
|
+
* On hit, re-inserts the entry so it moves to the back of the Map's
|
|
4083
|
+
* iteration order — turning FIFO eviction into true LRU.
|
|
4084
|
+
*/
|
|
4085
|
+
get(query: string): any | null;
|
|
4086
|
+
/**
|
|
4087
|
+
* Check if query exists in cache (not expired)
|
|
4088
|
+
*/
|
|
4089
|
+
has(query: string): boolean;
|
|
4090
|
+
/**
|
|
4091
|
+
* Remove a specific query from cache
|
|
4092
|
+
*/
|
|
4093
|
+
delete(query: string): void;
|
|
4094
|
+
/**
|
|
4095
|
+
* Clear all cached entries
|
|
4096
|
+
*/
|
|
4097
|
+
clear(): void;
|
|
4098
|
+
/**
|
|
4099
|
+
* Get cache statistics
|
|
4100
|
+
*/
|
|
4101
|
+
getStats(): {
|
|
4102
|
+
size: number;
|
|
4103
|
+
queryIdCount: number;
|
|
4104
|
+
oldestEntryAge: number | null;
|
|
4105
|
+
};
|
|
4106
|
+
/**
|
|
4107
|
+
* Start periodic cleanup of expired data cache entries.
|
|
4108
|
+
*/
|
|
4109
|
+
private startCleanup;
|
|
4110
|
+
/**
|
|
4111
|
+
* Encrypt a payload into a self-contained token.
|
|
4112
|
+
*/
|
|
4113
|
+
private encrypt;
|
|
4114
|
+
/**
|
|
4115
|
+
* Decrypt a token back to the original payload.
|
|
4116
|
+
*/
|
|
4117
|
+
private decrypt;
|
|
4118
|
+
/**
|
|
4119
|
+
* Store a query by generating an encrypted token as queryId.
|
|
4120
|
+
* The SQL is encrypted INTO the token — nothing stored in memory.
|
|
4121
|
+
* If data is provided, it's cached temporarily in the data cache.
|
|
4122
|
+
*/
|
|
4123
|
+
storeQuery(query: any, data?: any): string;
|
|
4124
|
+
/**
|
|
4125
|
+
* Get a stored query by decrypting its token.
|
|
4126
|
+
* Returns the SQL + any cached result data.
|
|
4127
|
+
*/
|
|
4128
|
+
getQuery(queryId: string): {
|
|
4129
|
+
query: any;
|
|
4130
|
+
data: any;
|
|
4131
|
+
} | null;
|
|
4132
|
+
/**
|
|
4133
|
+
* Update cached data for a queryId token
|
|
4134
|
+
*/
|
|
4135
|
+
setQueryData(queryId: string, data: any): void;
|
|
4136
|
+
/**
|
|
4137
|
+
* Stop cleanup interval (for graceful shutdown)
|
|
4138
|
+
*/
|
|
4139
|
+
destroy(): void;
|
|
4140
|
+
}
|
|
4141
|
+
declare const queryCache: QueryCache;
|
|
4142
|
+
|
|
4143
|
+
/**
|
|
4144
|
+
* Manages conversation history scoped per user + dashboard.
|
|
4145
|
+
* Each user-dashboard pair has its own isolated history that expires after a configurable TTL.
|
|
4146
|
+
*/
|
|
4147
|
+
declare class DashboardConversationHistory {
|
|
4148
|
+
private histories;
|
|
4149
|
+
private ttlMs;
|
|
4150
|
+
private maxEntries;
|
|
4151
|
+
private cleanupInterval;
|
|
4152
|
+
constructor();
|
|
4153
|
+
/**
|
|
4154
|
+
* Set the TTL for dashboard histories
|
|
4155
|
+
* @param minutes - TTL in minutes
|
|
4156
|
+
*/
|
|
4157
|
+
setTTL(minutes: number): void;
|
|
4158
|
+
/**
|
|
4159
|
+
* Set max entries per dashboard
|
|
4160
|
+
*/
|
|
4161
|
+
setMaxEntries(max: number): void;
|
|
4162
|
+
/**
|
|
4163
|
+
* Add a conversation entry for a user's dashboard
|
|
4164
|
+
*/
|
|
4165
|
+
addEntry(dashboardId: string, userPrompt: string, componentSummary: string, userId?: string): void;
|
|
4166
|
+
/**
|
|
4167
|
+
* Get formatted conversation history for a user's dashboard
|
|
4168
|
+
*/
|
|
4169
|
+
getHistory(dashboardId: string, userId?: string): string;
|
|
4170
|
+
/**
|
|
4171
|
+
* Clear history for a specific user's dashboard
|
|
4172
|
+
*/
|
|
4173
|
+
clearDashboard(dashboardId: string, userId?: string): void;
|
|
4174
|
+
/**
|
|
4175
|
+
* Clear all dashboard histories
|
|
4176
|
+
*/
|
|
4177
|
+
clearAll(): void;
|
|
4178
|
+
/**
|
|
4179
|
+
* Start periodic cleanup of expired histories
|
|
4180
|
+
*/
|
|
4181
|
+
private startCleanup;
|
|
4182
|
+
/**
|
|
4183
|
+
* Stop cleanup interval (for graceful shutdown)
|
|
4184
|
+
*/
|
|
4185
|
+
destroy(): void;
|
|
4186
|
+
}
|
|
4187
|
+
declare const dashboardConversationHistory: DashboardConversationHistory;
|
|
4188
|
+
|
|
4189
|
+
/**
|
|
4190
|
+
* Whole-dashboard generation via Pi, a terminal coding agent — as opposed to
|
|
4191
|
+
* DASH_COMP_REQ's single-widget-at-a-time flow. Runs Pi in-process via its
|
|
4192
|
+
* SDK (createAgentSession), not as a subprocess: no shell, no argument
|
|
4193
|
+
* quoting, no stdin/stdout piping, none of the Windows-specific subprocess
|
|
4194
|
+
* issues that came with spawning the `pi` CLI directly.
|
|
4195
|
+
*
|
|
4196
|
+
* Called from sdk-nodejs/src/dashboardAgent/index.ts (DASHBOARD_AGENT_REQ),
|
|
4197
|
+
* which owns the generic streaming/abort machinery (mirrors USER_PROMPT_REQ)
|
|
4198
|
+
* and passes `signal`/`onProgress` alongside the normal params — this stays
|
|
4199
|
+
* within CollectionHandler's loose (params) => Promise<result> typing, no
|
|
4200
|
+
* change needed to that shared type.
|
|
4201
|
+
*
|
|
4202
|
+
* This mechanism is generic and reusable across any deployment. What's
|
|
4203
|
+
* genuinely project-specific — where AGENTS.md lives, which model to use —
|
|
4204
|
+
* is supplied via `DashboardAgentCollectionConfig`, with defaults sensible
|
|
4205
|
+
* enough that most callers don't need to override them (see below). The
|
|
4206
|
+
* data-source tool list and the dashboard's current state both come from
|
|
4207
|
+
* things sdk-nodejs already exposes generically: `sdk.getTools()` (whatever
|
|
4208
|
+
* this deployment registered via `sdk.setTools()`) and `sdk.callCollection
|
|
4209
|
+
* ('dashboards', 'query', ...)` (whatever this deployment already registered
|
|
4210
|
+
* under that name/shape) — no per-deployment callback needed for either.
|
|
4211
|
+
* Same convention on the way out: after a successful run, the prompt and the
|
|
4212
|
+
* full response text are handed to `sdk.callCollection('dashboard-agent-
|
|
4213
|
+
* conversations', 'create', ...)` if this deployment has registered one —
|
|
4214
|
+
* skipped silently otherwise, since conversation history is optional.
|
|
4215
|
+
*
|
|
4216
|
+
* Pi verifies every query against the live database itself (via whatever
|
|
4217
|
+
* local tool-execution bridge the deployment exposes, e.g. an HTTP bridge
|
|
4218
|
+
* on localhost), but does NOT persist the result itself — it writes the
|
|
4219
|
+
* finished DSL to an absolute path inside `runtimeDir`, told to it explicitly
|
|
4220
|
+
* in the prompt, and stops there. This handler reads that file after the run
|
|
4221
|
+
* finishes and returns its content as `dashboard` in the result. The caller
|
|
4222
|
+
* (frontend) is the one that actually saves it, via whatever authenticated
|
|
4223
|
+
* create/update path any other dashboard edit goes through — Pi has no user
|
|
4224
|
+
* session/auth context of its own, so persistence shouldn't happen from
|
|
4225
|
+
* inside it.
|
|
4226
|
+
*
|
|
4227
|
+
* Session persistence: the FIRST call for a dashboardId pays the full cost
|
|
4228
|
+
* (explore KB, discover schema, plan, verify, build). Every call after that
|
|
4229
|
+
* resumes the same session file (SessionManager.open) so Pi has everything
|
|
4230
|
+
* it already learned — it only needs to reason about the new, smaller ask,
|
|
4231
|
+
* not rediscover the whole dashboard from scratch. The session's file path
|
|
4232
|
+
* (AgentSession.sessionFile) is captured right after creation and persisted
|
|
4233
|
+
* in a small local file, keyed by dashboardId, inside `runtimeDir`.
|
|
4234
|
+
*/
|
|
4235
|
+
interface DashboardAgentCollectionConfig {
|
|
4236
|
+
/**
|
|
4237
|
+
* Working directory Pi runs from — must contain AGENTS.md. This is a
|
|
4238
|
+
* version-controlled prompt file, so `cwd` is expected to live somewhere
|
|
4239
|
+
* like a `.prompts/` folder alongside the deployment's other prompts.
|
|
4240
|
+
* Default: `<process.cwd()>/.prompts/dashboard-agent` — the same
|
|
4241
|
+
* process.cwd()-based convention PromptLoader already uses for the main
|
|
4242
|
+
* agent's prompts, which needs no explicit override in the common case
|
|
4243
|
+
* (the backend process's own cwd already is its project root).
|
|
4244
|
+
*/
|
|
4245
|
+
cwd?: string;
|
|
4246
|
+
/**
|
|
4247
|
+
* Where drafts/, the session-id map, and dashboard.log get written —
|
|
4248
|
+
* separate from `cwd` deliberately, so this deployment's runtime state
|
|
4249
|
+
* (regenerated per session, safe to gitignore) doesn't sit inside the
|
|
4250
|
+
* same folder as the version-controlled AGENTS.md prompt.
|
|
4251
|
+
* Default: `<process.cwd()>/.pi-dashboard-agent-runtime`.
|
|
4252
|
+
*/
|
|
4253
|
+
runtimeDir?: string;
|
|
4254
|
+
/** Model provider (default: process.env.PI_AGENT_PROVIDER || 'openrouter'). */
|
|
4255
|
+
provider?: string;
|
|
4256
|
+
/** Model id (default: process.env.PI_AGENT_MODEL || 'anthropic/claude-sonnet-4.5'). */
|
|
4257
|
+
model?: string;
|
|
4258
|
+
/**
|
|
4259
|
+
* true (default): every request starts a brand-new pi session, with the 2
|
|
4260
|
+
* most recent prior responses (if any) injected into the prompt as
|
|
4261
|
+
* context — bounded cost per request, but pi re-explores schema/KB facts
|
|
4262
|
+
* it already verified in an earlier turn on this same dashboard.
|
|
4263
|
+
* false: resumes the same session file across requests on a given
|
|
4264
|
+
* dashboard — pi keeps everything it already learned, but context (and
|
|
4265
|
+
* cost) grows unbounded across turns (one observed turn: 2M+ cache-read
|
|
4266
|
+
* tokens after a handful of edits on the same dashboard).
|
|
4267
|
+
* Default: process.env.PI_AGENT_FRESH_SESSION !== 'false'.
|
|
4268
|
+
*/
|
|
4269
|
+
freshSession?: boolean;
|
|
4270
|
+
}
|
|
4271
|
+
declare function registerDashboardAgentCollection(sdk: SuperatomSDK, config?: DashboardAgentCollectionConfig): void;
|
|
4272
|
+
|
|
4273
|
+
/**
|
|
4274
|
+
* ScriptMatcher — LLM-Based Script Matching + Parameter Extraction
|
|
4275
|
+
*
|
|
4276
|
+
* Uses ONE LLM call to:
|
|
4277
|
+
* 1. Pick the best matching script from the library (or "none")
|
|
4278
|
+
* 2. Extract parameter values from the user question
|
|
4279
|
+
*
|
|
4280
|
+
* Why LLM over embeddings:
|
|
4281
|
+
* - Embeddings capture topic similarity ("overstock" ≈ "inventory" ≈ "revenue")
|
|
4282
|
+
* but can't distinguish structurally different questions about the same domain
|
|
4283
|
+
* - LLM understands that "overstock by warehouse" needs a different script than
|
|
4284
|
+
* "revenue by warehouse" even though they're semantically close
|
|
4285
|
+
* - One call does both matching AND parameter extraction
|
|
4286
|
+
*
|
|
4287
|
+
* When script library grows past ~50, add an embedding pre-filter
|
|
4288
|
+
* (ChromaDB narrows to top 10 → LLM picks from those 10).
|
|
4289
|
+
*/
|
|
4290
|
+
|
|
4291
|
+
declare class ScriptMatcher {
|
|
4292
|
+
private store;
|
|
4293
|
+
constructor(store: ScriptStore);
|
|
4294
|
+
/**
|
|
4295
|
+
* Find the best matching script for a user question.
|
|
4296
|
+
* Uses ONE LLM call that picks the script AND extracts parameters.
|
|
4297
|
+
* Returns null if no script matches.
|
|
4298
|
+
*/
|
|
4299
|
+
match(userPrompt: string, apiKey?: string, model?: string, signal?: AbortSignal,
|
|
4300
|
+
/**
|
|
4301
|
+
* Recent script-backed answers in this thread, newest first. Presence of at
|
|
4302
|
+
* least one is what makes the `edit` tier reachable at all (see the guards
|
|
4303
|
+
* below), and handing over SEVERAL is what lets an instruction name its own
|
|
4304
|
+
* target instead of always hitting the most recent script.
|
|
4305
|
+
*/
|
|
4306
|
+
activeBindings?: ScriptBinding[],
|
|
4307
|
+
/**
|
|
4308
|
+
* Recent conversation turns, most recent last. The gate needs this to tell
|
|
4309
|
+
* "this reply is an edit instruction for the active script" apart from
|
|
4310
|
+
* "this reply is answering a clarifying question about a DIFFERENT,
|
|
4311
|
+
* unresolved topic that never became a script" — a bare parameter-shaped
|
|
4312
|
+
* reply ("April 2025 to March 2026") is textually indistinguishable
|
|
4313
|
+
* between those two cases without seeing what the assistant just asked.
|
|
4314
|
+
* Once this tier is decided, nothing downstream re-checks it — the edit
|
|
4315
|
+
* path hands MainAgent a system prompt that explicitly instructs it to
|
|
4316
|
+
* trust the premise and not treat the turn as a new question — so this
|
|
4317
|
+
* gate is the only place that can catch a mismatch.
|
|
4318
|
+
*/
|
|
4319
|
+
conversationHistory?: string): Promise<ScriptMatch | null>;
|
|
4320
|
+
/**
|
|
4321
|
+
* Build the script catalog string for the LLM prompt.
|
|
4322
|
+
* Each script gets: index, ID, name, description, and parameter definitions.
|
|
4323
|
+
*/
|
|
4324
|
+
private buildScriptCatalog;
|
|
4325
|
+
/**
|
|
4326
|
+
* The recent script-backed answers in this thread — the bounded set an edit
|
|
4327
|
+
* may target. Rendered as its own prompt section (never merged into the
|
|
4328
|
+
* ranked catalog) so the `edit` rules have an unambiguous referent set, and
|
|
4329
|
+
* numbered newest-first so the prompt's "prefer the most recent when the
|
|
4330
|
+
* instruction is ambiguous" tie-break has something to point at.
|
|
4331
|
+
*
|
|
4332
|
+
* Each entry carries the QUESTION that produced it plus the columns it
|
|
4333
|
+
* returned — that is what lets the matcher resolve "use the mode for the WSP
|
|
4334
|
+
* one" instead of blindly taking the newest.
|
|
4335
|
+
*/
|
|
4336
|
+
private buildActiveScriptBlock;
|
|
4337
|
+
}
|
|
4338
|
+
|
|
4339
|
+
/**
|
|
4340
|
+
* ScriptRunner — Execute scripts in an isolated tsx subprocess.
|
|
4341
|
+
*
|
|
4342
|
+
* The subprocess approach replaces the earlier `new Function()` eval and gives us:
|
|
4343
|
+
* - Real sandbox (separate process, SIGKILL on timeout).
|
|
4344
|
+
* - Real TypeScript (tsx transpiles on the fly).
|
|
4345
|
+
* - npm imports available to scripts (clustering, stats, geo, etc.).
|
|
4346
|
+
*
|
|
4347
|
+
* Protocol: NDJSON over the child's stdin/stdout. See script-ipc.ts + backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md.
|
|
4348
|
+
*/
|
|
4349
|
+
|
|
4350
|
+
interface RunScriptOptions {
|
|
4351
|
+
/** Data sources the script is allowed to query via ctx.query */
|
|
4352
|
+
externalTools: ExternalTool[];
|
|
4353
|
+
/** Optional — for propagating per-query UI progress to the user */
|
|
4354
|
+
streamBuffer?: StreamBuffer;
|
|
4355
|
+
/** Override the wall-clock timeout (default `SCRIPT_TIMEOUT_MS`, 60s). */
|
|
4356
|
+
timeoutMs?: number;
|
|
4357
|
+
/**
|
|
4358
|
+
* Per-turn cancellation signal. When the user hits "Stop" mid-run, the child
|
|
4359
|
+
* process group is SIGKILLed and the run resolves as an aborted failure (the
|
|
4360
|
+
* caller is already unwinding, so the result is discarded).
|
|
4361
|
+
*/
|
|
4362
|
+
signal?: AbortSignal;
|
|
4363
|
+
}
|
|
4364
|
+
/**
|
|
4365
|
+
* Execute a recipe by spawning a tsx child on the script's .ts file.
|
|
4366
|
+
* `scriptPath` is the absolute path to the saved `.ts` body.
|
|
4367
|
+
*/
|
|
4368
|
+
declare function runScript(recipe: ScriptRecipe, scriptPath: string, params: Record<string, any>, options: RunScriptOptions): Promise<ScriptResult>;
|
|
4369
|
+
|
|
2109
4370
|
type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
|
|
2110
4371
|
declare class SuperatomSDK {
|
|
2111
4372
|
private ws;
|
|
@@ -2122,6 +4383,7 @@ declare class SuperatomSDK {
|
|
|
2122
4383
|
private collections;
|
|
2123
4384
|
private components;
|
|
2124
4385
|
private tools;
|
|
4386
|
+
private workflows;
|
|
2125
4387
|
private anthropicApiKey;
|
|
2126
4388
|
private groqApiKey;
|
|
2127
4389
|
private geminiApiKey;
|
|
@@ -2129,6 +4391,10 @@ declare class SuperatomSDK {
|
|
|
2129
4391
|
private llmProviders;
|
|
2130
4392
|
private databaseType;
|
|
2131
4393
|
private modelStrategy;
|
|
4394
|
+
private mainAgentModel;
|
|
4395
|
+
private sourceAgentModel;
|
|
4396
|
+
private dashCompModels?;
|
|
4397
|
+
private conversationSimilarityThreshold;
|
|
2132
4398
|
private userManager;
|
|
2133
4399
|
private dashboardManager;
|
|
2134
4400
|
private reportManager;
|
|
@@ -2136,6 +4402,8 @@ declare class SuperatomSDK {
|
|
|
2136
4402
|
private lastPong;
|
|
2137
4403
|
private readonly PING_INTERVAL_MS;
|
|
2138
4404
|
private readonly PONG_TIMEOUT_MS;
|
|
4405
|
+
private pendingOutbox;
|
|
4406
|
+
private readonly MAX_OUTBOX_SIZE;
|
|
2139
4407
|
constructor(config: SuperatomSDKConfig);
|
|
2140
4408
|
/**
|
|
2141
4409
|
* Initialize PromptLoader and load prompts into memory
|
|
@@ -2175,9 +4443,25 @@ declare class SuperatomSDK {
|
|
|
2175
4443
|
*/
|
|
2176
4444
|
private handleMessage;
|
|
2177
4445
|
/**
|
|
2178
|
-
* Send a message to the Superatom service
|
|
4446
|
+
* Send a message to the Superatom service.
|
|
4447
|
+
* Returns true if the message was sent, false if the WebSocket is not connected.
|
|
4448
|
+
* Does NOT throw on closed connections — callers can check the return value if needed.
|
|
4449
|
+
*/
|
|
4450
|
+
send(message: Message): boolean;
|
|
4451
|
+
/**
|
|
4452
|
+
* Queue a message that couldn't be delivered because the socket was down,
|
|
4453
|
+
* to be resent once it reconnects. Drops the oldest entry once the bound is
|
|
4454
|
+
* hit — an outage long enough to fill this queue means the oldest queued
|
|
4455
|
+
* responses are for requests the caller has likely already given up on.
|
|
4456
|
+
*/
|
|
4457
|
+
private queuePendingMessage;
|
|
4458
|
+
/**
|
|
4459
|
+
* Resend everything queued while the socket was down, now that it's back
|
|
4460
|
+
* up. Uses this.ws.send() directly (not send()) so a message that fails
|
|
4461
|
+
* again goes back through queuePendingMessage() rather than being silently
|
|
4462
|
+
* dropped a second time.
|
|
2179
4463
|
*/
|
|
2180
|
-
|
|
4464
|
+
private flushPendingOutbox;
|
|
2181
4465
|
/**
|
|
2182
4466
|
* Register a message handler to receive all messages
|
|
2183
4467
|
*/
|
|
@@ -2217,6 +4501,14 @@ declare class SuperatomSDK {
|
|
|
2217
4501
|
*/
|
|
2218
4502
|
private handlePong;
|
|
2219
4503
|
private storeComponents;
|
|
4504
|
+
/**
|
|
4505
|
+
* The live, frontend-registered component catalog (name, type, description,
|
|
4506
|
+
* and full prop schema per component) — the same authoritative source
|
|
4507
|
+
* DASH_COMP_REQ's LLM prompt is built from. Exposed so other integrations
|
|
4508
|
+
* (e.g. the dashboard-agent script bridge) can read real component
|
|
4509
|
+
* contracts instead of maintaining a separate, driftable hand-written copy.
|
|
4510
|
+
*/
|
|
4511
|
+
getComponents(): Component[];
|
|
2220
4512
|
/**
|
|
2221
4513
|
* Set tools for the SDK instance
|
|
2222
4514
|
*/
|
|
@@ -2225,6 +4517,29 @@ declare class SuperatomSDK {
|
|
|
2225
4517
|
* Get the stored tools
|
|
2226
4518
|
*/
|
|
2227
4519
|
getTools(): Tool$1[];
|
|
4520
|
+
/**
|
|
4521
|
+
* Call a registered collection operation in-process — no WebSocket
|
|
4522
|
+
* round-trip, since the caller is already running inside this same SDK
|
|
4523
|
+
* instance. Lets SDK-internal features (e.g. the dashboard agent) reuse
|
|
4524
|
+
* whatever collection a deployment has already registered (e.g.
|
|
4525
|
+
* 'dashboards'.'query') by name/convention, instead of requiring a
|
|
4526
|
+
* separate callback purely to re-expose data a collection already serves.
|
|
4527
|
+
* Throws if the collection or operation isn't registered.
|
|
4528
|
+
*/
|
|
4529
|
+
callCollection<TResult = any>(collectionName: string, operation: string, params?: any): Promise<TResult>;
|
|
4530
|
+
/**
|
|
4531
|
+
* Register workflow components for the SDK instance.
|
|
4532
|
+
*
|
|
4533
|
+
* Workflows are pre-built multi-step UI flows the main agent can pick when
|
|
4534
|
+
* the user's prompt matches a workflow's `whenToUse` trigger. Picking a
|
|
4535
|
+
* workflow short-circuits analysis text + dashboard component generation —
|
|
4536
|
+
* the workflow component is returned directly, with the LLM-extracted props.
|
|
4537
|
+
*/
|
|
4538
|
+
setWorkflows(workflows: WorkflowDescriptor[]): void;
|
|
4539
|
+
/**
|
|
4540
|
+
* Get the registered workflow components.
|
|
4541
|
+
*/
|
|
4542
|
+
getWorkflows(): WorkflowDescriptor[];
|
|
2228
4543
|
/**
|
|
2229
4544
|
* Apply model strategy to all LLM provider singletons
|
|
2230
4545
|
* @param strategy - 'best', 'fast', or 'balanced'
|
|
@@ -2239,6 +4554,20 @@ declare class SuperatomSDK {
|
|
|
2239
4554
|
* Get current model strategy
|
|
2240
4555
|
*/
|
|
2241
4556
|
getModelStrategy(): ModelStrategy;
|
|
4557
|
+
/**
|
|
4558
|
+
* Apply conversation similarity threshold to all LLM provider singletons
|
|
4559
|
+
* @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
|
|
4560
|
+
*/
|
|
4561
|
+
private applyConversationSimilarityThreshold;
|
|
4562
|
+
/**
|
|
4563
|
+
* Set conversation similarity threshold at runtime
|
|
4564
|
+
* @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
|
|
4565
|
+
*/
|
|
4566
|
+
setConversationSimilarityThreshold(threshold: number): void;
|
|
4567
|
+
/**
|
|
4568
|
+
* Get current conversation similarity threshold
|
|
4569
|
+
*/
|
|
4570
|
+
getConversationSimilarityThreshold(): number;
|
|
2242
4571
|
}
|
|
2243
4572
|
|
|
2244
|
-
export { type Action, BM25L, type BM25LOptions, type BaseLLMConfig, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, type Message, type ModelStrategy, type
|
|
4573
|
+
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 };
|