@superatomai/sdk-node 0.0.51-dsp → 0.0.51-mds
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 +309 -1991
- package/dist/index.d.ts +309 -1991
- package/dist/index.js +1719 -10664
- package/dist/index.mjs +1780 -10726
- package/package.json +5 -8
- package/dist/userResponse/scripts/script-bootstrap.d.mts +0 -2
- package/dist/userResponse/scripts/script-bootstrap.d.ts +0 -2
- package/dist/userResponse/scripts/script-bootstrap.js +0 -539
- package/dist/userResponse/scripts/script-bootstrap.mjs +0 -537
package/dist/index.d.ts
CHANGED
|
@@ -1,1050 +1,15 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import Anthropic from '@anthropic-ai/sdk';
|
|
3
3
|
|
|
4
|
-
/**
|
|
5
|
-
* Script Flow Types
|
|
6
|
-
*
|
|
7
|
-
* Defines interfaces for the script-based query architecture:
|
|
8
|
-
* - ScriptRecipe: metadata for matching, validation, and quality tracking
|
|
9
|
-
* - ScriptResult: output from executing a script
|
|
10
|
-
* - ScriptMatch: result from the LLM-based script matcher
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Recipe metadata stored alongside each script.
|
|
15
|
-
* Used for matching, validation, and quality tracking.
|
|
16
|
-
*/
|
|
17
|
-
interface ScriptRecipe {
|
|
18
|
-
/** Unique script identifier */
|
|
19
|
-
id: string;
|
|
20
|
-
/** Version number (incremented on regeneration) */
|
|
21
|
-
version: number;
|
|
22
|
-
/** Human-readable name (e.g., "Revenue by Dimension") */
|
|
23
|
-
name: string;
|
|
24
|
-
/** Natural language description of what this script does */
|
|
25
|
-
intentDescription: string;
|
|
26
|
-
/** Keyword tags for quick filtering */
|
|
27
|
-
tags: string[];
|
|
28
|
-
/** Source tool IDs this script queries (e.g., ["mssql-abc123_query"]) */
|
|
29
|
-
sourceIds: string[];
|
|
30
|
-
/** Table names used (for future schema drift detection) */
|
|
31
|
-
tables: string[];
|
|
32
|
-
/** Parameter definitions — what can vary */
|
|
33
|
-
parameters: ScriptParameter[];
|
|
34
|
-
/** The script function body as a string. Loaded from disk (scripts-store/<fileBase>.ts). */
|
|
35
|
-
scriptBody: string;
|
|
36
|
-
/**
|
|
37
|
-
* On-disk filename stem for the body: scripts-store/<fileBase>.ts.
|
|
38
|
-
* Editable in the IDE. Decided at authoring time (slug of `name`, with a
|
|
39
|
-
* short id suffix on collision) and stable across promotion.
|
|
40
|
-
*/
|
|
41
|
-
fileBase?: string;
|
|
42
|
-
/** sha256 of the on-disk body — lets the runtime detect manual edits. */
|
|
43
|
-
bodyHash?: string;
|
|
44
|
-
/** Project scope (single-VM deployments may leave this undefined). */
|
|
45
|
-
projectId?: string;
|
|
46
|
-
/** Times this script was used successfully */
|
|
47
|
-
successCount: number;
|
|
48
|
-
/** Times this script failed */
|
|
49
|
-
failureCount: number;
|
|
50
|
-
/** ISO timestamp of last usage */
|
|
51
|
-
lastUsed: string;
|
|
52
|
-
/** Original user question that created this script */
|
|
53
|
-
createdFrom: string;
|
|
54
|
-
/** ISO timestamp */
|
|
55
|
-
createdAt: string;
|
|
56
|
-
/** ISO timestamp */
|
|
57
|
-
updatedAt: string;
|
|
58
|
-
/**
|
|
59
|
-
* `recipe.id` of the parent this script was forked from.
|
|
60
|
-
* Undefined for root scripts (those written from scratch by MainAgent).
|
|
61
|
-
* See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md.
|
|
62
|
-
*/
|
|
63
|
-
parentId?: string;
|
|
64
|
-
/** 0 for root scripts; `parent.forkDepth + 1` for forks. Capped at 3. */
|
|
65
|
-
forkDepth?: number;
|
|
66
|
-
/**
|
|
67
|
-
* Brief description of what this fork changed vs its parent
|
|
68
|
-
* (sourced from the matcher's `modificationHint`).
|
|
69
|
-
*/
|
|
70
|
-
forkReason?: string;
|
|
71
|
-
/**
|
|
72
|
-
* Validated component specs captured at authoring time. On a tier-high
|
|
73
|
-
* replay these are rebound to fresh queryIds deterministically — no
|
|
74
|
-
* component-generation LLM call, and the rendered columns can't drift from
|
|
75
|
-
* what was validated when the script was authored. Absent on recipes
|
|
76
|
-
* authored before this landed; those fall back to LLM component generation.
|
|
77
|
-
* See backend/docs/SCRIPT-COMPONENT-CONSISTENCY.md.
|
|
78
|
-
*/
|
|
79
|
-
components?: ScriptComponentSpec[];
|
|
80
|
-
/**
|
|
81
|
-
* What the user explicitly asked the output to LOOK like, set by a display
|
|
82
|
-
* edit ("show that as a bar chart", "make the bars horizontal").
|
|
83
|
-
*
|
|
84
|
-
* Deliberately SEPARATE from `components`. Those are validated bindings that
|
|
85
|
-
* must be cleared on a data edit — after "break it down by brand" the axis
|
|
86
|
-
* keys are wrong, and after "use the mode" the stored title still says
|
|
87
|
-
* "Average…". A rendering CHOICE, by contrast, is still valid afterwards.
|
|
88
|
-
* Keeping them in one field meant every data edit silently discarded the
|
|
89
|
-
* user's chart type.
|
|
90
|
-
*
|
|
91
|
-
* Fed to the component generator as a hint whenever specs are (re)generated,
|
|
92
|
-
* so the chosen rendering comes back even after the SQL changes.
|
|
93
|
-
*/
|
|
94
|
-
displayPreference?: ScriptDisplayPreference;
|
|
95
|
-
/**
|
|
96
|
-
* Lifecycle stage of this recipe on disk.
|
|
97
|
-
* - 'draft': written by MainAgent's write_script during a turn; filtered out
|
|
98
|
-
* of FTS results (status='verified' only) so the matcher never picks it.
|
|
99
|
-
* Filename is suffixed with `turnId` to keep concurrent turns
|
|
100
|
-
* from clobbering each other's drafts.
|
|
101
|
-
* - 'verified': promoted after `execute_script` succeeded; the matcher sees it.
|
|
102
|
-
* Filename drops the turn suffix unless a verified file with
|
|
103
|
-
* the same slug already exists (collision case keeps the suffix).
|
|
104
|
-
*
|
|
105
|
-
* Recipes loaded from disk without this field default to 'verified' so
|
|
106
|
-
* existing scripts keep working unchanged.
|
|
107
|
-
*/
|
|
108
|
-
status?: 'draft' | 'verified';
|
|
109
|
-
/**
|
|
110
|
-
* Per-turn unique suffix used for draft filenames (e.g. `1714745623-x9k2`).
|
|
111
|
-
* Set when the draft is saved; carried until the recipe is promoted.
|
|
112
|
-
*/
|
|
113
|
-
turnId?: string;
|
|
114
|
-
/**
|
|
115
|
-
* Last execution error captured by `recordDraftError` while the recipe was
|
|
116
|
-
* still a draft. Lets users open the draft .json file and see why it failed
|
|
117
|
-
* without grepping logs. Cleared on promotion to 'verified'.
|
|
118
|
-
*/
|
|
119
|
-
lastError?: {
|
|
120
|
-
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
121
|
-
message: string;
|
|
122
|
-
at: string;
|
|
123
|
-
attempt: number;
|
|
124
|
-
};
|
|
125
|
-
/** userId who committed the most recent edit (audit trail — recipes are project-scoped). */
|
|
126
|
-
editedBy?: string;
|
|
127
|
-
/** The instruction that produced the current version. */
|
|
128
|
-
editedFrom?: string;
|
|
129
|
-
/**
|
|
130
|
-
* Prior versions, newest last. The body itself is archived on disk as
|
|
131
|
-
* `<fileBase>.v<version>.ts`; this records what changed and who did it.
|
|
132
|
-
*/
|
|
133
|
-
history?: ScriptVersionRecord[];
|
|
134
|
-
}
|
|
135
|
-
/**
|
|
136
|
-
* A durable, user-stated rendering choice for a recipe. Survives data edits.
|
|
137
|
-
*/
|
|
138
|
-
interface ScriptDisplayPreference {
|
|
139
|
-
/** Component types the user's chosen rendering resolved to, e.g. ["DynamicBarChart"]. */
|
|
140
|
-
componentTypes: string[];
|
|
141
|
-
/** The instruction itself — carries nuance the types can't ("horizontal", "sorted descending"). */
|
|
142
|
-
instruction: string;
|
|
143
|
-
/** ISO timestamp of the display edit that set this. */
|
|
144
|
-
at: string;
|
|
145
|
-
}
|
|
146
|
-
/** One superseded version of a recipe body (see ScriptStore.commitEdit). */
|
|
147
|
-
interface ScriptVersionRecord {
|
|
148
|
-
/** Version number this record superseded (i.e. the OLD version). */
|
|
149
|
-
version: number;
|
|
150
|
-
/** ISO timestamp of the edit that superseded it. */
|
|
151
|
-
at: string;
|
|
152
|
-
/** userId who made the edit, when known. */
|
|
153
|
-
by?: string;
|
|
154
|
-
/** The edit instruction that caused the supersede. */
|
|
155
|
-
instruction?: string;
|
|
156
|
-
/** One-line summary of what changed, for the version picker. */
|
|
157
|
-
changeSummary?: string;
|
|
158
|
-
/** sha256 of the superseded body — pairs with `<fileBase>.v<version>.ts`. */
|
|
159
|
-
bodyHash?: string;
|
|
160
|
-
}
|
|
161
|
-
interface ScriptParameter {
|
|
162
|
-
/** Parameter name (used in script body as params.name) */
|
|
163
|
-
name: string;
|
|
164
|
-
/** Parameter type */
|
|
165
|
-
type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
|
|
166
|
-
/** Whether this parameter is required */
|
|
167
|
-
required: boolean;
|
|
168
|
-
/** Default value if not provided */
|
|
169
|
-
default?: any;
|
|
170
|
-
/** For enum type — maps user-facing values to internal values */
|
|
171
|
-
enumValues?: Record<string, string>;
|
|
172
|
-
/** Human-readable description (used in the matcher LLM prompt) */
|
|
173
|
-
description: string;
|
|
174
|
-
}
|
|
175
|
-
/**
|
|
176
|
-
* A reusable component binding captured when a script is authored. Stored on
|
|
177
|
-
* the recipe so tier-high replays rebuild components deterministically (rebind
|
|
178
|
-
* to fresh queryIds) instead of re-running the component-picker LLM.
|
|
179
|
-
*/
|
|
180
|
-
interface ScriptComponentSpec {
|
|
181
|
-
/** Registered component name (e.g. "DynamicBarChart") — matched against the available component library. */
|
|
182
|
-
componentType: string;
|
|
183
|
-
/** `executedQuery.sourceId` to bind to (e.g. a tool id or 'computed:_final'), 'federation' for a cross-source component, or 'markdown' for a content-only narrative block (no data source). */
|
|
184
|
-
sourceRef: string;
|
|
185
|
-
/** Present only when sourceRef === 'federation' — the DuckDB SQL to re-execute on replay. */
|
|
186
|
-
federationSql?: string;
|
|
187
|
-
/** Present only when sourceRef === 'markdown' — the narrative text to render on replay (markdown has no data source, so its content must be persisted). */
|
|
188
|
-
content?: string;
|
|
189
|
-
title?: string;
|
|
190
|
-
description?: string;
|
|
191
|
-
/** Validated axis/value keys + aggregation — all referencing real columns of the bound source. */
|
|
192
|
-
config: Record<string, any>;
|
|
193
|
-
}
|
|
194
|
-
/**
|
|
195
|
-
* Result from executing a script via ScriptRunner.
|
|
196
|
-
*/
|
|
197
|
-
interface ScriptResult {
|
|
198
|
-
/** Whether the script executed successfully */
|
|
199
|
-
success: boolean;
|
|
200
|
-
/** Combined data from all queries */
|
|
201
|
-
data: any[];
|
|
202
|
-
/** Program-generated narrative, when the script exports getAnalysis. */
|
|
203
|
-
analysis?: AnalysisOutput;
|
|
204
|
-
/**
|
|
205
|
-
* getAnalysis threw. `success` stays true — the data is valid, so the caller
|
|
206
|
-
* falls back to LLM prose rather than losing the answer.
|
|
207
|
-
*/
|
|
208
|
-
analysisError?: string;
|
|
209
|
-
/** Program-generated component specs, when the script exports getComponents. */
|
|
210
|
-
components?: ScriptComponentSpec[];
|
|
211
|
-
/**
|
|
212
|
-
* getComponents threw or returned a non-array. `success` stays true — the data
|
|
213
|
-
* is valid, so the caller falls back to the recipe's stored specs and then to
|
|
214
|
-
* LLM generation rather than losing the dashboard.
|
|
215
|
-
*/
|
|
216
|
-
componentsError?: string;
|
|
217
|
-
/** Individual query results tracked during execution */
|
|
218
|
-
executedQueries: ScriptQueryResult[];
|
|
219
|
-
/** Error message if failed */
|
|
220
|
-
error?: string;
|
|
221
|
-
/**
|
|
222
|
-
* Where in the lifecycle the error occurred. Lets MainAgent's fix-loop
|
|
223
|
-
* decide between "rewrite the whole draft" (compile) and "patch the
|
|
224
|
-
* specific line" (runtime).
|
|
225
|
-
*/
|
|
226
|
-
errorPhase?: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
227
|
-
/** Total execution time in milliseconds */
|
|
228
|
-
executionTimeMs: number;
|
|
229
|
-
}
|
|
230
|
-
/**
|
|
231
|
-
* A single query executed during script runtime.
|
|
232
|
-
* Tracked by ScriptContext for component generation and debugging.
|
|
233
|
-
*/
|
|
234
|
-
interface ScriptQueryResult {
|
|
235
|
-
/** Source tool ID */
|
|
236
|
-
sourceId: string;
|
|
237
|
-
/** Human-readable source name */
|
|
238
|
-
sourceName: string;
|
|
239
|
-
/** The SQL that was executed */
|
|
240
|
-
sql: string;
|
|
241
|
-
/** Result data rows */
|
|
242
|
-
data: any[];
|
|
243
|
-
/** Number of rows returned */
|
|
244
|
-
count: number;
|
|
245
|
-
/** Total rows that matched before limit (if available) */
|
|
246
|
-
totalCount?: number;
|
|
247
|
-
/** Query execution time in milliseconds */
|
|
248
|
-
executionTimeMs: number;
|
|
249
|
-
/**
|
|
250
|
-
* True for rows that did NOT come from a real SQL execution — either a
|
|
251
|
-
* ctx.emit() dataset or the synthesized "computed:_final" entry that
|
|
252
|
-
* carries the script's post-JS returned data. The component generator
|
|
253
|
-
* uses this to route the resulting component through the script_dataset
|
|
254
|
-
* sentinel toolId so the frontend resolves it via the queryCache short-circuit.
|
|
255
|
-
*/
|
|
256
|
-
virtual?: boolean;
|
|
257
|
-
}
|
|
258
|
-
/**
|
|
259
|
-
* Match tier returned by the LLM script matcher.
|
|
260
|
-
*
|
|
261
|
-
* - 'high': the script answers the question directly; only parameter values
|
|
262
|
-
* may differ. The runtime replays it with extracted params (cheapest path).
|
|
263
|
-
* - 'near': the script answers a STRUCTURALLY similar question but needs
|
|
264
|
-
* body modification (different metric, dimension, table, filter shape).
|
|
265
|
-
* The runtime forks the parent and adapts the body via MainAgent's normal
|
|
266
|
-
* write_script + execute_script loop — no SourceAgent dispatch needed.
|
|
267
|
-
* See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md for the full design.
|
|
268
|
-
* - 'edit': the user is INSTRUCTING a change to the script that produced the
|
|
269
|
-
* previous answer (not asking a new question). Only reachable when the turn
|
|
270
|
-
* carries a ScriptBinding — without one the matcher coerces it to 'none', so
|
|
271
|
-
* a prompt regression can't turn this into a loose similarity path. The
|
|
272
|
-
* runtime runs MainAgent in edit mode and commits the result in place.
|
|
273
|
-
* See backend/docs/SCRIPT-EDIT-DESIGN.md.
|
|
274
|
-
* - 'none': no script is relevant; full agent flow runs.
|
|
275
|
-
*/
|
|
276
|
-
type MatchTier = 'high' | 'near' | 'edit' | 'none';
|
|
277
|
-
/**
|
|
278
|
-
* Which recipe produced the answer the user is currently looking at.
|
|
279
|
-
*
|
|
280
|
-
* Set whenever a turn's answer came from a script (replay, fresh authoring, or
|
|
281
|
-
* a committed edit) and carried on the UIBlock + saved conversation row. Two
|
|
282
|
-
* consumers:
|
|
283
|
-
* 1. The matcher — the 'edit' tier is ONLY reachable when a binding exists, so
|
|
284
|
-
* "use mode instead of mean" resolves to a concrete script instead of being
|
|
285
|
-
* matched on keywords it shares with no script name.
|
|
286
|
-
* 2. Cache invalidation — after an edit commits, conversations bound to that
|
|
287
|
-
* recipeId must be dropped, or the exact-match cache replays the pre-edit
|
|
288
|
-
* answer and the edit looks like a no-op.
|
|
289
|
-
*
|
|
290
|
-
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
291
|
-
*/
|
|
292
|
-
interface ScriptBinding {
|
|
293
|
-
recipeId: string;
|
|
294
|
-
/**
|
|
295
|
-
* The recipe's own version number at the moment THIS turn ran — not
|
|
296
|
-
* necessarily the recipe's current version. A later edit bumps the live
|
|
297
|
-
* version, so without this a past turn's binding would silently point at
|
|
298
|
-
* whatever the recipe looks like today instead of what actually produced
|
|
299
|
-
* that answer. Absent on bindings created before this field existed.
|
|
300
|
-
*/
|
|
301
|
-
version?: number;
|
|
302
|
-
/** Params the script ran with — the edit's starting point. */
|
|
303
|
-
params: Record<string, any>;
|
|
304
|
-
/** Recipe name at bind time (matcher catalog + user-facing confirmation). */
|
|
305
|
-
name: string;
|
|
306
|
-
/** Columns the last run returned — grounds the editor without a re-query. */
|
|
307
|
-
columns?: string[];
|
|
308
|
-
/**
|
|
309
|
-
* The question that produced this answer. Required for disambiguation when a
|
|
310
|
-
* thread ran several scripts — without it the candidates are just names and
|
|
311
|
-
* the matcher cannot resolve "use the mode for the WSP one".
|
|
312
|
-
*/
|
|
313
|
-
userPrompt?: string;
|
|
314
|
-
/**
|
|
315
|
-
* The polished analysis text this script actually produced last time it ran
|
|
316
|
-
* (the same programAnswer Thread.getConversationContext() shows elsewhere).
|
|
317
|
-
* Carried alongside the script's own shape (columns, params) so the matcher
|
|
318
|
-
* sees "what did this script actually say" right next to "what can I ask it
|
|
319
|
-
* to change", instead of needing a separate conversation-history transcript
|
|
320
|
-
* that would otherwise just repeat the same question this block already
|
|
321
|
-
* states. This is why ScriptMatcher's own prompt no longer receives a raw
|
|
322
|
-
* conversation-history transcript at all — this field is what replaced it.
|
|
323
|
-
*/
|
|
324
|
-
answerSummary?: string;
|
|
325
|
-
}
|
|
326
|
-
/**
|
|
327
|
-
* Result from the LLM-based script matcher.
|
|
328
|
-
*
|
|
329
|
-
* For `tier: 'high'`, `extractedParams` carries the values to pass to the
|
|
330
|
-
* existing script. For `tier: 'near'`, `gaps` and `modificationHint` describe
|
|
331
|
-
* what the fork-author needs to change in the parent body.
|
|
332
|
-
*/
|
|
333
|
-
interface ScriptMatch {
|
|
334
|
-
/** The matched script recipe */
|
|
335
|
-
recipe: ScriptRecipe;
|
|
336
|
-
/** Match tier — see MatchTier docs */
|
|
337
|
-
tier: MatchTier;
|
|
338
|
-
/** Similarity score (0-1, derived from LLM tier) */
|
|
339
|
-
similarity: number;
|
|
340
|
-
/**
|
|
341
|
-
* Legacy confidence level. Mirrors `tier === 'high'`/`'near'` for now;
|
|
342
|
-
* kept so existing callers compile while we migrate to tier-based logic.
|
|
343
|
-
*/
|
|
344
|
-
confidence: 'high' | 'medium';
|
|
345
|
-
/** Parameters extracted from the user question by the LLM (tier='high') */
|
|
346
|
-
extractedParams?: Record<string, any>;
|
|
347
|
-
/**
|
|
348
|
-
* Proper nouns the question named, VERBATIM, with the parameter each fills.
|
|
349
|
-
*
|
|
350
|
-
* The matcher must NOT resolve these itself. Observed live: it substituted the
|
|
351
|
-
* customer name "PREMER ENRGES PHOTOOTAIC" into an id parameter believing that
|
|
352
|
-
* "the runtime will resolve the customer name to its PartyId(s)" — nothing on
|
|
353
|
-
* the replay path does, and `WHERE BillingPartyId IN (PREMER ENRGES
|
|
354
|
-
* PHOTOOTAIC)` reached SQL. Reported here, the runtime resolves them before
|
|
355
|
-
* replay and rejects the match when one cannot be resolved.
|
|
356
|
-
*/
|
|
357
|
-
mentions?: Array<{
|
|
358
|
-
text: string;
|
|
359
|
-
param?: string;
|
|
360
|
-
}>;
|
|
361
|
-
/** Business concepts the question relies on (e.g. "outstanding balance"). */
|
|
362
|
-
entityTypes?: string[];
|
|
363
|
-
/** What the user question needs that the parent doesn't cover (tier='near') */
|
|
364
|
-
gaps?: string[];
|
|
365
|
-
/** One-sentence description of the change the fork-author should make (tier='near') */
|
|
366
|
-
modificationHint?: string;
|
|
367
|
-
/**
|
|
368
|
-
* Which HALF of the recipe the edit targets (tier='edit'). A recipe has two
|
|
369
|
-
* independently editable halves:
|
|
370
|
-
* - 'data' — the scriptBody: how the rows are produced (aggregation,
|
|
371
|
-
* filters, joins, grouping). Runs MainAgent in edit mode.
|
|
372
|
-
* - 'display' — the component specs: how those SAME rows are shown (chart
|
|
373
|
-
* type, orientation, columns, labels). Replays the proven SQL
|
|
374
|
-
* and regenerates the specs — never authors a script.
|
|
375
|
-
* Defaults to 'data' when the matcher omits it.
|
|
376
|
-
*/
|
|
377
|
-
editTarget?: 'data' | 'display';
|
|
378
|
-
/**
|
|
379
|
-
* Self-contained restatement of the change the user asked for (tier='edit').
|
|
380
|
-
* MUST have pronouns/deixis resolved ("this", "it", "that column") — the edit
|
|
381
|
-
* prompt never sees the conversation history, so an unresolved instruction is
|
|
382
|
-
* unusable downstream.
|
|
383
|
-
*/
|
|
384
|
-
editInstruction?: string;
|
|
385
|
-
/** Why the matcher made this choice (for logs and telemetry) */
|
|
386
|
-
reasoning?: string;
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
/**
|
|
390
|
-
* script-ipc.ts — Protocol definitions for parent/child IPC.
|
|
391
|
-
*
|
|
392
|
-
* Transport: newline-delimited JSON over the child's stdin/stdout.
|
|
393
|
-
* stderr is passed through for uncaught exceptions and compile errors.
|
|
394
|
-
*
|
|
395
|
-
* See backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md § IPC Bridge.
|
|
396
|
-
*/
|
|
397
|
-
|
|
398
|
-
/**
|
|
399
|
-
* What getAnalysis returns. `analysis` is the narrative and `summary` the short
|
|
400
|
-
* bullets the markdown block binds to — siblings over one dataset, never a
|
|
401
|
-
* summary OF the narrative. See backend/docs/ANALYSIS-AS-PROGRAM-DESIGN.md § 4.3.
|
|
402
|
-
*/
|
|
403
|
-
interface AnalysisOutput {
|
|
404
|
-
analysis?: string;
|
|
405
|
-
summary?: string[];
|
|
406
|
-
method?: string;
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
/**
|
|
410
|
-
* StreamBuffer - Buffered streaming utility for smoother text delivery
|
|
411
|
-
* Batches small chunks together and flushes at regular intervals
|
|
412
|
-
*/
|
|
413
|
-
type StreamCallback = (chunk: string) => void;
|
|
414
|
-
/**
|
|
415
|
-
* StreamBuffer class for managing buffered streaming output
|
|
416
|
-
* Provides smooth text delivery by batching small chunks
|
|
417
|
-
*/
|
|
418
|
-
declare class StreamBuffer {
|
|
419
|
-
private buffer;
|
|
420
|
-
private flushTimer;
|
|
421
|
-
private callback;
|
|
422
|
-
private fullText;
|
|
423
|
-
constructor(callback?: StreamCallback);
|
|
424
|
-
/**
|
|
425
|
-
* Check if the buffer has a callback configured
|
|
426
|
-
*/
|
|
427
|
-
hasCallback(): boolean;
|
|
428
|
-
/**
|
|
429
|
-
* Get all text that has been written (including already flushed)
|
|
430
|
-
*/
|
|
431
|
-
getFullText(): string;
|
|
432
|
-
/**
|
|
433
|
-
* Write a chunk to the buffer
|
|
434
|
-
* Large chunks or chunks with newlines are flushed immediately
|
|
435
|
-
* Small chunks are batched and flushed after a short interval
|
|
436
|
-
*
|
|
437
|
-
* @param chunk - Text chunk to write
|
|
438
|
-
*/
|
|
439
|
-
write(chunk: string): void;
|
|
440
|
-
/**
|
|
441
|
-
* Flush the buffer immediately
|
|
442
|
-
* Call this before tool execution or other operations that need clean output
|
|
443
|
-
*/
|
|
444
|
-
flush(): void;
|
|
445
|
-
/**
|
|
446
|
-
* Internal flush implementation
|
|
447
|
-
*/
|
|
448
|
-
private flushNow;
|
|
449
|
-
/**
|
|
450
|
-
* Clean up resources
|
|
451
|
-
* Call this when done with the buffer
|
|
452
|
-
*/
|
|
453
|
-
dispose(): void;
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
/**
|
|
457
|
-
* ToolExecutorService - Handles execution of SQL queries and external tools
|
|
458
|
-
* Extracted from BaseLLM.generateTextResponse for better separation of concerns
|
|
459
|
-
*/
|
|
460
|
-
|
|
461
|
-
/**
|
|
462
|
-
* External tool definition
|
|
463
|
-
*/
|
|
464
|
-
interface ExternalTool {
|
|
465
|
-
id: string;
|
|
466
|
-
name: string;
|
|
467
|
-
description?: string;
|
|
468
|
-
/** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
|
|
469
|
-
toolType?: 'source' | 'direct';
|
|
470
|
-
/** Full untruncated schema for source agent (all columns visible) */
|
|
471
|
-
fullSchema?: string;
|
|
472
|
-
/** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
|
|
473
|
-
schemaTier?: string;
|
|
474
|
-
/** Schema search function for very_large tier — keyword search over entities */
|
|
475
|
-
schemaSearchFn?: (keywords: string[]) => string;
|
|
476
|
-
/** `signal` fires when the user hits Stop mid-query — passed through to the backend's SourceTool.fn. */
|
|
477
|
-
fn: (input: any, signal?: AbortSignal) => Promise<any>;
|
|
478
|
-
limit?: number;
|
|
479
|
-
outputSchema?: any;
|
|
480
|
-
executionType?: 'immediate' | 'deferred';
|
|
481
|
-
userProvidedData?: any;
|
|
482
|
-
params?: Record<string, any>;
|
|
483
|
-
}
|
|
484
|
-
/**
|
|
485
|
-
* Executed tool tracking info
|
|
486
|
-
*/
|
|
487
|
-
interface ExecutedToolInfo {
|
|
488
|
-
id: string;
|
|
489
|
-
name: string;
|
|
490
|
-
params: any;
|
|
491
|
-
result: {
|
|
492
|
-
_totalRecords: number;
|
|
493
|
-
_recordsShown: number;
|
|
494
|
-
_metadata?: any;
|
|
495
|
-
_sampleData: any[];
|
|
496
|
-
/** Bounded summary over the FULL fetched result (complete structure). */
|
|
497
|
-
_summary?: any;
|
|
498
|
-
/** Up to MAIN_AGENT_COMPLETE_ROWS rows — the complete result when small. */
|
|
499
|
-
_mainAgentRows?: any[];
|
|
500
|
-
};
|
|
501
|
-
outputSchema?: any;
|
|
502
|
-
sourceSchema?: string;
|
|
503
|
-
sourceType?: string;
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
/**
|
|
507
|
-
* Multi-Agent Architecture Types
|
|
508
|
-
*
|
|
509
|
-
* Defines interfaces for the hierarchical agent system:
|
|
510
|
-
* - Main Agent: ONE LLM.streamWithTools() call with source agent tools
|
|
511
|
-
* - Source Agents: independent agents that query individual data sources
|
|
512
|
-
*
|
|
513
|
-
* The main agent sees only source summaries. When it calls a source tool,
|
|
514
|
-
* the SourceAgent runs independently (own LLM, own retries) and returns clean data.
|
|
515
|
-
*/
|
|
516
|
-
|
|
517
|
-
/**
|
|
518
|
-
* Per-entity detail: name, row count, and column names.
|
|
519
|
-
* Gives the main agent enough context to route to the right source.
|
|
520
|
-
*/
|
|
521
|
-
interface EntityDetail {
|
|
522
|
-
/** Entity name (table, sheet, endpoint) */
|
|
523
|
-
name: string;
|
|
524
|
-
/** Approximate row count */
|
|
525
|
-
rowCount?: number;
|
|
526
|
-
/** Column/field names */
|
|
527
|
-
columns: string[];
|
|
528
|
-
/** Entity-level semantic summary (what the table means) — for main-agent routing. */
|
|
529
|
-
summary?: string;
|
|
530
|
-
}
|
|
531
|
-
/**
|
|
532
|
-
* Representation of a data source for the main agent.
|
|
533
|
-
* Contains entity names WITH column names so the LLM can route accurately.
|
|
534
|
-
*/
|
|
535
|
-
interface SourceSummary {
|
|
536
|
-
/** Source ID (matches tool ID prefix) */
|
|
537
|
-
id: string;
|
|
538
|
-
/** Human-readable source name */
|
|
539
|
-
name: string;
|
|
540
|
-
/** Source type: postgres, excel, rest_api, etc. */
|
|
541
|
-
type: string;
|
|
542
|
-
/** Brief description of what data this source contains */
|
|
543
|
-
description: string;
|
|
544
|
-
/** Detailed entity info with column names for routing */
|
|
545
|
-
entityDetails: EntityDetail[];
|
|
546
|
-
/** The tool ID associated with this source */
|
|
547
|
-
toolId: string;
|
|
548
|
-
}
|
|
549
|
-
/**
|
|
550
|
-
* What a source agent returns after querying its data source.
|
|
551
|
-
* The main agent uses this to analyze and compose the final response.
|
|
552
|
-
*/
|
|
553
|
-
interface SourceAgentResult {
|
|
554
|
-
/** Source ID */
|
|
555
|
-
sourceId: string;
|
|
556
|
-
/** Source name */
|
|
557
|
-
sourceName: string;
|
|
558
|
-
/** Whether the query succeeded */
|
|
559
|
-
success: boolean;
|
|
560
|
-
/** Result data rows */
|
|
561
|
-
data: any[];
|
|
562
|
-
/** Metadata about the query execution */
|
|
563
|
-
metadata: SourceAgentMetadata;
|
|
564
|
-
/** Tool execution info for the last successful query (backward compat) */
|
|
565
|
-
executedTool: ExecutedToolInfo;
|
|
566
|
-
/** All successful tool executions (primary + follow-up queries) */
|
|
567
|
-
allExecutedTools?: ExecutedToolInfo[];
|
|
568
|
-
/** Error message if failed */
|
|
569
|
-
error?: string;
|
|
570
|
-
}
|
|
571
|
-
interface SourceAgentMetadata {
|
|
572
|
-
/** Total rows that matched the query (before limit) */
|
|
573
|
-
totalRowsMatched: number;
|
|
574
|
-
/** Rows actually returned (after limit) */
|
|
575
|
-
rowsReturned: number;
|
|
576
|
-
/** Whether the result was truncated by the row limit */
|
|
577
|
-
isLimited: boolean;
|
|
578
|
-
/** The query/params that were executed */
|
|
579
|
-
queryExecuted?: string;
|
|
580
|
-
/** Execution time in milliseconds */
|
|
581
|
-
executionTimeMs: number;
|
|
582
|
-
}
|
|
583
|
-
/**
|
|
584
|
-
* A pre-built, multi-step UI flow registered with the SDK.
|
|
585
|
-
*
|
|
586
|
-
* When the main agent decides a user's question matches a workflow's whenToUse
|
|
587
|
-
* trigger, it picks the workflow instead of running source agents / generating
|
|
588
|
-
* dashboard components. The LLM extracts the workflow's required props from the
|
|
589
|
-
* prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
|
|
590
|
-
* workflow component directly — no analysis text, no chart generation. The
|
|
591
|
-
* frontend renders the registered workflow component with the LLM-extracted
|
|
592
|
-
* props.
|
|
593
|
-
*/
|
|
594
|
-
interface WorkflowDescriptor {
|
|
595
|
-
/** Unique workflow id (used as the LLM tool name) */
|
|
596
|
-
id: string;
|
|
597
|
-
/** Component name on the frontend (matches the registered React component) */
|
|
598
|
-
name: string;
|
|
599
|
-
/** Short human-readable description of what this workflow does */
|
|
600
|
-
description: string;
|
|
601
|
-
/**
|
|
602
|
-
* 1–2 sentence trigger condition. The LLM uses this to decide if the
|
|
603
|
-
* user's prompt matches this workflow. Be specific — e.g.
|
|
604
|
-
* "User wants to *initiate* an inventory transfer (review + submit POs),
|
|
605
|
-
* not just see analysis or charts."
|
|
606
|
-
*/
|
|
607
|
-
whenToUse: string;
|
|
608
|
-
/**
|
|
609
|
-
* JSON-schema-style description of the props the workflow needs. Becomes
|
|
610
|
-
* the LLM tool's input_schema, so the model fills these from the prompt.
|
|
611
|
-
* Use the same shape as `params` on direct tools — string descriptors with
|
|
612
|
-
* an optional "(optional)" suffix.
|
|
613
|
-
*
|
|
614
|
-
* Example:
|
|
615
|
-
* ```
|
|
616
|
-
* {
|
|
617
|
-
* selectedStore: 'object — { id, name } of the source branch',
|
|
618
|
-
* minROI: 'number (optional) — only show transfers with ROI ≥ this',
|
|
619
|
-
* }
|
|
620
|
-
* ```
|
|
621
|
-
*/
|
|
622
|
-
propsSchema: Record<string, string>;
|
|
623
|
-
/**
|
|
624
|
-
* Optional: static prop defaults merged with LLM-extracted props before
|
|
625
|
-
* the component is returned. Useful for things like the embedded
|
|
626
|
-
* `externalTool` config that the workflow uses to fetch its own data.
|
|
627
|
-
*/
|
|
628
|
-
defaultProps?: Record<string, any>;
|
|
629
|
-
}
|
|
630
|
-
/**
|
|
631
|
-
* The workflow selection captured during a routing call.
|
|
632
|
-
* Set on AgentResponse when the LLM picks a workflow tool.
|
|
633
|
-
*/
|
|
634
|
-
interface SelectedWorkflow {
|
|
635
|
-
/** Component name (matches WorkflowDescriptor.name) */
|
|
636
|
-
name: string;
|
|
637
|
-
/** Props extracted from the prompt + merged with workflow.defaultProps */
|
|
638
|
-
props: Record<string, any>;
|
|
639
|
-
}
|
|
640
|
-
/**
|
|
641
|
-
* Set when this turn applies a user-directed edit to an existing script instead
|
|
642
|
-
* of authoring a new one. MainAgent keeps the SAME harness (tools, loop,
|
|
643
|
-
* write_script/execute_script verification) and swaps only the system prompt —
|
|
644
|
-
* `agent-main-edit` instead of `agent-main`.
|
|
645
|
-
*
|
|
646
|
-
* The two framings contradict each other on whether to query a source first, so
|
|
647
|
-
* they must never be resident in one rendered prompt.
|
|
648
|
-
* See backend/docs/SCRIPT-EDIT-DESIGN.md § D3.
|
|
649
|
-
*/
|
|
650
|
-
interface EditContext {
|
|
651
|
-
/** Recipe being edited — the shadow draft records it as parentId. */
|
|
652
|
-
recipeId: string;
|
|
653
|
-
parentName: string;
|
|
654
|
-
parentBody: string;
|
|
655
|
-
/** Self-contained restatement of the change (from the matcher). */
|
|
656
|
-
instruction: string;
|
|
657
|
-
/** Columns the last run returned — grounds the edit without a re-query. */
|
|
658
|
-
lastResultColumns?: string[];
|
|
659
|
-
/** Rendered parameter list of the parent, for the prompt. */
|
|
660
|
-
parentParams?: string;
|
|
661
|
-
}
|
|
662
|
-
/**
|
|
663
|
-
* The complete response from the multi-agent system.
|
|
664
|
-
* Contains everything needed for text display + component generation.
|
|
665
|
-
*/
|
|
666
|
-
interface AgentResponse {
|
|
667
|
-
/** Generated text response (analysis of the data) */
|
|
668
|
-
text: string;
|
|
669
|
-
/**
|
|
670
|
-
* Program-generated narrative when the script exported getAnalysis. `text`
|
|
671
|
-
* already carries `analysis.analysis`; this also exposes `summary`, which
|
|
672
|
-
* the markdown block binds to instead of being an LLM summary of the prose.
|
|
673
|
-
*/
|
|
674
|
-
analysis?: AnalysisOutput;
|
|
675
|
-
/** All executed tools across all source agents (for component generation) */
|
|
676
|
-
executedTools: ExecutedToolInfo[];
|
|
677
|
-
/** Individual results from each source agent */
|
|
678
|
-
sourceResults: SourceAgentResult[];
|
|
679
|
-
/**
|
|
680
|
-
* Populated when MainAgent wrote AND successfully executed a script during its turn.
|
|
681
|
-
* Caller (agent-user-response.ts) persists it via ScriptStore.save().
|
|
682
|
-
* Absent when MainAgent didn't write one (trivial question / all attempts failed).
|
|
683
|
-
*/
|
|
684
|
-
savedScript?: AgentWrittenScript;
|
|
685
|
-
/** Failed execute_script tool_result texts this turn, in order — see RunTrace.script.failedAttempts. */
|
|
686
|
-
failedScriptAttempts?: string[];
|
|
687
|
-
/**
|
|
688
|
-
* Set when the LLM routed the question to a registered workflow component.
|
|
689
|
-
* When present, the upstream caller should skip component generation and
|
|
690
|
-
* return this workflow as the response.
|
|
691
|
-
*/
|
|
692
|
-
workflow?: SelectedWorkflow;
|
|
693
|
-
/**
|
|
694
|
-
* Validated component specs the agent authored via `write_components`.
|
|
695
|
-
* When present the caller assembles the dashboard from these instead of
|
|
696
|
-
* running the component-generation LLM. Absent when the agent didn't call
|
|
697
|
-
* the tool — the caller then falls back to `generateScriptComponents`.
|
|
698
|
-
* See backend/docs/COMPONENT-GENERATION-V2.md §2.2.
|
|
699
|
-
*/
|
|
700
|
-
componentSpecs?: ScriptComponentSpec[];
|
|
701
|
-
/** Layout title/description from the same `write_components` call. */
|
|
702
|
-
componentLayout?: {
|
|
703
|
-
title: string;
|
|
704
|
-
description?: string;
|
|
705
|
-
};
|
|
706
|
-
}
|
|
707
|
-
/**
|
|
708
|
-
* A script MainAgent authored + verified during its turn. Shape aligns with
|
|
709
|
-
* what ScriptStore.save() needs — minus store-assigned fields (id, timestamps, counts).
|
|
710
|
-
*/
|
|
711
|
-
interface AgentWrittenScript {
|
|
712
|
-
/**
|
|
713
|
-
* `ScriptRecipe.id` of the draft that was authored + verified during this turn.
|
|
714
|
-
* The caller passes this to `ScriptStore.promoteToVerified(recipeId, …)` to
|
|
715
|
-
* flip the draft to verified status and (when possible) drop the turn-suffix
|
|
716
|
-
* from its filename.
|
|
717
|
-
*/
|
|
718
|
-
recipeId: string;
|
|
719
|
-
name: string;
|
|
720
|
-
intentDescription: string;
|
|
721
|
-
tags: string[];
|
|
722
|
-
parameters: Array<{
|
|
723
|
-
name: string;
|
|
724
|
-
type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
|
|
725
|
-
required: boolean;
|
|
726
|
-
default?: any;
|
|
727
|
-
enumValues?: Record<string, string>;
|
|
728
|
-
description: string;
|
|
729
|
-
}>;
|
|
730
|
-
scriptBody: string;
|
|
731
|
-
/** Source IDs referenced by the script (extracted from ctx.query calls) */
|
|
732
|
-
sourceIds: string[];
|
|
733
|
-
/** Tables referenced in the script's SQL (regex-extracted) */
|
|
734
|
-
tables: string[];
|
|
735
|
-
/** Executed queries from the verified run — fed to component generation */
|
|
736
|
-
executedQueries: Array<{
|
|
737
|
-
sourceId: string;
|
|
738
|
-
sourceName: string;
|
|
739
|
-
sql: string;
|
|
740
|
-
data: any[];
|
|
741
|
-
count: number;
|
|
742
|
-
totalCount?: number;
|
|
743
|
-
executionTimeMs: number;
|
|
744
|
-
/**
|
|
745
|
-
* True for synthetic entries (ctx.emit datasets, the computed:_final
|
|
746
|
-
* post-JS data). The component generator routes virtual sources through
|
|
747
|
-
* the script_dataset sentinel toolId so the frontend resolves them via
|
|
748
|
-
* queryCache instead of attempting to re-execute SQL.
|
|
749
|
-
*/
|
|
750
|
-
virtual?: boolean;
|
|
751
|
-
}>;
|
|
752
|
-
/** The tool_result JSON MainAgent's LLM got back from execute_script — see RunTrace.script.executionResult. */
|
|
753
|
-
executionResult?: string;
|
|
754
|
-
}
|
|
755
|
-
/**
|
|
756
|
-
* Debug trace for a single chat_agent turn — which KB/schema nodes were
|
|
757
|
-
* retrieved and considered, and which script (if any) produced the answer.
|
|
758
|
-
* Persisted separately from the answer itself (fusion-5's
|
|
759
|
-
* `conversation_traces` table, written via `saveTrace`), never sent through
|
|
760
|
-
* `analyticsClient` (data-residency — see design doc §5).
|
|
761
|
-
*/
|
|
762
|
-
interface RunTrace {
|
|
763
|
-
version: 1;
|
|
764
|
-
kbNodes: {
|
|
765
|
-
/**
|
|
766
|
-
* Always-on nodes included regardless of the question (getGlobalKnowledgeBase).
|
|
767
|
-
* `content` is the node's full text AS IT WAS at retrieval time — captured so a
|
|
768
|
-
* later edit/delete of the KB node doesn't erase what the LLM actually saw.
|
|
769
|
-
*/
|
|
770
|
-
global: Array<{
|
|
771
|
-
kbId: string;
|
|
772
|
-
title: string;
|
|
773
|
-
content?: string;
|
|
774
|
-
}>;
|
|
775
|
-
/** Semantically matched for this specific question (getKnowledgeBase). Same `content` reasoning as above. */
|
|
776
|
-
query: Array<{
|
|
777
|
-
kbId: string;
|
|
778
|
-
title: string;
|
|
779
|
-
similarity?: number;
|
|
780
|
-
content?: string;
|
|
781
|
-
}>;
|
|
782
|
-
};
|
|
783
|
-
schemaNodes: {
|
|
784
|
-
/** MainAgent's cross-source prefilter — which sources were even considered. */
|
|
785
|
-
routing: Array<{
|
|
786
|
-
sourceId: string;
|
|
787
|
-
sourceName?: string;
|
|
788
|
-
similarity: number;
|
|
789
|
-
}>;
|
|
790
|
-
/** SourceAgent-scope per-source table resolution (MainAgent.preResolveSchema). */
|
|
791
|
-
preResolve: Array<{
|
|
792
|
-
sourceId: string;
|
|
793
|
-
table?: string;
|
|
794
|
-
description?: string;
|
|
795
|
-
similarity: number;
|
|
796
|
-
}>;
|
|
797
|
-
/**
|
|
798
|
-
* The exact {{SOURCE_SUMMARIES}} text injected into MainAgent's system prompt
|
|
799
|
-
* (agent-prompt-builder.ts's formatSummariesForPrompt output) — every
|
|
800
|
-
* registered source's catalog entry, not retrieval-specific, captured once per
|
|
801
|
-
* turn. This is what the main agent actually saw when deciding which source(s)
|
|
802
|
-
* to call.
|
|
803
|
-
*/
|
|
804
|
-
mainAgentCatalog?: string;
|
|
805
|
-
/**
|
|
806
|
-
* One entry per SourceAgent dispatch (a source called twice in one turn gets
|
|
807
|
-
* two entries) — the exact {{FULL_SCHEMA}} text injected into that
|
|
808
|
-
* SourceAgent's own system prompt, however it was sourced, plus any
|
|
809
|
-
* search_schema follow-up lookups it made mid-conversation when the schema
|
|
810
|
-
* shown wasn't enough.
|
|
811
|
-
*/
|
|
812
|
-
sourceAgentSchemas: Array<{
|
|
813
|
-
sourceId: string;
|
|
814
|
-
sourceName?: string;
|
|
815
|
-
/**
|
|
816
|
-
* The exact intent text MainAgent wrote for this dispatch (before the
|
|
817
|
-
* resolved-entities block gets appended by code — see
|
|
818
|
-
* buildResolvedEntitiesBlock) — what MainAgent actually asked this
|
|
819
|
-
* source agent to go find.
|
|
820
|
-
*/
|
|
821
|
-
intent: string;
|
|
822
|
-
/** How `schemaText` was sourced — see SourceAgent.buildPrompt's fullSchema fallback chain. */
|
|
823
|
-
method: 'preresolved-embedding' | 'tool-full-schema' | 'tool-description' | 'none';
|
|
824
|
-
schemaText: string;
|
|
825
|
-
/** In call order — each search_schema tool call this SourceAgent made, and the exact result text handed back to its own LLM. */
|
|
826
|
-
searchSchemaLookups: Array<{
|
|
827
|
-
keywords: string[];
|
|
828
|
-
result: string;
|
|
829
|
-
}>;
|
|
830
|
-
/** The tool_result text MainAgent's LLM read back for this dispatch (formatResultForMainAgent output). */
|
|
831
|
-
result?: string;
|
|
832
|
-
}>;
|
|
833
|
-
};
|
|
834
|
-
/** The script that produced this answer, if any. Null for a general (no-tool) answer. */
|
|
835
|
-
script: {
|
|
836
|
-
/** True when an existing recipe was replayed unchanged (ScriptMatcher tier='high'). */
|
|
837
|
-
reused: boolean;
|
|
838
|
-
recipeId?: string | null;
|
|
839
|
-
body?: string | null;
|
|
840
|
-
/** Set when reused — the matcher's reasoning for picking this recipe. */
|
|
841
|
-
reasoning?: string | null;
|
|
842
|
-
/** The winning execute_script tool_result text. Only set when reused=false — a replay never re-runs execute_script. Failed attempts aren't kept. */
|
|
843
|
-
executionResult?: string | null;
|
|
844
|
-
/** Failed execute_script tool_result texts this turn, in order (before the winning one, if any). */
|
|
845
|
-
failedAttempts?: string[];
|
|
846
|
-
} | null;
|
|
847
|
-
/**
|
|
848
|
-
* Everything ScriptMatcher.match() built and sent to its one LLM call this
|
|
849
|
-
* turn — Step 2 of the request flow, immediately after Step 1's exact-match
|
|
850
|
-
* check misses. Captured even when short-circuited before any LLM call, or
|
|
851
|
-
* when the call itself errored, so "why didn't this reuse a script" can
|
|
852
|
-
* always be answered from the trace alone, not just the outcome in `script`.
|
|
853
|
-
* See backend/docs/user-prompt-req-flow/SCRIPT-MATCH-IMPROVEMENTS.md.
|
|
854
|
-
*/
|
|
855
|
-
scriptMatcher: {
|
|
856
|
-
/**
|
|
857
|
-
* Exactly what went INTO the one LLM call — every placeholder value
|
|
858
|
-
* substituted into `.prompts/script-match/system.md`, plus the routing
|
|
859
|
-
* facts (isExplicitEdit, the two counts) that aren't literal prompt text
|
|
860
|
-
* but explain WHY the catalog/active-script blocks look the way they do.
|
|
861
|
-
*/
|
|
862
|
-
sent: {
|
|
863
|
-
/** Whether the raw prompt carried the explicit "edit :" prefix (see parseEditPrefix). */
|
|
864
|
-
isExplicitEdit: boolean;
|
|
865
|
-
/** The prefix-stripped question actually shown to the LLM (the USER_PROMPT placeholder). */
|
|
866
|
-
userPrompt: string;
|
|
867
|
-
/** The Edit Signal text handed to the LLM this turn (CONFIRMED/NOT CONFIRMED wording). */
|
|
868
|
-
editSignal: string;
|
|
869
|
-
/** The rendered "Scripts From Your Past Questions" catalog text (SCRIPT_CATALOG placeholder). */
|
|
870
|
-
scriptCatalog: string;
|
|
871
|
-
/** Distinct scripts actually in scriptCatalog, after health-filtering and the MAX_CATALOG_RECIPES cap. */
|
|
872
|
-
catalogRecipeCount: number;
|
|
873
|
-
/** The rendered "EDITABLE SCRIPTS" block text (ACTIVE_SCRIPT placeholder) — '' when the thread has no active bindings. */
|
|
874
|
-
activeScript: string;
|
|
875
|
-
/** Active bindings offered as edit candidates this turn. */
|
|
876
|
-
activeBindingCount: number;
|
|
877
|
-
};
|
|
878
|
-
/**
|
|
879
|
-
* Everything that came back OUT — the LLM's raw answer plus what the
|
|
880
|
-
* runtime decided to do with it. `tier` here is the FINAL tier after
|
|
881
|
-
* every coercion (near→none, the edit-prefix gate, candidate checks) —
|
|
882
|
-
* it can legitimately differ from `rawResponse.tier`.
|
|
883
|
-
*/
|
|
884
|
-
received: {
|
|
885
|
-
/** False when short-circuited before any LLM call (no catalog match AND no active bindings) — `rawResponse`/`tier` below don't apply. */
|
|
886
|
-
calledLLM: boolean;
|
|
887
|
-
/** The raw JSON the LLM returned, when calledLLM is true and the call didn't throw. */
|
|
888
|
-
rawResponse?: any;
|
|
889
|
-
/** Set when calledLLM is true and the call threw, or the response named an unknown script id. */
|
|
890
|
-
error?: string;
|
|
891
|
-
/** Final tier after ALL coercions. Null when short-circuited, errored, or the call/coercions landed on no match. */
|
|
892
|
-
tier: MatchTier | null;
|
|
893
|
-
};
|
|
894
|
-
} | null;
|
|
895
|
-
/**
|
|
896
|
-
* `resolve_entities` tool activity this turn (see main-agent.ts's
|
|
897
|
-
* RESOLVE_ENTITIES_TOOL_DEF / handleResolveEntities) — names/identifiers the
|
|
898
|
-
* user mentioned, resolved to database ids before any SQL was written.
|
|
899
|
-
* Absent/empty entirely for a project with no entity-search collection
|
|
900
|
-
* registered, or a turn that named nothing.
|
|
901
|
-
*/
|
|
902
|
-
entityResolution: {
|
|
903
|
-
/**
|
|
904
|
-
* The entity-type catalog text injected into MainAgent's system prompt
|
|
905
|
-
* (loadEntityCatalog's output) — what let the LLM name a concept instead
|
|
906
|
-
* of guessing the project's vocabulary. Captured once per turn.
|
|
907
|
-
*/
|
|
908
|
-
catalogText?: string;
|
|
909
|
-
/**
|
|
910
|
-
* One entry per `resolve_entities` tool call this turn (a turn can call it
|
|
911
|
-
* more than once) — the FULL raw response from the entity-search
|
|
912
|
-
* collection, not just the trimmed {mention,entityType,instanceId,
|
|
913
|
-
* displayName} MainAgent keeps for itself to build the dispatch block.
|
|
914
|
-
* `score`/`ambiguous`/`alternatives` only exist here, nowhere else.
|
|
915
|
-
*/
|
|
916
|
-
calls: Array<{
|
|
917
|
-
mentions: Array<{
|
|
918
|
-
text: string;
|
|
919
|
-
entityType?: string;
|
|
920
|
-
}>;
|
|
921
|
-
entityTypes: string[];
|
|
922
|
-
resolved: Array<{
|
|
923
|
-
mention: string;
|
|
924
|
-
entityType: string;
|
|
925
|
-
instanceId: string;
|
|
926
|
-
displayName: string;
|
|
927
|
-
attrs?: Record<string, any>;
|
|
928
|
-
score?: number;
|
|
929
|
-
ambiguous?: boolean;
|
|
930
|
-
alternatives?: Array<{
|
|
931
|
-
instanceId: string;
|
|
932
|
-
displayName: string;
|
|
933
|
-
score: number;
|
|
934
|
-
}>;
|
|
935
|
-
}>;
|
|
936
|
-
unresolved: string[];
|
|
937
|
-
entityMap: Record<string, any>;
|
|
938
|
-
unmatchedEntityTypes?: Array<{
|
|
939
|
-
requested: string;
|
|
940
|
-
candidates?: string[];
|
|
941
|
-
}>;
|
|
942
|
-
/** Set when the collection call itself failed (fails open — see handleResolveEntities). */
|
|
943
|
-
error?: string;
|
|
944
|
-
/** Set on an early return (unavailable / nothing named) so the call is still visible in the trace, not indistinguishable from never having run. */
|
|
945
|
-
note?: string;
|
|
946
|
-
}>;
|
|
947
|
-
};
|
|
948
|
-
/**
|
|
949
|
-
* The prior-turn conversation context injected into this turn's prompt as
|
|
950
|
-
* CONVERSATION_HISTORY — exactly what each flow already builds for itself
|
|
951
|
-
* (chat: thread.getConversationContext(); report/dashboard: their own
|
|
952
|
-
* equivalents), captured as-is. Every call site sets this unconditionally
|
|
953
|
-
* (empty string '' when there's no prior context — new thread, or history
|
|
954
|
-
* trimmed to nothing), so an empty turn is visibly "no history" in the
|
|
955
|
-
* saved trace rather than a silently missing key. Optional only because
|
|
956
|
-
* traces saved before this field existed won't have it at all.
|
|
957
|
-
*/
|
|
958
|
-
conversationHistory?: string;
|
|
959
|
-
/**
|
|
960
|
-
* The exact {{USER_ACCESS_CONTEXT}} text injected into MainAgent's system
|
|
961
|
-
* prompt — the per-user authorization config (sa-api users.config)
|
|
962
|
-
* rendered by buildUserAccessContext, as-is. Captured once (MainAgent's
|
|
963
|
-
* prompt is what SourceAgent's identical value is derived from — no need
|
|
964
|
-
* to duplicate it per source dispatch). Set unconditionally (empty string
|
|
965
|
-
* '' when there's no config for this user), so "no restrictions" is
|
|
966
|
-
* visible in the saved trace rather than a silently missing key. Optional
|
|
967
|
-
* only because traces saved before this field existed won't have it.
|
|
968
|
-
*/
|
|
969
|
-
userAccessContext?: string;
|
|
970
|
-
}
|
|
971
|
-
/**
|
|
972
|
-
* Configuration for the multi-agent system.
|
|
973
|
-
* Controls limits, models, and behavior.
|
|
974
|
-
*/
|
|
975
|
-
interface AgentConfig {
|
|
976
|
-
/** Max rows shown to the UI preview / inlined per source (default: 10) */
|
|
977
|
-
maxRowsPerSource: number;
|
|
978
|
-
/**
|
|
979
|
-
* Max rows a source query may FETCH from the DB server-side (default: 2000).
|
|
980
|
-
* Decoupled from what the main agent is shown: the full result is fetched and
|
|
981
|
-
* summarized (bounded), but only a small/complete slice enters LLM context.
|
|
982
|
-
* This lets small lookups (benchmark maps) arrive COMPLETE without letting
|
|
983
|
-
* large results blow up context.
|
|
984
|
-
*/
|
|
985
|
-
maxRowsFetched: number;
|
|
986
|
-
/** Model for the main agent (routing + analysis in one LLM call) */
|
|
987
|
-
mainAgentModel: string;
|
|
988
|
-
/** Model for source agent query generation */
|
|
989
|
-
sourceAgentModel: string;
|
|
990
|
-
/** API key for LLM calls */
|
|
991
|
-
apiKey?: string;
|
|
992
|
-
/** Max retry attempts per source agent */
|
|
993
|
-
maxRetries: number;
|
|
994
|
-
/** Max tool calling iterations for the main agent loop */
|
|
995
|
-
maxIterations: number;
|
|
996
|
-
/** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
|
|
997
|
-
globalKnowledgeBase?: string;
|
|
998
|
-
/** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
|
|
999
|
-
knowledgeBaseContext?: string;
|
|
1000
|
-
/** Per-user authorization config (sa-api users.config), rendered to text — see buildUserAccessContext */
|
|
1001
|
-
userAccessContext?: string;
|
|
1002
|
-
/** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
|
|
1003
|
-
collections?: any;
|
|
1004
|
-
/** Optional project ID for scoping embedding searches */
|
|
1005
|
-
projectId?: string;
|
|
1006
|
-
/**
|
|
1007
|
-
* Optional debug-trace accumulator for this turn (Phase 1, chat_agent only).
|
|
1008
|
-
* When present, MainAgent-scope retrieval call sites (e.g. preResolveSchema)
|
|
1009
|
-
* push their structured results into it. Absent for callers that don't care
|
|
1010
|
-
* about trace capture (e.g. headless flows) — every push site must treat
|
|
1011
|
-
* this as optional and never let a capture failure affect the real answer.
|
|
1012
|
-
*/
|
|
1013
|
-
trace?: RunTrace;
|
|
1014
|
-
}
|
|
1015
|
-
/**
|
|
1016
|
-
* Default agent configuration
|
|
1017
|
-
*/
|
|
1018
|
-
declare const DEFAULT_AGENT_CONFIG: AgentConfig;
|
|
1019
|
-
|
|
1020
4
|
/**
|
|
1021
5
|
* Unified UIBlock structure for database storage
|
|
1022
|
-
* Used in both bookmarks and user-conversations tables
|
|
1023
|
-
*
|
|
1024
|
-
* `analysis` always holds whatever real narration exists — the full answer on
|
|
1025
|
-
* success, or whatever was actually streamed before a failure (may be empty).
|
|
1026
|
-
* `error` is a dedicated field, null on success — it can be a plain string OR
|
|
1027
|
-
* a structured object/array (e.g. the agent's raw `errors` list), whatever
|
|
1028
|
-
* shape the failure naturally has; it's never coerced into `analysis`.
|
|
6
|
+
* Used in both bookmarks and user-conversations tables
|
|
1029
7
|
*/
|
|
1030
8
|
interface DBUIBlock {
|
|
1031
9
|
id: string;
|
|
1032
10
|
component: Record<string, any> | null;
|
|
1033
11
|
analysis: string | null;
|
|
1034
12
|
user_prompt: string;
|
|
1035
|
-
error?: unknown | null;
|
|
1036
|
-
/**
|
|
1037
|
-
* The script recipe that produced this answer, when one did. Read back via
|
|
1038
|
-
* `conversation-history.exactMatch` so an edit follow-up still has a target
|
|
1039
|
-
* after a reload (the in-memory thread is gone by then), and indexed so
|
|
1040
|
-
* committing an edit can purge every cached answer bound to the recipe.
|
|
1041
|
-
*/
|
|
1042
|
-
scriptBinding?: {
|
|
1043
|
-
recipeId: string;
|
|
1044
|
-
params?: Record<string, any>;
|
|
1045
|
-
name?: string;
|
|
1046
|
-
columns?: string[];
|
|
1047
|
-
};
|
|
1048
13
|
}
|
|
1049
14
|
|
|
1050
15
|
/**
|
|
@@ -1195,7 +160,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
1195
160
|
dependencies?: string[] | undefined;
|
|
1196
161
|
} | undefined;
|
|
1197
162
|
props?: Record<string, any> | undefined;
|
|
1198
|
-
data?: Record<string, any> | undefined;
|
|
1199
163
|
render?: any;
|
|
1200
164
|
states?: Record<string, any> | undefined;
|
|
1201
165
|
methods?: Record<string, {
|
|
@@ -1206,6 +170,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
1206
170
|
fn: string;
|
|
1207
171
|
deps?: string[] | undefined;
|
|
1208
172
|
}[] | undefined;
|
|
173
|
+
data?: Record<string, any> | undefined;
|
|
1209
174
|
pages?: {
|
|
1210
175
|
id: string;
|
|
1211
176
|
name: string;
|
|
@@ -1227,7 +192,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
1227
192
|
dependencies?: string[] | undefined;
|
|
1228
193
|
} | undefined;
|
|
1229
194
|
props?: Record<string, any> | undefined;
|
|
1230
|
-
data?: Record<string, any> | undefined;
|
|
1231
195
|
render?: any;
|
|
1232
196
|
states?: Record<string, any> | undefined;
|
|
1233
197
|
methods?: Record<string, {
|
|
@@ -1238,6 +202,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
1238
202
|
fn: string;
|
|
1239
203
|
deps?: string[] | undefined;
|
|
1240
204
|
}[] | undefined;
|
|
205
|
+
data?: Record<string, any> | undefined;
|
|
1241
206
|
pages?: {
|
|
1242
207
|
id: string;
|
|
1243
208
|
name: string;
|
|
@@ -1263,7 +228,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
1263
228
|
dependencies?: string[] | undefined;
|
|
1264
229
|
} | undefined;
|
|
1265
230
|
props?: Record<string, any> | undefined;
|
|
1266
|
-
data?: Record<string, any> | undefined;
|
|
1267
231
|
render?: any;
|
|
1268
232
|
states?: Record<string, any> | undefined;
|
|
1269
233
|
methods?: Record<string, {
|
|
@@ -1274,6 +238,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
1274
238
|
fn: string;
|
|
1275
239
|
deps?: string[] | undefined;
|
|
1276
240
|
}[] | undefined;
|
|
241
|
+
data?: Record<string, any> | undefined;
|
|
1277
242
|
pages?: {
|
|
1278
243
|
id: string;
|
|
1279
244
|
name: string;
|
|
@@ -1299,7 +264,6 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
1299
264
|
dependencies?: string[] | undefined;
|
|
1300
265
|
} | undefined;
|
|
1301
266
|
props?: Record<string, any> | undefined;
|
|
1302
|
-
data?: Record<string, any> | undefined;
|
|
1303
267
|
render?: any;
|
|
1304
268
|
states?: Record<string, any> | undefined;
|
|
1305
269
|
methods?: Record<string, {
|
|
@@ -1310,6 +274,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
1310
274
|
fn: string;
|
|
1311
275
|
deps?: string[] | undefined;
|
|
1312
276
|
}[] | undefined;
|
|
277
|
+
data?: Record<string, any> | undefined;
|
|
1313
278
|
pages?: {
|
|
1314
279
|
id: string;
|
|
1315
280
|
name: string;
|
|
@@ -1390,7 +355,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
1390
355
|
dependencies?: string[] | undefined;
|
|
1391
356
|
} | undefined;
|
|
1392
357
|
props?: Record<string, any> | undefined;
|
|
1393
|
-
data?: Record<string, any> | undefined;
|
|
1394
358
|
render?: any;
|
|
1395
359
|
states?: Record<string, any> | undefined;
|
|
1396
360
|
methods?: Record<string, {
|
|
@@ -1401,6 +365,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
1401
365
|
fn: string;
|
|
1402
366
|
deps?: string[] | undefined;
|
|
1403
367
|
}[] | undefined;
|
|
368
|
+
data?: Record<string, any> | undefined;
|
|
1404
369
|
}, {
|
|
1405
370
|
id: string;
|
|
1406
371
|
name?: string | undefined;
|
|
@@ -1414,7 +379,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
1414
379
|
dependencies?: string[] | undefined;
|
|
1415
380
|
} | undefined;
|
|
1416
381
|
props?: Record<string, any> | undefined;
|
|
1417
|
-
data?: Record<string, any> | undefined;
|
|
1418
382
|
render?: any;
|
|
1419
383
|
states?: Record<string, any> | undefined;
|
|
1420
384
|
methods?: Record<string, {
|
|
@@ -1425,6 +389,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
1425
389
|
fn: string;
|
|
1426
390
|
deps?: string[] | undefined;
|
|
1427
391
|
}[] | undefined;
|
|
392
|
+
data?: Record<string, any> | undefined;
|
|
1428
393
|
}>;
|
|
1429
394
|
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
1430
395
|
context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
@@ -1442,7 +407,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
1442
407
|
dependencies?: string[] | undefined;
|
|
1443
408
|
} | undefined;
|
|
1444
409
|
props?: Record<string, any> | undefined;
|
|
1445
|
-
data?: Record<string, any> | undefined;
|
|
1446
410
|
render?: any;
|
|
1447
411
|
states?: Record<string, any> | undefined;
|
|
1448
412
|
methods?: Record<string, {
|
|
@@ -1453,6 +417,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
1453
417
|
fn: string;
|
|
1454
418
|
deps?: string[] | undefined;
|
|
1455
419
|
}[] | undefined;
|
|
420
|
+
data?: Record<string, any> | undefined;
|
|
1456
421
|
};
|
|
1457
422
|
data?: Record<string, any> | undefined;
|
|
1458
423
|
context?: Record<string, any> | undefined;
|
|
@@ -1470,7 +435,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
1470
435
|
dependencies?: string[] | undefined;
|
|
1471
436
|
} | undefined;
|
|
1472
437
|
props?: Record<string, any> | undefined;
|
|
1473
|
-
data?: Record<string, any> | undefined;
|
|
1474
438
|
render?: any;
|
|
1475
439
|
states?: Record<string, any> | undefined;
|
|
1476
440
|
methods?: Record<string, {
|
|
@@ -1481,6 +445,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
1481
445
|
fn: string;
|
|
1482
446
|
deps?: string[] | undefined;
|
|
1483
447
|
}[] | undefined;
|
|
448
|
+
data?: Record<string, any> | undefined;
|
|
1484
449
|
};
|
|
1485
450
|
data?: Record<string, any> | undefined;
|
|
1486
451
|
context?: Record<string, any> | undefined;
|
|
@@ -1896,10 +861,6 @@ interface SuperatomSDKConfig {
|
|
|
1896
861
|
bundleDir?: string;
|
|
1897
862
|
promptsDir?: string;
|
|
1898
863
|
databaseType?: DatabaseType;
|
|
1899
|
-
/** BCP-47 locale for `fmt` in generated analyses, e.g. 'en-IN', 'en-US'. Defaults to 'en-IN'. */
|
|
1900
|
-
locale?: string;
|
|
1901
|
-
/** ISO-4217 currency for `fmt`, e.g. 'INR', 'USD'. Defaults to 'INR'. */
|
|
1902
|
-
currency?: string;
|
|
1903
864
|
ANTHROPIC_API_KEY?: string;
|
|
1904
865
|
GROQ_API_KEY?: string;
|
|
1905
866
|
GEMINI_API_KEY?: string;
|
|
@@ -2047,7 +1008,7 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
|
|
|
2047
1008
|
content?: string | undefined;
|
|
2048
1009
|
}>>;
|
|
2049
1010
|
}, "strip", z.ZodTypeAny, {
|
|
2050
|
-
operation: "create" | "getOne" | "
|
|
1011
|
+
operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
|
|
2051
1012
|
data?: {
|
|
2052
1013
|
id?: number | undefined;
|
|
2053
1014
|
type?: "query" | "user" | "global" | undefined;
|
|
@@ -2070,7 +1031,7 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
|
|
|
2070
1031
|
content?: string | undefined;
|
|
2071
1032
|
} | undefined;
|
|
2072
1033
|
}, {
|
|
2073
|
-
operation: "create" | "getOne" | "
|
|
1034
|
+
operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
|
|
2074
1035
|
data?: {
|
|
2075
1036
|
id?: number | undefined;
|
|
2076
1037
|
type?: "query" | "user" | "global" | undefined;
|
|
@@ -2341,347 +1302,292 @@ declare class ReportManager {
|
|
|
2341
1302
|
*/
|
|
2342
1303
|
updateReport(reportId: string, report: DSLRendererProps): DSLRendererProps | null;
|
|
2343
1304
|
/**
|
|
2344
|
-
* Delete a report
|
|
2345
|
-
* @param reportId - Report ID
|
|
2346
|
-
* @returns True if deleted, false if not found
|
|
1305
|
+
* Delete a report
|
|
1306
|
+
* @param reportId - Report ID
|
|
1307
|
+
* @returns True if deleted, false if not found
|
|
1308
|
+
*/
|
|
1309
|
+
deleteReport(reportId: string): boolean;
|
|
1310
|
+
/**
|
|
1311
|
+
* Check if a report exists
|
|
1312
|
+
* @param reportId - Report ID
|
|
1313
|
+
* @returns True if report exists, false otherwise
|
|
1314
|
+
*/
|
|
1315
|
+
reportExists(reportId: string): boolean;
|
|
1316
|
+
/**
|
|
1317
|
+
* Get report count
|
|
1318
|
+
* @returns Number of reports
|
|
1319
|
+
*/
|
|
1320
|
+
getReportCount(): number;
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
/**
|
|
1324
|
+
* StreamBuffer - Buffered streaming utility for smoother text delivery
|
|
1325
|
+
* Batches small chunks together and flushes at regular intervals
|
|
1326
|
+
*/
|
|
1327
|
+
type StreamCallback = (chunk: string) => void;
|
|
1328
|
+
/**
|
|
1329
|
+
* StreamBuffer class for managing buffered streaming output
|
|
1330
|
+
* Provides smooth text delivery by batching small chunks
|
|
1331
|
+
*/
|
|
1332
|
+
declare class StreamBuffer {
|
|
1333
|
+
private buffer;
|
|
1334
|
+
private flushTimer;
|
|
1335
|
+
private callback;
|
|
1336
|
+
private fullText;
|
|
1337
|
+
constructor(callback?: StreamCallback);
|
|
1338
|
+
/**
|
|
1339
|
+
* Check if the buffer has a callback configured
|
|
1340
|
+
*/
|
|
1341
|
+
hasCallback(): boolean;
|
|
1342
|
+
/**
|
|
1343
|
+
* Get all text that has been written (including already flushed)
|
|
1344
|
+
*/
|
|
1345
|
+
getFullText(): string;
|
|
1346
|
+
/**
|
|
1347
|
+
* Write a chunk to the buffer
|
|
1348
|
+
* Large chunks or chunks with newlines are flushed immediately
|
|
1349
|
+
* Small chunks are batched and flushed after a short interval
|
|
1350
|
+
*
|
|
1351
|
+
* @param chunk - Text chunk to write
|
|
1352
|
+
*/
|
|
1353
|
+
write(chunk: string): void;
|
|
1354
|
+
/**
|
|
1355
|
+
* Flush the buffer immediately
|
|
1356
|
+
* Call this before tool execution or other operations that need clean output
|
|
1357
|
+
*/
|
|
1358
|
+
flush(): void;
|
|
1359
|
+
/**
|
|
1360
|
+
* Internal flush implementation
|
|
1361
|
+
*/
|
|
1362
|
+
private flushNow;
|
|
1363
|
+
/**
|
|
1364
|
+
* Clean up resources
|
|
1365
|
+
* Call this when done with the buffer
|
|
1366
|
+
*/
|
|
1367
|
+
dispose(): void;
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
/**
|
|
1371
|
+
* ToolExecutorService - Handles execution of SQL queries and external tools
|
|
1372
|
+
* Extracted from BaseLLM.generateTextResponse for better separation of concerns
|
|
1373
|
+
*/
|
|
1374
|
+
|
|
1375
|
+
/**
|
|
1376
|
+
* External tool definition
|
|
1377
|
+
*/
|
|
1378
|
+
interface ExternalTool {
|
|
1379
|
+
id: string;
|
|
1380
|
+
name: string;
|
|
1381
|
+
description?: string;
|
|
1382
|
+
/** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
|
|
1383
|
+
toolType?: 'source' | 'direct';
|
|
1384
|
+
/** Full untruncated schema for source agent (all columns visible) */
|
|
1385
|
+
fullSchema?: string;
|
|
1386
|
+
/** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
|
|
1387
|
+
schemaTier?: string;
|
|
1388
|
+
/** Schema search function for very_large tier — keyword search over entities */
|
|
1389
|
+
schemaSearchFn?: (keywords: string[]) => string;
|
|
1390
|
+
fn: (input: any) => Promise<any>;
|
|
1391
|
+
limit?: number;
|
|
1392
|
+
outputSchema?: any;
|
|
1393
|
+
executionType?: 'immediate' | 'deferred';
|
|
1394
|
+
userProvidedData?: any;
|
|
1395
|
+
params?: Record<string, any>;
|
|
1396
|
+
}
|
|
1397
|
+
/**
|
|
1398
|
+
* Executed tool tracking info
|
|
1399
|
+
*/
|
|
1400
|
+
interface ExecutedToolInfo {
|
|
1401
|
+
id: string;
|
|
1402
|
+
name: string;
|
|
1403
|
+
params: any;
|
|
1404
|
+
result: {
|
|
1405
|
+
_totalRecords: number;
|
|
1406
|
+
_recordsShown: number;
|
|
1407
|
+
_metadata?: any;
|
|
1408
|
+
_sampleData: any[];
|
|
1409
|
+
};
|
|
1410
|
+
outputSchema?: any;
|
|
1411
|
+
sourceSchema?: string;
|
|
1412
|
+
sourceType?: string;
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
/**
|
|
1416
|
+
* Multi-Agent Architecture Types
|
|
1417
|
+
*
|
|
1418
|
+
* Defines interfaces for the hierarchical agent system:
|
|
1419
|
+
* - Main Agent: ONE LLM.streamWithTools() call with source agent tools
|
|
1420
|
+
* - Source Agents: independent agents that query individual data sources
|
|
1421
|
+
*
|
|
1422
|
+
* The main agent sees only source summaries. When it calls a source tool,
|
|
1423
|
+
* the SourceAgent runs independently (own LLM, own retries) and returns clean data.
|
|
1424
|
+
*/
|
|
1425
|
+
|
|
1426
|
+
/**
|
|
1427
|
+
* Per-entity detail: name, row count, and column names.
|
|
1428
|
+
* Gives the main agent enough context to route to the right source.
|
|
1429
|
+
*/
|
|
1430
|
+
interface EntityDetail {
|
|
1431
|
+
/** Entity name (table, sheet, endpoint) */
|
|
1432
|
+
name: string;
|
|
1433
|
+
/** Approximate row count */
|
|
1434
|
+
rowCount?: number;
|
|
1435
|
+
/** Column/field names */
|
|
1436
|
+
columns: string[];
|
|
1437
|
+
}
|
|
1438
|
+
/**
|
|
1439
|
+
* Representation of a data source for the main agent.
|
|
1440
|
+
* Contains entity names WITH column names so the LLM can route accurately.
|
|
1441
|
+
*/
|
|
1442
|
+
interface SourceSummary {
|
|
1443
|
+
/** Source ID (matches tool ID prefix) */
|
|
1444
|
+
id: string;
|
|
1445
|
+
/** Human-readable source name */
|
|
1446
|
+
name: string;
|
|
1447
|
+
/** Source type: postgres, excel, rest_api, etc. */
|
|
1448
|
+
type: string;
|
|
1449
|
+
/** Brief description of what data this source contains */
|
|
1450
|
+
description: string;
|
|
1451
|
+
/** Detailed entity info with column names for routing */
|
|
1452
|
+
entityDetails: EntityDetail[];
|
|
1453
|
+
/** The tool ID associated with this source */
|
|
1454
|
+
toolId: string;
|
|
1455
|
+
}
|
|
1456
|
+
/**
|
|
1457
|
+
* What a source agent returns after querying its data source.
|
|
1458
|
+
* The main agent uses this to analyze and compose the final response.
|
|
1459
|
+
*/
|
|
1460
|
+
interface SourceAgentResult {
|
|
1461
|
+
/** Source ID */
|
|
1462
|
+
sourceId: string;
|
|
1463
|
+
/** Source name */
|
|
1464
|
+
sourceName: string;
|
|
1465
|
+
/** Whether the query succeeded */
|
|
1466
|
+
success: boolean;
|
|
1467
|
+
/** Result data rows */
|
|
1468
|
+
data: any[];
|
|
1469
|
+
/** Metadata about the query execution */
|
|
1470
|
+
metadata: SourceAgentMetadata;
|
|
1471
|
+
/** Tool execution info for the last successful query (backward compat) */
|
|
1472
|
+
executedTool: ExecutedToolInfo;
|
|
1473
|
+
/** All successful tool executions (primary + follow-up queries) */
|
|
1474
|
+
allExecutedTools?: ExecutedToolInfo[];
|
|
1475
|
+
/** Error message if failed */
|
|
1476
|
+
error?: string;
|
|
1477
|
+
}
|
|
1478
|
+
interface SourceAgentMetadata {
|
|
1479
|
+
/** Total rows that matched the query (before limit) */
|
|
1480
|
+
totalRowsMatched: number;
|
|
1481
|
+
/** Rows actually returned (after limit) */
|
|
1482
|
+
rowsReturned: number;
|
|
1483
|
+
/** Whether the result was truncated by the row limit */
|
|
1484
|
+
isLimited: boolean;
|
|
1485
|
+
/** The query/params that were executed */
|
|
1486
|
+
queryExecuted?: string;
|
|
1487
|
+
/** Execution time in milliseconds */
|
|
1488
|
+
executionTimeMs: number;
|
|
1489
|
+
}
|
|
1490
|
+
/**
|
|
1491
|
+
* A pre-built, multi-step UI flow registered with the SDK.
|
|
1492
|
+
*
|
|
1493
|
+
* When the main agent decides a user's question matches a workflow's whenToUse
|
|
1494
|
+
* trigger, it picks the workflow instead of running source agents / generating
|
|
1495
|
+
* dashboard components. The LLM extracts the workflow's required props from the
|
|
1496
|
+
* prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
|
|
1497
|
+
* workflow component directly — no analysis text, no chart generation. The
|
|
1498
|
+
* frontend renders the registered workflow component with the LLM-extracted
|
|
1499
|
+
* props.
|
|
1500
|
+
*/
|
|
1501
|
+
interface WorkflowDescriptor {
|
|
1502
|
+
/** Unique workflow id (used as the LLM tool name) */
|
|
1503
|
+
id: string;
|
|
1504
|
+
/** Component name on the frontend (matches the registered React component) */
|
|
1505
|
+
name: string;
|
|
1506
|
+
/** Short human-readable description of what this workflow does */
|
|
1507
|
+
description: string;
|
|
1508
|
+
/**
|
|
1509
|
+
* 1–2 sentence trigger condition. The LLM uses this to decide if the
|
|
1510
|
+
* user's prompt matches this workflow. Be specific — e.g.
|
|
1511
|
+
* "User wants to *initiate* an inventory transfer (review + submit POs),
|
|
1512
|
+
* not just see analysis or charts."
|
|
2347
1513
|
*/
|
|
2348
|
-
|
|
1514
|
+
whenToUse: string;
|
|
2349
1515
|
/**
|
|
2350
|
-
*
|
|
2351
|
-
*
|
|
2352
|
-
*
|
|
1516
|
+
* JSON-schema-style description of the props the workflow needs. Becomes
|
|
1517
|
+
* the LLM tool's input_schema, so the model fills these from the prompt.
|
|
1518
|
+
* Use the same shape as `params` on direct tools — string descriptors with
|
|
1519
|
+
* an optional "(optional)" suffix.
|
|
1520
|
+
*
|
|
1521
|
+
* Example:
|
|
1522
|
+
* ```
|
|
1523
|
+
* {
|
|
1524
|
+
* selectedStore: 'object — { id, name } of the source branch',
|
|
1525
|
+
* minROI: 'number (optional) — only show transfers with ROI ≥ this',
|
|
1526
|
+
* }
|
|
1527
|
+
* ```
|
|
2353
1528
|
*/
|
|
2354
|
-
|
|
1529
|
+
propsSchema: Record<string, string>;
|
|
2355
1530
|
/**
|
|
2356
|
-
*
|
|
2357
|
-
*
|
|
1531
|
+
* Optional: static prop defaults merged with LLM-extracted props before
|
|
1532
|
+
* the component is returned. Useful for things like the embedded
|
|
1533
|
+
* `externalTool` config that the workflow uses to fetch its own data.
|
|
2358
1534
|
*/
|
|
2359
|
-
|
|
1535
|
+
defaultProps?: Record<string, any>;
|
|
2360
1536
|
}
|
|
2361
|
-
|
|
2362
1537
|
/**
|
|
2363
|
-
*
|
|
2364
|
-
*
|
|
2365
|
-
* The SDK is standalone (no DB dependency). The backend implements this
|
|
2366
|
-
* interface over Postgres (full-text search + atomic counters) and injects it
|
|
2367
|
-
* via `collections['script-recipes']`, exactly like `collections['source-embeddings']`.
|
|
2368
|
-
* `ScriptStore` consumes it for all METADATA operations while keeping the
|
|
2369
|
-
* executable body on disk as scripts-store/<fileBase>.ts.
|
|
2370
|
-
*
|
|
2371
|
-
* All metadata rows are plain JSON (no scriptBody — that lives on disk).
|
|
2372
|
-
* See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md (#1, #3, #7).
|
|
1538
|
+
* The workflow selection captured during a routing call.
|
|
1539
|
+
* Set on AgentResponse when the LLM picks a workflow tool.
|
|
2373
1540
|
*/
|
|
2374
|
-
|
|
2375
|
-
/**
|
|
2376
|
-
interface ScriptRecipeMetaRow {
|
|
2377
|
-
id: string;
|
|
2378
|
-
projectId?: string | null;
|
|
2379
|
-
version: number;
|
|
1541
|
+
interface SelectedWorkflow {
|
|
1542
|
+
/** Component name (matches WorkflowDescriptor.name) */
|
|
2380
1543
|
name: string;
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
createdFrom: string | null;
|
|
2384
|
-
sourceIds: string[] | null;
|
|
2385
|
-
tables: string[] | null;
|
|
2386
|
-
parameters: ScriptParameter[] | null;
|
|
2387
|
-
components?: ScriptComponentSpec[] | null;
|
|
2388
|
-
displayPreference?: ScriptDisplayPreference | null;
|
|
2389
|
-
fileBase: string;
|
|
2390
|
-
bodyHash?: string | null;
|
|
2391
|
-
successCount: number;
|
|
2392
|
-
failureCount: number;
|
|
2393
|
-
lastUsed: string | null;
|
|
2394
|
-
parentId?: string | null;
|
|
2395
|
-
forkDepth?: number | null;
|
|
2396
|
-
forkReason?: string | null;
|
|
2397
|
-
status: 'draft' | 'verified' | string;
|
|
2398
|
-
turnId?: string | null;
|
|
2399
|
-
editedBy?: string | null;
|
|
2400
|
-
editedFrom?: string | null;
|
|
2401
|
-
history?: ScriptVersionRecord[] | null;
|
|
2402
|
-
lastError?: {
|
|
2403
|
-
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
2404
|
-
message: string;
|
|
2405
|
-
at: string;
|
|
2406
|
-
attempt: number;
|
|
2407
|
-
} | null;
|
|
2408
|
-
createdAt?: string | null;
|
|
2409
|
-
updatedAt?: string | null;
|
|
2410
|
-
}
|
|
2411
|
-
interface ScriptRecipeStore {
|
|
2412
|
-
/** FTS shortlist of healthy verified recipes for the matcher (metadata only). */
|
|
2413
|
-
search(params: {
|
|
2414
|
-
prompt: string;
|
|
2415
|
-
projectId?: string;
|
|
2416
|
-
limit?: number;
|
|
2417
|
-
}): Promise<ScriptRecipeMetaRow[]>;
|
|
2418
|
-
/** Fetch one recipe by id (any status). */
|
|
2419
|
-
getById(id: string): Promise<ScriptRecipeMetaRow | null>;
|
|
2420
|
-
/** Count healthy verified recipes (drives the "any scripts?" gate). */
|
|
2421
|
-
count(params?: {
|
|
2422
|
-
projectId?: string;
|
|
2423
|
-
}): Promise<number>;
|
|
2424
|
-
/** Insert or update a recipe row (keyed by id). */
|
|
2425
|
-
upsert(row: ScriptRecipeMetaRow): Promise<void>;
|
|
2426
|
-
/** Atomically bump counters / last-used. */
|
|
2427
|
-
updateStats(id: string, patch: {
|
|
2428
|
-
successDelta?: number;
|
|
2429
|
-
failureDelta?: number;
|
|
2430
|
-
lastUsed?: string;
|
|
2431
|
-
}): Promise<void>;
|
|
2432
|
-
/** Flip a draft to verified, applying provenance + optional fork lineage. */
|
|
2433
|
-
promote(id: string, patch: {
|
|
2434
|
-
sourceIds: string[];
|
|
2435
|
-
tables: string[];
|
|
2436
|
-
fileBase?: string;
|
|
2437
|
-
parentId?: string;
|
|
2438
|
-
forkDepth?: number;
|
|
2439
|
-
forkReason?: string;
|
|
2440
|
-
components?: ScriptComponentSpec[];
|
|
2441
|
-
}): Promise<ScriptRecipeMetaRow | null>;
|
|
2442
|
-
/**
|
|
2443
|
-
* Commit a verified edit onto an EXISTING recipe: bump `version`, replace the
|
|
2444
|
-
* body-bearing metadata, append a history record, reset health counters, and
|
|
2445
|
-
* clear the component specs (they were validated against the old shape).
|
|
2446
|
-
* Returns the updated row, or null when the target is gone.
|
|
2447
|
-
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5.
|
|
2448
|
-
*/
|
|
2449
|
-
commitEdit?(id: string, patch: {
|
|
2450
|
-
name?: string;
|
|
2451
|
-
intentDescription?: string;
|
|
2452
|
-
tags?: string[];
|
|
2453
|
-
parameters?: ScriptParameter[];
|
|
2454
|
-
bodyHash: string;
|
|
2455
|
-
/** New on-disk stem when the edit renamed the script; omitted otherwise. */
|
|
2456
|
-
fileBase?: string;
|
|
2457
|
-
sourceIds?: string[];
|
|
2458
|
-
tables?: string[];
|
|
2459
|
-
editedBy?: string;
|
|
2460
|
-
editedFrom?: string;
|
|
2461
|
-
historyEntry: {
|
|
2462
|
-
version: number;
|
|
2463
|
-
at: string;
|
|
2464
|
-
by?: string;
|
|
2465
|
-
instruction?: string;
|
|
2466
|
-
changeSummary?: string;
|
|
2467
|
-
bodyHash?: string;
|
|
2468
|
-
};
|
|
2469
|
-
}): Promise<ScriptRecipeMetaRow | null>;
|
|
2470
|
-
/** Stamp a draft's last execution error. */
|
|
2471
|
-
recordDraftError(id: string, err: {
|
|
2472
|
-
phase: string;
|
|
2473
|
-
message: string;
|
|
2474
|
-
attempt: number;
|
|
2475
|
-
at: string;
|
|
2476
|
-
}): Promise<void>;
|
|
2477
|
-
/** Delete a recipe row (body file removed separately). */
|
|
2478
|
-
remove(id: string): Promise<void>;
|
|
2479
|
-
/** True if `fileBase` is taken by a different recipe in this project. */
|
|
2480
|
-
fileBaseTaken(fileBase: string, excludeId: string, projectId?: string): Promise<boolean>;
|
|
1544
|
+
/** Props extracted from the prompt + merged with workflow.defaultProps */
|
|
1545
|
+
props: Record<string, any>;
|
|
2481
1546
|
}
|
|
2482
|
-
/** Pull the injected store off the collections bag (or null if not wired). */
|
|
2483
|
-
declare function resolveScriptRecipeStore(collections: any): ScriptRecipeStore | null;
|
|
2484
|
-
|
|
2485
1547
|
/**
|
|
2486
|
-
*
|
|
2487
|
-
*
|
|
2488
|
-
* Split of responsibilities:
|
|
2489
|
-
* - METADATA → injected `ScriptRecipeStore` (Postgres FTS + atomic counters),
|
|
2490
|
-
* resolved from `collections['script-recipes']`.
|
|
2491
|
-
* - BODY → scripts-store/<fileBase>.ts, editable in your IDE. Written
|
|
2492
|
-
* atomically (temp + rename); `bodyHash` (sha256) detects edits.
|
|
2493
|
-
*
|
|
2494
|
-
* The old "read every file every turn + send the whole catalog to the LLM"
|
|
2495
|
-
* matcher is gone — matching is `store.search(prompt)` (FTS shortlist). The
|
|
2496
|
-
* draft/verified filename dance is gone too: `status` is a DB column and the
|
|
2497
|
-
* file keeps a stable `<fileBase>.ts` name across promotion.
|
|
2498
|
-
*
|
|
2499
|
-
* When no metadata store is injected, the store degrades to a safe no-op
|
|
2500
|
-
* (count 0 → script flow disabled) instead of crashing.
|
|
2501
|
-
*
|
|
2502
|
-
* See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md.
|
|
1548
|
+
* The complete response from the multi-agent system.
|
|
1549
|
+
* Contains everything needed for text display + component generation.
|
|
2503
1550
|
*/
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
intentDescription: string;
|
|
2512
|
-
tags: string[];
|
|
2513
|
-
parameters: ScriptParameter[];
|
|
2514
|
-
scriptBody: string;
|
|
2515
|
-
createdFrom: string;
|
|
2516
|
-
/**
|
|
2517
|
-
* Set when this draft is a SHADOW of an existing recipe being edited. The
|
|
2518
|
-
* draft is verified independently and merged back onto the parent via
|
|
2519
|
-
* `commitEdit`, so the working script is never clobbered by an edit that
|
|
2520
|
-
* turns out not to run. See backend/docs/SCRIPT-EDIT-DESIGN.md § D5.
|
|
2521
|
-
*/
|
|
2522
|
-
parentId?: string;
|
|
2523
|
-
}
|
|
2524
|
-
interface PromoteToVerifiedInput {
|
|
2525
|
-
sourceIds: string[];
|
|
2526
|
-
tables: string[];
|
|
2527
|
-
parentId?: string;
|
|
2528
|
-
forkDepth?: number;
|
|
2529
|
-
forkReason?: string;
|
|
2530
|
-
components?: ScriptComponentSpec[];
|
|
2531
|
-
}
|
|
2532
|
-
interface ScriptStoreOptions {
|
|
2533
|
-
/** Explicit metadata store, or resolved from `collections['script-recipes']`. */
|
|
2534
|
-
store?: ScriptRecipeStore | null;
|
|
2535
|
-
collections?: any;
|
|
2536
|
-
/** Body directory (defaults to <cwd>/scripts-store). */
|
|
2537
|
-
baseDir?: string;
|
|
2538
|
-
/** Project scope stamped on every row. */
|
|
2539
|
-
projectId?: string;
|
|
2540
|
-
}
|
|
2541
|
-
declare function normalizeScriptBody(scriptBody: string): string;
|
|
2542
|
-
declare class ScriptStore {
|
|
2543
|
-
private store;
|
|
2544
|
-
private storeDir;
|
|
2545
|
-
private projectId?;
|
|
2546
|
-
constructor(opts?: ScriptStoreOptions);
|
|
2547
|
-
/** Whether a metadata store is wired (matcher / authoring are gated on this). */
|
|
2548
|
-
hasStore(): boolean;
|
|
2549
|
-
/** Number of healthy verified recipes (gates the script-matching path). */
|
|
2550
|
-
count(): Promise<number>;
|
|
2551
|
-
/**
|
|
2552
|
-
* FTS shortlist for the matcher (metadata only — bodies are loaded lazily by
|
|
2553
|
-
* `get()` once the LLM picks one). Returns verified, healthy recipes ranked
|
|
2554
|
-
* by relevance.
|
|
2555
|
-
*/
|
|
2556
|
-
search(prompt: string, limit?: number): Promise<ScriptRecipe[]>;
|
|
2557
|
-
/** Fetch one recipe by id with its body loaded from disk. */
|
|
2558
|
-
get(id: string): Promise<ScriptRecipe | null>;
|
|
2559
|
-
/**
|
|
2560
|
-
* Fetch one recipe by id, pinned to a SPECIFIC past version rather than
|
|
2561
|
-
* whatever is live today. Needed to render a past turn's conversation
|
|
2562
|
-
* history accurately after the script has since been edited — get() alone
|
|
2563
|
-
* always returns the CURRENT body, which may no longer be what that turn
|
|
2564
|
-
* actually ran.
|
|
2565
|
-
*
|
|
2566
|
-
* Returns null (never a silently-wrong version) when the requested version
|
|
2567
|
-
* isn't the current one and its archived body can't be found — e.g. the
|
|
2568
|
-
* archive was cleaned up after the whole recipe was later deleted.
|
|
2569
|
-
*/
|
|
2570
|
-
getVersion(id: string, version: number): Promise<ScriptRecipe | null>;
|
|
2571
|
-
/** Create or update a recipe (metadata upsert + body write when changed). */
|
|
2572
|
-
save(recipe: ScriptRecipe): Promise<void>;
|
|
2573
|
-
/**
|
|
2574
|
-
* Persist (or update) a draft. Within a turn, retries that pass the same
|
|
2575
|
-
* `recipeId` overwrite the same row + file; a fresh `recipeId` mints a new
|
|
2576
|
-
* draft. The body is visible at scripts-store/<fileBase>.ts immediately.
|
|
2577
|
-
*/
|
|
2578
|
-
saveDraft(input: SaveDraftInput): Promise<ScriptRecipe>;
|
|
2579
|
-
/** Stamp a draft's last execution error (metadata only). */
|
|
2580
|
-
recordDraftError(recipeId: string, err: {
|
|
2581
|
-
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
2582
|
-
message: string;
|
|
2583
|
-
attempt: number;
|
|
2584
|
-
}): Promise<void>;
|
|
2585
|
-
/**
|
|
2586
|
-
* Promote a successfully-executed draft into a verified script.
|
|
2587
|
-
* The on-disk body already exists at <fileBase>.ts (written at write_script
|
|
2588
|
-
* time) and keeps its name — only the DB row flips status + provenance.
|
|
2589
|
-
*/
|
|
2590
|
-
promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): Promise<ScriptRecipe | null>;
|
|
2591
|
-
/**
|
|
2592
|
-
* Commit a user-directed edit: merge a VERIFIED shadow draft back onto the
|
|
2593
|
-
* recipe it was editing, as version N+1 under the SAME recipe id.
|
|
2594
|
-
*
|
|
2595
|
-
* Keeping the id stable is the point of the whole feature — every cached
|
|
2596
|
-
* conversation, `script_dataset` regeneration descriptor and persisted
|
|
2597
|
-
* component spec already points at it, so the correction applies retroactively
|
|
2598
|
-
* to replays instead of stranding them on the old body.
|
|
2599
|
-
*
|
|
2600
|
-
* Steps (see backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5):
|
|
2601
|
-
* 1. archive the current body as `<fileBase>.v<version>.ts`
|
|
2602
|
-
* 2. write the edited body to the original fileBase (atomic)
|
|
2603
|
-
* 3. version++, copy name/description/params, append a history record
|
|
2604
|
-
* 4. reset health counters — the pre-edit failure history is stale
|
|
2605
|
-
* 5. clear component specs — they were validated against the OLD shape
|
|
2606
|
-
* 6. delete the shadow draft (row + file)
|
|
2607
|
-
*
|
|
2608
|
-
* Returns the updated recipe, or null when the commit could not be applied
|
|
2609
|
-
* (caller should then fall back to treating the draft as a new script).
|
|
2610
|
-
*/
|
|
2611
|
-
commitEdit(targetId: string, draft: {
|
|
2612
|
-
recipeId: string;
|
|
2613
|
-
name?: string;
|
|
2614
|
-
intentDescription?: string;
|
|
2615
|
-
tags?: string[];
|
|
2616
|
-
parameters?: ScriptParameter[];
|
|
2617
|
-
scriptBody: string;
|
|
2618
|
-
sourceIds?: string[];
|
|
2619
|
-
tables?: string[];
|
|
2620
|
-
}, meta: {
|
|
2621
|
-
instruction?: string;
|
|
2622
|
-
changeSummary?: string;
|
|
2623
|
-
editedBy?: string;
|
|
2624
|
-
}): Promise<ScriptRecipe | null>;
|
|
2625
|
-
/**
|
|
2626
|
-
* Drop a draft (row + body file). MainAgent calls this at end-of-turn when a
|
|
2627
|
-
* draft was authored but never verified — failed drafts are never matched, so
|
|
2628
|
-
* deleting them immediately avoids unbounded accumulation (#5). No-op if the
|
|
2629
|
-
* recipe isn't a draft (so a promoted/verified script is never removed here).
|
|
2630
|
-
*/
|
|
2631
|
-
discardDraft(recipeId: string): Promise<void>;
|
|
2632
|
-
/** Delete a recipe (row + body file). */
|
|
2633
|
-
delete(id: string): Promise<void>;
|
|
2634
|
-
/** Record a successful execution (atomic counter bump). */
|
|
2635
|
-
recordSuccess(id: string): Promise<void>;
|
|
2636
|
-
/** Record a failed execution (atomic counter bump). */
|
|
2637
|
-
recordFailure(id: string): Promise<void>;
|
|
2638
|
-
/** Absolute path to the .ts body for a recipe (used by the runner/MainAgent). */
|
|
2639
|
-
getScriptPath(recipe: ScriptRecipe): string;
|
|
2640
|
-
private removeById;
|
|
2641
|
-
private rowToRecipe;
|
|
2642
|
-
private recipeToRow;
|
|
2643
|
-
/** slug of name, with a short id suffix when the bare slug is already taken. */
|
|
2644
|
-
private computeFileBase;
|
|
2645
|
-
private toSlug;
|
|
2646
|
-
private hash;
|
|
2647
|
-
/**
|
|
2648
|
-
* Attach getComponents to the recipe body. The stored `components` column is
|
|
2649
|
-
* cleared at promotion (see promoteToVerified): once the body computes its own
|
|
2650
|
-
* specs, a stale spec array beside a live program is how the wrong one gets
|
|
2651
|
-
* read later. See backend/docs/COMPONENTS-AS-PROGRAM-DESIGN.md § 4.4.
|
|
2652
|
-
*/
|
|
2653
|
-
attachComponents(recipeId: string, componentsBody: string): Promise<boolean>;
|
|
2654
|
-
/**
|
|
2655
|
-
* Append (or replace) the `getAnalysis` export on an existing draft body.
|
|
2656
|
-
*
|
|
2657
|
-
* The narrative is authored AFTER execution, so it lands on a file that
|
|
2658
|
-
* already holds a working getData — rewriting the whole body would risk
|
|
2659
|
-
* losing the query that just succeeded. Replaces any earlier getAnalysis so
|
|
2660
|
-
* a retry does not stack duplicate exports.
|
|
2661
|
-
*/
|
|
2662
|
-
attachAnalysis(recipeId: string, analysisBody: string): Promise<boolean>;
|
|
2663
|
-
private bodyPath;
|
|
2664
|
-
private readBody;
|
|
2665
|
-
/** Directory holding superseded bodies. Dot-prefixed so IDEs/`ls` hide it. */
|
|
2666
|
-
private get archiveDir();
|
|
2667
|
-
/**
|
|
2668
|
-
* Archive a superseded body as `.versions/<fileBase>.v<n>.ts`.
|
|
2669
|
-
*
|
|
2670
|
-
* Kept out of the main store directory on purpose — see commitEdit step 1.
|
|
2671
|
-
* To roll back: copy the file back over `scripts-store/<fileBase>.ts`.
|
|
2672
|
-
*/
|
|
2673
|
-
private writeArchive;
|
|
1551
|
+
interface AgentResponse {
|
|
1552
|
+
/** Generated text response (analysis of the data) */
|
|
1553
|
+
text: string;
|
|
1554
|
+
/** All executed tools across all source agents (for component generation) */
|
|
1555
|
+
executedTools: ExecutedToolInfo[];
|
|
1556
|
+
/** Individual results from each source agent */
|
|
1557
|
+
sourceResults: SourceAgentResult[];
|
|
2674
1558
|
/**
|
|
2675
|
-
*
|
|
2676
|
-
*
|
|
2677
|
-
*
|
|
2678
|
-
* nothing linking them back to the live script.
|
|
1559
|
+
* Set when the LLM routed the question to a registered workflow component.
|
|
1560
|
+
* When present, the upstream caller should skip component generation and
|
|
1561
|
+
* return this workflow as the response.
|
|
2679
1562
|
*/
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
1563
|
+
workflow?: SelectedWorkflow;
|
|
1564
|
+
}
|
|
1565
|
+
/**
|
|
1566
|
+
* Configuration for the multi-agent system.
|
|
1567
|
+
* Controls limits, models, and behavior.
|
|
1568
|
+
*/
|
|
1569
|
+
interface AgentConfig {
|
|
1570
|
+
/** Max rows a source agent can return (default: 50) */
|
|
1571
|
+
maxRowsPerSource: number;
|
|
1572
|
+
/** Model for the main agent (routing + analysis in one LLM call) */
|
|
1573
|
+
mainAgentModel: string;
|
|
1574
|
+
/** Model for source agent query generation */
|
|
1575
|
+
sourceAgentModel: string;
|
|
1576
|
+
/** API key for LLM calls */
|
|
1577
|
+
apiKey?: string;
|
|
1578
|
+
/** Max retry attempts per source agent */
|
|
1579
|
+
maxRetries: number;
|
|
1580
|
+
/** Max tool calling iterations for the main agent loop */
|
|
1581
|
+
maxIterations: number;
|
|
1582
|
+
/** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
|
|
1583
|
+
globalKnowledgeBase?: string;
|
|
1584
|
+
/** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
|
|
1585
|
+
knowledgeBaseContext?: string;
|
|
2684
1586
|
}
|
|
1587
|
+
/**
|
|
1588
|
+
* Default agent configuration
|
|
1589
|
+
*/
|
|
1590
|
+
declare const DEFAULT_AGENT_CONFIG: AgentConfig;
|
|
2685
1591
|
|
|
2686
1592
|
/**
|
|
2687
1593
|
* Main Agent (Orchestrator)
|
|
@@ -2703,85 +1609,7 @@ declare class MainAgent {
|
|
|
2703
1609
|
private workflows;
|
|
2704
1610
|
private config;
|
|
2705
1611
|
private streamBuffer;
|
|
2706
|
-
|
|
2707
|
-
* Optional: when provided, MainAgent exposes the `write_script` /
|
|
2708
|
-
* `execute_script` tools to the LLM and persists drafts to disk via the
|
|
2709
|
-
* store. Headless callers (alert analyzer, metric resolver) omit these to
|
|
2710
|
-
* suppress script authoring entirely — drafts would otherwise leak onto
|
|
2711
|
-
* disk with no caller to promote or clean them up.
|
|
2712
|
-
*/
|
|
2713
|
-
private scriptStore;
|
|
2714
|
-
private turnId;
|
|
2715
|
-
private createdFromPrompt;
|
|
2716
|
-
private scriptState;
|
|
2717
|
-
/** Answer-flow component catalog (filtered + projected by the caller). */
|
|
2718
|
-
private componentCatalog;
|
|
2719
|
-
/** Specs accepted by `write_components` this turn; empty until it succeeds. */
|
|
2720
|
-
/**
|
|
2721
|
-
* Entities resolved this turn, appended verbatim to every source dispatch.
|
|
2722
|
-
*
|
|
2723
|
-
* Not left to the model to copy into its intent prose: observed live, the
|
|
2724
|
-
* MainAgent wrote names instead of ids on the first dispatch AND re-spelled
|
|
2725
|
-
* 'F D C LIMITED' as 'FDC Limited', so the source agent fell back to
|
|
2726
|
-
* `PartyName LIKE '%FDC%'` and found 2 of 3 customers. Carrying the ids
|
|
2727
|
-
* structurally makes that impossible rather than instruction-dependent.
|
|
2728
|
-
*/
|
|
2729
|
-
private resolvedEntities;
|
|
2730
|
-
/**
|
|
2731
|
-
* Concept bodies resolved this turn (via resolve_entities' embedded concept
|
|
2732
|
-
* lookup or a standalone resolve_concepts call) — retained the same way as
|
|
2733
|
-
* resolvedEntities above, so they can be attached to the SourceAgent dispatch.
|
|
2734
|
-
*
|
|
2735
|
-
* Without this, a concept resolved HERE (MainAgent's own tool loop) never
|
|
2736
|
-
* reaches SourceAgent at all: SourceAgent only gets the natural-language
|
|
2737
|
-
* `intent` MainAgent writes, which is a paraphrase, not the concept's
|
|
2738
|
-
* verbatim, authoritative body. Deduped on name so a mid-turn re-resolve
|
|
2739
|
-
* doesn't repeat an already-attached concept.
|
|
2740
|
-
*/
|
|
2741
|
-
private resolvedConcepts;
|
|
2742
|
-
private componentSpecs;
|
|
2743
|
-
private componentLayout;
|
|
2744
|
-
private renderComponentAttempts;
|
|
2745
|
-
/** Same repeated-violation tracking as ScriptState.lastAnalysisViolationTexts, for write_components. */
|
|
2746
|
-
private lastComponentsViolationTexts;
|
|
2747
|
-
/**
|
|
2748
|
-
* Fork mode — set when this turn is adapting a near-matching parent script.
|
|
2749
|
-
* In fork mode there is no legitimate "answer with bare text" outcome: the
|
|
2750
|
-
* only correct first move is a tool call (write_script, or a source tool for
|
|
2751
|
-
* schema discovery). We therefore force tool use on the first LLM iteration
|
|
2752
|
-
* so the model can't end its turn with a bare "I'll adapt…" preamble and zero
|
|
2753
|
-
* tool calls. Never set on the fresh-authoring / general-question path.
|
|
2754
|
-
*/
|
|
2755
|
-
private forkMode;
|
|
2756
|
-
/**
|
|
2757
|
-
* Edit mode — set when this turn applies a user-directed change to an
|
|
2758
|
-
* existing script. Swaps the system prompt to `agent-main-edit` and stamps
|
|
2759
|
-
* the shadow draft's parentId. Like fork mode there is no legitimate
|
|
2760
|
-
* "answer with bare text" outcome, so tool use is forced on iteration 1.
|
|
2761
|
-
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 4.
|
|
2762
|
-
*/
|
|
2763
|
-
private editContext;
|
|
2764
|
-
/** The recipe's durable rendering choice — see the constructor. */
|
|
2765
|
-
private displayPreference;
|
|
2766
|
-
/**
|
|
2767
|
-
* Per-turn cancellation signal (user hit "Stop"). Set at the top of
|
|
2768
|
-
* handleQuestion and read by the tool handler, the SourceAgent dispatch, and
|
|
2769
|
-
* the script subprocess so an abort tears down every layer of the turn.
|
|
2770
|
-
*/
|
|
2771
|
-
private abortSignal?;
|
|
2772
|
-
constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[], forkMode?: boolean, editContext?: EditContext, componentCatalog?: Component[],
|
|
2773
|
-
/**
|
|
2774
|
-
* The recipe's durable rendering choice, when it has one. A DATA edit
|
|
2775
|
-
* re-authors getComponents from scratch, so without this the user's chart
|
|
2776
|
-
* type is silently dropped whenever anyone changes the SQL.
|
|
2777
|
-
*/
|
|
2778
|
-
displayPreference?: {
|
|
2779
|
-
componentTypes: string[];
|
|
2780
|
-
instruction: string;
|
|
2781
|
-
});
|
|
2782
|
-
/** True when the turn is applying a user-directed script edit. */
|
|
2783
|
-
private get editMode();
|
|
2784
|
-
private get scriptingEnabled();
|
|
1612
|
+
constructor(externalTools: ExternalTool[], config: AgentConfig, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[]);
|
|
2785
1613
|
/**
|
|
2786
1614
|
* Handle a user question using the multi-agent system.
|
|
2787
1615
|
*
|
|
@@ -2792,175 +1620,7 @@ declare class MainAgent {
|
|
|
2792
1620
|
* 4. Direct tools → fn() called directly with LLM params → returns data
|
|
2793
1621
|
* 5. Generates final analysis text
|
|
2794
1622
|
*/
|
|
2795
|
-
handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void
|
|
2796
|
-
/**
|
|
2797
|
-
* Tool definition, with the catalog rendered from the registered `Metadata`
|
|
2798
|
-
* the caller passed in. Generated rather than hand-written so it cannot drift
|
|
2799
|
-
* from what the frontend actually ships.
|
|
2800
|
-
*/
|
|
2801
|
-
private buildWriteComponentsToolDef;
|
|
2802
|
-
/**
|
|
2803
|
-
* Validate the agent's component picks against the REAL columns of each bound
|
|
2804
|
-
* dataset. All-or-nothing: any error rejects the whole call and returns the
|
|
2805
|
-
* findings, because a partially-accepted dashboard makes the retry ambiguous.
|
|
2806
|
-
*/
|
|
2807
|
-
private validateSpecs;
|
|
2808
|
-
/**
|
|
2809
|
-
* Author the dashboard as a program. Attaches getComponents to the draft, runs
|
|
2810
|
-
* it over the verified rows, then validates the specs it RETURNED — the program
|
|
2811
|
-
* is never trusted because it is a program, exactly as an authored spec is not.
|
|
2812
|
-
*/
|
|
2813
|
-
private handleWriteComponents;
|
|
2814
|
-
/**
|
|
2815
|
-
* Author the answer as a program. Runs after execute_script, so the body is
|
|
2816
|
-
* written with the result already known and can react to what it found.
|
|
2817
|
-
*
|
|
2818
|
-
* Rejects a body that types numbers rather than computing them — see
|
|
2819
|
-
* analysis-lint. A hardcoded figure is worse than prose: it freezes into the
|
|
2820
|
-
* recipe and replays unchanged while the data moves underneath it.
|
|
2821
|
-
*/
|
|
2822
|
-
private handleWriteAnalysis;
|
|
2823
|
-
private handleWriteScript;
|
|
2824
|
-
private handleExecuteScript;
|
|
2825
|
-
/**
|
|
2826
|
-
* Build the AgentWrittenScript payload the caller will hand to
|
|
2827
|
-
* `ScriptStore.promoteToVerified()`. Only returned when a verified
|
|
2828
|
-
* successful execution is on record.
|
|
2829
|
-
*/
|
|
2830
|
-
private buildSavedScript;
|
|
2831
|
-
private normalizeParameterList;
|
|
2832
|
-
/**
|
|
2833
|
-
* Which declared parameter NAMES never actually appear wired into the
|
|
2834
|
-
* script body — checked as plain text, not a real parser, so it only
|
|
2835
|
-
* catches the worst case (completely unreferenced) rather than every
|
|
2836
|
-
* subtler variant (e.g. used for display text while the SQL itself still
|
|
2837
|
-
* hardcodes the value). That worst case is exactly what's been observed:
|
|
2838
|
-
* a parameter declared purely for show, with the actual filter hardcoded.
|
|
2839
|
-
* Accepts `params.name`, `params['name']`/`params["name"]`, and a
|
|
2840
|
-
* destructuring binding (`const { name } = params`) as valid wiring.
|
|
2841
|
-
*/
|
|
2842
|
-
private findUnwiredParams;
|
|
2843
|
-
/**
|
|
2844
|
-
* Use the schema embedding collection to pre-select relevant tables for
|
|
2845
|
-
* this source + intent. Returns a formatted schema block if confidence is
|
|
2846
|
-
* high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
|
|
2847
|
-
*
|
|
2848
|
-
* When this returns a block, we can skip the SourceAgent's `search_schema`
|
|
2849
|
-
* loop and reduce iteration budget. When it returns null, the SourceAgent
|
|
2850
|
-
* falls back to the existing LLM-driven keyword search (same as today).
|
|
2851
|
-
*/
|
|
2852
|
-
/**
|
|
2853
|
-
* Ids + verbatim names for everything resolved this turn, appended by CODE to
|
|
2854
|
-
* each source dispatch so neither omission nor re-spelling by the model can
|
|
2855
|
-
* lose them. Empty string when nothing was resolved, so intents are untouched
|
|
2856
|
-
* for questions that name no entities.
|
|
2857
|
-
*
|
|
2858
|
-
* Also appends `attrs.scopeSql` when the resolved instance carries one —
|
|
2859
|
-
* same "guaranteed by code" reasoning as the ids/names above, extended to
|
|
2860
|
-
* the one attrs field with a documented, cross-entity-type meaning: a
|
|
2861
|
-
* ready-made SQL predicate an entity's index precomputed (see
|
|
2862
|
-
* ENTITY-SEARCH-DESIGN.md's hierarchy-broadening pattern — branch/region/
|
|
2863
|
-
* state entity types attach it so a lane/route question never needs its
|
|
2864
|
-
* own city-matching join). Confirmed real cost of not doing this: a
|
|
2865
|
-
* branch/state resolved with scopeSql sat unused while the source agent
|
|
2866
|
-
* spent 4 failed exploratory queries rediscovering the exact same
|
|
2867
|
-
* branch-id list by hand (Invalid column name 'StateName'/'CityId'/
|
|
2868
|
-
* 'OrganizationLocationId', in that order, ~144s, before landing on ids
|
|
2869
|
-
* that were sitting in scopeSql from the very first resolve_entities
|
|
2870
|
-
* call). Other attrs (code, counts, etc.) are not dumped here — they are
|
|
2871
|
-
* descriptive, not actionable the way a precomputed predicate is, and
|
|
2872
|
-
* bloating every dispatch with all of them for no clear gain isn't worth
|
|
2873
|
-
* it; scopeSql is the one thing worth this guarantee today.
|
|
2874
|
-
*/
|
|
2875
|
-
private buildResolvedEntitiesBlock;
|
|
2876
|
-
/** Dedupe-and-retain helper shared by resolveConceptsForTurn and handleResolveConcepts. */
|
|
2877
|
-
private retainResolvedConcepts;
|
|
2878
|
-
/**
|
|
2879
|
-
* Same purpose as buildResolvedEntitiesBlock, for concept bodies instead of
|
|
2880
|
-
* entity ids — appended to the dispatch intent so SourceAgent's own,
|
|
2881
|
-
* independent LLM call receives the resolved definitions verbatim rather
|
|
2882
|
-
* than only MainAgent's paraphrased intent text.
|
|
2883
|
-
*/
|
|
2884
|
-
private buildResolvedConceptsBlock;
|
|
2885
|
-
/** True when the backend registered the entity-search collection. */
|
|
2886
|
-
private get entitySearchEnabled();
|
|
2887
|
-
/** True when the backend registered the concepts collection. */
|
|
2888
|
-
private get conceptsEnabled();
|
|
2889
|
-
/**
|
|
2890
|
-
* Concept names for the system prompt. Names ONLY — the body comes back from
|
|
2891
|
-
* resolve_concepts once the LLM has named one, exactly as with the entity
|
|
2892
|
-
* catalog. Putting bodies here would rebuild the always-on context problem
|
|
2893
|
-
* concepts exist to solve.
|
|
2894
|
-
*
|
|
2895
|
-
* Not cached, for the same reason loadEntityCatalog isn't: unchanged rows
|
|
2896
|
-
* render byte-identical text so the prompt-cache prefix still hits, and a
|
|
2897
|
-
* process cache would only buy a window where a new concept is invisible.
|
|
2898
|
-
*/
|
|
2899
|
-
private loadConceptCatalog;
|
|
2900
|
-
/**
|
|
2901
|
-
* The ALWAYS-INJECTED tier: preconditions no question is semantically close
|
|
2902
|
-
* to — date encodings, valid-row filters. These cannot be retrieval-gated.
|
|
2903
|
-
* "What was revenue last quarter?" has no similarity to "dates are DD/MM/YYYY
|
|
2904
|
-
* text", so leaving them to be requested means they are silently dropped and
|
|
2905
|
-
* the answer is confidently wrong rather than visibly missing.
|
|
2906
|
-
*
|
|
2907
|
-
* Bodies ARE included here — unlike the catalog — because there is nothing to
|
|
2908
|
-
* request: being unrequestable is what makes them invariants.
|
|
2909
|
-
*
|
|
2910
|
-
* Also retained into resolvedConcepts (same as an explicit resolve_concepts
|
|
2911
|
-
* call) so these bodies reach SourceAgent's dispatch too — an invariant is
|
|
2912
|
-
* meant to apply everywhere, not just wherever the model happens to ask for
|
|
2913
|
-
* something whose `requires` chain reaches it.
|
|
2914
|
-
*/
|
|
2915
|
-
private loadConceptInvariants;
|
|
2916
|
-
/**
|
|
2917
|
-
* Resolve the concepts for a turn, with a SERVER-SIDE FLOOR.
|
|
2918
|
-
*
|
|
2919
|
-
* Pinning a tool guarantees it is called; it does not guarantee the model
|
|
2920
|
-
* fills in the arguments. Observed: a question containing the exact words
|
|
2921
|
-
* "revenue forecast" produced a call with no concepts at all, and the agent
|
|
2922
|
-
* then used an incomplete copy of the formula from the knowledge base — the
|
|
2923
|
-
* resulting query filtered a customer id against a project column and
|
|
2924
|
-
* returned zero rows on every attempt.
|
|
2925
|
-
*
|
|
2926
|
-
* So when the model names nothing, scan the question itself for catalog names
|
|
2927
|
-
* and aliases on word boundaries. Precise (a literal name is evidence, not a
|
|
2928
|
-
* guess) and asymmetric in the safe direction: an unneeded definition costs a
|
|
2929
|
-
* few hundred ignorable tokens, a missing one costs a wrong answer.
|
|
2930
|
-
*/
|
|
2931
|
-
/**
|
|
2932
|
-
* Returns the tool-facing fields to spread into the resolve_entities JSON
|
|
2933
|
-
* response, PLUS a `_trace` field with everything the trace needs that the
|
|
2934
|
-
* model does not (asked/viaFloor/unmatched). Callers must pull `_trace` out
|
|
2935
|
-
* before spreading the rest into what the model sees — see handleResolveEntities.
|
|
2936
|
-
*/
|
|
2937
|
-
private resolveConceptsForTurn;
|
|
2938
|
-
/**
|
|
2939
|
-
* Never throws: a concept-store outage must degrade to "no definition found"
|
|
2940
|
-
* and leave the agent deriving the formula as it does today, not take the
|
|
2941
|
-
* whole answer down.
|
|
2942
|
-
*/
|
|
2943
|
-
private handleResolveConcepts;
|
|
2944
|
-
/**
|
|
2945
|
-
* Compact catalog (type + gloss) for the system prompt. This is what lets the
|
|
2946
|
-
* LLM NAME a concept instead of guessing at our vocabulary — it can infer
|
|
2947
|
-
* that a question is about unpaid money, but not that we call that
|
|
2948
|
-
* `outstanding-balance`. Full `resolution` detail is fetched by the tool.
|
|
2949
|
-
*
|
|
2950
|
-
* Deliberately NOT cached in-process. The token cost is already handled by
|
|
2951
|
-
* prompt caching (the system prompt carries a cache_control breakpoint), and
|
|
2952
|
-
* re-reading a tiny PK-ordered table costs ~nothing. Fetching fresh does not
|
|
2953
|
-
* weaken the prompt cache either: unchanged data renders byte-identical text,
|
|
2954
|
-
* so the prefix still hits. A process cache would only buy a staleness window
|
|
2955
|
-
* in which a newly indexed entity is invisible to the agent.
|
|
2956
|
-
*/
|
|
2957
|
-
private loadEntityCatalog;
|
|
2958
|
-
/**
|
|
2959
|
-
* Never throws: a resolver outage must degrade to "nothing resolved" and
|
|
2960
|
-
* leave the agent exactly as it was, not take the whole answer down.
|
|
2961
|
-
*/
|
|
2962
|
-
private handleResolveEntities;
|
|
2963
|
-
private preResolveSchema;
|
|
1623
|
+
handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void): Promise<AgentResponse>;
|
|
2964
1624
|
/**
|
|
2965
1625
|
* Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
|
|
2966
1626
|
*/
|
|
@@ -3028,43 +1688,6 @@ interface LLMOptions {
|
|
|
3028
1688
|
apiKey?: string;
|
|
3029
1689
|
baseURL?: string;
|
|
3030
1690
|
partial?: (chunk: string) => void;
|
|
3031
|
-
/**
|
|
3032
|
-
* Per-request cancellation. When the caller aborts this signal (user hit
|
|
3033
|
-
* "Stop"), the underlying provider request is cancelled and the call throws
|
|
3034
|
-
* a RequestAbortedError. Threaded into the provider `messages.create` request
|
|
3035
|
-
* options and checked between tool-loop iterations. Currently honored on the
|
|
3036
|
-
* Anthropic path (the agent flow's default provider).
|
|
3037
|
-
*/
|
|
3038
|
-
signal?: AbortSignal;
|
|
3039
|
-
/**
|
|
3040
|
-
* Forces a tool call on the FIRST iteration of streamWithTools only
|
|
3041
|
-
* (subsequent iterations revert to auto). Used by fork mode to stop the
|
|
3042
|
-
* model from ending its turn with a bare "I'll adapt the script…" preamble
|
|
3043
|
-
* and zero tool calls. `{ type: 'any' }` lets the model pick which tool
|
|
3044
|
-
* (write_script in the common case, a source tool for schema discovery);
|
|
3045
|
-
* `{ type: 'tool', name }` pins a specific tool. Honored on both the
|
|
3046
|
-
* Anthropic path and the OpenAI/OpenRouter path (mapped to OpenAI's
|
|
3047
|
-
* tool_choice: 'required' / a named function).
|
|
3048
|
-
*/
|
|
3049
|
-
firstIterationToolChoice?: {
|
|
3050
|
-
type: 'any';
|
|
3051
|
-
} | {
|
|
3052
|
-
type: 'tool';
|
|
3053
|
-
name: string;
|
|
3054
|
-
};
|
|
3055
|
-
/**
|
|
3056
|
-
* Internal — set only by the OpenRouter wrappers when the target is a Claude
|
|
3057
|
-
* model. Tells the OpenAI-wire path to emit Anthropic `cache_control`
|
|
3058
|
-
* breakpoints (OpenRouter forwards them to Anthropic for prompt caching).
|
|
3059
|
-
* Never set for direct OpenAI/Groq calls, so their requests are unchanged.
|
|
3060
|
-
*/
|
|
3061
|
-
_openrouterClaudeCaching?: boolean;
|
|
3062
|
-
/**
|
|
3063
|
-
* Internal — OpenRouter provider-routing preferences (forwarded as the
|
|
3064
|
-
* `provider` body field). Set by the OpenRouter wrappers to steer routing to
|
|
3065
|
-
* a fast backend (e.g. {sort:'throughput'}). Never set for direct OpenAI/Groq.
|
|
3066
|
-
*/
|
|
3067
|
-
_openrouterProvider?: Record<string, unknown>;
|
|
3068
1691
|
}
|
|
3069
1692
|
interface Tool {
|
|
3070
1693
|
name: string;
|
|
@@ -3117,41 +1740,15 @@ declare class LLM {
|
|
|
3117
1740
|
* (e.g. "claude-sonnet-4.5"). OpenRouter slugs drop the date suffix and use dotted versions.
|
|
3118
1741
|
*/
|
|
3119
1742
|
private static _toOpenRouterSlug;
|
|
3120
|
-
/**
|
|
3121
|
-
* Per-provider proxy base URL. Returns `${SUPERATOM_LLM_PROXY_URL}/<provider>`
|
|
3122
|
-
* when our Cloudflare LLM proxy is configured, else undefined (→ talk to the
|
|
3123
|
-
* provider directly, legacy behaviour). An explicit options.baseURL (e.g.
|
|
3124
|
-
* OpenRouter) always wins and is never overridden. See backend/docs/llm-proxy.md.
|
|
3125
|
-
*/
|
|
3126
|
-
private static _proxyBaseURL;
|
|
3127
1743
|
private static _openrouterOptions;
|
|
3128
|
-
private static _isRetryableProviderError;
|
|
3129
|
-
private static _withOpenrouterRetry;
|
|
3130
1744
|
private static _openrouterText;
|
|
3131
1745
|
private static _openrouterStream;
|
|
3132
1746
|
private static _openrouterStreamWithTools;
|
|
3133
|
-
/**
|
|
3134
|
-
* Build an Anthropic client. Routes through our Cloudflare LLM proxy when
|
|
3135
|
-
* SUPERATOM_LLM_PROXY_URL is set (each client ships a per-client proxy key as
|
|
3136
|
-
* ANTHROPIC_API_KEY and never holds the real key); otherwise talks to
|
|
3137
|
-
* api.anthropic.com directly. See backend/docs/llm-proxy.md.
|
|
3138
|
-
*/
|
|
3139
|
-
private static _anthropicClient;
|
|
3140
|
-
/** True when OpenRouter is configured as a fail-open fallback for Claude. */
|
|
3141
|
-
private static _openrouterAvailable;
|
|
3142
|
-
/** Remap an Anthropic model id to the OpenRouter model path for fail-open. */
|
|
3143
|
-
private static _anthropicFallbackModel;
|
|
3144
1747
|
private static _anthropicText;
|
|
3145
1748
|
private static _anthropicStream;
|
|
3146
1749
|
private static _anthropicStreamWithTools;
|
|
3147
1750
|
private static _groqText;
|
|
3148
1751
|
private static _groqStream;
|
|
3149
|
-
/**
|
|
3150
|
-
* Gemini request options carrying the proxy base URL, or undefined → talk to
|
|
3151
|
-
* generativelanguage.googleapis.com directly. The Google SDK takes baseUrl as a
|
|
3152
|
-
* per-model request option, not a constructor arg. See backend/docs/llm-proxy.md.
|
|
3153
|
-
*/
|
|
3154
|
-
private static _geminiRequestOptions;
|
|
3155
1752
|
private static _geminiText;
|
|
3156
1753
|
private static _geminiStream;
|
|
3157
1754
|
/**
|
|
@@ -3160,28 +1757,8 @@ declare class LLM {
|
|
|
3160
1757
|
*/
|
|
3161
1758
|
private static _cleanSchemaForGemini;
|
|
3162
1759
|
private static _geminiStreamWithTools;
|
|
3163
|
-
/** True for Anthropic/Claude model ids — gates OpenRouter prompt caching. */
|
|
3164
|
-
private static _isClaudeModel;
|
|
3165
|
-
/**
|
|
3166
|
-
* Build the OpenAI-wire system message. For OpenRouter + Claude
|
|
3167
|
-
* (cacheClaude=true) it emits content parts carrying Anthropic
|
|
3168
|
-
* `cache_control` breakpoints (preserving any the caller set, else marking
|
|
3169
|
-
* the last block), so OpenRouter forwards them to Anthropic for prompt
|
|
3170
|
-
* caching. Otherwise it returns a plain flattened string — unchanged for
|
|
3171
|
-
* direct OpenAI/Groq.
|
|
3172
|
-
*/
|
|
3173
|
-
private static _openaiSystemMessage;
|
|
3174
|
-
/**
|
|
3175
|
-
* Split an OpenAI-wire usage object. `prompt_tokens` INCLUDES cached tokens,
|
|
3176
|
-
* so we subtract them out (Anthropic-style: input excludes cache reads) and
|
|
3177
|
-
* report cached separately — this makes calculateCost price cache reads at
|
|
3178
|
-
* the discounted rate and reflects OpenRouter prompt-cache savings in logs.
|
|
3179
|
-
*/
|
|
3180
|
-
private static _openaiUsage;
|
|
3181
1760
|
private static _openaiText;
|
|
3182
1761
|
private static _openaiStream;
|
|
3183
|
-
/** Map the Anthropic-style firstIterationToolChoice to OpenAI's tool_choice. */
|
|
3184
|
-
private static _openaiToolChoice;
|
|
3185
1762
|
private static _openaiStreamWithTools;
|
|
3186
1763
|
/**
|
|
3187
1764
|
* Parse JSON string, handling markdown code blocks and surrounding text
|
|
@@ -3283,13 +1860,6 @@ declare class UIBlock {
|
|
|
3283
1860
|
private textResponse;
|
|
3284
1861
|
private actions;
|
|
3285
1862
|
private createdAt;
|
|
3286
|
-
/**
|
|
3287
|
-
* Which script recipe produced this answer, when a script did. Read on the
|
|
3288
|
-
* NEXT turn so the user can say "use mode instead" and have the matcher
|
|
3289
|
-
* resolve it to a concrete script (the `edit` tier is unreachable without it).
|
|
3290
|
-
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
3291
|
-
*/
|
|
3292
|
-
private scriptBinding;
|
|
3293
1863
|
/**
|
|
3294
1864
|
* Creates a new UIBlock instance
|
|
3295
1865
|
* @param userQuestion - The user's question or input
|
|
@@ -3298,8 +1868,11 @@ declare class UIBlock {
|
|
|
3298
1868
|
* @param actions - Optional array of available actions
|
|
3299
1869
|
* @param id - Optional custom ID, generates UUID if not provided
|
|
3300
1870
|
* @param textResponse - Optional text response from LLM
|
|
1871
|
+
* @param createdAt - Optional original timestamp. Needed when a block is rebuilt from
|
|
1872
|
+
* storage: conversation context is ordered by this, so defaulting to now would make
|
|
1873
|
+
* a restored turn look newer than the live one.
|
|
3301
1874
|
*/
|
|
3302
|
-
constructor(userQuestion: string, componentData?: Record<string, any>, generatedComponentMetadata?: Record<string, any>, actions?: Action[], id?: string, textResponse?: string | null);
|
|
1875
|
+
constructor(userQuestion: string, componentData?: Record<string, any>, generatedComponentMetadata?: Record<string, any>, actions?: Action[], id?: string, textResponse?: string | null, createdAt?: Date);
|
|
3303
1876
|
/**
|
|
3304
1877
|
* Get the UIBlock ID
|
|
3305
1878
|
*/
|
|
@@ -3381,22 +1954,9 @@ declare class UIBlock {
|
|
|
3381
1954
|
* Clear all actions
|
|
3382
1955
|
*/
|
|
3383
1956
|
clearActions(): void;
|
|
3384
|
-
/** The program-generated half of the answer — see setProgramAnswer. */
|
|
3385
|
-
programAnswer?: string | null;
|
|
3386
|
-
/**
|
|
3387
|
-
* Bind this block to the script recipe that produced its answer.
|
|
3388
|
-
*/
|
|
3389
|
-
setScriptBinding(binding: Record<string, any> | null): void;
|
|
3390
|
-
/**
|
|
3391
|
-
* The program-generated half of the answer, kept verbatim so a reload can
|
|
3392
|
-
* replace exactly that text without disturbing the streamed narration.
|
|
3393
|
-
*/
|
|
3394
|
-
setProgramAnswer(text: string | null): void;
|
|
3395
|
-
getProgramAnswer(): string | null;
|
|
3396
1957
|
/**
|
|
3397
|
-
*
|
|
1958
|
+
* Get creation timestamp
|
|
3398
1959
|
*/
|
|
3399
|
-
getScriptBinding(): Record<string, any> | null;
|
|
3400
1960
|
getCreatedAt(): Date;
|
|
3401
1961
|
/**
|
|
3402
1962
|
* Convert UIBlock to JSON-serializable object
|
|
@@ -3404,6 +1964,14 @@ declare class UIBlock {
|
|
|
3404
1964
|
toJSON(): Record<string, any>;
|
|
3405
1965
|
}
|
|
3406
1966
|
|
|
1967
|
+
/** One stored turn, as a host's conversation collection hands it back. */
|
|
1968
|
+
interface HydratedTurn {
|
|
1969
|
+
id: string;
|
|
1970
|
+
userQuestion?: string;
|
|
1971
|
+
textResponse?: string | null;
|
|
1972
|
+
componentMetadata?: Record<string, any>;
|
|
1973
|
+
createdAt?: Date | string;
|
|
1974
|
+
}
|
|
3407
1975
|
/**
|
|
3408
1976
|
* Thread represents a conversation thread containing multiple UIBlocks
|
|
3409
1977
|
* Each UIBlock in a thread represents a user question and assistant response pair
|
|
@@ -3412,6 +1980,7 @@ declare class Thread {
|
|
|
3412
1980
|
private id;
|
|
3413
1981
|
private uiblocks;
|
|
3414
1982
|
private createdAt;
|
|
1983
|
+
private hydrated;
|
|
3415
1984
|
/**
|
|
3416
1985
|
* Creates a new Thread instance
|
|
3417
1986
|
* @param id - Optional custom ID, generates UUID if not provided
|
|
@@ -3425,6 +1994,14 @@ declare class Thread {
|
|
|
3425
1994
|
* Add a UIBlock to the thread
|
|
3426
1995
|
*/
|
|
3427
1996
|
addUIBlock(uiblock: UIBlock): void;
|
|
1997
|
+
/**
|
|
1998
|
+
* Rebuild past turns from storage so a thread survives a restart or a new session.
|
|
1999
|
+
* Once only, and never over a block already held: anything in memory is the live
|
|
2000
|
+
* copy and may carry state the stored row does not.
|
|
2001
|
+
*/
|
|
2002
|
+
hydrate(turns: HydratedTurn[]): number;
|
|
2003
|
+
/** Whether hydration has already been attempted, successful or not. */
|
|
2004
|
+
isHydrated(): boolean;
|
|
3428
2005
|
/**
|
|
3429
2006
|
* Get a UIBlock by ID
|
|
3430
2007
|
*/
|
|
@@ -3464,40 +2041,7 @@ declare class Thread {
|
|
|
3464
2041
|
* @param currentUIBlockId - ID of current UIBlock to exclude from context (optional)
|
|
3465
2042
|
* @returns Formatted conversation history string
|
|
3466
2043
|
*/
|
|
3467
|
-
|
|
3468
|
-
* The script recipe bound to the most recent completed UIBlock — i.e. the
|
|
3469
|
-
* script behind the answer the user is currently looking at. Drives the
|
|
3470
|
-
* matcher's `edit` tier: without it, "use mode instead" has no target and
|
|
3471
|
-
* falls through to regeneration.
|
|
3472
|
-
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
3473
|
-
*/
|
|
3474
|
-
getActiveScriptBinding(currentUIBlockId?: string): Record<string, any> | null;
|
|
3475
|
-
/**
|
|
3476
|
-
* The recent script-backed answers in this thread, newest first — the
|
|
3477
|
-
* candidate set a user-directed edit can target.
|
|
3478
|
-
*
|
|
3479
|
-
* Returning several rather than only the newest is what lets an instruction
|
|
3480
|
-
* name its own target ("use the mode for the WSP one"). With a single
|
|
3481
|
-
* candidate every edit lands on the most recent script, which silently edits
|
|
3482
|
-
* the wrong recipe whenever the user meant an earlier one.
|
|
3483
|
-
*
|
|
3484
|
-
* Deduped by recipeId (newest occurrence wins) so a long editing session on
|
|
3485
|
-
* one script doesn't crowd out the others. Each entry carries the question
|
|
3486
|
-
* that produced it — without that the candidates are indistinguishable.
|
|
3487
|
-
*
|
|
3488
|
-
* In-memory only: dies with the process. The caller falls back to the
|
|
3489
|
-
* persisted bindings when this comes back empty.
|
|
3490
|
-
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
3491
|
-
*/
|
|
3492
|
-
getScriptBindings(limit?: number, currentUIBlockId?: string): Record<string, any>[];
|
|
3493
|
-
/**
|
|
3494
|
-
* @param getScriptBody Resolves a script-backed turn's EXACT script, pinned
|
|
3495
|
-
* to the version that turn actually ran — never today's (possibly
|
|
3496
|
-
* since-edited) live body. Owned by the caller (needs a ScriptStore, which
|
|
3497
|
-
* Thread doesn't hold) — omit it and every turn falls back to the
|
|
3498
|
-
* no-script summary below.
|
|
3499
|
-
*/
|
|
3500
|
-
getConversationContext(limit?: number, currentUIBlockId?: string, getScriptBody?: (recipeId: string, version: number) => Promise<string | null>): Promise<string>;
|
|
2044
|
+
getConversationContext(limit?: number, currentUIBlockId?: string): string;
|
|
3501
2045
|
/**
|
|
3502
2046
|
* Convert Thread to JSON-serializable object
|
|
3503
2047
|
*/
|
|
@@ -4159,7 +2703,7 @@ declare abstract class BaseLLM {
|
|
|
4159
2703
|
* This helps provide intelligent suggestions for follow-up queries
|
|
4160
2704
|
* For general/conversational questions without components, pass textResponse instead
|
|
4161
2705
|
*/
|
|
4162
|
-
generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string
|
|
2706
|
+
generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string): Promise<string[]>;
|
|
4163
2707
|
}
|
|
4164
2708
|
|
|
4165
2709
|
interface AnthropicLLMConfig extends BaseLLMConfig {
|
|
@@ -4365,198 +2909,6 @@ declare class DashboardConversationHistory {
|
|
|
4365
2909
|
}
|
|
4366
2910
|
declare const dashboardConversationHistory: DashboardConversationHistory;
|
|
4367
2911
|
|
|
4368
|
-
/**
|
|
4369
|
-
* Whole-dashboard generation via Pi, a terminal coding agent — as opposed to
|
|
4370
|
-
* DASH_COMP_REQ's single-widget-at-a-time flow. Runs Pi in-process via its
|
|
4371
|
-
* SDK (createAgentSession), not as a subprocess: no shell, no argument
|
|
4372
|
-
* quoting, no stdin/stdout piping, none of the Windows-specific subprocess
|
|
4373
|
-
* issues that came with spawning the `pi` CLI directly.
|
|
4374
|
-
*
|
|
4375
|
-
* Called from sdk-nodejs/src/dashboardAgent/index.ts (DASHBOARD_AGENT_REQ),
|
|
4376
|
-
* which owns the generic streaming/abort machinery (mirrors USER_PROMPT_REQ)
|
|
4377
|
-
* and passes `signal`/`onProgress` alongside the normal params — this stays
|
|
4378
|
-
* within CollectionHandler's loose (params) => Promise<result> typing, no
|
|
4379
|
-
* change needed to that shared type.
|
|
4380
|
-
*
|
|
4381
|
-
* This mechanism is generic and reusable across any deployment. What's
|
|
4382
|
-
* genuinely project-specific — where AGENTS.md lives, which model to use —
|
|
4383
|
-
* is supplied via `DashboardAgentCollectionConfig`, with defaults sensible
|
|
4384
|
-
* enough that most callers don't need to override them (see below). The
|
|
4385
|
-
* data-source tool list and the dashboard's current state both come from
|
|
4386
|
-
* things sdk-nodejs already exposes generically: `sdk.getTools()` (whatever
|
|
4387
|
-
* this deployment registered via `sdk.setTools()`) and `sdk.callCollection
|
|
4388
|
-
* ('dashboards', 'query', ...)` (whatever this deployment already registered
|
|
4389
|
-
* under that name/shape) — no per-deployment callback needed for either.
|
|
4390
|
-
* Same convention on the way out: after a successful run, the prompt and the
|
|
4391
|
-
* full response text are handed to `sdk.callCollection('dashboard-agent-
|
|
4392
|
-
* conversations', 'create', ...)` if this deployment has registered one —
|
|
4393
|
-
* skipped silently otherwise, since conversation history is optional.
|
|
4394
|
-
*
|
|
4395
|
-
* Pi verifies every query against the live database itself (via whatever
|
|
4396
|
-
* local tool-execution bridge the deployment exposes, e.g. an HTTP bridge
|
|
4397
|
-
* on localhost), but does NOT persist the result itself — it writes the
|
|
4398
|
-
* finished DSL to an absolute path inside `runtimeDir`, told to it explicitly
|
|
4399
|
-
* in the prompt, and stops there. This handler reads that file after the run
|
|
4400
|
-
* finishes and returns its content as `dashboard` in the result. The caller
|
|
4401
|
-
* (frontend) is the one that actually saves it, via whatever authenticated
|
|
4402
|
-
* create/update path any other dashboard edit goes through — Pi has no user
|
|
4403
|
-
* session/auth context of its own, so persistence shouldn't happen from
|
|
4404
|
-
* inside it.
|
|
4405
|
-
*
|
|
4406
|
-
* Session persistence: the FIRST call for a dashboardId pays the full cost
|
|
4407
|
-
* (explore KB, discover schema, plan, verify, build). Every call after that
|
|
4408
|
-
* resumes the same session file (SessionManager.open) so Pi has everything
|
|
4409
|
-
* it already learned — it only needs to reason about the new, smaller ask,
|
|
4410
|
-
* not rediscover the whole dashboard from scratch. The session's file path
|
|
4411
|
-
* (AgentSession.sessionFile) is captured right after creation and persisted
|
|
4412
|
-
* in a small local file, keyed by dashboardId, inside `runtimeDir`.
|
|
4413
|
-
*/
|
|
4414
|
-
interface DashboardAgentCollectionConfig {
|
|
4415
|
-
/**
|
|
4416
|
-
* Working directory Pi runs from — must contain AGENTS.md. This is a
|
|
4417
|
-
* version-controlled prompt file, so `cwd` is expected to live somewhere
|
|
4418
|
-
* like a `.prompts/` folder alongside the deployment's other prompts.
|
|
4419
|
-
* Default: `<process.cwd()>/.prompts/dashboard-agent` — the same
|
|
4420
|
-
* process.cwd()-based convention PromptLoader already uses for the main
|
|
4421
|
-
* agent's prompts, which needs no explicit override in the common case
|
|
4422
|
-
* (the backend process's own cwd already is its project root).
|
|
4423
|
-
*/
|
|
4424
|
-
cwd?: string;
|
|
4425
|
-
/**
|
|
4426
|
-
* Where drafts/, the session-id map, and dashboard.log get written —
|
|
4427
|
-
* separate from `cwd` deliberately, so this deployment's runtime state
|
|
4428
|
-
* (regenerated per session, safe to gitignore) doesn't sit inside the
|
|
4429
|
-
* same folder as the version-controlled AGENTS.md prompt.
|
|
4430
|
-
* Default: `<process.cwd()>/.pi-dashboard-agent-runtime`.
|
|
4431
|
-
*/
|
|
4432
|
-
runtimeDir?: string;
|
|
4433
|
-
/** Model provider (default: process.env.PI_AGENT_PROVIDER || 'openrouter'). */
|
|
4434
|
-
provider?: string;
|
|
4435
|
-
/** Model id (default: process.env.PI_AGENT_MODEL || 'anthropic/claude-sonnet-4.5'). */
|
|
4436
|
-
model?: string;
|
|
4437
|
-
/**
|
|
4438
|
-
* true (default): every request starts a brand-new pi session, with the 2
|
|
4439
|
-
* most recent prior responses (if any) injected into the prompt as
|
|
4440
|
-
* context — bounded cost per request, but pi re-explores schema/KB facts
|
|
4441
|
-
* it already verified in an earlier turn on this same dashboard.
|
|
4442
|
-
* false: resumes the same session file across requests on a given
|
|
4443
|
-
* dashboard — pi keeps everything it already learned, but context (and
|
|
4444
|
-
* cost) grows unbounded across turns (one observed turn: 2M+ cache-read
|
|
4445
|
-
* tokens after a handful of edits on the same dashboard).
|
|
4446
|
-
* Default: process.env.PI_AGENT_FRESH_SESSION !== 'false'.
|
|
4447
|
-
*/
|
|
4448
|
-
freshSession?: boolean;
|
|
4449
|
-
}
|
|
4450
|
-
declare function registerDashboardAgentCollection(sdk: SuperatomSDK, config?: DashboardAgentCollectionConfig): void;
|
|
4451
|
-
|
|
4452
|
-
/**
|
|
4453
|
-
* ScriptMatcher — LLM-Based Script Matching + Parameter Extraction
|
|
4454
|
-
*
|
|
4455
|
-
* Uses ONE LLM call to:
|
|
4456
|
-
* 1. Pick the best matching script from the library (or "none")
|
|
4457
|
-
* 2. Extract parameter values from the user question
|
|
4458
|
-
*
|
|
4459
|
-
* Why LLM over embeddings:
|
|
4460
|
-
* - Embeddings capture topic similarity ("overstock" ≈ "inventory" ≈ "revenue")
|
|
4461
|
-
* but can't distinguish structurally different questions about the same domain
|
|
4462
|
-
* - LLM understands that "overstock by warehouse" needs a different script than
|
|
4463
|
-
* "revenue by warehouse" even though they're semantically close
|
|
4464
|
-
* - One call does both matching AND parameter extraction
|
|
4465
|
-
*
|
|
4466
|
-
* When script library grows past ~50, add an embedding pre-filter
|
|
4467
|
-
* (ChromaDB narrows to top 10 → LLM picks from those 10).
|
|
4468
|
-
*/
|
|
4469
|
-
|
|
4470
|
-
declare class ScriptMatcher {
|
|
4471
|
-
private store;
|
|
4472
|
-
private collections?;
|
|
4473
|
-
private userId?;
|
|
4474
|
-
private trace?;
|
|
4475
|
-
constructor(store: ScriptStore, opts?: {
|
|
4476
|
-
collections?: any;
|
|
4477
|
-
userId?: string;
|
|
4478
|
-
trace?: RunTrace;
|
|
4479
|
-
});
|
|
4480
|
-
/**
|
|
4481
|
-
* Find the best matching script for a user question.
|
|
4482
|
-
* Uses ONE LLM call that picks the script AND extracts parameters.
|
|
4483
|
-
* Returns null if no script matches.
|
|
4484
|
-
*
|
|
4485
|
-
* Thin wrapper around `doMatch` whose only job is guaranteeing the trace
|
|
4486
|
-
* capture happens exactly once, on every exit path (short-circuit, normal
|
|
4487
|
-
* return, or the LLM call erroring) — see RunTrace.scriptMatcher.
|
|
4488
|
-
*/
|
|
4489
|
-
match(userPrompt: string, apiKey?: string, model?: string, signal?: AbortSignal, activeBindings?: ScriptBinding[]): Promise<ScriptMatch | null>;
|
|
4490
|
-
private doMatch;
|
|
4491
|
-
/**
|
|
4492
|
-
* Renders a recipe's declared parameters the same way in every prompt
|
|
4493
|
-
* section (catalog, active-script, edit candidates) so the LLM sees one
|
|
4494
|
-
* consistent format regardless of which block a script came from.
|
|
4495
|
-
*/
|
|
4496
|
-
private formatParamList;
|
|
4497
|
-
/**
|
|
4498
|
-
* Semantic search over THIS user's own past prompts (`conversation-history`
|
|
4499
|
-
* ChromaDB embeddings, already user-scoped) — not a project-wide name/tag
|
|
4500
|
-
* search. Groups hits by the recipe that answered them, so a script gets
|
|
4501
|
-
* ONE catalog entry carrying every matched past question, not one per hit.
|
|
4502
|
-
*
|
|
4503
|
-
* Scope is deliberate (see SCRIPT-MATCH-IMPROVEMENTS.md, Change 2): a
|
|
4504
|
-
* script only shows up here because THIS user has, before, asked something
|
|
4505
|
-
* similar that it answered — not because some other user's question did.
|
|
4506
|
-
*/
|
|
4507
|
-
private searchPromptHistory;
|
|
4508
|
-
/**
|
|
4509
|
-
* Build the script catalog string for the LLM prompt from prompt-history
|
|
4510
|
-
* matches: each script's declared parameters PLUS the actual past questions
|
|
4511
|
-
* of this user's that it answered (real precedent, not a hand-written
|
|
4512
|
-
* description) and what params they ran with.
|
|
4513
|
-
*/
|
|
4514
|
-
private buildPromptHistoryCatalog;
|
|
4515
|
-
/**
|
|
4516
|
-
* The recent script-backed answers in this thread — the bounded set an edit
|
|
4517
|
-
* may target. Rendered as its own prompt section (never merged into the
|
|
4518
|
-
* ranked catalog) so the `edit` rules have an unambiguous referent set, and
|
|
4519
|
-
* numbered newest-first so the prompt's "prefer the most recent when the
|
|
4520
|
-
* instruction is ambiguous" tie-break has something to point at.
|
|
4521
|
-
*
|
|
4522
|
-
* Each entry carries the QUESTION that produced it plus the columns it
|
|
4523
|
-
* returned — that is what lets the matcher resolve "use the mode for the WSP
|
|
4524
|
-
* one" instead of blindly taking the newest.
|
|
4525
|
-
*/
|
|
4526
|
-
private buildActiveScriptBlock;
|
|
4527
|
-
}
|
|
4528
|
-
|
|
4529
|
-
/**
|
|
4530
|
-
* ScriptRunner — Execute scripts in an isolated tsx subprocess.
|
|
4531
|
-
*
|
|
4532
|
-
* The subprocess approach replaces the earlier `new Function()` eval and gives us:
|
|
4533
|
-
* - Real sandbox (separate process, SIGKILL on timeout).
|
|
4534
|
-
* - Real TypeScript (tsx transpiles on the fly).
|
|
4535
|
-
* - npm imports available to scripts (clustering, stats, geo, etc.).
|
|
4536
|
-
*
|
|
4537
|
-
* Protocol: NDJSON over the child's stdin/stdout. See script-ipc.ts + backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md.
|
|
4538
|
-
*/
|
|
4539
|
-
|
|
4540
|
-
interface RunScriptOptions {
|
|
4541
|
-
/** Data sources the script is allowed to query via ctx.query */
|
|
4542
|
-
externalTools: ExternalTool[];
|
|
4543
|
-
/** Optional — for propagating per-query UI progress to the user */
|
|
4544
|
-
streamBuffer?: StreamBuffer;
|
|
4545
|
-
/** Override the wall-clock timeout (default `SCRIPT_TIMEOUT_MS`, 60s). */
|
|
4546
|
-
timeoutMs?: number;
|
|
4547
|
-
/**
|
|
4548
|
-
* Per-turn cancellation signal. When the user hits "Stop" mid-run, the child
|
|
4549
|
-
* process group is SIGKILLed and the run resolves as an aborted failure (the
|
|
4550
|
-
* caller is already unwinding, so the result is discarded).
|
|
4551
|
-
*/
|
|
4552
|
-
signal?: AbortSignal;
|
|
4553
|
-
}
|
|
4554
|
-
/**
|
|
4555
|
-
* Execute a recipe by spawning a tsx child on the script's .ts file.
|
|
4556
|
-
* `scriptPath` is the absolute path to the saved `.ts` body.
|
|
4557
|
-
*/
|
|
4558
|
-
declare function runScript(recipe: ScriptRecipe, scriptPath: string, params: Record<string, any>, options: RunScriptOptions): Promise<ScriptResult>;
|
|
4559
|
-
|
|
4560
2912
|
type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
|
|
4561
2913
|
declare class SuperatomSDK {
|
|
4562
2914
|
private ws;
|
|
@@ -4592,8 +2944,6 @@ declare class SuperatomSDK {
|
|
|
4592
2944
|
private lastPong;
|
|
4593
2945
|
private readonly PING_INTERVAL_MS;
|
|
4594
2946
|
private readonly PONG_TIMEOUT_MS;
|
|
4595
|
-
private pendingOutbox;
|
|
4596
|
-
private readonly MAX_OUTBOX_SIZE;
|
|
4597
2947
|
constructor(config: SuperatomSDKConfig);
|
|
4598
2948
|
/**
|
|
4599
2949
|
* Initialize PromptLoader and load prompts into memory
|
|
@@ -4638,20 +2988,6 @@ declare class SuperatomSDK {
|
|
|
4638
2988
|
* Does NOT throw on closed connections — callers can check the return value if needed.
|
|
4639
2989
|
*/
|
|
4640
2990
|
send(message: Message): boolean;
|
|
4641
|
-
/**
|
|
4642
|
-
* Queue a message that couldn't be delivered because the socket was down,
|
|
4643
|
-
* to be resent once it reconnects. Drops the oldest entry once the bound is
|
|
4644
|
-
* hit — an outage long enough to fill this queue means the oldest queued
|
|
4645
|
-
* responses are for requests the caller has likely already given up on.
|
|
4646
|
-
*/
|
|
4647
|
-
private queuePendingMessage;
|
|
4648
|
-
/**
|
|
4649
|
-
* Resend everything queued while the socket was down, now that it's back
|
|
4650
|
-
* up. Uses this.ws.send() directly (not send()) so a message that fails
|
|
4651
|
-
* again goes back through queuePendingMessage() rather than being silently
|
|
4652
|
-
* dropped a second time.
|
|
4653
|
-
*/
|
|
4654
|
-
private flushPendingOutbox;
|
|
4655
2991
|
/**
|
|
4656
2992
|
* Register a message handler to receive all messages
|
|
4657
2993
|
*/
|
|
@@ -4691,14 +3027,6 @@ declare class SuperatomSDK {
|
|
|
4691
3027
|
*/
|
|
4692
3028
|
private handlePong;
|
|
4693
3029
|
private storeComponents;
|
|
4694
|
-
/**
|
|
4695
|
-
* The live, frontend-registered component catalog (name, type, description,
|
|
4696
|
-
* and full prop schema per component) — the same authoritative source
|
|
4697
|
-
* DASH_COMP_REQ's LLM prompt is built from. Exposed so other integrations
|
|
4698
|
-
* (e.g. the dashboard-agent script bridge) can read real component
|
|
4699
|
-
* contracts instead of maintaining a separate, driftable hand-written copy.
|
|
4700
|
-
*/
|
|
4701
|
-
getComponents(): Component[];
|
|
4702
3030
|
/**
|
|
4703
3031
|
* Set tools for the SDK instance
|
|
4704
3032
|
*/
|
|
@@ -4707,16 +3035,6 @@ declare class SuperatomSDK {
|
|
|
4707
3035
|
* Get the stored tools
|
|
4708
3036
|
*/
|
|
4709
3037
|
getTools(): Tool$1[];
|
|
4710
|
-
/**
|
|
4711
|
-
* Call a registered collection operation in-process — no WebSocket
|
|
4712
|
-
* round-trip, since the caller is already running inside this same SDK
|
|
4713
|
-
* instance. Lets SDK-internal features (e.g. the dashboard agent) reuse
|
|
4714
|
-
* whatever collection a deployment has already registered (e.g.
|
|
4715
|
-
* 'dashboards'.'query') by name/convention, instead of requiring a
|
|
4716
|
-
* separate callback purely to re-expose data a collection already serves.
|
|
4717
|
-
* Throws if the collection or operation isn't registered.
|
|
4718
|
-
*/
|
|
4719
|
-
callCollection<TResult = any>(collectionName: string, operation: string, params?: any): Promise<TResult>;
|
|
4720
3038
|
/**
|
|
4721
3039
|
* Register workflow components for the SDK instance.
|
|
4722
3040
|
*
|
|
@@ -4760,4 +3078,4 @@ declare class SuperatomSDK {
|
|
|
4760
3078
|
getConversationSimilarityThreshold(): number;
|
|
4761
3079
|
}
|
|
4762
3080
|
|
|
4763
|
-
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
|
|
3081
|
+
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 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 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, openaiLLM, queryCache, rerankChromaResults, rerankConversationResults, userPromptErrorLogger };
|