@superatomai/sdk-node 0.0.28 → 0.0.29-dsp
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +2623 -166
- package/dist/index.d.ts +2623 -166
- package/dist/index.js +20946 -5985
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +20961 -6015
- package/dist/index.mjs.map +1 -1
- package/dist/userResponse/scripts/script-bootstrap.d.mts +2 -0
- package/dist/userResponse/scripts/script-bootstrap.d.ts +2 -0
- package/dist/userResponse/scripts/script-bootstrap.js +302 -0
- package/dist/userResponse/scripts/script-bootstrap.js.map +1 -0
- package/dist/userResponse/scripts/script-bootstrap.mjs +300 -0
- package/dist/userResponse/scripts/script-bootstrap.mjs.map +1 -0
- package/package.json +3 -1
package/dist/index.d.mts
CHANGED
|
@@ -3,13 +3,32 @@ import Anthropic from '@anthropic-ai/sdk';
|
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Unified UIBlock structure for database storage
|
|
6
|
-
* Used in both bookmarks and user-conversations tables
|
|
6
|
+
* Used in both bookmarks and user-conversations tables.
|
|
7
|
+
*
|
|
8
|
+
* `analysis` always holds whatever real narration exists — the full answer on
|
|
9
|
+
* success, or whatever was actually streamed before a failure (may be empty).
|
|
10
|
+
* `error` is a dedicated field, null on success — it can be a plain string OR
|
|
11
|
+
* a structured object/array (e.g. the agent's raw `errors` list), whatever
|
|
12
|
+
* shape the failure naturally has; it's never coerced into `analysis`.
|
|
7
13
|
*/
|
|
8
14
|
interface DBUIBlock {
|
|
9
15
|
id: string;
|
|
10
16
|
component: Record<string, any> | null;
|
|
11
17
|
analysis: string | null;
|
|
12
18
|
user_prompt: string;
|
|
19
|
+
error?: unknown | null;
|
|
20
|
+
/**
|
|
21
|
+
* The script recipe that produced this answer, when one did. Read back via
|
|
22
|
+
* `conversation-history.exactMatch` so an edit follow-up still has a target
|
|
23
|
+
* after a reload (the in-memory thread is gone by then), and indexed so
|
|
24
|
+
* committing an edit can purge every cached answer bound to the recipe.
|
|
25
|
+
*/
|
|
26
|
+
scriptBinding?: {
|
|
27
|
+
recipeId: string;
|
|
28
|
+
params?: Record<string, any>;
|
|
29
|
+
name?: string;
|
|
30
|
+
columns?: string[];
|
|
31
|
+
};
|
|
13
32
|
}
|
|
14
33
|
|
|
15
34
|
/**
|
|
@@ -59,7 +78,18 @@ declare class Logger {
|
|
|
59
78
|
* Log debug message (only shown for verbose level)
|
|
60
79
|
*/
|
|
61
80
|
debug(...args: any[]): void;
|
|
81
|
+
/**
|
|
82
|
+
* Write to log file
|
|
83
|
+
*/
|
|
62
84
|
file(...args: any[]): void;
|
|
85
|
+
/**
|
|
86
|
+
* Clear the log file (call at start of new user request)
|
|
87
|
+
*/
|
|
88
|
+
clearFile(): void;
|
|
89
|
+
/**
|
|
90
|
+
* Log LLM method prompts with clear labeling
|
|
91
|
+
*/
|
|
92
|
+
logLLMPrompt(methodName: string, promptType: 'system' | 'user', content: string | object | any[]): void;
|
|
63
93
|
}
|
|
64
94
|
declare const logger: Logger;
|
|
65
95
|
|
|
@@ -90,7 +120,27 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
90
120
|
deps?: string[] | undefined;
|
|
91
121
|
}>, "many">>;
|
|
92
122
|
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
93
|
-
render: z.ZodType<any, z.ZodTypeDef, any
|
|
123
|
+
render: z.ZodOptional<z.ZodType<any, z.ZodTypeDef, any>>;
|
|
124
|
+
pages: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
125
|
+
id: z.ZodString;
|
|
126
|
+
name: z.ZodString;
|
|
127
|
+
order: z.ZodNumber;
|
|
128
|
+
icon: z.ZodOptional<z.ZodString>;
|
|
129
|
+
render: z.ZodType<any, z.ZodTypeDef, any>;
|
|
130
|
+
}, "strip", z.ZodTypeAny, {
|
|
131
|
+
id: string;
|
|
132
|
+
name: string;
|
|
133
|
+
order: number;
|
|
134
|
+
icon?: string | undefined;
|
|
135
|
+
render?: any;
|
|
136
|
+
}, {
|
|
137
|
+
id: string;
|
|
138
|
+
name: string;
|
|
139
|
+
order: number;
|
|
140
|
+
icon?: string | undefined;
|
|
141
|
+
render?: any;
|
|
142
|
+
}>, "many">>;
|
|
143
|
+
defaultPageId: z.ZodOptional<z.ZodString>;
|
|
94
144
|
query: z.ZodOptional<z.ZodObject<{
|
|
95
145
|
graphql: z.ZodOptional<z.ZodString>;
|
|
96
146
|
sql: z.ZodOptional<z.ZodString>;
|
|
@@ -129,6 +179,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
129
179
|
dependencies?: string[] | undefined;
|
|
130
180
|
} | undefined;
|
|
131
181
|
props?: Record<string, any> | undefined;
|
|
182
|
+
render?: any;
|
|
132
183
|
states?: Record<string, any> | undefined;
|
|
133
184
|
methods?: Record<string, {
|
|
134
185
|
fn: string;
|
|
@@ -139,7 +190,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
139
190
|
deps?: string[] | undefined;
|
|
140
191
|
}[] | undefined;
|
|
141
192
|
data?: Record<string, any> | undefined;
|
|
142
|
-
|
|
193
|
+
pages?: {
|
|
194
|
+
id: string;
|
|
195
|
+
name: string;
|
|
196
|
+
order: number;
|
|
197
|
+
icon?: string | undefined;
|
|
198
|
+
render?: any;
|
|
199
|
+
}[] | undefined;
|
|
200
|
+
defaultPageId?: string | undefined;
|
|
143
201
|
}, {
|
|
144
202
|
id: string;
|
|
145
203
|
name?: string | undefined;
|
|
@@ -153,6 +211,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
153
211
|
dependencies?: string[] | undefined;
|
|
154
212
|
} | undefined;
|
|
155
213
|
props?: Record<string, any> | undefined;
|
|
214
|
+
render?: any;
|
|
156
215
|
states?: Record<string, any> | undefined;
|
|
157
216
|
methods?: Record<string, {
|
|
158
217
|
fn: string;
|
|
@@ -163,7 +222,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
163
222
|
deps?: string[] | undefined;
|
|
164
223
|
}[] | undefined;
|
|
165
224
|
data?: Record<string, any> | undefined;
|
|
166
|
-
|
|
225
|
+
pages?: {
|
|
226
|
+
id: string;
|
|
227
|
+
name: string;
|
|
228
|
+
order: number;
|
|
229
|
+
icon?: string | undefined;
|
|
230
|
+
render?: any;
|
|
231
|
+
}[] | undefined;
|
|
232
|
+
defaultPageId?: string | undefined;
|
|
167
233
|
}>;
|
|
168
234
|
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
169
235
|
context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
@@ -181,6 +247,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
181
247
|
dependencies?: string[] | undefined;
|
|
182
248
|
} | undefined;
|
|
183
249
|
props?: Record<string, any> | undefined;
|
|
250
|
+
render?: any;
|
|
184
251
|
states?: Record<string, any> | undefined;
|
|
185
252
|
methods?: Record<string, {
|
|
186
253
|
fn: string;
|
|
@@ -191,7 +258,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
191
258
|
deps?: string[] | undefined;
|
|
192
259
|
}[] | undefined;
|
|
193
260
|
data?: Record<string, any> | undefined;
|
|
194
|
-
|
|
261
|
+
pages?: {
|
|
262
|
+
id: string;
|
|
263
|
+
name: string;
|
|
264
|
+
order: number;
|
|
265
|
+
icon?: string | undefined;
|
|
266
|
+
render?: any;
|
|
267
|
+
}[] | undefined;
|
|
268
|
+
defaultPageId?: string | undefined;
|
|
195
269
|
};
|
|
196
270
|
data?: Record<string, any> | undefined;
|
|
197
271
|
context?: Record<string, any> | undefined;
|
|
@@ -209,6 +283,7 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
209
283
|
dependencies?: string[] | undefined;
|
|
210
284
|
} | undefined;
|
|
211
285
|
props?: Record<string, any> | undefined;
|
|
286
|
+
render?: any;
|
|
212
287
|
states?: Record<string, any> | undefined;
|
|
213
288
|
methods?: Record<string, {
|
|
214
289
|
fn: string;
|
|
@@ -219,7 +294,14 @@ declare const DSLRendererPropsSchema$1: z.ZodObject<{
|
|
|
219
294
|
deps?: string[] | undefined;
|
|
220
295
|
}[] | undefined;
|
|
221
296
|
data?: Record<string, any> | undefined;
|
|
222
|
-
|
|
297
|
+
pages?: {
|
|
298
|
+
id: string;
|
|
299
|
+
name: string;
|
|
300
|
+
order: number;
|
|
301
|
+
icon?: string | undefined;
|
|
302
|
+
render?: any;
|
|
303
|
+
}[] | undefined;
|
|
304
|
+
defaultPageId?: string | undefined;
|
|
223
305
|
};
|
|
224
306
|
data?: Record<string, any> | undefined;
|
|
225
307
|
context?: Record<string, any> | undefined;
|
|
@@ -292,6 +374,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
292
374
|
dependencies?: string[] | undefined;
|
|
293
375
|
} | undefined;
|
|
294
376
|
props?: Record<string, any> | undefined;
|
|
377
|
+
render?: any;
|
|
295
378
|
states?: Record<string, any> | undefined;
|
|
296
379
|
methods?: Record<string, {
|
|
297
380
|
fn: string;
|
|
@@ -302,7 +385,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
302
385
|
deps?: string[] | undefined;
|
|
303
386
|
}[] | undefined;
|
|
304
387
|
data?: Record<string, any> | undefined;
|
|
305
|
-
render?: any;
|
|
306
388
|
}, {
|
|
307
389
|
id: string;
|
|
308
390
|
name?: string | undefined;
|
|
@@ -316,6 +398,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
316
398
|
dependencies?: string[] | undefined;
|
|
317
399
|
} | undefined;
|
|
318
400
|
props?: Record<string, any> | undefined;
|
|
401
|
+
render?: any;
|
|
319
402
|
states?: Record<string, any> | undefined;
|
|
320
403
|
methods?: Record<string, {
|
|
321
404
|
fn: string;
|
|
@@ -326,7 +409,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
326
409
|
deps?: string[] | undefined;
|
|
327
410
|
}[] | undefined;
|
|
328
411
|
data?: Record<string, any> | undefined;
|
|
329
|
-
render?: any;
|
|
330
412
|
}>;
|
|
331
413
|
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
332
414
|
context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
@@ -344,6 +426,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
344
426
|
dependencies?: string[] | undefined;
|
|
345
427
|
} | undefined;
|
|
346
428
|
props?: Record<string, any> | undefined;
|
|
429
|
+
render?: any;
|
|
347
430
|
states?: Record<string, any> | undefined;
|
|
348
431
|
methods?: Record<string, {
|
|
349
432
|
fn: string;
|
|
@@ -354,7 +437,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
354
437
|
deps?: string[] | undefined;
|
|
355
438
|
}[] | undefined;
|
|
356
439
|
data?: Record<string, any> | undefined;
|
|
357
|
-
render?: any;
|
|
358
440
|
};
|
|
359
441
|
data?: Record<string, any> | undefined;
|
|
360
442
|
context?: Record<string, any> | undefined;
|
|
@@ -372,6 +454,7 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
372
454
|
dependencies?: string[] | undefined;
|
|
373
455
|
} | undefined;
|
|
374
456
|
props?: Record<string, any> | undefined;
|
|
457
|
+
render?: any;
|
|
375
458
|
states?: Record<string, any> | undefined;
|
|
376
459
|
methods?: Record<string, {
|
|
377
460
|
fn: string;
|
|
@@ -382,7 +465,6 @@ declare const DSLRendererPropsSchema: z.ZodObject<{
|
|
|
382
465
|
deps?: string[] | undefined;
|
|
383
466
|
}[] | undefined;
|
|
384
467
|
data?: Record<string, any> | undefined;
|
|
385
|
-
render?: any;
|
|
386
468
|
};
|
|
387
469
|
data?: Record<string, any> | undefined;
|
|
388
470
|
context?: Record<string, any> | undefined;
|
|
@@ -563,36 +645,237 @@ declare const IncomingMessageSchema: z.ZodObject<{
|
|
|
563
645
|
payload?: unknown;
|
|
564
646
|
}>;
|
|
565
647
|
type IncomingMessage = z.infer<typeof IncomingMessageSchema>;
|
|
648
|
+
declare const ComponentSchema: z.ZodObject<{
|
|
649
|
+
id: z.ZodString;
|
|
650
|
+
name: z.ZodString;
|
|
651
|
+
displayName: z.ZodOptional<z.ZodString>;
|
|
652
|
+
isDisplayComp: z.ZodOptional<z.ZodBoolean>;
|
|
653
|
+
type: z.ZodString;
|
|
654
|
+
description: z.ZodString;
|
|
655
|
+
props: z.ZodObject<{
|
|
656
|
+
query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
|
|
657
|
+
title: z.ZodOptional<z.ZodString>;
|
|
658
|
+
description: z.ZodOptional<z.ZodString>;
|
|
659
|
+
config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
660
|
+
actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
|
|
661
|
+
}, "passthrough", z.ZodTypeAny, z.objectOutputType<{
|
|
662
|
+
query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
|
|
663
|
+
title: z.ZodOptional<z.ZodString>;
|
|
664
|
+
description: z.ZodOptional<z.ZodString>;
|
|
665
|
+
config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
666
|
+
actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
|
|
667
|
+
}, z.ZodTypeAny, "passthrough">, z.objectInputType<{
|
|
668
|
+
query: z.ZodOptional<z.ZodNullable<z.ZodUnion<[z.ZodString, z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>]>>>;
|
|
669
|
+
title: z.ZodOptional<z.ZodString>;
|
|
670
|
+
description: z.ZodOptional<z.ZodString>;
|
|
671
|
+
config: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
672
|
+
actions: z.ZodOptional<z.ZodArray<z.ZodAny, "many">>;
|
|
673
|
+
}, z.ZodTypeAny, "passthrough">>;
|
|
674
|
+
category: z.ZodOptional<z.ZodString>;
|
|
675
|
+
keywords: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
676
|
+
}, "strip", z.ZodTypeAny, {
|
|
677
|
+
id: string;
|
|
678
|
+
type: string;
|
|
679
|
+
name: string;
|
|
680
|
+
description: string;
|
|
681
|
+
props: {
|
|
682
|
+
description?: string | undefined;
|
|
683
|
+
query?: string | {} | null | undefined;
|
|
684
|
+
title?: string | undefined;
|
|
685
|
+
config?: Record<string, unknown> | undefined;
|
|
686
|
+
actions?: any[] | undefined;
|
|
687
|
+
} & {
|
|
688
|
+
[k: string]: unknown;
|
|
689
|
+
};
|
|
690
|
+
displayName?: string | undefined;
|
|
691
|
+
isDisplayComp?: boolean | undefined;
|
|
692
|
+
category?: string | undefined;
|
|
693
|
+
keywords?: string[] | undefined;
|
|
694
|
+
}, {
|
|
695
|
+
id: string;
|
|
696
|
+
type: string;
|
|
697
|
+
name: string;
|
|
698
|
+
description: string;
|
|
699
|
+
props: {
|
|
700
|
+
description?: string | undefined;
|
|
701
|
+
query?: string | {} | null | undefined;
|
|
702
|
+
title?: string | undefined;
|
|
703
|
+
config?: Record<string, unknown> | undefined;
|
|
704
|
+
actions?: any[] | undefined;
|
|
705
|
+
} & {
|
|
706
|
+
[k: string]: unknown;
|
|
707
|
+
};
|
|
708
|
+
displayName?: string | undefined;
|
|
709
|
+
isDisplayComp?: boolean | undefined;
|
|
710
|
+
category?: string | undefined;
|
|
711
|
+
keywords?: string[] | undefined;
|
|
712
|
+
}>;
|
|
713
|
+
type Component = z.infer<typeof ComponentSchema>;
|
|
714
|
+
declare const OutputFieldSchema: z.ZodObject<{
|
|
715
|
+
name: z.ZodString;
|
|
716
|
+
type: z.ZodEnum<["string", "number", "boolean", "date"]>;
|
|
717
|
+
description: z.ZodString;
|
|
718
|
+
}, "strip", z.ZodTypeAny, {
|
|
719
|
+
type: "string" | "number" | "boolean" | "date";
|
|
720
|
+
name: string;
|
|
721
|
+
description: string;
|
|
722
|
+
}, {
|
|
723
|
+
type: "string" | "number" | "boolean" | "date";
|
|
724
|
+
name: string;
|
|
725
|
+
description: string;
|
|
726
|
+
}>;
|
|
727
|
+
type OutputField = z.infer<typeof OutputFieldSchema>;
|
|
728
|
+
declare const OutputSchema: z.ZodObject<{
|
|
729
|
+
description: z.ZodString;
|
|
730
|
+
fields: z.ZodArray<z.ZodObject<{
|
|
731
|
+
name: z.ZodString;
|
|
732
|
+
type: z.ZodEnum<["string", "number", "boolean", "date"]>;
|
|
733
|
+
description: z.ZodString;
|
|
734
|
+
}, "strip", z.ZodTypeAny, {
|
|
735
|
+
type: "string" | "number" | "boolean" | "date";
|
|
736
|
+
name: string;
|
|
737
|
+
description: string;
|
|
738
|
+
}, {
|
|
739
|
+
type: "string" | "number" | "boolean" | "date";
|
|
740
|
+
name: string;
|
|
741
|
+
description: string;
|
|
742
|
+
}>, "many">;
|
|
743
|
+
}, "strip", z.ZodTypeAny, {
|
|
744
|
+
description: string;
|
|
745
|
+
fields: {
|
|
746
|
+
type: "string" | "number" | "boolean" | "date";
|
|
747
|
+
name: string;
|
|
748
|
+
description: string;
|
|
749
|
+
}[];
|
|
750
|
+
}, {
|
|
751
|
+
description: string;
|
|
752
|
+
fields: {
|
|
753
|
+
type: "string" | "number" | "boolean" | "date";
|
|
754
|
+
name: string;
|
|
755
|
+
description: string;
|
|
756
|
+
}[];
|
|
757
|
+
}>;
|
|
758
|
+
type ToolOutputSchema = z.infer<typeof OutputSchema>;
|
|
566
759
|
declare const ToolSchema: z.ZodObject<{
|
|
567
760
|
id: z.ZodString;
|
|
568
761
|
name: z.ZodString;
|
|
569
762
|
description: z.ZodString;
|
|
763
|
+
/** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
|
|
764
|
+
toolType: z.ZodOptional<z.ZodEnum<["source", "direct"]>>;
|
|
765
|
+
/** Full untruncated schema for source agent (all columns visible) */
|
|
766
|
+
fullSchema: z.ZodOptional<z.ZodString>;
|
|
570
767
|
params: z.ZodRecord<z.ZodString, z.ZodString>;
|
|
571
768
|
fn: z.ZodFunction<z.ZodTuple<[z.ZodAny], z.ZodUnknown>, z.ZodAny>;
|
|
769
|
+
outputSchema: z.ZodOptional<z.ZodObject<{
|
|
770
|
+
description: z.ZodString;
|
|
771
|
+
fields: z.ZodArray<z.ZodObject<{
|
|
772
|
+
name: z.ZodString;
|
|
773
|
+
type: z.ZodEnum<["string", "number", "boolean", "date"]>;
|
|
774
|
+
description: z.ZodString;
|
|
775
|
+
}, "strip", z.ZodTypeAny, {
|
|
776
|
+
type: "string" | "number" | "boolean" | "date";
|
|
777
|
+
name: string;
|
|
778
|
+
description: string;
|
|
779
|
+
}, {
|
|
780
|
+
type: "string" | "number" | "boolean" | "date";
|
|
781
|
+
name: string;
|
|
782
|
+
description: string;
|
|
783
|
+
}>, "many">;
|
|
784
|
+
}, "strip", z.ZodTypeAny, {
|
|
785
|
+
description: string;
|
|
786
|
+
fields: {
|
|
787
|
+
type: "string" | "number" | "boolean" | "date";
|
|
788
|
+
name: string;
|
|
789
|
+
description: string;
|
|
790
|
+
}[];
|
|
791
|
+
}, {
|
|
792
|
+
description: string;
|
|
793
|
+
fields: {
|
|
794
|
+
type: "string" | "number" | "boolean" | "date";
|
|
795
|
+
name: string;
|
|
796
|
+
description: string;
|
|
797
|
+
}[];
|
|
798
|
+
}>>;
|
|
799
|
+
/** Cache policy. `false` = never cache (live data, write ops). Mirrors HTTP `Cache-Control: no-store`. */
|
|
800
|
+
cache: z.ZodOptional<z.ZodUnion<[z.ZodLiteral<false>, z.ZodObject<{
|
|
801
|
+
ttlMs: z.ZodOptional<z.ZodNumber>;
|
|
802
|
+
}, "strip", z.ZodTypeAny, {
|
|
803
|
+
ttlMs?: number | undefined;
|
|
804
|
+
}, {
|
|
805
|
+
ttlMs?: number | undefined;
|
|
806
|
+
}>]>>;
|
|
572
807
|
}, "strip", z.ZodTypeAny, {
|
|
573
808
|
id: string;
|
|
574
809
|
params: Record<string, string>;
|
|
575
810
|
name: string;
|
|
576
811
|
description: string;
|
|
577
812
|
fn: (args_0: any, ...args: unknown[]) => any;
|
|
813
|
+
toolType?: "source" | "direct" | undefined;
|
|
814
|
+
fullSchema?: string | undefined;
|
|
815
|
+
outputSchema?: {
|
|
816
|
+
description: string;
|
|
817
|
+
fields: {
|
|
818
|
+
type: "string" | "number" | "boolean" | "date";
|
|
819
|
+
name: string;
|
|
820
|
+
description: string;
|
|
821
|
+
}[];
|
|
822
|
+
} | undefined;
|
|
823
|
+
cache?: false | {
|
|
824
|
+
ttlMs?: number | undefined;
|
|
825
|
+
} | undefined;
|
|
578
826
|
}, {
|
|
579
827
|
id: string;
|
|
580
828
|
params: Record<string, string>;
|
|
581
829
|
name: string;
|
|
582
830
|
description: string;
|
|
583
831
|
fn: (args_0: any, ...args: unknown[]) => any;
|
|
832
|
+
toolType?: "source" | "direct" | undefined;
|
|
833
|
+
fullSchema?: string | undefined;
|
|
834
|
+
outputSchema?: {
|
|
835
|
+
description: string;
|
|
836
|
+
fields: {
|
|
837
|
+
type: "string" | "number" | "boolean" | "date";
|
|
838
|
+
name: string;
|
|
839
|
+
description: string;
|
|
840
|
+
}[];
|
|
841
|
+
} | undefined;
|
|
842
|
+
cache?: false | {
|
|
843
|
+
ttlMs?: number | undefined;
|
|
844
|
+
} | undefined;
|
|
584
845
|
}>;
|
|
585
846
|
type Tool$1 = z.infer<typeof ToolSchema>;
|
|
586
847
|
type CollectionOperation = 'getMany' | 'getOne' | 'query' | 'mutation' | 'updateOne' | 'deleteOne' | 'createOne';
|
|
587
848
|
type CollectionHandler<TParams = any, TResult = any> = (params: TParams) => Promise<TResult> | TResult;
|
|
588
849
|
type LLMProvider = 'anthropic' | 'groq' | 'gemini' | 'openai';
|
|
589
850
|
|
|
590
|
-
type DatabaseType = 'postgresql' | 'mssql';
|
|
851
|
+
type DatabaseType = 'postgresql' | 'mssql' | 'snowflake' | 'mysql';
|
|
852
|
+
/**
|
|
853
|
+
* Model strategy for controlling which models are used for different tasks
|
|
854
|
+
* - 'best': Use the best model (e.g., Sonnet) for all tasks - highest quality, higher cost
|
|
855
|
+
* - 'fast': Use the fast model (e.g., Haiku) for all tasks - lower quality, lower cost
|
|
856
|
+
* - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
|
|
857
|
+
*/
|
|
858
|
+
type ModelStrategy = 'best' | 'fast' | 'balanced';
|
|
859
|
+
/**
|
|
860
|
+
* Model configuration for DASH_COMP flow (dashboard component picking)
|
|
861
|
+
* Allows separate control of models used for component selection
|
|
862
|
+
*/
|
|
863
|
+
interface DashCompModelConfig {
|
|
864
|
+
/**
|
|
865
|
+
* Primary model for DASH_COMP requests
|
|
866
|
+
* Format: "provider/model-name" (e.g., "anthropic/claude-sonnet-4-5-20250929")
|
|
867
|
+
*/
|
|
868
|
+
model?: string;
|
|
869
|
+
/**
|
|
870
|
+
* Fast model for simpler DASH_COMP tasks (optional)
|
|
871
|
+
* Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
|
|
872
|
+
*/
|
|
873
|
+
fastModel?: string;
|
|
874
|
+
}
|
|
591
875
|
interface SuperatomSDKConfig {
|
|
592
876
|
url?: string;
|
|
593
877
|
apiKey?: string;
|
|
594
878
|
projectId: string;
|
|
595
|
-
userId?: string;
|
|
596
879
|
type?: string;
|
|
597
880
|
bundleDir?: string;
|
|
598
881
|
promptsDir?: string;
|
|
@@ -603,22 +886,68 @@ interface SuperatomSDKConfig {
|
|
|
603
886
|
OPENAI_API_KEY?: string;
|
|
604
887
|
LLM_PROVIDERS?: LLMProvider[];
|
|
605
888
|
logLevel?: LogLevel;
|
|
889
|
+
/**
|
|
890
|
+
* Model selection strategy for LLM API calls:
|
|
891
|
+
* - 'best': Use best model for all tasks (highest quality, higher cost)
|
|
892
|
+
* - 'fast': Use fast model for all tasks (lower quality, lower cost)
|
|
893
|
+
* - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
|
|
894
|
+
*/
|
|
895
|
+
modelStrategy?: ModelStrategy;
|
|
896
|
+
/**
|
|
897
|
+
* Model for the main agent (routing + analysis).
|
|
898
|
+
* Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
|
|
899
|
+
* If not set, uses the provider's default model.
|
|
900
|
+
*/
|
|
901
|
+
mainAgentModel?: string;
|
|
902
|
+
/**
|
|
903
|
+
* Model for source agents (per-source query generation).
|
|
904
|
+
* Format: "provider/model-name" (e.g., "anthropic/claude-haiku-4-5-20251001")
|
|
905
|
+
* If not set, uses the provider's default model.
|
|
906
|
+
*/
|
|
907
|
+
sourceAgentModel?: string;
|
|
908
|
+
/**
|
|
909
|
+
* Separate model configuration for DASH_COMP flow (dashboard component picking)
|
|
910
|
+
* If not provided, falls back to provider-based model selection
|
|
911
|
+
*/
|
|
912
|
+
dashCompModels?: DashCompModelConfig;
|
|
913
|
+
/**
|
|
914
|
+
* Similarity threshold for conversation search (semantic matching)
|
|
915
|
+
* Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
|
|
916
|
+
* Higher values require closer matches, lower values allow more distant matches
|
|
917
|
+
* Default: 0.8
|
|
918
|
+
*/
|
|
919
|
+
conversationSimilarityThreshold?: number;
|
|
920
|
+
/**
|
|
921
|
+
* Query cache TTL (Time To Live) in minutes
|
|
922
|
+
* Cached query results expire after this duration
|
|
923
|
+
* Default: 5 minutes
|
|
924
|
+
*/
|
|
925
|
+
queryCacheTTL?: number;
|
|
926
|
+
/**
|
|
927
|
+
* Dashboard conversation history TTL (Time To Live) in minutes
|
|
928
|
+
* Per-dashboard conversation histories expire after this duration
|
|
929
|
+
* Default: 30 minutes
|
|
930
|
+
*/
|
|
931
|
+
dashboardHistoryTTL?: number;
|
|
606
932
|
}
|
|
607
933
|
|
|
608
934
|
declare const KbNodesQueryFiltersSchema: z.ZodObject<{
|
|
609
935
|
query: z.ZodOptional<z.ZodString>;
|
|
610
936
|
category: z.ZodOptional<z.ZodString>;
|
|
611
937
|
tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
612
|
-
|
|
938
|
+
type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
|
|
939
|
+
createdBy: z.ZodOptional<z.ZodString>;
|
|
613
940
|
}, "strip", z.ZodTypeAny, {
|
|
941
|
+
type?: "query" | "user" | "global" | undefined;
|
|
614
942
|
query?: string | undefined;
|
|
615
943
|
category?: string | undefined;
|
|
616
|
-
createdBy?:
|
|
944
|
+
createdBy?: string | undefined;
|
|
617
945
|
tags?: string[] | undefined;
|
|
618
946
|
}, {
|
|
947
|
+
type?: "query" | "user" | "global" | undefined;
|
|
619
948
|
query?: string | undefined;
|
|
620
949
|
category?: string | undefined;
|
|
621
|
-
createdBy?:
|
|
950
|
+
createdBy?: string | undefined;
|
|
622
951
|
tags?: string[] | undefined;
|
|
623
952
|
}>;
|
|
624
953
|
type KbNodesQueryFilters = z.infer<typeof KbNodesQueryFiltersSchema>;
|
|
@@ -630,109 +959,126 @@ declare const KbNodesRequestPayloadSchema: z.ZodObject<{
|
|
|
630
959
|
content: z.ZodOptional<z.ZodString>;
|
|
631
960
|
category: z.ZodOptional<z.ZodString>;
|
|
632
961
|
tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
962
|
+
type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
|
|
963
|
+
createdBy: z.ZodOptional<z.ZodString>;
|
|
964
|
+
updatedBy: z.ZodOptional<z.ZodString>;
|
|
965
|
+
userId: z.ZodOptional<z.ZodString>;
|
|
636
966
|
query: z.ZodOptional<z.ZodString>;
|
|
637
967
|
filters: z.ZodOptional<z.ZodObject<{
|
|
638
968
|
query: z.ZodOptional<z.ZodString>;
|
|
639
969
|
category: z.ZodOptional<z.ZodString>;
|
|
640
970
|
tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
641
|
-
|
|
971
|
+
type: z.ZodOptional<z.ZodEnum<["global", "user", "query"]>>;
|
|
972
|
+
createdBy: z.ZodOptional<z.ZodString>;
|
|
642
973
|
}, "strip", z.ZodTypeAny, {
|
|
974
|
+
type?: "query" | "user" | "global" | undefined;
|
|
643
975
|
query?: string | undefined;
|
|
644
976
|
category?: string | undefined;
|
|
645
|
-
createdBy?:
|
|
977
|
+
createdBy?: string | undefined;
|
|
646
978
|
tags?: string[] | undefined;
|
|
647
979
|
}, {
|
|
980
|
+
type?: "query" | "user" | "global" | undefined;
|
|
648
981
|
query?: string | undefined;
|
|
649
982
|
category?: string | undefined;
|
|
650
|
-
createdBy?:
|
|
983
|
+
createdBy?: string | undefined;
|
|
651
984
|
tags?: string[] | undefined;
|
|
652
985
|
}>>;
|
|
653
986
|
limit: z.ZodOptional<z.ZodNumber>;
|
|
654
987
|
offset: z.ZodOptional<z.ZodNumber>;
|
|
655
988
|
}, "strip", z.ZodTypeAny, {
|
|
656
989
|
id?: number | undefined;
|
|
990
|
+
type?: "query" | "user" | "global" | undefined;
|
|
657
991
|
query?: string | undefined;
|
|
658
992
|
title?: string | undefined;
|
|
659
993
|
category?: string | undefined;
|
|
660
|
-
userId?:
|
|
994
|
+
userId?: string | undefined;
|
|
661
995
|
limit?: number | undefined;
|
|
662
996
|
filters?: {
|
|
997
|
+
type?: "query" | "user" | "global" | undefined;
|
|
663
998
|
query?: string | undefined;
|
|
664
999
|
category?: string | undefined;
|
|
665
|
-
createdBy?:
|
|
1000
|
+
createdBy?: string | undefined;
|
|
666
1001
|
tags?: string[] | undefined;
|
|
667
1002
|
} | undefined;
|
|
668
|
-
createdBy?:
|
|
669
|
-
updatedBy?:
|
|
1003
|
+
createdBy?: string | undefined;
|
|
1004
|
+
updatedBy?: string | undefined;
|
|
1005
|
+
offset?: number | undefined;
|
|
670
1006
|
tags?: string[] | undefined;
|
|
671
1007
|
content?: string | undefined;
|
|
672
|
-
offset?: number | undefined;
|
|
673
1008
|
}, {
|
|
674
1009
|
id?: number | undefined;
|
|
1010
|
+
type?: "query" | "user" | "global" | undefined;
|
|
675
1011
|
query?: string | undefined;
|
|
676
1012
|
title?: string | undefined;
|
|
677
1013
|
category?: string | undefined;
|
|
678
|
-
userId?:
|
|
1014
|
+
userId?: string | undefined;
|
|
679
1015
|
limit?: number | undefined;
|
|
680
1016
|
filters?: {
|
|
1017
|
+
type?: "query" | "user" | "global" | undefined;
|
|
681
1018
|
query?: string | undefined;
|
|
682
1019
|
category?: string | undefined;
|
|
683
|
-
createdBy?:
|
|
1020
|
+
createdBy?: string | undefined;
|
|
684
1021
|
tags?: string[] | undefined;
|
|
685
1022
|
} | undefined;
|
|
686
|
-
createdBy?:
|
|
687
|
-
updatedBy?:
|
|
1023
|
+
createdBy?: string | undefined;
|
|
1024
|
+
updatedBy?: string | undefined;
|
|
1025
|
+
offset?: number | undefined;
|
|
688
1026
|
tags?: string[] | undefined;
|
|
689
1027
|
content?: string | undefined;
|
|
690
|
-
offset?: number | undefined;
|
|
691
1028
|
}>>;
|
|
692
1029
|
}, "strip", z.ZodTypeAny, {
|
|
693
1030
|
operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
|
|
694
1031
|
data?: {
|
|
695
1032
|
id?: number | undefined;
|
|
1033
|
+
type?: "query" | "user" | "global" | undefined;
|
|
696
1034
|
query?: string | undefined;
|
|
697
1035
|
title?: string | undefined;
|
|
698
1036
|
category?: string | undefined;
|
|
699
|
-
userId?:
|
|
1037
|
+
userId?: string | undefined;
|
|
700
1038
|
limit?: number | undefined;
|
|
701
1039
|
filters?: {
|
|
1040
|
+
type?: "query" | "user" | "global" | undefined;
|
|
702
1041
|
query?: string | undefined;
|
|
703
1042
|
category?: string | undefined;
|
|
704
|
-
createdBy?:
|
|
1043
|
+
createdBy?: string | undefined;
|
|
705
1044
|
tags?: string[] | undefined;
|
|
706
1045
|
} | undefined;
|
|
707
|
-
createdBy?:
|
|
708
|
-
updatedBy?:
|
|
1046
|
+
createdBy?: string | undefined;
|
|
1047
|
+
updatedBy?: string | undefined;
|
|
1048
|
+
offset?: number | undefined;
|
|
709
1049
|
tags?: string[] | undefined;
|
|
710
1050
|
content?: string | undefined;
|
|
711
|
-
offset?: number | undefined;
|
|
712
1051
|
} | undefined;
|
|
713
1052
|
}, {
|
|
714
1053
|
operation: "create" | "getOne" | "update" | "delete" | "getAll" | "search" | "getByCategory" | "getByUser" | "getCategories" | "getTags";
|
|
715
1054
|
data?: {
|
|
716
1055
|
id?: number | undefined;
|
|
1056
|
+
type?: "query" | "user" | "global" | undefined;
|
|
717
1057
|
query?: string | undefined;
|
|
718
1058
|
title?: string | undefined;
|
|
719
1059
|
category?: string | undefined;
|
|
720
|
-
userId?:
|
|
1060
|
+
userId?: string | undefined;
|
|
721
1061
|
limit?: number | undefined;
|
|
722
1062
|
filters?: {
|
|
1063
|
+
type?: "query" | "user" | "global" | undefined;
|
|
723
1064
|
query?: string | undefined;
|
|
724
1065
|
category?: string | undefined;
|
|
725
|
-
createdBy?:
|
|
1066
|
+
createdBy?: string | undefined;
|
|
726
1067
|
tags?: string[] | undefined;
|
|
727
1068
|
} | undefined;
|
|
728
|
-
createdBy?:
|
|
729
|
-
updatedBy?:
|
|
1069
|
+
createdBy?: string | undefined;
|
|
1070
|
+
updatedBy?: string | undefined;
|
|
1071
|
+
offset?: number | undefined;
|
|
730
1072
|
tags?: string[] | undefined;
|
|
731
1073
|
content?: string | undefined;
|
|
732
|
-
offset?: number | undefined;
|
|
733
1074
|
} | undefined;
|
|
734
1075
|
}>;
|
|
735
1076
|
type KbNodesRequestPayload = z.infer<typeof KbNodesRequestPayloadSchema>;
|
|
1077
|
+
interface T_RESPONSE {
|
|
1078
|
+
success: boolean;
|
|
1079
|
+
data?: any;
|
|
1080
|
+
errors: string[];
|
|
1081
|
+
}
|
|
736
1082
|
|
|
737
1083
|
/**
|
|
738
1084
|
* UserManager class to handle CRUD operations on users with file persistence
|
|
@@ -993,114 +1339,1359 @@ declare class ReportManager {
|
|
|
993
1339
|
getReportCount(): number;
|
|
994
1340
|
}
|
|
995
1341
|
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
description: string;
|
|
1012
|
-
input_schema: {
|
|
1013
|
-
type: string;
|
|
1014
|
-
properties: Record<string, any>;
|
|
1015
|
-
required?: string[];
|
|
1016
|
-
};
|
|
1017
|
-
}
|
|
1018
|
-
declare class LLM {
|
|
1019
|
-
static text(messages: LLMMessages, options?: LLMOptions): Promise<string>;
|
|
1020
|
-
static stream<T = string>(messages: LLMMessages, options?: LLMOptions, json?: boolean): Promise<T extends string ? string : any>;
|
|
1021
|
-
static streamWithTools(messages: LLMMessages, tools: Tool[], toolHandler: (toolName: string, toolInput: any) => Promise<any>, options?: LLMOptions, maxIterations?: number): Promise<string>;
|
|
1342
|
+
/**
|
|
1343
|
+
* StreamBuffer - Buffered streaming utility for smoother text delivery
|
|
1344
|
+
* Batches small chunks together and flushes at regular intervals
|
|
1345
|
+
*/
|
|
1346
|
+
type StreamCallback = (chunk: string) => void;
|
|
1347
|
+
/**
|
|
1348
|
+
* StreamBuffer class for managing buffered streaming output
|
|
1349
|
+
* Provides smooth text delivery by batching small chunks
|
|
1350
|
+
*/
|
|
1351
|
+
declare class StreamBuffer {
|
|
1352
|
+
private buffer;
|
|
1353
|
+
private flushTimer;
|
|
1354
|
+
private callback;
|
|
1355
|
+
private fullText;
|
|
1356
|
+
constructor(callback?: StreamCallback);
|
|
1022
1357
|
/**
|
|
1023
|
-
*
|
|
1024
|
-
* Converts string to array format if needed
|
|
1025
|
-
* @param sys - System prompt (string or array of blocks)
|
|
1026
|
-
* @returns Normalized system prompt for Anthropic API
|
|
1358
|
+
* Check if the buffer has a callback configured
|
|
1027
1359
|
*/
|
|
1028
|
-
|
|
1360
|
+
hasCallback(): boolean;
|
|
1029
1361
|
/**
|
|
1030
|
-
*
|
|
1031
|
-
* Shows cache hits, costs, and savings
|
|
1362
|
+
* Get all text that has been written (including already flushed)
|
|
1032
1363
|
*/
|
|
1033
|
-
|
|
1364
|
+
getFullText(): string;
|
|
1034
1365
|
/**
|
|
1035
|
-
*
|
|
1036
|
-
*
|
|
1037
|
-
*
|
|
1366
|
+
* Write a chunk to the buffer
|
|
1367
|
+
* Large chunks or chunks with newlines are flushed immediately
|
|
1368
|
+
* Small chunks are batched and flushed after a short interval
|
|
1038
1369
|
*
|
|
1039
|
-
* @
|
|
1040
|
-
* "anthropic/claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"]
|
|
1041
|
-
* "groq/openai/gpt-oss-120b" → ["groq", "openai/gpt-oss-120b"]
|
|
1042
|
-
* "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
|
|
1370
|
+
* @param chunk - Text chunk to write
|
|
1043
1371
|
*/
|
|
1044
|
-
|
|
1045
|
-
private static _anthropicText;
|
|
1046
|
-
private static _anthropicStream;
|
|
1047
|
-
private static _anthropicStreamWithTools;
|
|
1048
|
-
private static _groqText;
|
|
1049
|
-
private static _groqStream;
|
|
1050
|
-
private static _geminiText;
|
|
1051
|
-
private static _geminiStream;
|
|
1052
|
-
private static _geminiStreamWithTools;
|
|
1053
|
-
private static _openaiText;
|
|
1054
|
-
private static _openaiStream;
|
|
1055
|
-
private static _openaiStreamWithTools;
|
|
1372
|
+
write(chunk: string): void;
|
|
1056
1373
|
/**
|
|
1057
|
-
*
|
|
1058
|
-
*
|
|
1059
|
-
* @param text - Text that may contain JSON wrapped in ```json...``` or with surrounding text
|
|
1060
|
-
* @returns Parsed JSON object or array
|
|
1374
|
+
* Flush the buffer immediately
|
|
1375
|
+
* Call this before tool execution or other operations that need clean output
|
|
1061
1376
|
*/
|
|
1062
|
-
|
|
1377
|
+
flush(): void;
|
|
1378
|
+
/**
|
|
1379
|
+
* Internal flush implementation
|
|
1380
|
+
*/
|
|
1381
|
+
private flushNow;
|
|
1382
|
+
/**
|
|
1383
|
+
* Clean up resources
|
|
1384
|
+
* Call this when done with the buffer
|
|
1385
|
+
*/
|
|
1386
|
+
dispose(): void;
|
|
1063
1387
|
}
|
|
1064
1388
|
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1389
|
+
/**
|
|
1390
|
+
* ToolExecutorService - Handles execution of SQL queries and external tools
|
|
1391
|
+
* Extracted from BaseLLM.generateTextResponse for better separation of concerns
|
|
1392
|
+
*/
|
|
1393
|
+
|
|
1394
|
+
/**
|
|
1395
|
+
* External tool definition
|
|
1396
|
+
*/
|
|
1397
|
+
interface ExternalTool {
|
|
1398
|
+
id: string;
|
|
1399
|
+
name: string;
|
|
1400
|
+
description?: string;
|
|
1401
|
+
/** Tool type: "source" = routed through SourceAgent, "direct" = called directly by MainAgent */
|
|
1402
|
+
toolType?: 'source' | 'direct';
|
|
1403
|
+
/** Full untruncated schema for source agent (all columns visible) */
|
|
1404
|
+
fullSchema?: string;
|
|
1405
|
+
/** Schema size tier: small (≤50 tables), medium (51-200), large (201-500), very_large (500+) */
|
|
1406
|
+
schemaTier?: string;
|
|
1407
|
+
/** Schema search function for very_large tier — keyword search over entities */
|
|
1408
|
+
schemaSearchFn?: (keywords: string[]) => string;
|
|
1409
|
+
fn: (input: any) => Promise<any>;
|
|
1410
|
+
limit?: number;
|
|
1411
|
+
outputSchema?: any;
|
|
1412
|
+
executionType?: 'immediate' | 'deferred';
|
|
1413
|
+
userProvidedData?: any;
|
|
1414
|
+
params?: Record<string, any>;
|
|
1071
1415
|
}
|
|
1072
1416
|
/**
|
|
1073
|
-
*
|
|
1074
|
-
* and sends them to runtime via ui_logs message with uiBlockId as the message id
|
|
1075
|
-
* Logs are sent in real-time for streaming effect in the UI
|
|
1076
|
-
* Respects the global log level configuration
|
|
1417
|
+
* Executed tool tracking info
|
|
1077
1418
|
*/
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1419
|
+
interface ExecutedToolInfo {
|
|
1420
|
+
id: string;
|
|
1421
|
+
name: string;
|
|
1422
|
+
params: any;
|
|
1423
|
+
result: {
|
|
1424
|
+
_totalRecords: number;
|
|
1425
|
+
_recordsShown: number;
|
|
1426
|
+
_metadata?: any;
|
|
1427
|
+
_sampleData: any[];
|
|
1428
|
+
/** Bounded summary over the FULL fetched result (complete structure). */
|
|
1429
|
+
_summary?: any;
|
|
1430
|
+
/** Up to MAIN_AGENT_COMPLETE_ROWS rows — the complete result when small. */
|
|
1431
|
+
_mainAgentRows?: any[];
|
|
1432
|
+
};
|
|
1433
|
+
outputSchema?: any;
|
|
1434
|
+
sourceSchema?: string;
|
|
1435
|
+
sourceType?: string;
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
/**
|
|
1439
|
+
* Multi-Agent Architecture Types
|
|
1440
|
+
*
|
|
1441
|
+
* Defines interfaces for the hierarchical agent system:
|
|
1442
|
+
* - Main Agent: ONE LLM.streamWithTools() call with source agent tools
|
|
1443
|
+
* - Source Agents: independent agents that query individual data sources
|
|
1444
|
+
*
|
|
1445
|
+
* The main agent sees only source summaries. When it calls a source tool,
|
|
1446
|
+
* the SourceAgent runs independently (own LLM, own retries) and returns clean data.
|
|
1447
|
+
*/
|
|
1448
|
+
|
|
1449
|
+
/**
|
|
1450
|
+
* Per-entity detail: name, row count, and column names.
|
|
1451
|
+
* Gives the main agent enough context to route to the right source.
|
|
1452
|
+
*/
|
|
1453
|
+
interface EntityDetail {
|
|
1454
|
+
/** Entity name (table, sheet, endpoint) */
|
|
1455
|
+
name: string;
|
|
1456
|
+
/** Approximate row count */
|
|
1457
|
+
rowCount?: number;
|
|
1458
|
+
/** Column/field names */
|
|
1459
|
+
columns: string[];
|
|
1460
|
+
/** Entity-level semantic summary (what the table means) — for main-agent routing. */
|
|
1461
|
+
summary?: string;
|
|
1462
|
+
}
|
|
1463
|
+
/**
|
|
1464
|
+
* Representation of a data source for the main agent.
|
|
1465
|
+
* Contains entity names WITH column names so the LLM can route accurately.
|
|
1466
|
+
*/
|
|
1467
|
+
interface SourceSummary {
|
|
1468
|
+
/** Source ID (matches tool ID prefix) */
|
|
1469
|
+
id: string;
|
|
1470
|
+
/** Human-readable source name */
|
|
1471
|
+
name: string;
|
|
1472
|
+
/** Source type: postgres, excel, rest_api, etc. */
|
|
1473
|
+
type: string;
|
|
1474
|
+
/** Brief description of what data this source contains */
|
|
1475
|
+
description: string;
|
|
1476
|
+
/** Detailed entity info with column names for routing */
|
|
1477
|
+
entityDetails: EntityDetail[];
|
|
1478
|
+
/** The tool ID associated with this source */
|
|
1479
|
+
toolId: string;
|
|
1480
|
+
}
|
|
1481
|
+
/**
|
|
1482
|
+
* What a source agent returns after querying its data source.
|
|
1483
|
+
* The main agent uses this to analyze and compose the final response.
|
|
1484
|
+
*/
|
|
1485
|
+
interface SourceAgentResult {
|
|
1486
|
+
/** Source ID */
|
|
1487
|
+
sourceId: string;
|
|
1488
|
+
/** Source name */
|
|
1489
|
+
sourceName: string;
|
|
1490
|
+
/** Whether the query succeeded */
|
|
1491
|
+
success: boolean;
|
|
1492
|
+
/** Result data rows */
|
|
1493
|
+
data: any[];
|
|
1494
|
+
/** Metadata about the query execution */
|
|
1495
|
+
metadata: SourceAgentMetadata;
|
|
1496
|
+
/** Tool execution info for the last successful query (backward compat) */
|
|
1497
|
+
executedTool: ExecutedToolInfo;
|
|
1498
|
+
/** All successful tool executions (primary + follow-up queries) */
|
|
1499
|
+
allExecutedTools?: ExecutedToolInfo[];
|
|
1500
|
+
/** Error message if failed */
|
|
1501
|
+
error?: string;
|
|
1502
|
+
}
|
|
1503
|
+
interface SourceAgentMetadata {
|
|
1504
|
+
/** Total rows that matched the query (before limit) */
|
|
1505
|
+
totalRowsMatched: number;
|
|
1506
|
+
/** Rows actually returned (after limit) */
|
|
1507
|
+
rowsReturned: number;
|
|
1508
|
+
/** Whether the result was truncated by the row limit */
|
|
1509
|
+
isLimited: boolean;
|
|
1510
|
+
/** The query/params that were executed */
|
|
1511
|
+
queryExecuted?: string;
|
|
1512
|
+
/** Execution time in milliseconds */
|
|
1513
|
+
executionTimeMs: number;
|
|
1514
|
+
}
|
|
1515
|
+
/**
|
|
1516
|
+
* A pre-built, multi-step UI flow registered with the SDK.
|
|
1517
|
+
*
|
|
1518
|
+
* When the main agent decides a user's question matches a workflow's whenToUse
|
|
1519
|
+
* trigger, it picks the workflow instead of running source agents / generating
|
|
1520
|
+
* dashboard components. The LLM extracts the workflow's required props from the
|
|
1521
|
+
* prompt (using `propsSchema` as the tool input_schema) and the SDK returns the
|
|
1522
|
+
* workflow component directly — no analysis text, no chart generation. The
|
|
1523
|
+
* frontend renders the registered workflow component with the LLM-extracted
|
|
1524
|
+
* props.
|
|
1525
|
+
*/
|
|
1526
|
+
interface WorkflowDescriptor {
|
|
1527
|
+
/** Unique workflow id (used as the LLM tool name) */
|
|
1528
|
+
id: string;
|
|
1529
|
+
/** Component name on the frontend (matches the registered React component) */
|
|
1530
|
+
name: string;
|
|
1531
|
+
/** Short human-readable description of what this workflow does */
|
|
1532
|
+
description: string;
|
|
1089
1533
|
/**
|
|
1090
|
-
*
|
|
1534
|
+
* 1–2 sentence trigger condition. The LLM uses this to decide if the
|
|
1535
|
+
* user's prompt matches this workflow. Be specific — e.g.
|
|
1536
|
+
* "User wants to *initiate* an inventory transfer (review + submit POs),
|
|
1537
|
+
* not just see analysis or charts."
|
|
1091
1538
|
*/
|
|
1092
|
-
|
|
1539
|
+
whenToUse: string;
|
|
1093
1540
|
/**
|
|
1094
|
-
*
|
|
1095
|
-
*
|
|
1541
|
+
* JSON-schema-style description of the props the workflow needs. Becomes
|
|
1542
|
+
* the LLM tool's input_schema, so the model fills these from the prompt.
|
|
1543
|
+
* Use the same shape as `params` on direct tools — string descriptors with
|
|
1544
|
+
* an optional "(optional)" suffix.
|
|
1545
|
+
*
|
|
1546
|
+
* Example:
|
|
1547
|
+
* ```
|
|
1548
|
+
* {
|
|
1549
|
+
* selectedStore: 'object — { id, name } of the source branch',
|
|
1550
|
+
* minROI: 'number (optional) — only show transfers with ROI ≥ this',
|
|
1551
|
+
* }
|
|
1552
|
+
* ```
|
|
1096
1553
|
*/
|
|
1097
|
-
|
|
1554
|
+
propsSchema: Record<string, string>;
|
|
1098
1555
|
/**
|
|
1099
|
-
*
|
|
1556
|
+
* Optional: static prop defaults merged with LLM-extracted props before
|
|
1557
|
+
* the component is returned. Useful for things like the embedded
|
|
1558
|
+
* `externalTool` config that the workflow uses to fetch its own data.
|
|
1100
1559
|
*/
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1560
|
+
defaultProps?: Record<string, any>;
|
|
1561
|
+
}
|
|
1562
|
+
/**
|
|
1563
|
+
* The workflow selection captured during a routing call.
|
|
1564
|
+
* Set on AgentResponse when the LLM picks a workflow tool.
|
|
1565
|
+
*/
|
|
1566
|
+
interface SelectedWorkflow {
|
|
1567
|
+
/** Component name (matches WorkflowDescriptor.name) */
|
|
1568
|
+
name: string;
|
|
1569
|
+
/** Props extracted from the prompt + merged with workflow.defaultProps */
|
|
1570
|
+
props: Record<string, any>;
|
|
1571
|
+
}
|
|
1572
|
+
/**
|
|
1573
|
+
* Set when this turn applies a user-directed edit to an existing script instead
|
|
1574
|
+
* of authoring a new one. MainAgent keeps the SAME harness (tools, loop,
|
|
1575
|
+
* write_script/execute_script verification) and swaps only the system prompt —
|
|
1576
|
+
* `agent-main-edit` instead of `agent-main`.
|
|
1577
|
+
*
|
|
1578
|
+
* The two framings contradict each other on whether to query a source first, so
|
|
1579
|
+
* they must never be resident in one rendered prompt.
|
|
1580
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § D3.
|
|
1581
|
+
*/
|
|
1582
|
+
interface EditContext {
|
|
1583
|
+
/** Recipe being edited — the shadow draft records it as parentId. */
|
|
1584
|
+
recipeId: string;
|
|
1585
|
+
parentName: string;
|
|
1586
|
+
parentBody: string;
|
|
1587
|
+
/** Self-contained restatement of the change (from the matcher). */
|
|
1588
|
+
instruction: string;
|
|
1589
|
+
/** Columns the last run returned — grounds the edit without a re-query. */
|
|
1590
|
+
lastResultColumns?: string[];
|
|
1591
|
+
/** Rendered parameter list of the parent, for the prompt. */
|
|
1592
|
+
parentParams?: string;
|
|
1593
|
+
}
|
|
1594
|
+
/**
|
|
1595
|
+
* The complete response from the multi-agent system.
|
|
1596
|
+
* Contains everything needed for text display + component generation.
|
|
1597
|
+
*/
|
|
1598
|
+
interface AgentResponse {
|
|
1599
|
+
/** Generated text response (analysis of the data) */
|
|
1600
|
+
text: string;
|
|
1601
|
+
/** All executed tools across all source agents (for component generation) */
|
|
1602
|
+
executedTools: ExecutedToolInfo[];
|
|
1603
|
+
/** Individual results from each source agent */
|
|
1604
|
+
sourceResults: SourceAgentResult[];
|
|
1605
|
+
/**
|
|
1606
|
+
* Populated when MainAgent wrote AND successfully executed a script during its turn.
|
|
1607
|
+
* Caller (agent-user-response.ts) persists it via ScriptStore.save().
|
|
1608
|
+
* Absent when MainAgent didn't write one (trivial question / all attempts failed).
|
|
1609
|
+
*/
|
|
1610
|
+
savedScript?: AgentWrittenScript;
|
|
1611
|
+
/**
|
|
1612
|
+
* Set when the LLM routed the question to a registered workflow component.
|
|
1613
|
+
* When present, the upstream caller should skip component generation and
|
|
1614
|
+
* return this workflow as the response.
|
|
1615
|
+
*/
|
|
1616
|
+
workflow?: SelectedWorkflow;
|
|
1617
|
+
}
|
|
1618
|
+
/**
|
|
1619
|
+
* A script MainAgent authored + verified during its turn. Shape aligns with
|
|
1620
|
+
* what ScriptStore.save() needs — minus store-assigned fields (id, timestamps, counts).
|
|
1621
|
+
*/
|
|
1622
|
+
interface AgentWrittenScript {
|
|
1623
|
+
/**
|
|
1624
|
+
* `ScriptRecipe.id` of the draft that was authored + verified during this turn.
|
|
1625
|
+
* The caller passes this to `ScriptStore.promoteToVerified(recipeId, …)` to
|
|
1626
|
+
* flip the draft to verified status and (when possible) drop the turn-suffix
|
|
1627
|
+
* from its filename.
|
|
1628
|
+
*/
|
|
1629
|
+
recipeId: string;
|
|
1630
|
+
name: string;
|
|
1631
|
+
intentDescription: string;
|
|
1632
|
+
tags: string[];
|
|
1633
|
+
parameters: Array<{
|
|
1634
|
+
name: string;
|
|
1635
|
+
type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
|
|
1636
|
+
required: boolean;
|
|
1637
|
+
default?: any;
|
|
1638
|
+
enumValues?: Record<string, string>;
|
|
1639
|
+
description: string;
|
|
1640
|
+
}>;
|
|
1641
|
+
scriptBody: string;
|
|
1642
|
+
/** Source IDs referenced by the script (extracted from ctx.query calls) */
|
|
1643
|
+
sourceIds: string[];
|
|
1644
|
+
/** Tables referenced in the script's SQL (regex-extracted) */
|
|
1645
|
+
tables: string[];
|
|
1646
|
+
/** Executed queries from the verified run — fed to component generation */
|
|
1647
|
+
executedQueries: Array<{
|
|
1648
|
+
sourceId: string;
|
|
1649
|
+
sourceName: string;
|
|
1650
|
+
sql: string;
|
|
1651
|
+
data: any[];
|
|
1652
|
+
count: number;
|
|
1653
|
+
totalCount?: number;
|
|
1654
|
+
executionTimeMs: number;
|
|
1655
|
+
/**
|
|
1656
|
+
* True for synthetic entries (ctx.emit datasets, the computed:_final
|
|
1657
|
+
* post-JS data). The component generator routes virtual sources through
|
|
1658
|
+
* the script_dataset sentinel toolId so the frontend resolves them via
|
|
1659
|
+
* queryCache instead of attempting to re-execute SQL.
|
|
1660
|
+
*/
|
|
1661
|
+
virtual?: boolean;
|
|
1662
|
+
}>;
|
|
1663
|
+
}
|
|
1664
|
+
/**
|
|
1665
|
+
* Configuration for the multi-agent system.
|
|
1666
|
+
* Controls limits, models, and behavior.
|
|
1667
|
+
*/
|
|
1668
|
+
interface AgentConfig {
|
|
1669
|
+
/** Max rows shown to the UI preview / inlined per source (default: 10) */
|
|
1670
|
+
maxRowsPerSource: number;
|
|
1671
|
+
/**
|
|
1672
|
+
* Max rows a source query may FETCH from the DB server-side (default: 2000).
|
|
1673
|
+
* Decoupled from what the main agent is shown: the full result is fetched and
|
|
1674
|
+
* summarized (bounded), but only a small/complete slice enters LLM context.
|
|
1675
|
+
* This lets small lookups (benchmark maps) arrive COMPLETE without letting
|
|
1676
|
+
* large results blow up context.
|
|
1677
|
+
*/
|
|
1678
|
+
maxRowsFetched: number;
|
|
1679
|
+
/** Model for the main agent (routing + analysis in one LLM call) */
|
|
1680
|
+
mainAgentModel: string;
|
|
1681
|
+
/** Model for source agent query generation */
|
|
1682
|
+
sourceAgentModel: string;
|
|
1683
|
+
/** API key for LLM calls */
|
|
1684
|
+
apiKey?: string;
|
|
1685
|
+
/** Max retry attempts per source agent */
|
|
1686
|
+
maxRetries: number;
|
|
1687
|
+
/** Max tool calling iterations for the main agent loop */
|
|
1688
|
+
maxIterations: number;
|
|
1689
|
+
/** Global knowledge base context (static, same for all users/questions — cached in system prompt) */
|
|
1690
|
+
globalKnowledgeBase?: string;
|
|
1691
|
+
/** Per-request knowledge base context (user-specific + query-matched — dynamic, not cached) */
|
|
1692
|
+
knowledgeBaseContext?: string;
|
|
1693
|
+
/** Collections registry (ChromaDB search hooks) for embedding-based schema + source search */
|
|
1694
|
+
collections?: any;
|
|
1695
|
+
/** Optional project ID for scoping embedding searches */
|
|
1696
|
+
projectId?: string;
|
|
1697
|
+
}
|
|
1698
|
+
/**
|
|
1699
|
+
* Default agent configuration
|
|
1700
|
+
*/
|
|
1701
|
+
declare const DEFAULT_AGENT_CONFIG: AgentConfig;
|
|
1702
|
+
|
|
1703
|
+
/**
|
|
1704
|
+
* Script Flow Types
|
|
1705
|
+
*
|
|
1706
|
+
* Defines interfaces for the script-based query architecture:
|
|
1707
|
+
* - ScriptRecipe: metadata for matching, validation, and quality tracking
|
|
1708
|
+
* - ScriptResult: output from executing a script
|
|
1709
|
+
* - ScriptMatch: result from the LLM-based script matcher
|
|
1710
|
+
*/
|
|
1711
|
+
/**
|
|
1712
|
+
* Recipe metadata stored alongside each script.
|
|
1713
|
+
* Used for matching, validation, and quality tracking.
|
|
1714
|
+
*/
|
|
1715
|
+
interface ScriptRecipe {
|
|
1716
|
+
/** Unique script identifier */
|
|
1717
|
+
id: string;
|
|
1718
|
+
/** Version number (incremented on regeneration) */
|
|
1719
|
+
version: number;
|
|
1720
|
+
/** Human-readable name (e.g., "Revenue by Dimension") */
|
|
1721
|
+
name: string;
|
|
1722
|
+
/** Natural language description of what this script does */
|
|
1723
|
+
intentDescription: string;
|
|
1724
|
+
/** Keyword tags for quick filtering */
|
|
1725
|
+
tags: string[];
|
|
1726
|
+
/** Source tool IDs this script queries (e.g., ["mssql-abc123_query"]) */
|
|
1727
|
+
sourceIds: string[];
|
|
1728
|
+
/** Table names used (for future schema drift detection) */
|
|
1729
|
+
tables: string[];
|
|
1730
|
+
/** Parameter definitions — what can vary */
|
|
1731
|
+
parameters: ScriptParameter[];
|
|
1732
|
+
/** The script function body as a string. Loaded from disk (scripts-store/<fileBase>.ts). */
|
|
1733
|
+
scriptBody: string;
|
|
1734
|
+
/**
|
|
1735
|
+
* On-disk filename stem for the body: scripts-store/<fileBase>.ts.
|
|
1736
|
+
* Editable in the IDE. Decided at authoring time (slug of `name`, with a
|
|
1737
|
+
* short id suffix on collision) and stable across promotion.
|
|
1738
|
+
*/
|
|
1739
|
+
fileBase?: string;
|
|
1740
|
+
/** sha256 of the on-disk body — lets the runtime detect manual edits. */
|
|
1741
|
+
bodyHash?: string;
|
|
1742
|
+
/** Project scope (single-VM deployments may leave this undefined). */
|
|
1743
|
+
projectId?: string;
|
|
1744
|
+
/** Times this script was used successfully */
|
|
1745
|
+
successCount: number;
|
|
1746
|
+
/** Times this script failed */
|
|
1747
|
+
failureCount: number;
|
|
1748
|
+
/** ISO timestamp of last usage */
|
|
1749
|
+
lastUsed: string;
|
|
1750
|
+
/** Original user question that created this script */
|
|
1751
|
+
createdFrom: string;
|
|
1752
|
+
/** ISO timestamp */
|
|
1753
|
+
createdAt: string;
|
|
1754
|
+
/** ISO timestamp */
|
|
1755
|
+
updatedAt: string;
|
|
1756
|
+
/**
|
|
1757
|
+
* `recipe.id` of the parent this script was forked from.
|
|
1758
|
+
* Undefined for root scripts (those written from scratch by MainAgent).
|
|
1759
|
+
* See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md.
|
|
1760
|
+
*/
|
|
1761
|
+
parentId?: string;
|
|
1762
|
+
/** 0 for root scripts; `parent.forkDepth + 1` for forks. Capped at 3. */
|
|
1763
|
+
forkDepth?: number;
|
|
1764
|
+
/**
|
|
1765
|
+
* Brief description of what this fork changed vs its parent
|
|
1766
|
+
* (sourced from the matcher's `modificationHint`).
|
|
1767
|
+
*/
|
|
1768
|
+
forkReason?: string;
|
|
1769
|
+
/**
|
|
1770
|
+
* Validated component specs captured at authoring time. On a tier-high
|
|
1771
|
+
* replay these are rebound to fresh queryIds deterministically — no
|
|
1772
|
+
* component-generation LLM call, and the rendered columns can't drift from
|
|
1773
|
+
* what was validated when the script was authored. Absent on recipes
|
|
1774
|
+
* authored before this landed; those fall back to LLM component generation.
|
|
1775
|
+
* See backend/docs/SCRIPT-COMPONENT-CONSISTENCY.md.
|
|
1776
|
+
*/
|
|
1777
|
+
components?: ScriptComponentSpec[];
|
|
1778
|
+
/**
|
|
1779
|
+
* What the user explicitly asked the output to LOOK like, set by a display
|
|
1780
|
+
* edit ("show that as a bar chart", "make the bars horizontal").
|
|
1781
|
+
*
|
|
1782
|
+
* Deliberately SEPARATE from `components`. Those are validated bindings that
|
|
1783
|
+
* must be cleared on a data edit — after "break it down by brand" the axis
|
|
1784
|
+
* keys are wrong, and after "use the mode" the stored title still says
|
|
1785
|
+
* "Average…". A rendering CHOICE, by contrast, is still valid afterwards.
|
|
1786
|
+
* Keeping them in one field meant every data edit silently discarded the
|
|
1787
|
+
* user's chart type.
|
|
1788
|
+
*
|
|
1789
|
+
* Fed to the component generator as a hint whenever specs are (re)generated,
|
|
1790
|
+
* so the chosen rendering comes back even after the SQL changes.
|
|
1791
|
+
*/
|
|
1792
|
+
displayPreference?: ScriptDisplayPreference;
|
|
1793
|
+
/**
|
|
1794
|
+
* Lifecycle stage of this recipe on disk.
|
|
1795
|
+
* - 'draft': written by MainAgent's write_script during a turn; filtered out
|
|
1796
|
+
* of FTS results (status='verified' only) so the matcher never picks it.
|
|
1797
|
+
* Filename is suffixed with `turnId` to keep concurrent turns
|
|
1798
|
+
* from clobbering each other's drafts.
|
|
1799
|
+
* - 'verified': promoted after `execute_script` succeeded; the matcher sees it.
|
|
1800
|
+
* Filename drops the turn suffix unless a verified file with
|
|
1801
|
+
* the same slug already exists (collision case keeps the suffix).
|
|
1802
|
+
*
|
|
1803
|
+
* Recipes loaded from disk without this field default to 'verified' so
|
|
1804
|
+
* existing scripts keep working unchanged.
|
|
1805
|
+
*/
|
|
1806
|
+
status?: 'draft' | 'verified';
|
|
1807
|
+
/**
|
|
1808
|
+
* Per-turn unique suffix used for draft filenames (e.g. `1714745623-x9k2`).
|
|
1809
|
+
* Set when the draft is saved; carried until the recipe is promoted.
|
|
1810
|
+
*/
|
|
1811
|
+
turnId?: string;
|
|
1812
|
+
/**
|
|
1813
|
+
* Last execution error captured by `recordDraftError` while the recipe was
|
|
1814
|
+
* still a draft. Lets users open the draft .json file and see why it failed
|
|
1815
|
+
* without grepping logs. Cleared on promotion to 'verified'.
|
|
1816
|
+
*/
|
|
1817
|
+
lastError?: {
|
|
1818
|
+
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
1819
|
+
message: string;
|
|
1820
|
+
at: string;
|
|
1821
|
+
attempt: number;
|
|
1822
|
+
};
|
|
1823
|
+
/** userId who committed the most recent edit (audit trail — recipes are project-scoped). */
|
|
1824
|
+
editedBy?: string;
|
|
1825
|
+
/** The instruction that produced the current version. */
|
|
1826
|
+
editedFrom?: string;
|
|
1827
|
+
/**
|
|
1828
|
+
* Prior versions, newest last. The body itself is archived on disk as
|
|
1829
|
+
* `<fileBase>.v<version>.ts`; this records what changed and who did it.
|
|
1830
|
+
*/
|
|
1831
|
+
history?: ScriptVersionRecord[];
|
|
1832
|
+
}
|
|
1833
|
+
/**
|
|
1834
|
+
* A durable, user-stated rendering choice for a recipe. Survives data edits.
|
|
1835
|
+
*/
|
|
1836
|
+
interface ScriptDisplayPreference {
|
|
1837
|
+
/** Component types the user's chosen rendering resolved to, e.g. ["DynamicBarChart"]. */
|
|
1838
|
+
componentTypes: string[];
|
|
1839
|
+
/** The instruction itself — carries nuance the types can't ("horizontal", "sorted descending"). */
|
|
1840
|
+
instruction: string;
|
|
1841
|
+
/** ISO timestamp of the display edit that set this. */
|
|
1842
|
+
at: string;
|
|
1843
|
+
}
|
|
1844
|
+
/** One superseded version of a recipe body (see ScriptStore.commitEdit). */
|
|
1845
|
+
interface ScriptVersionRecord {
|
|
1846
|
+
/** Version number this record superseded (i.e. the OLD version). */
|
|
1847
|
+
version: number;
|
|
1848
|
+
/** ISO timestamp of the edit that superseded it. */
|
|
1849
|
+
at: string;
|
|
1850
|
+
/** userId who made the edit, when known. */
|
|
1851
|
+
by?: string;
|
|
1852
|
+
/** The edit instruction that caused the supersede. */
|
|
1853
|
+
instruction?: string;
|
|
1854
|
+
/** One-line summary of what changed, for the version picker. */
|
|
1855
|
+
changeSummary?: string;
|
|
1856
|
+
/** sha256 of the superseded body — pairs with `<fileBase>.v<version>.ts`. */
|
|
1857
|
+
bodyHash?: string;
|
|
1858
|
+
}
|
|
1859
|
+
interface ScriptParameter {
|
|
1860
|
+
/** Parameter name (used in script body as params.name) */
|
|
1861
|
+
name: string;
|
|
1862
|
+
/** Parameter type */
|
|
1863
|
+
type: 'string' | 'number' | 'date' | 'date_range' | 'enum' | 'boolean';
|
|
1864
|
+
/** Whether this parameter is required */
|
|
1865
|
+
required: boolean;
|
|
1866
|
+
/** Default value if not provided */
|
|
1867
|
+
default?: any;
|
|
1868
|
+
/** For enum type — maps user-facing values to internal values */
|
|
1869
|
+
enumValues?: Record<string, string>;
|
|
1870
|
+
/** Human-readable description (used in the matcher LLM prompt) */
|
|
1871
|
+
description: string;
|
|
1872
|
+
}
|
|
1873
|
+
/**
|
|
1874
|
+
* A reusable component binding captured when a script is authored. Stored on
|
|
1875
|
+
* the recipe so tier-high replays rebuild components deterministically (rebind
|
|
1876
|
+
* to fresh queryIds) instead of re-running the component-picker LLM.
|
|
1877
|
+
*/
|
|
1878
|
+
interface ScriptComponentSpec {
|
|
1879
|
+
/** Registered component name (e.g. "DynamicBarChart") — matched against the available component library. */
|
|
1880
|
+
componentType: string;
|
|
1881
|
+
/** `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). */
|
|
1882
|
+
sourceRef: string;
|
|
1883
|
+
/** Present only when sourceRef === 'federation' — the DuckDB SQL to re-execute on replay. */
|
|
1884
|
+
federationSql?: string;
|
|
1885
|
+
/** Present only when sourceRef === 'markdown' — the narrative text to render on replay (markdown has no data source, so its content must be persisted). */
|
|
1886
|
+
content?: string;
|
|
1887
|
+
title?: string;
|
|
1888
|
+
description?: string;
|
|
1889
|
+
/** Validated axis/value keys + aggregation — all referencing real columns of the bound source. */
|
|
1890
|
+
config: Record<string, any>;
|
|
1891
|
+
}
|
|
1892
|
+
/**
|
|
1893
|
+
* Result from executing a script via ScriptRunner.
|
|
1894
|
+
*/
|
|
1895
|
+
interface ScriptResult {
|
|
1896
|
+
/** Whether the script executed successfully */
|
|
1897
|
+
success: boolean;
|
|
1898
|
+
/** Combined data from all queries */
|
|
1899
|
+
data: any[];
|
|
1900
|
+
/** Individual query results tracked during execution */
|
|
1901
|
+
executedQueries: ScriptQueryResult[];
|
|
1902
|
+
/** Error message if failed */
|
|
1903
|
+
error?: string;
|
|
1904
|
+
/**
|
|
1905
|
+
* Where in the lifecycle the error occurred. Lets MainAgent's fix-loop
|
|
1906
|
+
* decide between "rewrite the whole draft" (compile) and "patch the
|
|
1907
|
+
* specific line" (runtime).
|
|
1908
|
+
*/
|
|
1909
|
+
errorPhase?: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
1910
|
+
/** Total execution time in milliseconds */
|
|
1911
|
+
executionTimeMs: number;
|
|
1912
|
+
}
|
|
1913
|
+
/**
|
|
1914
|
+
* A single query executed during script runtime.
|
|
1915
|
+
* Tracked by ScriptContext for component generation and debugging.
|
|
1916
|
+
*/
|
|
1917
|
+
interface ScriptQueryResult {
|
|
1918
|
+
/** Source tool ID */
|
|
1919
|
+
sourceId: string;
|
|
1920
|
+
/** Human-readable source name */
|
|
1921
|
+
sourceName: string;
|
|
1922
|
+
/** The SQL that was executed */
|
|
1923
|
+
sql: string;
|
|
1924
|
+
/** Result data rows */
|
|
1925
|
+
data: any[];
|
|
1926
|
+
/** Number of rows returned */
|
|
1927
|
+
count: number;
|
|
1928
|
+
/** Total rows that matched before limit (if available) */
|
|
1929
|
+
totalCount?: number;
|
|
1930
|
+
/** Query execution time in milliseconds */
|
|
1931
|
+
executionTimeMs: number;
|
|
1932
|
+
/**
|
|
1933
|
+
* True for rows that did NOT come from a real SQL execution — either a
|
|
1934
|
+
* ctx.emit() dataset or the synthesized "computed:_final" entry that
|
|
1935
|
+
* carries the script's post-JS returned data. The component generator
|
|
1936
|
+
* uses this to route the resulting component through the script_dataset
|
|
1937
|
+
* sentinel toolId so the frontend resolves it via the queryCache short-circuit.
|
|
1938
|
+
*/
|
|
1939
|
+
virtual?: boolean;
|
|
1940
|
+
}
|
|
1941
|
+
/**
|
|
1942
|
+
* Match tier returned by the LLM script matcher.
|
|
1943
|
+
*
|
|
1944
|
+
* - 'high': the script answers the question directly; only parameter values
|
|
1945
|
+
* may differ. The runtime replays it with extracted params (cheapest path).
|
|
1946
|
+
* - 'near': the script answers a STRUCTURALLY similar question but needs
|
|
1947
|
+
* body modification (different metric, dimension, table, filter shape).
|
|
1948
|
+
* The runtime forks the parent and adapts the body via MainAgent's normal
|
|
1949
|
+
* write_script + execute_script loop — no SourceAgent dispatch needed.
|
|
1950
|
+
* See backend/docs/SCRIPT-FLOW-FORK-ADAPT.md for the full design.
|
|
1951
|
+
* - 'edit': the user is INSTRUCTING a change to the script that produced the
|
|
1952
|
+
* previous answer (not asking a new question). Only reachable when the turn
|
|
1953
|
+
* carries a ScriptBinding — without one the matcher coerces it to 'none', so
|
|
1954
|
+
* a prompt regression can't turn this into a loose similarity path. The
|
|
1955
|
+
* runtime runs MainAgent in edit mode and commits the result in place.
|
|
1956
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md.
|
|
1957
|
+
* - 'none': no script is relevant; full agent flow runs.
|
|
1958
|
+
*/
|
|
1959
|
+
type MatchTier = 'high' | 'near' | 'edit' | 'none';
|
|
1960
|
+
/**
|
|
1961
|
+
* Which recipe produced the answer the user is currently looking at.
|
|
1962
|
+
*
|
|
1963
|
+
* Set whenever a turn's answer came from a script (replay, fresh authoring, or
|
|
1964
|
+
* a committed edit) and carried on the UIBlock + saved conversation row. Two
|
|
1965
|
+
* consumers:
|
|
1966
|
+
* 1. The matcher — the 'edit' tier is ONLY reachable when a binding exists, so
|
|
1967
|
+
* "use mode instead of mean" resolves to a concrete script instead of being
|
|
1968
|
+
* matched on keywords it shares with no script name.
|
|
1969
|
+
* 2. Cache invalidation — after an edit commits, conversations bound to that
|
|
1970
|
+
* recipeId must be dropped, or the exact-match cache replays the pre-edit
|
|
1971
|
+
* answer and the edit looks like a no-op.
|
|
1972
|
+
*
|
|
1973
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
1974
|
+
*/
|
|
1975
|
+
interface ScriptBinding {
|
|
1976
|
+
recipeId: string;
|
|
1977
|
+
/** Params the script ran with — the edit's starting point. */
|
|
1978
|
+
params: Record<string, any>;
|
|
1979
|
+
/** Recipe name at bind time (matcher catalog + user-facing confirmation). */
|
|
1980
|
+
name: string;
|
|
1981
|
+
/** Columns the last run returned — grounds the editor without a re-query. */
|
|
1982
|
+
columns?: string[];
|
|
1983
|
+
/**
|
|
1984
|
+
* The question that produced this answer. Required for disambiguation when a
|
|
1985
|
+
* thread ran several scripts — without it the candidates are just names and
|
|
1986
|
+
* the matcher cannot resolve "use the mode for the WSP one".
|
|
1987
|
+
*/
|
|
1988
|
+
userPrompt?: string;
|
|
1989
|
+
}
|
|
1990
|
+
/**
|
|
1991
|
+
* Result from the LLM-based script matcher.
|
|
1992
|
+
*
|
|
1993
|
+
* For `tier: 'high'`, `extractedParams` carries the values to pass to the
|
|
1994
|
+
* existing script. For `tier: 'near'`, `gaps` and `modificationHint` describe
|
|
1995
|
+
* what the fork-author needs to change in the parent body.
|
|
1996
|
+
*/
|
|
1997
|
+
interface ScriptMatch {
|
|
1998
|
+
/** The matched script recipe */
|
|
1999
|
+
recipe: ScriptRecipe;
|
|
2000
|
+
/** Match tier — see MatchTier docs */
|
|
2001
|
+
tier: MatchTier;
|
|
2002
|
+
/** Similarity score (0-1, derived from LLM tier) */
|
|
2003
|
+
similarity: number;
|
|
2004
|
+
/**
|
|
2005
|
+
* Legacy confidence level. Mirrors `tier === 'high'`/`'near'` for now;
|
|
2006
|
+
* kept so existing callers compile while we migrate to tier-based logic.
|
|
2007
|
+
*/
|
|
2008
|
+
confidence: 'high' | 'medium';
|
|
2009
|
+
/** Parameters extracted from the user question by the LLM (tier='high') */
|
|
2010
|
+
extractedParams?: Record<string, any>;
|
|
2011
|
+
/** What the user question needs that the parent doesn't cover (tier='near') */
|
|
2012
|
+
gaps?: string[];
|
|
2013
|
+
/** One-sentence description of the change the fork-author should make (tier='near') */
|
|
2014
|
+
modificationHint?: string;
|
|
2015
|
+
/**
|
|
2016
|
+
* Which HALF of the recipe the edit targets (tier='edit'). A recipe has two
|
|
2017
|
+
* independently editable halves:
|
|
2018
|
+
* - 'data' — the scriptBody: how the rows are produced (aggregation,
|
|
2019
|
+
* filters, joins, grouping). Runs MainAgent in edit mode.
|
|
2020
|
+
* - 'display' — the component specs: how those SAME rows are shown (chart
|
|
2021
|
+
* type, orientation, columns, labels). Replays the proven SQL
|
|
2022
|
+
* and regenerates the specs — never authors a script.
|
|
2023
|
+
* Defaults to 'data' when the matcher omits it.
|
|
2024
|
+
*/
|
|
2025
|
+
editTarget?: 'data' | 'display';
|
|
2026
|
+
/**
|
|
2027
|
+
* Self-contained restatement of the change the user asked for (tier='edit').
|
|
2028
|
+
* MUST have pronouns/deixis resolved ("this", "it", "that column") — the edit
|
|
2029
|
+
* prompt never sees the conversation history, so an unresolved instruction is
|
|
2030
|
+
* unusable downstream.
|
|
2031
|
+
*/
|
|
2032
|
+
editInstruction?: string;
|
|
2033
|
+
/** Why the matcher made this choice (for logs and telemetry) */
|
|
2034
|
+
reasoning?: string;
|
|
2035
|
+
}
|
|
2036
|
+
|
|
2037
|
+
/**
|
|
2038
|
+
* ScriptRecipeStore — injected metadata backend for the script flow.
|
|
2039
|
+
*
|
|
2040
|
+
* The SDK is standalone (no DB dependency). The backend implements this
|
|
2041
|
+
* interface over Postgres (full-text search + atomic counters) and injects it
|
|
2042
|
+
* via `collections['script-recipes']`, exactly like `collections['source-embeddings']`.
|
|
2043
|
+
* `ScriptStore` consumes it for all METADATA operations while keeping the
|
|
2044
|
+
* executable body on disk as scripts-store/<fileBase>.ts.
|
|
2045
|
+
*
|
|
2046
|
+
* All metadata rows are plain JSON (no scriptBody — that lives on disk).
|
|
2047
|
+
* See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md (#1, #3, #7).
|
|
2048
|
+
*/
|
|
2049
|
+
|
|
2050
|
+
/** One recipe's metadata as stored in Postgres (mirrors the script_recipes table). */
|
|
2051
|
+
interface ScriptRecipeMetaRow {
|
|
2052
|
+
id: string;
|
|
2053
|
+
projectId?: string | null;
|
|
2054
|
+
version: number;
|
|
2055
|
+
name: string;
|
|
2056
|
+
intentDescription: string;
|
|
2057
|
+
tags: string[] | null;
|
|
2058
|
+
createdFrom: string | null;
|
|
2059
|
+
sourceIds: string[] | null;
|
|
2060
|
+
tables: string[] | null;
|
|
2061
|
+
parameters: ScriptParameter[] | null;
|
|
2062
|
+
components?: ScriptComponentSpec[] | null;
|
|
2063
|
+
displayPreference?: ScriptDisplayPreference | null;
|
|
2064
|
+
fileBase: string;
|
|
2065
|
+
bodyHash?: string | null;
|
|
2066
|
+
successCount: number;
|
|
2067
|
+
failureCount: number;
|
|
2068
|
+
lastUsed: string | null;
|
|
2069
|
+
parentId?: string | null;
|
|
2070
|
+
forkDepth?: number | null;
|
|
2071
|
+
forkReason?: string | null;
|
|
2072
|
+
status: 'draft' | 'verified' | string;
|
|
2073
|
+
turnId?: string | null;
|
|
2074
|
+
editedBy?: string | null;
|
|
2075
|
+
editedFrom?: string | null;
|
|
2076
|
+
history?: ScriptVersionRecord[] | null;
|
|
2077
|
+
lastError?: {
|
|
2078
|
+
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
2079
|
+
message: string;
|
|
2080
|
+
at: string;
|
|
2081
|
+
attempt: number;
|
|
2082
|
+
} | null;
|
|
2083
|
+
createdAt?: string | null;
|
|
2084
|
+
updatedAt?: string | null;
|
|
2085
|
+
}
|
|
2086
|
+
interface ScriptRecipeStore {
|
|
2087
|
+
/** FTS shortlist of healthy verified recipes for the matcher (metadata only). */
|
|
2088
|
+
search(params: {
|
|
2089
|
+
prompt: string;
|
|
2090
|
+
projectId?: string;
|
|
2091
|
+
limit?: number;
|
|
2092
|
+
}): Promise<ScriptRecipeMetaRow[]>;
|
|
2093
|
+
/** Fetch one recipe by id (any status). */
|
|
2094
|
+
getById(id: string): Promise<ScriptRecipeMetaRow | null>;
|
|
2095
|
+
/** Count healthy verified recipes (drives the "any scripts?" gate). */
|
|
2096
|
+
count(params?: {
|
|
2097
|
+
projectId?: string;
|
|
2098
|
+
}): Promise<number>;
|
|
2099
|
+
/** Insert or update a recipe row (keyed by id). */
|
|
2100
|
+
upsert(row: ScriptRecipeMetaRow): Promise<void>;
|
|
2101
|
+
/** Atomically bump counters / last-used. */
|
|
2102
|
+
updateStats(id: string, patch: {
|
|
2103
|
+
successDelta?: number;
|
|
2104
|
+
failureDelta?: number;
|
|
2105
|
+
lastUsed?: string;
|
|
2106
|
+
}): Promise<void>;
|
|
2107
|
+
/** Flip a draft to verified, applying provenance + optional fork lineage. */
|
|
2108
|
+
promote(id: string, patch: {
|
|
2109
|
+
sourceIds: string[];
|
|
2110
|
+
tables: string[];
|
|
2111
|
+
fileBase?: string;
|
|
2112
|
+
parentId?: string;
|
|
2113
|
+
forkDepth?: number;
|
|
2114
|
+
forkReason?: string;
|
|
2115
|
+
components?: ScriptComponentSpec[];
|
|
2116
|
+
}): Promise<ScriptRecipeMetaRow | null>;
|
|
2117
|
+
/**
|
|
2118
|
+
* Commit a verified edit onto an EXISTING recipe: bump `version`, replace the
|
|
2119
|
+
* body-bearing metadata, append a history record, reset health counters, and
|
|
2120
|
+
* clear the component specs (they were validated against the old shape).
|
|
2121
|
+
* Returns the updated row, or null when the target is gone.
|
|
2122
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5.
|
|
2123
|
+
*/
|
|
2124
|
+
commitEdit?(id: string, patch: {
|
|
2125
|
+
name?: string;
|
|
2126
|
+
intentDescription?: string;
|
|
2127
|
+
tags?: string[];
|
|
2128
|
+
parameters?: ScriptParameter[];
|
|
2129
|
+
bodyHash: string;
|
|
2130
|
+
/** New on-disk stem when the edit renamed the script; omitted otherwise. */
|
|
2131
|
+
fileBase?: string;
|
|
2132
|
+
sourceIds?: string[];
|
|
2133
|
+
tables?: string[];
|
|
2134
|
+
editedBy?: string;
|
|
2135
|
+
editedFrom?: string;
|
|
2136
|
+
historyEntry: {
|
|
2137
|
+
version: number;
|
|
2138
|
+
at: string;
|
|
2139
|
+
by?: string;
|
|
2140
|
+
instruction?: string;
|
|
2141
|
+
changeSummary?: string;
|
|
2142
|
+
bodyHash?: string;
|
|
2143
|
+
};
|
|
2144
|
+
}): Promise<ScriptRecipeMetaRow | null>;
|
|
2145
|
+
/** Stamp a draft's last execution error. */
|
|
2146
|
+
recordDraftError(id: string, err: {
|
|
2147
|
+
phase: string;
|
|
2148
|
+
message: string;
|
|
2149
|
+
attempt: number;
|
|
2150
|
+
at: string;
|
|
2151
|
+
}): Promise<void>;
|
|
2152
|
+
/** Delete a recipe row (body file removed separately). */
|
|
2153
|
+
remove(id: string): Promise<void>;
|
|
2154
|
+
/** True if `fileBase` is taken by a different recipe in this project. */
|
|
2155
|
+
fileBaseTaken(fileBase: string, excludeId: string, projectId?: string): Promise<boolean>;
|
|
2156
|
+
}
|
|
2157
|
+
/** Pull the injected store off the collections bag (or null if not wired). */
|
|
2158
|
+
declare function resolveScriptRecipeStore(collections: any): ScriptRecipeStore | null;
|
|
2159
|
+
|
|
2160
|
+
/**
|
|
2161
|
+
* ScriptStore — Postgres metadata + on-disk body for script recipes.
|
|
2162
|
+
*
|
|
2163
|
+
* Split of responsibilities:
|
|
2164
|
+
* - METADATA → injected `ScriptRecipeStore` (Postgres FTS + atomic counters),
|
|
2165
|
+
* resolved from `collections['script-recipes']`.
|
|
2166
|
+
* - BODY → scripts-store/<fileBase>.ts, editable in your IDE. Written
|
|
2167
|
+
* atomically (temp + rename); `bodyHash` (sha256) detects edits.
|
|
2168
|
+
*
|
|
2169
|
+
* The old "read every file every turn + send the whole catalog to the LLM"
|
|
2170
|
+
* matcher is gone — matching is `store.search(prompt)` (FTS shortlist). The
|
|
2171
|
+
* draft/verified filename dance is gone too: `status` is a DB column and the
|
|
2172
|
+
* file keeps a stable `<fileBase>.ts` name across promotion.
|
|
2173
|
+
*
|
|
2174
|
+
* When no metadata store is injected, the store degrades to a safe no-op
|
|
2175
|
+
* (count 0 → script flow disabled) instead of crashing.
|
|
2176
|
+
*
|
|
2177
|
+
* See backend/docs/SCRIPT-FLOW-SCALING-ISSUES.md.
|
|
2178
|
+
*/
|
|
2179
|
+
|
|
2180
|
+
interface SaveDraftInput {
|
|
2181
|
+
/** Reuse an existing draft (retry); omit to mint a new one. */
|
|
2182
|
+
recipeId?: string;
|
|
2183
|
+
/** Per-turn unique suffix, stable across retries within the turn. */
|
|
2184
|
+
turnId: string;
|
|
2185
|
+
name: string;
|
|
2186
|
+
intentDescription: string;
|
|
2187
|
+
tags: string[];
|
|
2188
|
+
parameters: ScriptParameter[];
|
|
2189
|
+
scriptBody: string;
|
|
2190
|
+
createdFrom: string;
|
|
2191
|
+
/**
|
|
2192
|
+
* Set when this draft is a SHADOW of an existing recipe being edited. The
|
|
2193
|
+
* draft is verified independently and merged back onto the parent via
|
|
2194
|
+
* `commitEdit`, so the working script is never clobbered by an edit that
|
|
2195
|
+
* turns out not to run. See backend/docs/SCRIPT-EDIT-DESIGN.md § D5.
|
|
2196
|
+
*/
|
|
2197
|
+
parentId?: string;
|
|
2198
|
+
}
|
|
2199
|
+
interface PromoteToVerifiedInput {
|
|
2200
|
+
sourceIds: string[];
|
|
2201
|
+
tables: string[];
|
|
2202
|
+
parentId?: string;
|
|
2203
|
+
forkDepth?: number;
|
|
2204
|
+
forkReason?: string;
|
|
2205
|
+
components?: ScriptComponentSpec[];
|
|
2206
|
+
}
|
|
2207
|
+
interface ScriptStoreOptions {
|
|
2208
|
+
/** Explicit metadata store, or resolved from `collections['script-recipes']`. */
|
|
2209
|
+
store?: ScriptRecipeStore | null;
|
|
2210
|
+
collections?: any;
|
|
2211
|
+
/** Body directory (defaults to <cwd>/scripts-store). */
|
|
2212
|
+
baseDir?: string;
|
|
2213
|
+
/** Project scope stamped on every row. */
|
|
2214
|
+
projectId?: string;
|
|
2215
|
+
}
|
|
2216
|
+
/**
|
|
2217
|
+
* Normalize a scriptBody into the on-disk form (strip a leading comment block,
|
|
2218
|
+
* ensure `export async function getData`). Exported for MainAgent.
|
|
2219
|
+
*/
|
|
2220
|
+
declare function normalizeScriptBody(scriptBody: string): string;
|
|
2221
|
+
declare class ScriptStore {
|
|
2222
|
+
private store;
|
|
2223
|
+
private storeDir;
|
|
2224
|
+
private projectId?;
|
|
2225
|
+
constructor(opts?: ScriptStoreOptions);
|
|
2226
|
+
/** Whether a metadata store is wired (matcher / authoring are gated on this). */
|
|
2227
|
+
hasStore(): boolean;
|
|
2228
|
+
/** Number of healthy verified recipes (gates the script-matching path). */
|
|
2229
|
+
count(): Promise<number>;
|
|
2230
|
+
/**
|
|
2231
|
+
* FTS shortlist for the matcher (metadata only — bodies are loaded lazily by
|
|
2232
|
+
* `get()` once the LLM picks one). Returns verified, healthy recipes ranked
|
|
2233
|
+
* by relevance.
|
|
2234
|
+
*/
|
|
2235
|
+
search(prompt: string, limit?: number): Promise<ScriptRecipe[]>;
|
|
2236
|
+
/** Fetch one recipe by id with its body loaded from disk. */
|
|
2237
|
+
get(id: string): Promise<ScriptRecipe | null>;
|
|
2238
|
+
/** Create or update a recipe (metadata upsert + body write when changed). */
|
|
2239
|
+
save(recipe: ScriptRecipe): Promise<void>;
|
|
2240
|
+
/**
|
|
2241
|
+
* Persist (or update) a draft. Within a turn, retries that pass the same
|
|
2242
|
+
* `recipeId` overwrite the same row + file; a fresh `recipeId` mints a new
|
|
2243
|
+
* draft. The body is visible at scripts-store/<fileBase>.ts immediately.
|
|
2244
|
+
*/
|
|
2245
|
+
saveDraft(input: SaveDraftInput): Promise<ScriptRecipe>;
|
|
2246
|
+
/** Stamp a draft's last execution error (metadata only). */
|
|
2247
|
+
recordDraftError(recipeId: string, err: {
|
|
2248
|
+
phase: 'compile' | 'runtime' | 'timeout' | 'ipc';
|
|
2249
|
+
message: string;
|
|
2250
|
+
attempt: number;
|
|
2251
|
+
}): Promise<void>;
|
|
2252
|
+
/**
|
|
2253
|
+
* Promote a successfully-executed draft into a verified script.
|
|
2254
|
+
* The on-disk body already exists at <fileBase>.ts (written at write_script
|
|
2255
|
+
* time) and keeps its name — only the DB row flips status + provenance.
|
|
2256
|
+
*/
|
|
2257
|
+
promoteToVerified(recipeId: string, input: PromoteToVerifiedInput): Promise<ScriptRecipe | null>;
|
|
2258
|
+
/**
|
|
2259
|
+
* Commit a user-directed edit: merge a VERIFIED shadow draft back onto the
|
|
2260
|
+
* recipe it was editing, as version N+1 under the SAME recipe id.
|
|
2261
|
+
*
|
|
2262
|
+
* Keeping the id stable is the point of the whole feature — every cached
|
|
2263
|
+
* conversation, `script_dataset` regeneration descriptor and persisted
|
|
2264
|
+
* component spec already points at it, so the correction applies retroactively
|
|
2265
|
+
* to replays instead of stranding them on the old body.
|
|
2266
|
+
*
|
|
2267
|
+
* Steps (see backend/docs/SCRIPT-EDIT-DESIGN.md § Component 5):
|
|
2268
|
+
* 1. archive the current body as `<fileBase>.v<version>.ts`
|
|
2269
|
+
* 2. write the edited body to the original fileBase (atomic)
|
|
2270
|
+
* 3. version++, copy name/description/params, append a history record
|
|
2271
|
+
* 4. reset health counters — the pre-edit failure history is stale
|
|
2272
|
+
* 5. clear component specs — they were validated against the OLD shape
|
|
2273
|
+
* 6. delete the shadow draft (row + file)
|
|
2274
|
+
*
|
|
2275
|
+
* Returns the updated recipe, or null when the commit could not be applied
|
|
2276
|
+
* (caller should then fall back to treating the draft as a new script).
|
|
2277
|
+
*/
|
|
2278
|
+
commitEdit(targetId: string, draft: {
|
|
2279
|
+
recipeId: string;
|
|
2280
|
+
name?: string;
|
|
2281
|
+
intentDescription?: string;
|
|
2282
|
+
tags?: string[];
|
|
2283
|
+
parameters?: ScriptParameter[];
|
|
2284
|
+
scriptBody: string;
|
|
2285
|
+
sourceIds?: string[];
|
|
2286
|
+
tables?: string[];
|
|
2287
|
+
}, meta: {
|
|
2288
|
+
instruction?: string;
|
|
2289
|
+
changeSummary?: string;
|
|
2290
|
+
editedBy?: string;
|
|
2291
|
+
}): Promise<ScriptRecipe | null>;
|
|
2292
|
+
/**
|
|
2293
|
+
* Drop a draft (row + body file). MainAgent calls this at end-of-turn when a
|
|
2294
|
+
* draft was authored but never verified — failed drafts are never matched, so
|
|
2295
|
+
* deleting them immediately avoids unbounded accumulation (#5). No-op if the
|
|
2296
|
+
* recipe isn't a draft (so a promoted/verified script is never removed here).
|
|
2297
|
+
*/
|
|
2298
|
+
discardDraft(recipeId: string): Promise<void>;
|
|
2299
|
+
/** Delete a recipe (row + body file). */
|
|
2300
|
+
delete(id: string): Promise<void>;
|
|
2301
|
+
/** Record a successful execution (atomic counter bump). */
|
|
2302
|
+
recordSuccess(id: string): Promise<void>;
|
|
2303
|
+
/** Record a failed execution (atomic counter bump). */
|
|
2304
|
+
recordFailure(id: string): Promise<void>;
|
|
2305
|
+
/** Absolute path to the .ts body for a recipe (used by the runner/MainAgent). */
|
|
2306
|
+
getScriptPath(recipe: ScriptRecipe): string;
|
|
2307
|
+
private removeById;
|
|
2308
|
+
private rowToRecipe;
|
|
2309
|
+
private recipeToRow;
|
|
2310
|
+
/** slug of name, with a short id suffix when the bare slug is already taken. */
|
|
2311
|
+
private computeFileBase;
|
|
2312
|
+
private toSlug;
|
|
2313
|
+
private hash;
|
|
2314
|
+
private bodyPath;
|
|
2315
|
+
private readBody;
|
|
2316
|
+
/** Directory holding superseded bodies. Dot-prefixed so IDEs/`ls` hide it. */
|
|
2317
|
+
private get archiveDir();
|
|
2318
|
+
/**
|
|
2319
|
+
* Archive a superseded body as `.versions/<fileBase>.v<n>.ts`.
|
|
2320
|
+
*
|
|
2321
|
+
* Kept out of the main store directory on purpose — see commitEdit step 1.
|
|
2322
|
+
* To roll back: copy the file back over `scripts-store/<fileBase>.ts`.
|
|
2323
|
+
*/
|
|
2324
|
+
private writeArchive;
|
|
2325
|
+
/**
|
|
2326
|
+
* Move a recipe's archived versions to a new prefix when its fileBase changes,
|
|
2327
|
+
* so all versions of one recipe stay grouped. Without this, two renames would
|
|
2328
|
+
* scatter a single recipe's history across three prefixes in `.versions/` with
|
|
2329
|
+
* nothing linking them back to the live script.
|
|
2330
|
+
*/
|
|
2331
|
+
private renameArchives;
|
|
2332
|
+
/** Atomic body write (temp + rename) so concurrent reads never see a partial file. */
|
|
2333
|
+
private writeBody;
|
|
2334
|
+
private unlinkBody;
|
|
2335
|
+
}
|
|
2336
|
+
|
|
2337
|
+
/**
|
|
2338
|
+
* Main Agent (Orchestrator)
|
|
2339
|
+
*
|
|
2340
|
+
* A single LLM.streamWithTools() call that handles everything:
|
|
2341
|
+
* - Routing: decides which source(s) to query based on summaries
|
|
2342
|
+
* - Querying: calls source tools (each wraps an independent SourceAgent)
|
|
2343
|
+
* - Direct tools: calls pre-built function tools directly with LLM-provided params
|
|
2344
|
+
* - Re-querying: if data is wrong/incomplete, calls tools again with modified intent
|
|
2345
|
+
* - Analysis: generates final text response from the data
|
|
2346
|
+
*
|
|
2347
|
+
* Two tool types:
|
|
2348
|
+
* - "source" tools: main agent sees summaries, SourceAgent handles SQL generation independently
|
|
2349
|
+
* - "direct" tools: main agent calls fn() directly with structured params (no SourceAgent)
|
|
2350
|
+
*/
|
|
2351
|
+
|
|
2352
|
+
declare class MainAgent {
|
|
2353
|
+
private externalTools;
|
|
2354
|
+
private workflows;
|
|
2355
|
+
private config;
|
|
2356
|
+
private streamBuffer;
|
|
2357
|
+
/**
|
|
2358
|
+
* Optional: when provided, MainAgent exposes the `write_script` /
|
|
2359
|
+
* `execute_script` tools to the LLM and persists drafts to disk via the
|
|
2360
|
+
* store. Headless callers (alert analyzer, metric resolver) omit these to
|
|
2361
|
+
* suppress script authoring entirely — drafts would otherwise leak onto
|
|
2362
|
+
* disk with no caller to promote or clean them up.
|
|
2363
|
+
*/
|
|
2364
|
+
private scriptStore;
|
|
2365
|
+
private turnId;
|
|
2366
|
+
private createdFromPrompt;
|
|
2367
|
+
private scriptState;
|
|
2368
|
+
/**
|
|
2369
|
+
* Fork mode — set when this turn is adapting a near-matching parent script.
|
|
2370
|
+
* In fork mode there is no legitimate "answer with bare text" outcome: the
|
|
2371
|
+
* only correct first move is a tool call (write_script, or a source tool for
|
|
2372
|
+
* schema discovery). We therefore force tool use on the first LLM iteration
|
|
2373
|
+
* so the model can't end its turn with a bare "I'll adapt…" preamble and zero
|
|
2374
|
+
* tool calls. Never set on the fresh-authoring / general-question path.
|
|
2375
|
+
*/
|
|
2376
|
+
private forkMode;
|
|
2377
|
+
/**
|
|
2378
|
+
* Edit mode — set when this turn applies a user-directed change to an
|
|
2379
|
+
* existing script. Swaps the system prompt to `agent-main-edit` and stamps
|
|
2380
|
+
* the shadow draft's parentId. Like fork mode there is no legitimate
|
|
2381
|
+
* "answer with bare text" outcome, so tool use is forced on iteration 1.
|
|
2382
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 4.
|
|
2383
|
+
*/
|
|
2384
|
+
private editContext;
|
|
2385
|
+
/**
|
|
2386
|
+
* Per-turn cancellation signal (user hit "Stop"). Set at the top of
|
|
2387
|
+
* handleQuestion and read by the tool handler, the SourceAgent dispatch, and
|
|
2388
|
+
* the script subprocess so an abort tears down every layer of the turn.
|
|
2389
|
+
*/
|
|
2390
|
+
private abortSignal?;
|
|
2391
|
+
constructor(externalTools: ExternalTool[], config: AgentConfig, scriptStore?: ScriptStore, turnId?: string, streamBuffer?: StreamBuffer, workflows?: WorkflowDescriptor[], forkMode?: boolean, editContext?: EditContext);
|
|
2392
|
+
/** True when the turn is applying a user-directed script edit. */
|
|
2393
|
+
private get editMode();
|
|
2394
|
+
private get scriptingEnabled();
|
|
2395
|
+
/**
|
|
2396
|
+
* Handle a user question using the multi-agent system.
|
|
2397
|
+
*
|
|
2398
|
+
* This is ONE LLM.streamWithTools() call. The LLM:
|
|
2399
|
+
* 1. Sees source summaries + direct tool descriptions in system prompt
|
|
2400
|
+
* 2. Decides which tool(s) to call (routing)
|
|
2401
|
+
* 3. Source tools → SourceAgent runs independently → returns data
|
|
2402
|
+
* 4. Direct tools → fn() called directly with LLM params → returns data
|
|
2403
|
+
* 5. Generates final analysis text
|
|
2404
|
+
*/
|
|
2405
|
+
handleQuestion(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, signal?: AbortSignal): Promise<AgentResponse>;
|
|
2406
|
+
private handleWriteScript;
|
|
2407
|
+
private handleExecuteScript;
|
|
2408
|
+
/**
|
|
2409
|
+
* Build the AgentWrittenScript payload the caller will hand to
|
|
2410
|
+
* `ScriptStore.promoteToVerified()`. Only returned when a verified
|
|
2411
|
+
* successful execution is on record.
|
|
2412
|
+
*/
|
|
2413
|
+
private buildSavedScript;
|
|
2414
|
+
private normalizeParameterList;
|
|
2415
|
+
/**
|
|
2416
|
+
* Use the schema embedding collection to pre-select relevant tables for
|
|
2417
|
+
* this source + intent. Returns a formatted schema block if confidence is
|
|
2418
|
+
* high (top match ≥ 0.55 and ≥3 candidates), otherwise null.
|
|
2419
|
+
*
|
|
2420
|
+
* When this returns a block, we can skip the SourceAgent's `search_schema`
|
|
2421
|
+
* loop and reduce iteration budget. When it returns null, the SourceAgent
|
|
2422
|
+
* falls back to the existing LLM-driven keyword search (same as today).
|
|
2423
|
+
*/
|
|
2424
|
+
private preResolveSchema;
|
|
2425
|
+
/**
|
|
2426
|
+
* Execute a direct tool — call fn() with LLM-provided params, no SourceAgent.
|
|
2427
|
+
*/
|
|
2428
|
+
private handleDirectTool;
|
|
2429
|
+
/**
|
|
2430
|
+
* Build the main agent's system prompt with source summaries, direct tool descriptions,
|
|
2431
|
+
* and workflow component descriptions.
|
|
2432
|
+
*/
|
|
2433
|
+
private buildSystemPrompt;
|
|
2434
|
+
/**
|
|
2435
|
+
* Build tool definitions for source tools — summary-only descriptions.
|
|
2436
|
+
* The full schema is inside the SourceAgent which runs independently.
|
|
2437
|
+
*/
|
|
2438
|
+
private buildSourceToolDefinitions;
|
|
2439
|
+
/**
|
|
2440
|
+
* Build tool definitions for direct tools — expose their actual params.
|
|
2441
|
+
* These are called directly by the main agent LLM, no SourceAgent.
|
|
2442
|
+
*/
|
|
2443
|
+
private buildDirectToolDefinitions;
|
|
2444
|
+
/**
|
|
2445
|
+
* Capture a workflow selection. We do NOT execute anything — the LLM has
|
|
2446
|
+
* already extracted the props it wants the workflow rendered with. We
|
|
2447
|
+
* record the selection (via the capture callback) and return a short
|
|
2448
|
+
* acknowledgement so the LLM ends its turn cleanly without writing
|
|
2449
|
+
* analysis text or calling more tools.
|
|
2450
|
+
*/
|
|
2451
|
+
private handleWorkflow;
|
|
2452
|
+
/**
|
|
2453
|
+
* Build LLM tool definitions for workflow components. The workflow's
|
|
2454
|
+
* propsSchema becomes the tool's input_schema so the LLM extracts props
|
|
2455
|
+
* directly from the prompt — same mechanic as direct tools.
|
|
2456
|
+
*/
|
|
2457
|
+
private buildWorkflowToolDefinitions;
|
|
2458
|
+
/**
|
|
2459
|
+
* Format a source agent's result as a clean string for the main agent LLM.
|
|
2460
|
+
*/
|
|
2461
|
+
private formatResultForMainAgent;
|
|
2462
|
+
/**
|
|
2463
|
+
* Get source summaries (for external inspection/debugging).
|
|
2464
|
+
*/
|
|
2465
|
+
getSourceSummaries(): SourceSummary[];
|
|
2466
|
+
}
|
|
2467
|
+
|
|
2468
|
+
/**
|
|
2469
|
+
* Represents an action that can be performed on a UIBlock
|
|
2470
|
+
*/
|
|
2471
|
+
interface Action {
|
|
2472
|
+
id: string;
|
|
2473
|
+
name: string;
|
|
2474
|
+
type: string;
|
|
2475
|
+
[key: string]: any;
|
|
2476
|
+
}
|
|
2477
|
+
|
|
2478
|
+
type SystemPrompt = string | Anthropic.Messages.TextBlockParam[];
|
|
2479
|
+
interface LLMMessages {
|
|
2480
|
+
sys: SystemPrompt;
|
|
2481
|
+
user: string;
|
|
2482
|
+
prefill?: string;
|
|
2483
|
+
}
|
|
2484
|
+
interface LLMOptions {
|
|
2485
|
+
model?: string;
|
|
2486
|
+
maxTokens?: number;
|
|
2487
|
+
temperature?: number;
|
|
2488
|
+
topP?: number;
|
|
2489
|
+
apiKey?: string;
|
|
2490
|
+
baseURL?: string;
|
|
2491
|
+
partial?: (chunk: string) => void;
|
|
2492
|
+
/**
|
|
2493
|
+
* Per-request cancellation. When the caller aborts this signal (user hit
|
|
2494
|
+
* "Stop"), the underlying provider request is cancelled and the call throws
|
|
2495
|
+
* a RequestAbortedError. Threaded into the provider `messages.create` request
|
|
2496
|
+
* options and checked between tool-loop iterations. Currently honored on the
|
|
2497
|
+
* Anthropic path (the agent flow's default provider).
|
|
2498
|
+
*/
|
|
2499
|
+
signal?: AbortSignal;
|
|
2500
|
+
/**
|
|
2501
|
+
* Forces a tool call on the FIRST iteration of streamWithTools only
|
|
2502
|
+
* (subsequent iterations revert to auto). Used by fork mode to stop the
|
|
2503
|
+
* model from ending its turn with a bare "I'll adapt the script…" preamble
|
|
2504
|
+
* and zero tool calls. `{ type: 'any' }` lets the model pick which tool
|
|
2505
|
+
* (write_script in the common case, a source tool for schema discovery);
|
|
2506
|
+
* `{ type: 'tool', name }` pins a specific tool. Honored on both the
|
|
2507
|
+
* Anthropic path and the OpenAI/OpenRouter path (mapped to OpenAI's
|
|
2508
|
+
* tool_choice: 'required' / a named function).
|
|
2509
|
+
*/
|
|
2510
|
+
firstIterationToolChoice?: {
|
|
2511
|
+
type: 'any';
|
|
2512
|
+
} | {
|
|
2513
|
+
type: 'tool';
|
|
2514
|
+
name: string;
|
|
2515
|
+
};
|
|
2516
|
+
/**
|
|
2517
|
+
* Internal — set only by the OpenRouter wrappers when the target is a Claude
|
|
2518
|
+
* model. Tells the OpenAI-wire path to emit Anthropic `cache_control`
|
|
2519
|
+
* breakpoints (OpenRouter forwards them to Anthropic for prompt caching).
|
|
2520
|
+
* Never set for direct OpenAI/Groq calls, so their requests are unchanged.
|
|
2521
|
+
*/
|
|
2522
|
+
_openrouterClaudeCaching?: boolean;
|
|
2523
|
+
/**
|
|
2524
|
+
* Internal — OpenRouter provider-routing preferences (forwarded as the
|
|
2525
|
+
* `provider` body field). Set by the OpenRouter wrappers to steer routing to
|
|
2526
|
+
* a fast backend (e.g. {sort:'throughput'}). Never set for direct OpenAI/Groq.
|
|
2527
|
+
*/
|
|
2528
|
+
_openrouterProvider?: Record<string, unknown>;
|
|
2529
|
+
}
|
|
2530
|
+
interface Tool {
|
|
2531
|
+
name: string;
|
|
2532
|
+
description: string;
|
|
2533
|
+
input_schema: {
|
|
2534
|
+
type: string;
|
|
2535
|
+
properties: Record<string, any>;
|
|
2536
|
+
required?: string[];
|
|
2537
|
+
};
|
|
2538
|
+
}
|
|
2539
|
+
declare class LLM {
|
|
2540
|
+
static text(messages: LLMMessages, options?: LLMOptions): Promise<string>;
|
|
2541
|
+
static stream<T = string>(messages: LLMMessages, options?: LLMOptions, json?: boolean): Promise<T extends string ? string : any>;
|
|
2542
|
+
static streamWithTools(messages: LLMMessages, tools: Tool[], toolHandler: (toolName: string, toolInput: any) => Promise<any>, options?: LLMOptions, maxIterations?: number): Promise<string>;
|
|
2543
|
+
/**
|
|
2544
|
+
* Normalize system prompt to Anthropic format
|
|
2545
|
+
* Converts string to array format if needed
|
|
2546
|
+
* @param sys - System prompt (string or array of blocks)
|
|
2547
|
+
* @returns Normalized system prompt for Anthropic API
|
|
2548
|
+
*/
|
|
2549
|
+
private static _normalizeSystemPrompt;
|
|
2550
|
+
/**
|
|
2551
|
+
* Strip unpaired UTF-16 surrogates from every text field of a message set.
|
|
2552
|
+
*
|
|
2553
|
+
* A lone surrogate (from mid-pair string slicing or corrupt source data)
|
|
2554
|
+
* serializes to a bare `\udXXX` escape that strict JSON parsers — including
|
|
2555
|
+
* the one on Anthropic's API — reject with "no low surrogate in string",
|
|
2556
|
+
* failing the whole request. Sanitizing here, at the single boundary every
|
|
2557
|
+
* provider call flows through, guarantees no request can carry one.
|
|
2558
|
+
*/
|
|
2559
|
+
private static _sanitizeMessages;
|
|
2560
|
+
/**
|
|
2561
|
+
* Log cache usage metrics from Anthropic API response
|
|
2562
|
+
* Shows cache hits, costs, and savings
|
|
2563
|
+
*/
|
|
2564
|
+
private static _logCacheUsage;
|
|
2565
|
+
/**
|
|
2566
|
+
* Parse model string to extract provider and model name
|
|
2567
|
+
* @param modelString - Format: "provider/model-name" or just "model-name"
|
|
2568
|
+
* @returns [provider, modelName]
|
|
2569
|
+
*
|
|
2570
|
+
* @example
|
|
2571
|
+
* "anthropic/claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"]
|
|
2572
|
+
* "groq/openai/gpt-oss-120b" → ["groq", "openai/gpt-oss-120b"]
|
|
2573
|
+
* "claude-sonnet-4-5" → ["anthropic", "claude-sonnet-4-5"] (default)
|
|
2574
|
+
*/
|
|
2575
|
+
private static _parseModel;
|
|
2576
|
+
/**
|
|
2577
|
+
* Map an Anthropic model id (e.g. "claude-sonnet-4-5-20250929") to the OpenRouter slug
|
|
2578
|
+
* (e.g. "claude-sonnet-4.5"). OpenRouter slugs drop the date suffix and use dotted versions.
|
|
2579
|
+
*/
|
|
2580
|
+
private static _toOpenRouterSlug;
|
|
2581
|
+
/**
|
|
2582
|
+
* Per-provider proxy base URL. Returns `${SUPERATOM_LLM_PROXY_URL}/<provider>`
|
|
2583
|
+
* when our Cloudflare LLM proxy is configured, else undefined (→ talk to the
|
|
2584
|
+
* provider directly, legacy behaviour). An explicit options.baseURL (e.g.
|
|
2585
|
+
* OpenRouter) always wins and is never overridden. See backend/docs/llm-proxy.md.
|
|
2586
|
+
*/
|
|
2587
|
+
private static _proxyBaseURL;
|
|
2588
|
+
private static _openrouterOptions;
|
|
2589
|
+
private static _isRetryableProviderError;
|
|
2590
|
+
private static _withOpenrouterRetry;
|
|
2591
|
+
private static _openrouterText;
|
|
2592
|
+
private static _openrouterStream;
|
|
2593
|
+
private static _openrouterStreamWithTools;
|
|
2594
|
+
/**
|
|
2595
|
+
* Build an Anthropic client. Routes through our Cloudflare LLM proxy when
|
|
2596
|
+
* SUPERATOM_LLM_PROXY_URL is set (each client ships a per-client proxy key as
|
|
2597
|
+
* ANTHROPIC_API_KEY and never holds the real key); otherwise talks to
|
|
2598
|
+
* api.anthropic.com directly. See backend/docs/llm-proxy.md.
|
|
2599
|
+
*/
|
|
2600
|
+
private static _anthropicClient;
|
|
2601
|
+
/** True when OpenRouter is configured as a fail-open fallback for Claude. */
|
|
2602
|
+
private static _openrouterAvailable;
|
|
2603
|
+
/** Remap an Anthropic model id to the OpenRouter model path for fail-open. */
|
|
2604
|
+
private static _anthropicFallbackModel;
|
|
2605
|
+
private static _anthropicText;
|
|
2606
|
+
private static _anthropicStream;
|
|
2607
|
+
private static _anthropicStreamWithTools;
|
|
2608
|
+
private static _groqText;
|
|
2609
|
+
private static _groqStream;
|
|
2610
|
+
/**
|
|
2611
|
+
* Gemini request options carrying the proxy base URL, or undefined → talk to
|
|
2612
|
+
* generativelanguage.googleapis.com directly. The Google SDK takes baseUrl as a
|
|
2613
|
+
* per-model request option, not a constructor arg. See backend/docs/llm-proxy.md.
|
|
2614
|
+
*/
|
|
2615
|
+
private static _geminiRequestOptions;
|
|
2616
|
+
private static _geminiText;
|
|
2617
|
+
private static _geminiStream;
|
|
2618
|
+
/**
|
|
2619
|
+
* Recursively strip unsupported JSON Schema properties for Gemini
|
|
2620
|
+
* Gemini doesn't support: additionalProperties, $schema, etc.
|
|
2621
|
+
*/
|
|
2622
|
+
private static _cleanSchemaForGemini;
|
|
2623
|
+
private static _geminiStreamWithTools;
|
|
2624
|
+
/** True for Anthropic/Claude model ids — gates OpenRouter prompt caching. */
|
|
2625
|
+
private static _isClaudeModel;
|
|
2626
|
+
/**
|
|
2627
|
+
* Build the OpenAI-wire system message. For OpenRouter + Claude
|
|
2628
|
+
* (cacheClaude=true) it emits content parts carrying Anthropic
|
|
2629
|
+
* `cache_control` breakpoints (preserving any the caller set, else marking
|
|
2630
|
+
* the last block), so OpenRouter forwards them to Anthropic for prompt
|
|
2631
|
+
* caching. Otherwise it returns a plain flattened string — unchanged for
|
|
2632
|
+
* direct OpenAI/Groq.
|
|
2633
|
+
*/
|
|
2634
|
+
private static _openaiSystemMessage;
|
|
2635
|
+
/**
|
|
2636
|
+
* Split an OpenAI-wire usage object. `prompt_tokens` INCLUDES cached tokens,
|
|
2637
|
+
* so we subtract them out (Anthropic-style: input excludes cache reads) and
|
|
2638
|
+
* report cached separately — this makes calculateCost price cache reads at
|
|
2639
|
+
* the discounted rate and reflects OpenRouter prompt-cache savings in logs.
|
|
2640
|
+
*/
|
|
2641
|
+
private static _openaiUsage;
|
|
2642
|
+
private static _openaiText;
|
|
2643
|
+
private static _openaiStream;
|
|
2644
|
+
/** Map the Anthropic-style firstIterationToolChoice to OpenAI's tool_choice. */
|
|
2645
|
+
private static _openaiToolChoice;
|
|
2646
|
+
private static _openaiStreamWithTools;
|
|
2647
|
+
/**
|
|
2648
|
+
* Parse JSON string, handling markdown code blocks and surrounding text
|
|
2649
|
+
* Enhanced version with jsonrepair to handle malformed JSON from LLMs
|
|
2650
|
+
* @param text - Text that may contain JSON wrapped in ```json...``` or with surrounding text
|
|
2651
|
+
* @returns Parsed JSON object or array
|
|
2652
|
+
*/
|
|
2653
|
+
private static _parseJSON;
|
|
2654
|
+
}
|
|
2655
|
+
|
|
2656
|
+
interface CapturedLog {
|
|
2657
|
+
timestamp: number;
|
|
2658
|
+
level: 'info' | 'error' | 'warn' | 'debug';
|
|
2659
|
+
message: string;
|
|
2660
|
+
type?: 'explanation' | 'query' | 'general';
|
|
2661
|
+
data?: Record<string, any>;
|
|
2662
|
+
}
|
|
2663
|
+
/**
|
|
2664
|
+
* UILogCollector captures logs during user prompt processing
|
|
2665
|
+
* and sends them to runtime via ui_logs message with uiBlockId as the message id
|
|
2666
|
+
* Logs are sent in real-time for streaming effect in the UI
|
|
2667
|
+
* Respects the global log level configuration
|
|
2668
|
+
*/
|
|
2669
|
+
declare class UILogCollector {
|
|
2670
|
+
private logs;
|
|
2671
|
+
private uiBlockId;
|
|
2672
|
+
private clientId;
|
|
2673
|
+
private sendMessage;
|
|
2674
|
+
private currentLogLevel;
|
|
2675
|
+
constructor(clientId: string, sendMessage: (message: Message) => void, uiBlockId?: string);
|
|
2676
|
+
/**
|
|
2677
|
+
* Check if logging is enabled (uiBlockId is provided)
|
|
2678
|
+
*/
|
|
2679
|
+
isEnabled(): boolean;
|
|
2680
|
+
/**
|
|
2681
|
+
* Check if a message should be logged based on current log level
|
|
2682
|
+
*/
|
|
2683
|
+
private shouldLog;
|
|
2684
|
+
/**
|
|
2685
|
+
* Add a log entry with timestamp and immediately send to runtime
|
|
2686
|
+
* Only logs that pass the log level filter are captured and sent
|
|
2687
|
+
*/
|
|
2688
|
+
private addLog;
|
|
2689
|
+
/**
|
|
2690
|
+
* Send a single log to runtime immediately
|
|
2691
|
+
*/
|
|
2692
|
+
private sendLogImmediately;
|
|
2693
|
+
/**
|
|
2694
|
+
* Log info message
|
|
1104
2695
|
*/
|
|
1105
2696
|
info(message: string, type?: 'explanation' | 'query' | 'general', data?: Record<string, any>): void;
|
|
1106
2697
|
/**
|
|
@@ -1141,16 +2732,6 @@ declare class UILogCollector {
|
|
|
1141
2732
|
setUIBlockId(uiBlockId: string): void;
|
|
1142
2733
|
}
|
|
1143
2734
|
|
|
1144
|
-
/**
|
|
1145
|
-
* Represents an action that can be performed on a UIBlock
|
|
1146
|
-
*/
|
|
1147
|
-
interface Action {
|
|
1148
|
-
id: string;
|
|
1149
|
-
name: string;
|
|
1150
|
-
type: string;
|
|
1151
|
-
[key: string]: any;
|
|
1152
|
-
}
|
|
1153
|
-
|
|
1154
2735
|
/**
|
|
1155
2736
|
* UIBlock represents a single user and assistant message block in a thread
|
|
1156
2737
|
* Contains user question, component metadata, component data, text response, and available actions
|
|
@@ -1163,6 +2744,13 @@ declare class UIBlock {
|
|
|
1163
2744
|
private textResponse;
|
|
1164
2745
|
private actions;
|
|
1165
2746
|
private createdAt;
|
|
2747
|
+
/**
|
|
2748
|
+
* Which script recipe produced this answer, when a script did. Read on the
|
|
2749
|
+
* NEXT turn so the user can say "use mode instead" and have the matcher
|
|
2750
|
+
* resolve it to a concrete script (the `edit` tier is unreachable without it).
|
|
2751
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
2752
|
+
*/
|
|
2753
|
+
private scriptBinding;
|
|
1166
2754
|
/**
|
|
1167
2755
|
* Creates a new UIBlock instance
|
|
1168
2756
|
* @param userQuestion - The user's question or input
|
|
@@ -1257,6 +2845,14 @@ declare class UIBlock {
|
|
|
1257
2845
|
/**
|
|
1258
2846
|
* Get creation timestamp
|
|
1259
2847
|
*/
|
|
2848
|
+
/**
|
|
2849
|
+
* Bind this block to the script recipe that produced its answer.
|
|
2850
|
+
*/
|
|
2851
|
+
setScriptBinding(binding: Record<string, any> | null): void;
|
|
2852
|
+
/**
|
|
2853
|
+
* The script recipe bound to this block, if any.
|
|
2854
|
+
*/
|
|
2855
|
+
getScriptBinding(): Record<string, any> | null;
|
|
1260
2856
|
getCreatedAt(): Date;
|
|
1261
2857
|
/**
|
|
1262
2858
|
* Convert UIBlock to JSON-serializable object
|
|
@@ -1324,6 +2920,32 @@ declare class Thread {
|
|
|
1324
2920
|
* @param currentUIBlockId - ID of current UIBlock to exclude from context (optional)
|
|
1325
2921
|
* @returns Formatted conversation history string
|
|
1326
2922
|
*/
|
|
2923
|
+
/**
|
|
2924
|
+
* The script recipe bound to the most recent completed UIBlock — i.e. the
|
|
2925
|
+
* script behind the answer the user is currently looking at. Drives the
|
|
2926
|
+
* matcher's `edit` tier: without it, "use mode instead" has no target and
|
|
2927
|
+
* falls through to regeneration.
|
|
2928
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
2929
|
+
*/
|
|
2930
|
+
getActiveScriptBinding(currentUIBlockId?: string): Record<string, any> | null;
|
|
2931
|
+
/**
|
|
2932
|
+
* The recent script-backed answers in this thread, newest first — the
|
|
2933
|
+
* candidate set a user-directed edit can target.
|
|
2934
|
+
*
|
|
2935
|
+
* Returning several rather than only the newest is what lets an instruction
|
|
2936
|
+
* name its own target ("use the mode for the WSP one"). With a single
|
|
2937
|
+
* candidate every edit lands on the most recent script, which silently edits
|
|
2938
|
+
* the wrong recipe whenever the user meant an earlier one.
|
|
2939
|
+
*
|
|
2940
|
+
* Deduped by recipeId (newest occurrence wins) so a long editing session on
|
|
2941
|
+
* one script doesn't crowd out the others. Each entry carries the question
|
|
2942
|
+
* that produced it — without that the candidates are indistinguishable.
|
|
2943
|
+
*
|
|
2944
|
+
* In-memory only: dies with the process. The caller falls back to the
|
|
2945
|
+
* persisted bindings when this comes back empty.
|
|
2946
|
+
* See backend/docs/SCRIPT-EDIT-DESIGN.md § Component 1.
|
|
2947
|
+
*/
|
|
2948
|
+
getScriptBindings(limit?: number, currentUIBlockId?: string): Record<string, any>[];
|
|
1327
2949
|
getConversationContext(limit?: number, currentUIBlockId?: string): string;
|
|
1328
2950
|
/**
|
|
1329
2951
|
* Convert Thread to JSON-serializable object
|
|
@@ -1333,12 +2955,20 @@ declare class Thread {
|
|
|
1333
2955
|
|
|
1334
2956
|
/**
|
|
1335
2957
|
* ThreadManager manages all threads globally
|
|
1336
|
-
* Provides methods to create, retrieve, and delete threads
|
|
2958
|
+
* Provides methods to create, retrieve, and delete threads.
|
|
2959
|
+
* Includes automatic cleanup to prevent unbounded memory growth.
|
|
1337
2960
|
*/
|
|
1338
2961
|
declare class ThreadManager {
|
|
1339
2962
|
private static instance;
|
|
1340
2963
|
private threads;
|
|
2964
|
+
private cleanupInterval;
|
|
2965
|
+
private readonly threadTtlMs;
|
|
1341
2966
|
private constructor();
|
|
2967
|
+
/**
|
|
2968
|
+
* Periodically remove threads older than 7 days.
|
|
2969
|
+
* Runs every hour to avoid frequent iteration over the map.
|
|
2970
|
+
*/
|
|
2971
|
+
private startCleanup;
|
|
1342
2972
|
/**
|
|
1343
2973
|
* Get singleton instance of ThreadManager
|
|
1344
2974
|
*/
|
|
@@ -1464,36 +3094,150 @@ declare class CleanupService {
|
|
|
1464
3094
|
*/
|
|
1465
3095
|
declare const STORAGE_CONFIG: {
|
|
1466
3096
|
/**
|
|
1467
|
-
* Maximum number of rows to store in UIBlock data
|
|
3097
|
+
* Maximum number of rows to store in UIBlock data
|
|
3098
|
+
*/
|
|
3099
|
+
MAX_ROWS_PER_BLOCK: number;
|
|
3100
|
+
/**
|
|
3101
|
+
* Maximum size in bytes per UIBlock (500KB - reduced to save memory)
|
|
3102
|
+
*/
|
|
3103
|
+
MAX_SIZE_PER_BLOCK_BYTES: number;
|
|
3104
|
+
/**
|
|
3105
|
+
* Number of days to keep threads before cleanup
|
|
3106
|
+
* Note: This is for in-memory storage. Conversations are also persisted to database.
|
|
3107
|
+
*/
|
|
3108
|
+
THREAD_RETENTION_DAYS: number;
|
|
3109
|
+
/**
|
|
3110
|
+
* Number of days to keep UIBlocks before cleanup
|
|
3111
|
+
* Note: This is for in-memory storage. Data is also persisted to database.
|
|
3112
|
+
*/
|
|
3113
|
+
UIBLOCK_RETENTION_DAYS: number;
|
|
3114
|
+
};
|
|
3115
|
+
|
|
3116
|
+
/**
|
|
3117
|
+
* Configuration for conversation context and history management
|
|
3118
|
+
*/
|
|
3119
|
+
declare const CONTEXT_CONFIG: {
|
|
3120
|
+
/**
|
|
3121
|
+
* Maximum number of previous UIBlocks to include as conversation context
|
|
3122
|
+
* Set to 0 to disable conversation history
|
|
3123
|
+
* Higher values provide more context but may increase token usage
|
|
3124
|
+
*/
|
|
3125
|
+
MAX_CONVERSATION_CONTEXT_BLOCKS: number;
|
|
3126
|
+
};
|
|
3127
|
+
|
|
3128
|
+
/**
|
|
3129
|
+
* LLM Usage Logger - Tracks token usage, costs, and timing for all LLM API calls
|
|
3130
|
+
*/
|
|
3131
|
+
interface LLMUsageEntry {
|
|
3132
|
+
timestamp: string;
|
|
3133
|
+
requestId: string;
|
|
3134
|
+
provider: string;
|
|
3135
|
+
model: string;
|
|
3136
|
+
method: string;
|
|
3137
|
+
inputTokens: number;
|
|
3138
|
+
outputTokens: number;
|
|
3139
|
+
cacheReadTokens?: number;
|
|
3140
|
+
cacheWriteTokens?: number;
|
|
3141
|
+
totalTokens: number;
|
|
3142
|
+
costUSD: number;
|
|
3143
|
+
durationMs: number;
|
|
3144
|
+
toolCalls?: number;
|
|
3145
|
+
success: boolean;
|
|
3146
|
+
error?: string;
|
|
3147
|
+
}
|
|
3148
|
+
declare class LLMUsageLogger {
|
|
3149
|
+
private logStream;
|
|
3150
|
+
private logPath;
|
|
3151
|
+
private enabled;
|
|
3152
|
+
private sessionStats;
|
|
3153
|
+
constructor();
|
|
3154
|
+
private initLogStream;
|
|
3155
|
+
private writeHeader;
|
|
3156
|
+
/**
|
|
3157
|
+
* Calculate cost based on token usage and model
|
|
3158
|
+
*/
|
|
3159
|
+
calculateCost(model: string, inputTokens: number, outputTokens: number, cacheReadTokens?: number, cacheWriteTokens?: number): number;
|
|
3160
|
+
/**
|
|
3161
|
+
* Log an LLM API call
|
|
3162
|
+
*/
|
|
3163
|
+
log(entry: LLMUsageEntry): void;
|
|
3164
|
+
/**
|
|
3165
|
+
* Log session summary (call at end of request)
|
|
3166
|
+
*/
|
|
3167
|
+
logSessionSummary(requestContext?: string): void;
|
|
3168
|
+
/**
|
|
3169
|
+
* Reset session stats (call at start of new user request)
|
|
3170
|
+
*/
|
|
3171
|
+
resetSession(): void;
|
|
3172
|
+
/**
|
|
3173
|
+
* Reset the log file for a new request (clears previous logs)
|
|
3174
|
+
* Call this at the start of each USER_PROMPT_REQ
|
|
3175
|
+
*/
|
|
3176
|
+
resetLogFile(requestContext?: string): void;
|
|
3177
|
+
/**
|
|
3178
|
+
* Get current session stats
|
|
3179
|
+
*/
|
|
3180
|
+
getSessionStats(): {
|
|
3181
|
+
totalCalls: number;
|
|
3182
|
+
totalInputTokens: number;
|
|
3183
|
+
totalOutputTokens: number;
|
|
3184
|
+
totalCacheReadTokens: number;
|
|
3185
|
+
totalCacheWriteTokens: number;
|
|
3186
|
+
totalCostUSD: number;
|
|
3187
|
+
totalDurationMs: number;
|
|
3188
|
+
};
|
|
3189
|
+
/**
|
|
3190
|
+
* Generate a unique request ID
|
|
3191
|
+
*/
|
|
3192
|
+
generateRequestId(): string;
|
|
3193
|
+
}
|
|
3194
|
+
declare const llmUsageLogger: LLMUsageLogger;
|
|
3195
|
+
|
|
3196
|
+
/**
|
|
3197
|
+
* User Prompt Error Logger - Captures detailed errors for USER_PROMPT_REQ
|
|
3198
|
+
* Logs full error details including raw strings for parse failures
|
|
3199
|
+
*/
|
|
3200
|
+
declare class UserPromptErrorLogger {
|
|
3201
|
+
private logStream;
|
|
3202
|
+
private logPath;
|
|
3203
|
+
private enabled;
|
|
3204
|
+
private hasErrors;
|
|
3205
|
+
constructor();
|
|
3206
|
+
/**
|
|
3207
|
+
* Reset the error log file for a new request
|
|
3208
|
+
*/
|
|
3209
|
+
resetLogFile(requestContext?: string): void;
|
|
3210
|
+
/**
|
|
3211
|
+
* Log a JSON parse error with the raw string that failed
|
|
1468
3212
|
*/
|
|
1469
|
-
|
|
3213
|
+
logJsonParseError(context: string, rawString: string, error: Error): void;
|
|
1470
3214
|
/**
|
|
1471
|
-
*
|
|
3215
|
+
* Log a general error with full details
|
|
1472
3216
|
*/
|
|
1473
|
-
|
|
3217
|
+
logError(context: string, error: Error | string, additionalData?: Record<string, any>): void;
|
|
1474
3218
|
/**
|
|
1475
|
-
*
|
|
1476
|
-
* Note: This is for in-memory storage. Conversations are also persisted to database.
|
|
3219
|
+
* Log a SQL query error with the full query
|
|
1477
3220
|
*/
|
|
1478
|
-
|
|
3221
|
+
logSqlError(query: string, error: Error | string, params?: any[]): void;
|
|
1479
3222
|
/**
|
|
1480
|
-
*
|
|
1481
|
-
* Note: This is for in-memory storage. Data is also persisted to database.
|
|
3223
|
+
* Log an LLM API error
|
|
1482
3224
|
*/
|
|
1483
|
-
|
|
1484
|
-
};
|
|
1485
|
-
|
|
1486
|
-
/**
|
|
1487
|
-
* Configuration for conversation context and history management
|
|
1488
|
-
*/
|
|
1489
|
-
declare const CONTEXT_CONFIG: {
|
|
3225
|
+
logLlmError(provider: string, model: string, method: string, error: Error | string, requestData?: any): void;
|
|
1490
3226
|
/**
|
|
1491
|
-
*
|
|
1492
|
-
* Set to 0 to disable conversation history
|
|
1493
|
-
* Higher values provide more context but may increase token usage
|
|
3227
|
+
* Log tool execution error
|
|
1494
3228
|
*/
|
|
1495
|
-
|
|
1496
|
-
|
|
3229
|
+
logToolError(toolName: string, toolInput: any, error: Error | string): void;
|
|
3230
|
+
/**
|
|
3231
|
+
* Write final summary if there were errors
|
|
3232
|
+
*/
|
|
3233
|
+
writeSummary(): void;
|
|
3234
|
+
/**
|
|
3235
|
+
* Check if any errors were logged
|
|
3236
|
+
*/
|
|
3237
|
+
hadErrors(): boolean;
|
|
3238
|
+
private write;
|
|
3239
|
+
}
|
|
3240
|
+
declare const userPromptErrorLogger: UserPromptErrorLogger;
|
|
1497
3241
|
|
|
1498
3242
|
/**
|
|
1499
3243
|
* BM25L Reranker for hybrid semantic search
|
|
@@ -1623,14 +3367,627 @@ declare function rerankConversationResults<T extends {
|
|
|
1623
3367
|
bm25Score: number;
|
|
1624
3368
|
}>;
|
|
1625
3369
|
|
|
1626
|
-
|
|
3370
|
+
/**
|
|
3371
|
+
* QueryExecutionService - Handles all query execution, validation, and retry logic
|
|
3372
|
+
* Extracted from BaseLLM for better separation of concerns
|
|
3373
|
+
*/
|
|
3374
|
+
|
|
3375
|
+
/**
|
|
3376
|
+
* Context for component when requesting query fix
|
|
3377
|
+
*/
|
|
3378
|
+
interface ComponentContext {
|
|
3379
|
+
name: string;
|
|
3380
|
+
type: string;
|
|
3381
|
+
title?: string;
|
|
3382
|
+
}
|
|
3383
|
+
/**
|
|
3384
|
+
* Result of query validation
|
|
3385
|
+
*/
|
|
3386
|
+
interface QueryValidationResult {
|
|
3387
|
+
component: Component | null;
|
|
3388
|
+
queryKey: string;
|
|
3389
|
+
result: any;
|
|
3390
|
+
validated: boolean;
|
|
3391
|
+
}
|
|
3392
|
+
/**
|
|
3393
|
+
* Result of batch query validation
|
|
3394
|
+
*/
|
|
3395
|
+
interface BatchValidationResult {
|
|
3396
|
+
components: Component[];
|
|
3397
|
+
queryResults: Map<string, any>;
|
|
3398
|
+
}
|
|
3399
|
+
/**
|
|
3400
|
+
* Configuration for QueryExecutionService
|
|
3401
|
+
*/
|
|
3402
|
+
interface QueryExecutionServiceConfig {
|
|
3403
|
+
defaultLimit: number;
|
|
3404
|
+
getModelForTask: (taskType: 'simple' | 'complex') => string;
|
|
3405
|
+
getApiKey: (apiKey?: string) => string | undefined;
|
|
3406
|
+
providerName: string;
|
|
3407
|
+
}
|
|
3408
|
+
/**
|
|
3409
|
+
* QueryExecutionService handles all query-related operations
|
|
3410
|
+
*/
|
|
3411
|
+
declare class QueryExecutionService {
|
|
3412
|
+
private config;
|
|
3413
|
+
constructor(config: QueryExecutionServiceConfig);
|
|
3414
|
+
/**
|
|
3415
|
+
* Get the cache key for a query
|
|
3416
|
+
* This ensures the cache key matches what the frontend will send
|
|
3417
|
+
*/
|
|
3418
|
+
getQueryCacheKey(query: any): string;
|
|
3419
|
+
/**
|
|
3420
|
+
* Execute a query against the database
|
|
3421
|
+
* @param query - The SQL query to execute (string or object with sql/values)
|
|
3422
|
+
* @param collections - Collections object containing database execute function
|
|
3423
|
+
* @returns Object with result data and cache key
|
|
3424
|
+
*/
|
|
3425
|
+
executeQuery(query: any, collections: any): Promise<{
|
|
3426
|
+
result: any;
|
|
3427
|
+
cacheKey: string;
|
|
3428
|
+
}>;
|
|
3429
|
+
/**
|
|
3430
|
+
* Request the LLM to fix a failed SQL query
|
|
3431
|
+
* @param failedQuery - The query that failed execution
|
|
3432
|
+
* @param errorMessage - The error message from the failed execution
|
|
3433
|
+
* @param componentContext - Context about the component
|
|
3434
|
+
* @param apiKey - Optional API key
|
|
3435
|
+
* @returns Fixed query string
|
|
3436
|
+
*/
|
|
3437
|
+
requestQueryFix(failedQuery: string, errorMessage: string, componentContext: ComponentContext, apiKey?: string): Promise<string>;
|
|
3438
|
+
/**
|
|
3439
|
+
* Validate a single component's query with retry logic
|
|
3440
|
+
* @param component - The component to validate
|
|
3441
|
+
* @param collections - Collections object containing database execute function
|
|
3442
|
+
* @param apiKey - Optional API key for LLM calls
|
|
3443
|
+
* @returns Validation result with component, query key, and result
|
|
3444
|
+
*/
|
|
3445
|
+
validateSingleQuery(component: Component, collections: any, apiKey?: string): Promise<QueryValidationResult>;
|
|
3446
|
+
/**
|
|
3447
|
+
* Validate multiple component queries in parallel
|
|
3448
|
+
* @param components - Array of components with potential queries
|
|
3449
|
+
* @param collections - Collections object containing database execute function
|
|
3450
|
+
* @param apiKey - Optional API key for LLM calls
|
|
3451
|
+
* @returns Object with validated components and query results map
|
|
3452
|
+
*/
|
|
3453
|
+
validateComponentQueries(components: Component[], collections: any, apiKey?: string): Promise<BatchValidationResult>;
|
|
3454
|
+
}
|
|
3455
|
+
|
|
3456
|
+
/**
|
|
3457
|
+
* Task types for model selection
|
|
3458
|
+
* - 'complex': Text generation, component matching, parameter adaptation (uses best model in balanced mode)
|
|
3459
|
+
* - 'simple': Classification, action generation (uses fast model in balanced mode)
|
|
3460
|
+
*/
|
|
3461
|
+
type TaskType = 'complex' | 'simple';
|
|
3462
|
+
interface BaseLLMConfig {
|
|
3463
|
+
model?: string;
|
|
3464
|
+
fastModel?: string;
|
|
3465
|
+
defaultLimit?: number;
|
|
3466
|
+
apiKey?: string;
|
|
3467
|
+
/**
|
|
3468
|
+
* Model selection strategy:
|
|
3469
|
+
* - 'best': Use best model for all tasks (highest quality, higher cost)
|
|
3470
|
+
* - 'fast': Use fast model for all tasks (lower quality, lower cost)
|
|
3471
|
+
* - 'balanced': Use best model for complex tasks, fast model for simple tasks (default)
|
|
3472
|
+
*/
|
|
3473
|
+
modelStrategy?: ModelStrategy;
|
|
3474
|
+
conversationSimilarityThreshold?: number;
|
|
3475
|
+
}
|
|
3476
|
+
/**
|
|
3477
|
+
* BaseLLM abstract class for AI-powered component generation and matching
|
|
3478
|
+
* Provides common functionality for all LLM providers
|
|
3479
|
+
*/
|
|
3480
|
+
declare abstract class BaseLLM {
|
|
3481
|
+
protected model: string;
|
|
3482
|
+
protected fastModel: string;
|
|
3483
|
+
protected defaultLimit: number;
|
|
3484
|
+
protected apiKey?: string;
|
|
3485
|
+
protected modelStrategy: ModelStrategy;
|
|
3486
|
+
protected conversationSimilarityThreshold: number;
|
|
3487
|
+
protected queryService: QueryExecutionService;
|
|
3488
|
+
constructor(config?: BaseLLMConfig);
|
|
3489
|
+
/**
|
|
3490
|
+
* Get the appropriate model based on task type and model strategy
|
|
3491
|
+
* @param taskType - 'complex' for text generation/matching, 'simple' for classification/actions
|
|
3492
|
+
* @returns The model string to use for this task
|
|
3493
|
+
*/
|
|
3494
|
+
protected getModelForTask(taskType: TaskType): string;
|
|
3495
|
+
/**
|
|
3496
|
+
* Set the model strategy at runtime
|
|
3497
|
+
* @param strategy - 'best', 'fast', or 'balanced'
|
|
3498
|
+
*/
|
|
3499
|
+
setModelStrategy(strategy: ModelStrategy): void;
|
|
3500
|
+
/**
|
|
3501
|
+
* Get the current model strategy
|
|
3502
|
+
* @returns The current model strategy
|
|
3503
|
+
*/
|
|
3504
|
+
getModelStrategy(): ModelStrategy;
|
|
3505
|
+
/**
|
|
3506
|
+
* Set the conversation similarity threshold at runtime
|
|
3507
|
+
* @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
|
|
3508
|
+
*/
|
|
3509
|
+
setConversationSimilarityThreshold(threshold: number): void;
|
|
3510
|
+
/**
|
|
3511
|
+
* Get the current conversation similarity threshold
|
|
3512
|
+
* @returns The current threshold value
|
|
3513
|
+
*/
|
|
3514
|
+
getConversationSimilarityThreshold(): number;
|
|
3515
|
+
/**
|
|
3516
|
+
* Get the default model for this provider (used for complex tasks like text generation)
|
|
3517
|
+
*/
|
|
3518
|
+
protected abstract getDefaultModel(): string;
|
|
3519
|
+
/**
|
|
3520
|
+
* Get the default fast model for this provider (used for simple tasks: classification, matching, actions)
|
|
3521
|
+
* Should return a cheaper/faster model like Haiku for Anthropic
|
|
3522
|
+
*/
|
|
3523
|
+
protected abstract getDefaultFastModel(): string;
|
|
3524
|
+
/**
|
|
3525
|
+
* Get the default API key from environment
|
|
3526
|
+
*/
|
|
3527
|
+
protected abstract getDefaultApiKey(): string | undefined;
|
|
3528
|
+
/**
|
|
3529
|
+
* Get the provider name (for logging)
|
|
3530
|
+
*/
|
|
3531
|
+
protected abstract getProviderName(): string;
|
|
3532
|
+
/**
|
|
3533
|
+
* Get the API key (from instance, parameter, or environment)
|
|
3534
|
+
*/
|
|
3535
|
+
protected getApiKey(apiKey?: string): string | undefined;
|
|
3536
|
+
/**
|
|
3537
|
+
* Check if a component contains a Form (data_modification component)
|
|
3538
|
+
* Forms have hardcoded defaultValues that become stale when cached
|
|
3539
|
+
* This checks both single Form components and Forms inside MultiComponentContainer
|
|
3540
|
+
*/
|
|
3541
|
+
protected containsFormComponent(component: any): boolean;
|
|
3542
|
+
/**
|
|
3543
|
+
* Match components from text response suggestions and generate follow-up questions
|
|
3544
|
+
* Takes a text response with component suggestions (c1:type format) and matches with available components
|
|
3545
|
+
* Also generates title, description, and intelligent follow-up questions (actions) based on the analysis
|
|
3546
|
+
* All components are placed in a default MultiComponentContainer layout
|
|
3547
|
+
* @param analysisContent - The text response containing component suggestions
|
|
3548
|
+
* @param components - List of available components
|
|
3549
|
+
* @param apiKey - Optional API key
|
|
3550
|
+
* @param componentStreamCallback - Optional callback to stream primary KPI component as soon as it's identified
|
|
3551
|
+
* @returns Object containing matched components, layout title/description, and follow-up actions
|
|
3552
|
+
*/
|
|
3553
|
+
matchComponentsFromAnalysis(analysisContent: string, components: Component[], userPrompt: string, apiKey?: string, componentStreamCallback?: (component: Component) => void, deferredTools?: any[], executedTools?: any[], collections?: any, userId?: string): Promise<{
|
|
3554
|
+
components: Component[];
|
|
3555
|
+
layoutTitle: string;
|
|
3556
|
+
layoutDescription: string;
|
|
3557
|
+
actions: Action[];
|
|
3558
|
+
}>;
|
|
3559
|
+
/**
|
|
3560
|
+
* Classify user question into category and detect external tools needed
|
|
3561
|
+
* Determines if question is for data analysis, requires external tools, or needs text response
|
|
3562
|
+
*/
|
|
3563
|
+
classifyQuestionCategory(userPrompt: string, apiKey?: string, conversationHistory?: string, externalTools?: any[]): Promise<{
|
|
3564
|
+
category: 'data_analysis' | 'data_modification' | 'general';
|
|
3565
|
+
externalTools: Array<{
|
|
3566
|
+
type: string;
|
|
3567
|
+
name: string;
|
|
3568
|
+
description: string;
|
|
3569
|
+
parameters: Record<string, any>;
|
|
3570
|
+
}>;
|
|
3571
|
+
dataAnalysisType?: 'visualization' | 'calculation' | 'comparison' | 'trend';
|
|
3572
|
+
reasoning: string;
|
|
3573
|
+
confidence: number;
|
|
3574
|
+
}>;
|
|
3575
|
+
/**
|
|
3576
|
+
* Adapt UI block parameters based on current user question
|
|
3577
|
+
* Takes a matched UI block from semantic search and modifies its props to answer the new question
|
|
3578
|
+
* Also adapts the cached text response to match the new question
|
|
3579
|
+
*/
|
|
3580
|
+
adaptUIBlockParameters(currentUserPrompt: string, originalUserPrompt: string, matchedUIBlock: any, apiKey?: string, cachedTextResponse?: string): Promise<{
|
|
3581
|
+
success: boolean;
|
|
3582
|
+
adaptedComponent?: Component;
|
|
3583
|
+
adaptedTextResponse?: string;
|
|
3584
|
+
parametersChanged?: Array<{
|
|
3585
|
+
field: string;
|
|
3586
|
+
reason: string;
|
|
3587
|
+
}>;
|
|
3588
|
+
explanation: string;
|
|
3589
|
+
}>;
|
|
3590
|
+
/**
|
|
3591
|
+
* Generate text-based response for user question
|
|
3592
|
+
* This provides conversational text responses instead of component generation
|
|
3593
|
+
* Supports tool calling for query execution with automatic retry on errors (max 3 attempts)
|
|
3594
|
+
* After generating text response, if components are provided, matches suggested components
|
|
3595
|
+
*/
|
|
3596
|
+
generateTextResponse(userPrompt: string, apiKey?: string, conversationHistory?: string, streamCallback?: (chunk: string) => void, collections?: any, components?: Component[], externalTools?: any[], category?: 'data_analysis' | 'data_modification' | 'general', userId?: string): Promise<T_RESPONSE>;
|
|
3597
|
+
/**
|
|
3598
|
+
* Main orchestration function with semantic search and multi-step classification
|
|
3599
|
+
* NEW FLOW (Recommended):
|
|
3600
|
+
* 1. Semantic search: Check previous conversations (>60% match)
|
|
3601
|
+
* - If match found → Adapt UI block parameters and return
|
|
3602
|
+
* 2. Category classification: Determine if data_analysis, requires_external_tools, or text_response
|
|
3603
|
+
* 3. Route appropriately based on category and response mode
|
|
3604
|
+
*/
|
|
3605
|
+
handleUserRequest(userPrompt: string, components: Component[], apiKey?: string, conversationHistory?: string, responseMode?: 'component' | 'text', streamCallback?: (chunk: string) => void, collections?: any, externalTools?: any[], userId?: string): Promise<T_RESPONSE>;
|
|
3606
|
+
/**
|
|
3607
|
+
* Generate next questions that the user might ask based on the original prompt and generated component
|
|
3608
|
+
* This helps provide intelligent suggestions for follow-up queries
|
|
3609
|
+
* For general/conversational questions without components, pass textResponse instead
|
|
3610
|
+
*/
|
|
3611
|
+
generateNextQuestions(originalUserPrompt: string, component?: Component | null, componentData?: Record<string, unknown>, apiKey?: string, conversationHistory?: string, textResponse?: string, signal?: AbortSignal): Promise<string[]>;
|
|
3612
|
+
}
|
|
3613
|
+
|
|
3614
|
+
interface AnthropicLLMConfig extends BaseLLMConfig {
|
|
3615
|
+
}
|
|
3616
|
+
/**
|
|
3617
|
+
* AnthropicLLM class for handling AI-powered component generation and matching using Anthropic Claude
|
|
3618
|
+
*/
|
|
3619
|
+
declare class AnthropicLLM extends BaseLLM {
|
|
3620
|
+
constructor(config?: AnthropicLLMConfig);
|
|
3621
|
+
protected getDefaultModel(): string;
|
|
3622
|
+
protected getDefaultFastModel(): string;
|
|
3623
|
+
protected getDefaultApiKey(): string | undefined;
|
|
3624
|
+
protected getProviderName(): string;
|
|
3625
|
+
}
|
|
3626
|
+
declare const anthropicLLM: AnthropicLLM;
|
|
3627
|
+
|
|
3628
|
+
interface GroqLLMConfig extends BaseLLMConfig {
|
|
3629
|
+
}
|
|
3630
|
+
/**
|
|
3631
|
+
* GroqLLM class for handling AI-powered component generation and matching using Groq
|
|
3632
|
+
*/
|
|
3633
|
+
declare class GroqLLM extends BaseLLM {
|
|
3634
|
+
constructor(config?: GroqLLMConfig);
|
|
3635
|
+
protected getDefaultModel(): string;
|
|
3636
|
+
protected getDefaultFastModel(): string;
|
|
3637
|
+
protected getDefaultApiKey(): string | undefined;
|
|
3638
|
+
protected getProviderName(): string;
|
|
3639
|
+
}
|
|
3640
|
+
declare const groqLLM: GroqLLM;
|
|
3641
|
+
|
|
3642
|
+
interface GeminiLLMConfig extends BaseLLMConfig {
|
|
3643
|
+
}
|
|
3644
|
+
/**
|
|
3645
|
+
* GeminiLLM class for handling AI-powered component generation and matching using Google Gemini
|
|
3646
|
+
*/
|
|
3647
|
+
declare class GeminiLLM extends BaseLLM {
|
|
3648
|
+
constructor(config?: GeminiLLMConfig);
|
|
3649
|
+
protected getDefaultModel(): string;
|
|
3650
|
+
protected getDefaultFastModel(): string;
|
|
3651
|
+
protected getDefaultApiKey(): string | undefined;
|
|
3652
|
+
protected getProviderName(): string;
|
|
3653
|
+
}
|
|
3654
|
+
declare const geminiLLM: GeminiLLM;
|
|
3655
|
+
|
|
3656
|
+
interface OpenAILLMConfig extends BaseLLMConfig {
|
|
3657
|
+
}
|
|
3658
|
+
/**
|
|
3659
|
+
* OpenAILLM class for handling AI-powered component generation and matching using OpenAI GPT models
|
|
3660
|
+
*/
|
|
3661
|
+
declare class OpenAILLM extends BaseLLM {
|
|
3662
|
+
constructor(config?: OpenAILLMConfig);
|
|
3663
|
+
protected getDefaultModel(): string;
|
|
3664
|
+
protected getDefaultFastModel(): string;
|
|
3665
|
+
protected getDefaultApiKey(): string | undefined;
|
|
3666
|
+
protected getProviderName(): string;
|
|
3667
|
+
}
|
|
3668
|
+
declare const openaiLLM: OpenAILLM;
|
|
3669
|
+
|
|
3670
|
+
/**
|
|
3671
|
+
* Query Cache — Two mechanisms:
|
|
3672
|
+
*
|
|
3673
|
+
* 1. `cache` (query string → result data) — TTL-based with max size, for avoiding re-execution
|
|
3674
|
+
* of recently validated queries. True LRU eviction: reads bubble entries to the back via
|
|
3675
|
+
* delete+re-set so the oldest *unused* entry is evicted, not the oldest *inserted*.
|
|
3676
|
+
*
|
|
3677
|
+
* 2. Encrypted queryId tokens — SQL is encrypted into the queryId itself (self-contained).
|
|
3678
|
+
* No server-side storage needed for SQL mappings. The token is decrypted on each request.
|
|
3679
|
+
* This eliminates the unbounded queryIdCache that previously grew forever and caused
|
|
3680
|
+
* memory bloat (hundreds of MBs after thousands of queries).
|
|
3681
|
+
*
|
|
3682
|
+
* Result data can still be cached temporarily via the data cache (mechanism 1).
|
|
3683
|
+
*/
|
|
3684
|
+
declare class QueryCache {
|
|
3685
|
+
private cache;
|
|
3686
|
+
private ttlMs;
|
|
3687
|
+
private maxCacheSize;
|
|
3688
|
+
private cleanupInterval;
|
|
3689
|
+
private readonly algorithm;
|
|
3690
|
+
private encryptionKey;
|
|
3691
|
+
constructor();
|
|
3692
|
+
/**
|
|
3693
|
+
* Set the cache TTL (Time To Live)
|
|
3694
|
+
* @param minutes - TTL in minutes (default: 10)
|
|
3695
|
+
*/
|
|
3696
|
+
setTTL(minutes: number): void;
|
|
3697
|
+
/**
|
|
3698
|
+
* Get the current TTL in minutes
|
|
3699
|
+
*/
|
|
3700
|
+
getTTL(): number;
|
|
3701
|
+
/**
|
|
3702
|
+
* Store query result in data cache.
|
|
3703
|
+
* If the key already exists, it's removed first so the re-insert places it
|
|
3704
|
+
* at the back of the iteration order (LRU). Eviction only fires when adding
|
|
3705
|
+
* a genuinely new key past the size limit.
|
|
3706
|
+
*/
|
|
3707
|
+
set(query: string, data: any): void;
|
|
3708
|
+
/**
|
|
3709
|
+
* Get cached result if exists and not expired.
|
|
3710
|
+
* On hit, re-inserts the entry so it moves to the back of the Map's
|
|
3711
|
+
* iteration order — turning FIFO eviction into true LRU.
|
|
3712
|
+
*/
|
|
3713
|
+
get(query: string): any | null;
|
|
3714
|
+
/**
|
|
3715
|
+
* Check if query exists in cache (not expired)
|
|
3716
|
+
*/
|
|
3717
|
+
has(query: string): boolean;
|
|
3718
|
+
/**
|
|
3719
|
+
* Remove a specific query from cache
|
|
3720
|
+
*/
|
|
3721
|
+
delete(query: string): void;
|
|
3722
|
+
/**
|
|
3723
|
+
* Clear all cached entries
|
|
3724
|
+
*/
|
|
3725
|
+
clear(): void;
|
|
3726
|
+
/**
|
|
3727
|
+
* Get cache statistics
|
|
3728
|
+
*/
|
|
3729
|
+
getStats(): {
|
|
3730
|
+
size: number;
|
|
3731
|
+
queryIdCount: number;
|
|
3732
|
+
oldestEntryAge: number | null;
|
|
3733
|
+
};
|
|
3734
|
+
/**
|
|
3735
|
+
* Start periodic cleanup of expired data cache entries.
|
|
3736
|
+
*/
|
|
3737
|
+
private startCleanup;
|
|
3738
|
+
/**
|
|
3739
|
+
* Encrypt a payload into a self-contained token.
|
|
3740
|
+
*/
|
|
3741
|
+
private encrypt;
|
|
3742
|
+
/**
|
|
3743
|
+
* Decrypt a token back to the original payload.
|
|
3744
|
+
*/
|
|
3745
|
+
private decrypt;
|
|
3746
|
+
/**
|
|
3747
|
+
* Store a query by generating an encrypted token as queryId.
|
|
3748
|
+
* The SQL is encrypted INTO the token — nothing stored in memory.
|
|
3749
|
+
* If data is provided, it's cached temporarily in the data cache.
|
|
3750
|
+
*/
|
|
3751
|
+
storeQuery(query: any, data?: any): string;
|
|
3752
|
+
/**
|
|
3753
|
+
* Get a stored query by decrypting its token.
|
|
3754
|
+
* Returns the SQL + any cached result data.
|
|
3755
|
+
*/
|
|
3756
|
+
getQuery(queryId: string): {
|
|
3757
|
+
query: any;
|
|
3758
|
+
data: any;
|
|
3759
|
+
} | null;
|
|
3760
|
+
/**
|
|
3761
|
+
* Update cached data for a queryId token
|
|
3762
|
+
*/
|
|
3763
|
+
setQueryData(queryId: string, data: any): void;
|
|
3764
|
+
/**
|
|
3765
|
+
* Stop cleanup interval (for graceful shutdown)
|
|
3766
|
+
*/
|
|
3767
|
+
destroy(): void;
|
|
3768
|
+
}
|
|
3769
|
+
declare const queryCache: QueryCache;
|
|
3770
|
+
|
|
3771
|
+
/**
|
|
3772
|
+
* Manages conversation history scoped per user + dashboard.
|
|
3773
|
+
* Each user-dashboard pair has its own isolated history that expires after a configurable TTL.
|
|
3774
|
+
*/
|
|
3775
|
+
declare class DashboardConversationHistory {
|
|
3776
|
+
private histories;
|
|
3777
|
+
private ttlMs;
|
|
3778
|
+
private maxEntries;
|
|
3779
|
+
private cleanupInterval;
|
|
3780
|
+
constructor();
|
|
3781
|
+
/**
|
|
3782
|
+
* Set the TTL for dashboard histories
|
|
3783
|
+
* @param minutes - TTL in minutes
|
|
3784
|
+
*/
|
|
3785
|
+
setTTL(minutes: number): void;
|
|
3786
|
+
/**
|
|
3787
|
+
* Set max entries per dashboard
|
|
3788
|
+
*/
|
|
3789
|
+
setMaxEntries(max: number): void;
|
|
3790
|
+
/**
|
|
3791
|
+
* Add a conversation entry for a user's dashboard
|
|
3792
|
+
*/
|
|
3793
|
+
addEntry(dashboardId: string, userPrompt: string, componentSummary: string, userId?: string): void;
|
|
3794
|
+
/**
|
|
3795
|
+
* Get formatted conversation history for a user's dashboard
|
|
3796
|
+
*/
|
|
3797
|
+
getHistory(dashboardId: string, userId?: string): string;
|
|
3798
|
+
/**
|
|
3799
|
+
* Clear history for a specific user's dashboard
|
|
3800
|
+
*/
|
|
3801
|
+
clearDashboard(dashboardId: string, userId?: string): void;
|
|
3802
|
+
/**
|
|
3803
|
+
* Clear all dashboard histories
|
|
3804
|
+
*/
|
|
3805
|
+
clearAll(): void;
|
|
3806
|
+
/**
|
|
3807
|
+
* Start periodic cleanup of expired histories
|
|
3808
|
+
*/
|
|
3809
|
+
private startCleanup;
|
|
3810
|
+
/**
|
|
3811
|
+
* Stop cleanup interval (for graceful shutdown)
|
|
3812
|
+
*/
|
|
3813
|
+
destroy(): void;
|
|
3814
|
+
}
|
|
3815
|
+
declare const dashboardConversationHistory: DashboardConversationHistory;
|
|
3816
|
+
|
|
3817
|
+
/**
|
|
3818
|
+
* Whole-dashboard generation via Pi, a terminal coding agent — as opposed to
|
|
3819
|
+
* DASH_COMP_REQ's single-widget-at-a-time flow. Runs Pi in-process via its
|
|
3820
|
+
* SDK (createAgentSession), not as a subprocess: no shell, no argument
|
|
3821
|
+
* quoting, no stdin/stdout piping, none of the Windows-specific subprocess
|
|
3822
|
+
* issues that came with spawning the `pi` CLI directly.
|
|
3823
|
+
*
|
|
3824
|
+
* Called from sdk-nodejs/src/dashboardAgent/index.ts (DASHBOARD_AGENT_REQ),
|
|
3825
|
+
* which owns the generic streaming/abort machinery (mirrors USER_PROMPT_REQ)
|
|
3826
|
+
* and passes `signal`/`onProgress` alongside the normal params — this stays
|
|
3827
|
+
* within CollectionHandler's loose (params) => Promise<result> typing, no
|
|
3828
|
+
* change needed to that shared type.
|
|
3829
|
+
*
|
|
3830
|
+
* This mechanism is generic and reusable across any deployment. What's
|
|
3831
|
+
* genuinely project-specific — where AGENTS.md lives, which model to use —
|
|
3832
|
+
* is supplied via `DashboardAgentCollectionConfig`, with defaults sensible
|
|
3833
|
+
* enough that most callers don't need to override them (see below). The
|
|
3834
|
+
* data-source tool list and the dashboard's current state both come from
|
|
3835
|
+
* things sdk-nodejs already exposes generically: `sdk.getTools()` (whatever
|
|
3836
|
+
* this deployment registered via `sdk.setTools()`) and `sdk.callCollection
|
|
3837
|
+
* ('dashboards', 'query', ...)` (whatever this deployment already registered
|
|
3838
|
+
* under that name/shape) — no per-deployment callback needed for either.
|
|
3839
|
+
* Same convention on the way out: after a successful run, the prompt and the
|
|
3840
|
+
* full response text are handed to `sdk.callCollection('dashboard-agent-
|
|
3841
|
+
* conversations', 'create', ...)` if this deployment has registered one —
|
|
3842
|
+
* skipped silently otherwise, since conversation history is optional.
|
|
3843
|
+
*
|
|
3844
|
+
* Pi verifies every query against the live database itself (via whatever
|
|
3845
|
+
* local tool-execution bridge the deployment exposes, e.g. an HTTP bridge
|
|
3846
|
+
* on localhost), but does NOT persist the result itself — it writes the
|
|
3847
|
+
* finished DSL to an absolute path inside `runtimeDir`, told to it explicitly
|
|
3848
|
+
* in the prompt, and stops there. This handler reads that file after the run
|
|
3849
|
+
* finishes and returns its content as `dashboard` in the result. The caller
|
|
3850
|
+
* (frontend) is the one that actually saves it, via whatever authenticated
|
|
3851
|
+
* create/update path any other dashboard edit goes through — Pi has no user
|
|
3852
|
+
* session/auth context of its own, so persistence shouldn't happen from
|
|
3853
|
+
* inside it.
|
|
3854
|
+
*
|
|
3855
|
+
* Session persistence: the FIRST call for a dashboardId pays the full cost
|
|
3856
|
+
* (explore KB, discover schema, plan, verify, build). Every call after that
|
|
3857
|
+
* resumes the same session file (SessionManager.open) so Pi has everything
|
|
3858
|
+
* it already learned — it only needs to reason about the new, smaller ask,
|
|
3859
|
+
* not rediscover the whole dashboard from scratch. The session's file path
|
|
3860
|
+
* (AgentSession.sessionFile) is captured right after creation and persisted
|
|
3861
|
+
* in a small local file, keyed by dashboardId, inside `runtimeDir`.
|
|
3862
|
+
*/
|
|
3863
|
+
interface DashboardAgentCollectionConfig {
|
|
3864
|
+
/**
|
|
3865
|
+
* Working directory Pi runs from — must contain AGENTS.md. This is a
|
|
3866
|
+
* version-controlled prompt file, so `cwd` is expected to live somewhere
|
|
3867
|
+
* like a `.prompts/` folder alongside the deployment's other prompts.
|
|
3868
|
+
* Default: `<process.cwd()>/.prompts/dashboard-agent` — the same
|
|
3869
|
+
* process.cwd()-based convention PromptLoader already uses for the main
|
|
3870
|
+
* agent's prompts, which needs no explicit override in the common case
|
|
3871
|
+
* (the backend process's own cwd already is its project root).
|
|
3872
|
+
*/
|
|
3873
|
+
cwd?: string;
|
|
3874
|
+
/**
|
|
3875
|
+
* Where drafts/, the session-id map, and dashboard.log get written —
|
|
3876
|
+
* separate from `cwd` deliberately, so this deployment's runtime state
|
|
3877
|
+
* (regenerated per session, safe to gitignore) doesn't sit inside the
|
|
3878
|
+
* same folder as the version-controlled AGENTS.md prompt.
|
|
3879
|
+
* Default: `<process.cwd()>/.pi-dashboard-agent-runtime`.
|
|
3880
|
+
*/
|
|
3881
|
+
runtimeDir?: string;
|
|
3882
|
+
/** Model provider (default: process.env.PI_AGENT_PROVIDER || 'openrouter'). */
|
|
3883
|
+
provider?: string;
|
|
3884
|
+
/** Model id (default: process.env.PI_AGENT_MODEL || 'anthropic/claude-sonnet-4.5'). */
|
|
3885
|
+
model?: string;
|
|
3886
|
+
/**
|
|
3887
|
+
* true (default): every request starts a brand-new pi session, with the 2
|
|
3888
|
+
* most recent prior responses (if any) injected into the prompt as
|
|
3889
|
+
* context — bounded cost per request, but pi re-explores schema/KB facts
|
|
3890
|
+
* it already verified in an earlier turn on this same dashboard.
|
|
3891
|
+
* false: resumes the same session file across requests on a given
|
|
3892
|
+
* dashboard — pi keeps everything it already learned, but context (and
|
|
3893
|
+
* cost) grows unbounded across turns (one observed turn: 2M+ cache-read
|
|
3894
|
+
* tokens after a handful of edits on the same dashboard).
|
|
3895
|
+
* Default: process.env.PI_AGENT_FRESH_SESSION !== 'false'.
|
|
3896
|
+
*/
|
|
3897
|
+
freshSession?: boolean;
|
|
3898
|
+
}
|
|
3899
|
+
declare function registerDashboardAgentCollection(sdk: SuperatomSDK, config?: DashboardAgentCollectionConfig): void;
|
|
3900
|
+
|
|
3901
|
+
/**
|
|
3902
|
+
* ScriptMatcher — LLM-Based Script Matching + Parameter Extraction
|
|
3903
|
+
*
|
|
3904
|
+
* Uses ONE LLM call to:
|
|
3905
|
+
* 1. Pick the best matching script from the library (or "none")
|
|
3906
|
+
* 2. Extract parameter values from the user question
|
|
3907
|
+
*
|
|
3908
|
+
* Why LLM over embeddings:
|
|
3909
|
+
* - Embeddings capture topic similarity ("overstock" ≈ "inventory" ≈ "revenue")
|
|
3910
|
+
* but can't distinguish structurally different questions about the same domain
|
|
3911
|
+
* - LLM understands that "overstock by warehouse" needs a different script than
|
|
3912
|
+
* "revenue by warehouse" even though they're semantically close
|
|
3913
|
+
* - One call does both matching AND parameter extraction
|
|
3914
|
+
*
|
|
3915
|
+
* When script library grows past ~50, add an embedding pre-filter
|
|
3916
|
+
* (ChromaDB narrows to top 10 → LLM picks from those 10).
|
|
3917
|
+
*/
|
|
3918
|
+
|
|
3919
|
+
declare class ScriptMatcher {
|
|
3920
|
+
private store;
|
|
3921
|
+
constructor(store: ScriptStore);
|
|
3922
|
+
/**
|
|
3923
|
+
* Find the best matching script for a user question.
|
|
3924
|
+
* Uses ONE LLM call that picks the script AND extracts parameters.
|
|
3925
|
+
* Returns null if no script matches.
|
|
3926
|
+
*/
|
|
3927
|
+
match(userPrompt: string, apiKey?: string, model?: string, signal?: AbortSignal,
|
|
3928
|
+
/**
|
|
3929
|
+
* Recent script-backed answers in this thread, newest first. Presence of at
|
|
3930
|
+
* least one is what makes the `edit` tier reachable at all (see the guards
|
|
3931
|
+
* below), and handing over SEVERAL is what lets an instruction name its own
|
|
3932
|
+
* target instead of always hitting the most recent script.
|
|
3933
|
+
*/
|
|
3934
|
+
activeBindings?: ScriptBinding[]): Promise<ScriptMatch | null>;
|
|
3935
|
+
/**
|
|
3936
|
+
* Build the script catalog string for the LLM prompt.
|
|
3937
|
+
* Each script gets: index, ID, name, description, and parameter definitions.
|
|
3938
|
+
*/
|
|
3939
|
+
private buildScriptCatalog;
|
|
3940
|
+
/**
|
|
3941
|
+
* The recent script-backed answers in this thread — the bounded set an edit
|
|
3942
|
+
* may target. Rendered as its own prompt section (never merged into the
|
|
3943
|
+
* ranked catalog) so the `edit` rules have an unambiguous referent set, and
|
|
3944
|
+
* numbered newest-first so the prompt's "prefer the most recent when the
|
|
3945
|
+
* instruction is ambiguous" tie-break has something to point at.
|
|
3946
|
+
*
|
|
3947
|
+
* Each entry carries the QUESTION that produced it plus the columns it
|
|
3948
|
+
* returned — that is what lets the matcher resolve "use the mode for the WSP
|
|
3949
|
+
* one" instead of blindly taking the newest.
|
|
3950
|
+
*/
|
|
3951
|
+
private buildActiveScriptBlock;
|
|
3952
|
+
}
|
|
3953
|
+
|
|
3954
|
+
/**
|
|
3955
|
+
* ScriptRunner — Execute scripts in an isolated tsx subprocess.
|
|
3956
|
+
*
|
|
3957
|
+
* The subprocess approach replaces the earlier `new Function()` eval and gives us:
|
|
3958
|
+
* - Real sandbox (separate process, SIGKILL on timeout).
|
|
3959
|
+
* - Real TypeScript (tsx transpiles on the fly).
|
|
3960
|
+
* - npm imports available to scripts (clustering, stats, geo, etc.).
|
|
3961
|
+
*
|
|
3962
|
+
* Protocol: NDJSON over the child's stdin/stdout. See script-ipc.ts + backend/docs/SCRIPT-FLOW-IMPLEMENTATION.md.
|
|
3963
|
+
*/
|
|
3964
|
+
|
|
3965
|
+
interface RunScriptOptions {
|
|
3966
|
+
/** Data sources the script is allowed to query via ctx.query */
|
|
3967
|
+
externalTools: ExternalTool[];
|
|
3968
|
+
/** Optional — for propagating per-query UI progress to the user */
|
|
3969
|
+
streamBuffer?: StreamBuffer;
|
|
3970
|
+
/** Override the wall-clock timeout (default `SCRIPT_TIMEOUT_MS`, 60s). */
|
|
3971
|
+
timeoutMs?: number;
|
|
3972
|
+
/**
|
|
3973
|
+
* Per-turn cancellation signal. When the user hits "Stop" mid-run, the child
|
|
3974
|
+
* process group is SIGKILLed and the run resolves as an aborted failure (the
|
|
3975
|
+
* caller is already unwinding, so the result is discarded).
|
|
3976
|
+
*/
|
|
3977
|
+
signal?: AbortSignal;
|
|
3978
|
+
}
|
|
3979
|
+
/**
|
|
3980
|
+
* Execute a recipe by spawning a tsx child on the script's .ts file.
|
|
3981
|
+
* `scriptPath` is the absolute path to the saved `.ts` body.
|
|
3982
|
+
*/
|
|
3983
|
+
declare function runScript(recipe: ScriptRecipe, scriptPath: string, params: Record<string, any>, options: RunScriptOptions): Promise<ScriptResult>;
|
|
3984
|
+
|
|
1627
3985
|
type MessageTypeHandler = (message: IncomingMessage) => void | Promise<void>;
|
|
1628
3986
|
declare class SuperatomSDK {
|
|
1629
3987
|
private ws;
|
|
1630
3988
|
private url;
|
|
1631
3989
|
private apiKey?;
|
|
1632
3990
|
private projectId;
|
|
1633
|
-
private userId;
|
|
1634
3991
|
private type;
|
|
1635
3992
|
private bundleDir;
|
|
1636
3993
|
private messageHandlers;
|
|
@@ -1641,15 +3998,27 @@ declare class SuperatomSDK {
|
|
|
1641
3998
|
private collections;
|
|
1642
3999
|
private components;
|
|
1643
4000
|
private tools;
|
|
4001
|
+
private workflows;
|
|
1644
4002
|
private anthropicApiKey;
|
|
1645
4003
|
private groqApiKey;
|
|
1646
4004
|
private geminiApiKey;
|
|
1647
4005
|
private openaiApiKey;
|
|
1648
4006
|
private llmProviders;
|
|
1649
4007
|
private databaseType;
|
|
4008
|
+
private modelStrategy;
|
|
4009
|
+
private mainAgentModel;
|
|
4010
|
+
private sourceAgentModel;
|
|
4011
|
+
private dashCompModels?;
|
|
4012
|
+
private conversationSimilarityThreshold;
|
|
1650
4013
|
private userManager;
|
|
1651
4014
|
private dashboardManager;
|
|
1652
4015
|
private reportManager;
|
|
4016
|
+
private pingInterval;
|
|
4017
|
+
private lastPong;
|
|
4018
|
+
private readonly PING_INTERVAL_MS;
|
|
4019
|
+
private readonly PONG_TIMEOUT_MS;
|
|
4020
|
+
private pendingOutbox;
|
|
4021
|
+
private readonly MAX_OUTBOX_SIZE;
|
|
1653
4022
|
constructor(config: SuperatomSDKConfig);
|
|
1654
4023
|
/**
|
|
1655
4024
|
* Initialize PromptLoader and load prompts into memory
|
|
@@ -1689,9 +4058,25 @@ declare class SuperatomSDK {
|
|
|
1689
4058
|
*/
|
|
1690
4059
|
private handleMessage;
|
|
1691
4060
|
/**
|
|
1692
|
-
* Send a message to the Superatom service
|
|
4061
|
+
* Send a message to the Superatom service.
|
|
4062
|
+
* Returns true if the message was sent, false if the WebSocket is not connected.
|
|
4063
|
+
* Does NOT throw on closed connections — callers can check the return value if needed.
|
|
4064
|
+
*/
|
|
4065
|
+
send(message: Message): boolean;
|
|
4066
|
+
/**
|
|
4067
|
+
* Queue a message that couldn't be delivered because the socket was down,
|
|
4068
|
+
* to be resent once it reconnects. Drops the oldest entry once the bound is
|
|
4069
|
+
* hit — an outage long enough to fill this queue means the oldest queued
|
|
4070
|
+
* responses are for requests the caller has likely already given up on.
|
|
4071
|
+
*/
|
|
4072
|
+
private queuePendingMessage;
|
|
4073
|
+
/**
|
|
4074
|
+
* Resend everything queued while the socket was down, now that it's back
|
|
4075
|
+
* up. Uses this.ws.send() directly (not send()) so a message that fails
|
|
4076
|
+
* again goes back through queuePendingMessage() rather than being silently
|
|
4077
|
+
* dropped a second time.
|
|
1693
4078
|
*/
|
|
1694
|
-
|
|
4079
|
+
private flushPendingOutbox;
|
|
1695
4080
|
/**
|
|
1696
4081
|
* Register a message handler to receive all messages
|
|
1697
4082
|
*/
|
|
@@ -1717,7 +4102,28 @@ declare class SuperatomSDK {
|
|
|
1717
4102
|
*/
|
|
1718
4103
|
addCollection<TParams = any, TResult = any>(collectionName: string, operation: CollectionOperation | string, handler: CollectionHandler<TParams, TResult>): void;
|
|
1719
4104
|
private handleReconnect;
|
|
4105
|
+
/**
|
|
4106
|
+
* Start heartbeat to keep WebSocket connection alive
|
|
4107
|
+
* Sends PING every 3 minutes to prevent idle timeout from cloud infrastructure
|
|
4108
|
+
*/
|
|
4109
|
+
private startHeartbeat;
|
|
4110
|
+
/**
|
|
4111
|
+
* Stop the heartbeat interval
|
|
4112
|
+
*/
|
|
4113
|
+
private stopHeartbeat;
|
|
4114
|
+
/**
|
|
4115
|
+
* Handle PONG response from server
|
|
4116
|
+
*/
|
|
4117
|
+
private handlePong;
|
|
1720
4118
|
private storeComponents;
|
|
4119
|
+
/**
|
|
4120
|
+
* The live, frontend-registered component catalog (name, type, description,
|
|
4121
|
+
* and full prop schema per component) — the same authoritative source
|
|
4122
|
+
* DASH_COMP_REQ's LLM prompt is built from. Exposed so other integrations
|
|
4123
|
+
* (e.g. the dashboard-agent script bridge) can read real component
|
|
4124
|
+
* contracts instead of maintaining a separate, driftable hand-written copy.
|
|
4125
|
+
*/
|
|
4126
|
+
getComponents(): Component[];
|
|
1721
4127
|
/**
|
|
1722
4128
|
* Set tools for the SDK instance
|
|
1723
4129
|
*/
|
|
@@ -1726,6 +4132,57 @@ declare class SuperatomSDK {
|
|
|
1726
4132
|
* Get the stored tools
|
|
1727
4133
|
*/
|
|
1728
4134
|
getTools(): Tool$1[];
|
|
4135
|
+
/**
|
|
4136
|
+
* Call a registered collection operation in-process — no WebSocket
|
|
4137
|
+
* round-trip, since the caller is already running inside this same SDK
|
|
4138
|
+
* instance. Lets SDK-internal features (e.g. the dashboard agent) reuse
|
|
4139
|
+
* whatever collection a deployment has already registered (e.g.
|
|
4140
|
+
* 'dashboards'.'query') by name/convention, instead of requiring a
|
|
4141
|
+
* separate callback purely to re-expose data a collection already serves.
|
|
4142
|
+
* Throws if the collection or operation isn't registered.
|
|
4143
|
+
*/
|
|
4144
|
+
callCollection<TResult = any>(collectionName: string, operation: string, params?: any): Promise<TResult>;
|
|
4145
|
+
/**
|
|
4146
|
+
* Register workflow components for the SDK instance.
|
|
4147
|
+
*
|
|
4148
|
+
* Workflows are pre-built multi-step UI flows the main agent can pick when
|
|
4149
|
+
* the user's prompt matches a workflow's `whenToUse` trigger. Picking a
|
|
4150
|
+
* workflow short-circuits analysis text + dashboard component generation —
|
|
4151
|
+
* the workflow component is returned directly, with the LLM-extracted props.
|
|
4152
|
+
*/
|
|
4153
|
+
setWorkflows(workflows: WorkflowDescriptor[]): void;
|
|
4154
|
+
/**
|
|
4155
|
+
* Get the registered workflow components.
|
|
4156
|
+
*/
|
|
4157
|
+
getWorkflows(): WorkflowDescriptor[];
|
|
4158
|
+
/**
|
|
4159
|
+
* Apply model strategy to all LLM provider singletons
|
|
4160
|
+
* @param strategy - 'best', 'fast', or 'balanced'
|
|
4161
|
+
*/
|
|
4162
|
+
private applyModelStrategy;
|
|
4163
|
+
/**
|
|
4164
|
+
* Set model strategy at runtime
|
|
4165
|
+
* @param strategy - 'best', 'fast', or 'balanced'
|
|
4166
|
+
*/
|
|
4167
|
+
setModelStrategy(strategy: ModelStrategy): void;
|
|
4168
|
+
/**
|
|
4169
|
+
* Get current model strategy
|
|
4170
|
+
*/
|
|
4171
|
+
getModelStrategy(): ModelStrategy;
|
|
4172
|
+
/**
|
|
4173
|
+
* Apply conversation similarity threshold to all LLM provider singletons
|
|
4174
|
+
* @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
|
|
4175
|
+
*/
|
|
4176
|
+
private applyConversationSimilarityThreshold;
|
|
4177
|
+
/**
|
|
4178
|
+
* Set conversation similarity threshold at runtime
|
|
4179
|
+
* @param threshold - Value between 0 and 1 (e.g., 0.8 = 80% similarity required)
|
|
4180
|
+
*/
|
|
4181
|
+
setConversationSimilarityThreshold(threshold: number): void;
|
|
4182
|
+
/**
|
|
4183
|
+
* Get current conversation similarity threshold
|
|
4184
|
+
*/
|
|
4185
|
+
getConversationSimilarityThreshold(): number;
|
|
1729
4186
|
}
|
|
1730
4187
|
|
|
1731
|
-
export { type Action, BM25L, type BM25LOptions, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LogLevel, type Message, type
|
|
4188
|
+
export { type Action, type AgentConfig, type AgentResponse, BM25L, type BM25LOptions, type BaseLLMConfig, CONTEXT_CONFIG, type CapturedLog, CleanupService, type CollectionHandler, type CollectionOperation, type DBUIBlock, DEFAULT_AGENT_CONFIG, type DashboardAgentCollectionConfig, type DatabaseType, type HybridSearchOptions, type IncomingMessage, type KbNodesQueryFilters, type KbNodesRequestPayload, LLM, type LLMUsageEntry, type LogLevel, MainAgent, type Message, type ModelStrategy, type OutputField, type RerankedResult, STORAGE_CONFIG, type ScriptComponentSpec, ScriptMatcher, type ScriptParameter, type ScriptRecipe, type ScriptRecipeMetaRow, type ScriptRecipeStore, type ScriptResult, ScriptStore, type ScriptStoreOptions, type SelectedWorkflow, SuperatomSDK, type SuperatomSDKConfig, type TaskType, Thread, ThreadManager, type Tool$1 as Tool, type ToolOutputSchema, UIBlock, UILogCollector, type User, UserManager, type UsersData, type WorkflowDescriptor, anthropicLLM, dashboardConversationHistory, geminiLLM, groqLLM, hybridRerank, llmUsageLogger, logger, normalizeScriptBody, openaiLLM, queryCache, registerDashboardAgentCollection, rerankChromaResults, rerankConversationResults, resolveScriptRecipeStore, runScript, userPromptErrorLogger };
|