@deepagents/text2sql 0.11.0 → 0.12.1
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.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1334 -491
- package/dist/index.js.map +4 -4
- package/dist/lib/adapters/groundings/index.js +2034 -50
- package/dist/lib/adapters/groundings/index.js.map +4 -4
- package/dist/lib/adapters/groundings/report.grounding.d.ts.map +1 -1
- package/dist/lib/adapters/mysql/index.js +2034 -50
- package/dist/lib/adapters/mysql/index.js.map +4 -4
- package/dist/lib/adapters/postgres/index.js +2034 -50
- package/dist/lib/adapters/postgres/index.js.map +4 -4
- package/dist/lib/adapters/spreadsheet/index.js +35 -49
- package/dist/lib/adapters/spreadsheet/index.js.map +4 -4
- package/dist/lib/adapters/sqlite/index.js +2034 -50
- package/dist/lib/adapters/sqlite/index.js.map +4 -4
- package/dist/lib/adapters/sqlserver/column-stats.sqlserver.grounding.d.ts.map +1 -1
- package/dist/lib/adapters/sqlserver/index.js +2035 -53
- package/dist/lib/adapters/sqlserver/index.js.map +4 -4
- package/dist/lib/agents/developer.agent.d.ts.map +1 -1
- package/dist/lib/agents/explainer.agent.d.ts +4 -5
- package/dist/lib/agents/explainer.agent.d.ts.map +1 -1
- package/dist/lib/agents/question.agent.d.ts.map +1 -1
- package/dist/lib/agents/result-tools.d.ts +37 -0
- package/dist/lib/agents/result-tools.d.ts.map +1 -0
- package/dist/lib/agents/sql.agent.d.ts +1 -1
- package/dist/lib/agents/sql.agent.d.ts.map +1 -1
- package/dist/lib/agents/teachables.agent.d.ts.map +1 -1
- package/dist/lib/agents/text2sql.agent.d.ts +0 -21
- package/dist/lib/agents/text2sql.agent.d.ts.map +1 -1
- package/dist/lib/checkpoint.d.ts +1 -1
- package/dist/lib/checkpoint.d.ts.map +1 -1
- package/dist/lib/instructions.d.ts +9 -28
- package/dist/lib/instructions.d.ts.map +1 -1
- package/dist/lib/sql.d.ts +1 -1
- package/dist/lib/sql.d.ts.map +1 -1
- package/dist/lib/synthesis/extractors/base-contextual-extractor.d.ts +6 -7
- package/dist/lib/synthesis/extractors/base-contextual-extractor.d.ts.map +1 -1
- package/dist/lib/synthesis/extractors/last-query-extractor.d.ts.map +1 -1
- package/dist/lib/synthesis/extractors/segmented-context-extractor.d.ts +0 -6
- package/dist/lib/synthesis/extractors/segmented-context-extractor.d.ts.map +1 -1
- package/dist/lib/synthesis/extractors/sql-extractor.d.ts.map +1 -1
- package/dist/lib/synthesis/index.js +2394 -2132
- package/dist/lib/synthesis/index.js.map +4 -4
- package/dist/lib/synthesis/synthesizers/breadth-evolver.d.ts.map +1 -1
- package/dist/lib/synthesis/synthesizers/depth-evolver.d.ts +3 -3
- package/dist/lib/synthesis/synthesizers/depth-evolver.d.ts.map +1 -1
- package/dist/lib/synthesis/synthesizers/persona-generator.d.ts.map +1 -1
- package/dist/lib/synthesis/synthesizers/schema-synthesizer.d.ts +1 -1
- package/dist/lib/synthesis/synthesizers/schema-synthesizer.d.ts.map +1 -1
- package/package.json +9 -15
- package/dist/lib/instructions.js +0 -432
- package/dist/lib/instructions.js.map +0 -7
- package/dist/lib/teach/teachings.d.ts +0 -11
- package/dist/lib/teach/teachings.d.ts.map +0 -1
|
@@ -219,57 +219,1995 @@ var InfoGrounding = class extends AbstractGrounding {
|
|
|
219
219
|
};
|
|
220
220
|
|
|
221
221
|
// packages/text2sql/src/lib/adapters/groundings/report.grounding.ts
|
|
222
|
-
import { groq } from "@ai-sdk/groq";
|
|
222
|
+
import { groq as groq2 } from "@ai-sdk/groq";
|
|
223
223
|
import { tool } from "ai";
|
|
224
224
|
import dedent from "dedent";
|
|
225
225
|
import z from "zod";
|
|
226
|
+
import "@deepagents/agent";
|
|
227
|
+
|
|
228
|
+
// packages/context/dist/index.js
|
|
229
|
+
import { encode } from "gpt-tokenizer";
|
|
230
|
+
import { generateId } from "ai";
|
|
231
|
+
import pluralize from "pluralize";
|
|
232
|
+
import { titlecase } from "stringcase";
|
|
233
|
+
import chalk from "chalk";
|
|
234
|
+
import { defineCommand } from "just-bash";
|
|
235
|
+
import spawn from "nano-spawn";
|
|
236
|
+
import "bash-tool";
|
|
237
|
+
import spawn2 from "nano-spawn";
|
|
238
|
+
import {
|
|
239
|
+
createBashTool
|
|
240
|
+
} from "bash-tool";
|
|
241
|
+
import YAML from "yaml";
|
|
242
|
+
import { DatabaseSync } from "node:sqlite";
|
|
243
|
+
import { groq } from "@ai-sdk/groq";
|
|
226
244
|
import {
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
245
|
+
NoSuchToolError,
|
|
246
|
+
Output,
|
|
247
|
+
convertToModelMessages,
|
|
248
|
+
createUIMessageStream,
|
|
249
|
+
generateId as generateId2,
|
|
250
|
+
generateText,
|
|
251
|
+
smoothStream,
|
|
252
|
+
stepCountIs,
|
|
253
|
+
streamText
|
|
254
|
+
} from "ai";
|
|
255
|
+
import chalk2 from "chalk";
|
|
256
|
+
import "zod";
|
|
257
|
+
import "@deepagents/agent";
|
|
258
|
+
var defaultTokenizer = {
|
|
259
|
+
encode(text) {
|
|
260
|
+
return encode(text);
|
|
261
|
+
},
|
|
262
|
+
count(text) {
|
|
263
|
+
return encode(text).length;
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
var ModelsRegistry = class {
|
|
267
|
+
#cache = /* @__PURE__ */ new Map();
|
|
268
|
+
#loaded = false;
|
|
269
|
+
#tokenizers = /* @__PURE__ */ new Map();
|
|
270
|
+
#defaultTokenizer = defaultTokenizer;
|
|
271
|
+
/**
|
|
272
|
+
* Load models data from models.dev API
|
|
273
|
+
*/
|
|
274
|
+
async load() {
|
|
275
|
+
if (this.#loaded) return;
|
|
276
|
+
const response = await fetch("https://models.dev/api.json");
|
|
277
|
+
if (!response.ok) {
|
|
278
|
+
throw new Error(`Failed to fetch models: ${response.statusText}`);
|
|
279
|
+
}
|
|
280
|
+
const data = await response.json();
|
|
281
|
+
for (const [providerId, provider] of Object.entries(data)) {
|
|
282
|
+
for (const [modelId, model] of Object.entries(provider.models)) {
|
|
283
|
+
const info = {
|
|
284
|
+
id: model.id,
|
|
285
|
+
name: model.name,
|
|
286
|
+
family: model.family,
|
|
287
|
+
cost: model.cost,
|
|
288
|
+
limit: model.limit,
|
|
289
|
+
provider: providerId
|
|
290
|
+
};
|
|
291
|
+
this.#cache.set(`${providerId}:${modelId}`, info);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
this.#loaded = true;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Get model info by ID
|
|
298
|
+
* @param modelId - Model ID (e.g., "openai:gpt-4o")
|
|
299
|
+
*/
|
|
300
|
+
get(modelId) {
|
|
301
|
+
return this.#cache.get(modelId);
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Check if a model exists in the registry
|
|
305
|
+
*/
|
|
306
|
+
has(modelId) {
|
|
307
|
+
return this.#cache.has(modelId);
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* List all available model IDs
|
|
311
|
+
*/
|
|
312
|
+
list() {
|
|
313
|
+
return [...this.#cache.keys()];
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Register a custom tokenizer for specific model families
|
|
317
|
+
* @param family - Model family name (e.g., "llama", "claude")
|
|
318
|
+
* @param tokenizer - Tokenizer implementation
|
|
319
|
+
*/
|
|
320
|
+
registerTokenizer(family, tokenizer) {
|
|
321
|
+
this.#tokenizers.set(family, tokenizer);
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Set the default tokenizer used when no family-specific tokenizer is registered
|
|
325
|
+
*/
|
|
326
|
+
setDefaultTokenizer(tokenizer) {
|
|
327
|
+
this.#defaultTokenizer = tokenizer;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Get the appropriate tokenizer for a model
|
|
331
|
+
*/
|
|
332
|
+
getTokenizer(modelId) {
|
|
333
|
+
const model = this.get(modelId);
|
|
334
|
+
if (model) {
|
|
335
|
+
const familyTokenizer = this.#tokenizers.get(model.family);
|
|
336
|
+
if (familyTokenizer) {
|
|
337
|
+
return familyTokenizer;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return this.#defaultTokenizer;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Estimate token count and cost for given text and model
|
|
344
|
+
* @param modelId - Model ID to use for pricing (e.g., "openai:gpt-4o")
|
|
345
|
+
* @param input - Input text (prompt)
|
|
346
|
+
*/
|
|
347
|
+
estimate(modelId, input) {
|
|
348
|
+
const model = this.get(modelId);
|
|
349
|
+
if (!model) {
|
|
350
|
+
throw new Error(
|
|
351
|
+
`Model "${modelId}" not found. Call load() first or check model ID.`
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
const tokenizer = this.getTokenizer(modelId);
|
|
355
|
+
const tokens = tokenizer.count(input);
|
|
356
|
+
const cost = tokens / 1e6 * model.cost.input;
|
|
357
|
+
return {
|
|
358
|
+
model: model.id,
|
|
359
|
+
provider: model.provider,
|
|
360
|
+
tokens,
|
|
361
|
+
cost,
|
|
362
|
+
limits: {
|
|
363
|
+
context: model.limit.context,
|
|
364
|
+
output: model.limit.output,
|
|
365
|
+
exceedsContext: tokens > model.limit.context
|
|
366
|
+
},
|
|
367
|
+
fragments: []
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
var _registry = null;
|
|
372
|
+
function getModelsRegistry() {
|
|
373
|
+
if (!_registry) {
|
|
374
|
+
_registry = new ModelsRegistry();
|
|
375
|
+
}
|
|
376
|
+
return _registry;
|
|
377
|
+
}
|
|
378
|
+
function isFragment(data) {
|
|
379
|
+
return typeof data === "object" && data !== null && "name" in data && "data" in data && typeof data.name === "string";
|
|
380
|
+
}
|
|
381
|
+
function isFragmentObject(data) {
|
|
382
|
+
return typeof data === "object" && data !== null && !Array.isArray(data) && !isFragment(data);
|
|
383
|
+
}
|
|
384
|
+
function isMessageFragment(fragment2) {
|
|
385
|
+
return fragment2.type === "message";
|
|
386
|
+
}
|
|
387
|
+
function fragment(name, ...children) {
|
|
388
|
+
return {
|
|
389
|
+
name,
|
|
390
|
+
data: children
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
function user(content) {
|
|
394
|
+
const message2 = typeof content === "string" ? {
|
|
395
|
+
id: generateId(),
|
|
396
|
+
role: "user",
|
|
397
|
+
parts: [{ type: "text", text: content }]
|
|
398
|
+
} : content;
|
|
399
|
+
return {
|
|
400
|
+
id: message2.id,
|
|
401
|
+
name: "user",
|
|
402
|
+
data: "content",
|
|
403
|
+
type: "message",
|
|
404
|
+
persist: true,
|
|
405
|
+
codec: {
|
|
406
|
+
decode() {
|
|
407
|
+
return message2;
|
|
408
|
+
},
|
|
409
|
+
encode() {
|
|
410
|
+
return message2;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
function assistant(message2) {
|
|
416
|
+
return {
|
|
417
|
+
id: message2.id,
|
|
418
|
+
name: "assistant",
|
|
419
|
+
data: "content",
|
|
420
|
+
type: "message",
|
|
421
|
+
persist: true,
|
|
422
|
+
codec: {
|
|
423
|
+
decode() {
|
|
424
|
+
return message2;
|
|
425
|
+
},
|
|
426
|
+
encode() {
|
|
427
|
+
return message2;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
function message(content) {
|
|
433
|
+
const message2 = typeof content === "string" ? {
|
|
434
|
+
id: generateId(),
|
|
435
|
+
role: "user",
|
|
436
|
+
parts: [{ type: "text", text: content }]
|
|
437
|
+
} : content;
|
|
438
|
+
return {
|
|
439
|
+
id: message2.id,
|
|
440
|
+
name: message2.role,
|
|
441
|
+
data: "content",
|
|
442
|
+
type: "message",
|
|
443
|
+
persist: true,
|
|
444
|
+
codec: {
|
|
445
|
+
decode() {
|
|
446
|
+
return message2;
|
|
447
|
+
},
|
|
448
|
+
encode() {
|
|
449
|
+
return message2;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
function assistantText(content, options) {
|
|
455
|
+
const id = options?.id ?? crypto.randomUUID();
|
|
456
|
+
return assistant({
|
|
457
|
+
id,
|
|
458
|
+
role: "assistant",
|
|
459
|
+
parts: [{ type: "text", text: content }]
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
var LAZY_ID = Symbol("lazy-id");
|
|
463
|
+
function isLazyFragment(fragment2) {
|
|
464
|
+
return LAZY_ID in fragment2;
|
|
465
|
+
}
|
|
466
|
+
function lastAssistantMessage(content) {
|
|
467
|
+
return {
|
|
468
|
+
name: "assistant",
|
|
469
|
+
type: "message",
|
|
470
|
+
persist: true,
|
|
471
|
+
data: "content",
|
|
472
|
+
[LAZY_ID]: {
|
|
473
|
+
type: "last-assistant",
|
|
474
|
+
content
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
var ContextRenderer = class {
|
|
479
|
+
options;
|
|
480
|
+
constructor(options = {}) {
|
|
481
|
+
this.options = options;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Check if data is a primitive (string, number, boolean).
|
|
485
|
+
*/
|
|
486
|
+
isPrimitive(data) {
|
|
487
|
+
return typeof data === "string" || typeof data === "number" || typeof data === "boolean";
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Group fragments by name for groupFragments option.
|
|
491
|
+
*/
|
|
492
|
+
groupByName(fragments) {
|
|
493
|
+
const groups = /* @__PURE__ */ new Map();
|
|
494
|
+
for (const fragment2 of fragments) {
|
|
495
|
+
const existing = groups.get(fragment2.name) ?? [];
|
|
496
|
+
existing.push(fragment2);
|
|
497
|
+
groups.set(fragment2.name, existing);
|
|
498
|
+
}
|
|
499
|
+
return groups;
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Remove null/undefined from fragments and fragment data recursively.
|
|
503
|
+
* This protects renderers from nullish values and ensures they are ignored
|
|
504
|
+
* consistently across all output formats.
|
|
505
|
+
*/
|
|
506
|
+
sanitizeFragments(fragments) {
|
|
507
|
+
const sanitized = [];
|
|
508
|
+
for (const fragment2 of fragments) {
|
|
509
|
+
const cleaned = this.sanitizeFragment(fragment2, /* @__PURE__ */ new WeakSet());
|
|
510
|
+
if (cleaned) {
|
|
511
|
+
sanitized.push(cleaned);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
return sanitized;
|
|
515
|
+
}
|
|
516
|
+
sanitizeFragment(fragment2, seen) {
|
|
517
|
+
const data = this.sanitizeData(fragment2.data, seen);
|
|
518
|
+
if (data == null) {
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
521
|
+
return {
|
|
522
|
+
...fragment2,
|
|
523
|
+
data
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
sanitizeData(data, seen) {
|
|
527
|
+
if (data == null) {
|
|
528
|
+
return void 0;
|
|
529
|
+
}
|
|
530
|
+
if (isFragment(data)) {
|
|
531
|
+
return this.sanitizeFragment(data, seen) ?? void 0;
|
|
532
|
+
}
|
|
533
|
+
if (Array.isArray(data)) {
|
|
534
|
+
if (seen.has(data)) {
|
|
535
|
+
return void 0;
|
|
536
|
+
}
|
|
537
|
+
seen.add(data);
|
|
538
|
+
const cleaned = [];
|
|
539
|
+
for (const item of data) {
|
|
540
|
+
const sanitizedItem = this.sanitizeData(item, seen);
|
|
541
|
+
if (sanitizedItem != null) {
|
|
542
|
+
cleaned.push(sanitizedItem);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
return cleaned;
|
|
546
|
+
}
|
|
547
|
+
if (isFragmentObject(data)) {
|
|
548
|
+
if (seen.has(data)) {
|
|
549
|
+
return void 0;
|
|
550
|
+
}
|
|
551
|
+
seen.add(data);
|
|
552
|
+
const cleaned = {};
|
|
553
|
+
for (const [key, value] of Object.entries(data)) {
|
|
554
|
+
const sanitizedValue = this.sanitizeData(value, seen);
|
|
555
|
+
if (sanitizedValue != null) {
|
|
556
|
+
cleaned[key] = sanitizedValue;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
return cleaned;
|
|
560
|
+
}
|
|
561
|
+
return data;
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Template method - dispatches value to appropriate handler.
|
|
565
|
+
*/
|
|
566
|
+
renderValue(key, value, ctx) {
|
|
567
|
+
if (value == null) {
|
|
568
|
+
return "";
|
|
569
|
+
}
|
|
570
|
+
if (isFragment(value)) {
|
|
571
|
+
return this.renderFragment(value, ctx);
|
|
572
|
+
}
|
|
573
|
+
if (Array.isArray(value)) {
|
|
574
|
+
return this.renderArray(key, value, ctx);
|
|
575
|
+
}
|
|
576
|
+
if (isFragmentObject(value)) {
|
|
577
|
+
return this.renderObject(key, value, ctx);
|
|
578
|
+
}
|
|
579
|
+
return this.renderPrimitive(key, String(value), ctx);
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Render all entries of an object.
|
|
583
|
+
*/
|
|
584
|
+
renderEntries(data, ctx) {
|
|
585
|
+
return Object.entries(data).map(([key, value]) => this.renderValue(key, value, ctx)).filter(Boolean);
|
|
586
|
+
}
|
|
587
|
+
};
|
|
588
|
+
var XmlRenderer = class extends ContextRenderer {
|
|
589
|
+
render(fragments) {
|
|
590
|
+
const sanitized = this.sanitizeFragments(fragments);
|
|
591
|
+
return sanitized.map((f) => this.#renderTopLevel(f)).filter(Boolean).join("\n");
|
|
592
|
+
}
|
|
593
|
+
#renderTopLevel(fragment2) {
|
|
594
|
+
if (this.isPrimitive(fragment2.data)) {
|
|
595
|
+
return this.#leafRoot(fragment2.name, String(fragment2.data));
|
|
596
|
+
}
|
|
597
|
+
if (Array.isArray(fragment2.data)) {
|
|
598
|
+
return this.#renderArray(fragment2.name, fragment2.data, 0);
|
|
599
|
+
}
|
|
600
|
+
if (isFragment(fragment2.data)) {
|
|
601
|
+
const child = this.renderFragment(fragment2.data, { depth: 1, path: [] });
|
|
602
|
+
return this.#wrap(fragment2.name, [child]);
|
|
603
|
+
}
|
|
604
|
+
if (isFragmentObject(fragment2.data)) {
|
|
605
|
+
return this.#wrap(
|
|
606
|
+
fragment2.name,
|
|
607
|
+
this.renderEntries(fragment2.data, { depth: 1, path: [] })
|
|
608
|
+
);
|
|
609
|
+
}
|
|
610
|
+
return "";
|
|
611
|
+
}
|
|
612
|
+
#renderArray(name, items, depth) {
|
|
613
|
+
const fragmentItems = items.filter(isFragment);
|
|
614
|
+
const nonFragmentItems = items.filter((item) => !isFragment(item));
|
|
615
|
+
const children = [];
|
|
616
|
+
for (const item of nonFragmentItems) {
|
|
617
|
+
if (item != null) {
|
|
618
|
+
if (isFragmentObject(item)) {
|
|
619
|
+
children.push(
|
|
620
|
+
this.#wrapIndented(
|
|
621
|
+
pluralize.singular(name),
|
|
622
|
+
this.renderEntries(item, { depth: depth + 2, path: [] }),
|
|
623
|
+
depth + 1
|
|
624
|
+
)
|
|
625
|
+
);
|
|
626
|
+
} else {
|
|
627
|
+
children.push(
|
|
628
|
+
this.#leaf(pluralize.singular(name), String(item), depth + 1)
|
|
629
|
+
);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
if (this.options.groupFragments && fragmentItems.length > 0) {
|
|
634
|
+
const groups = this.groupByName(fragmentItems);
|
|
635
|
+
for (const [groupName, groupFragments] of groups) {
|
|
636
|
+
const groupChildren = groupFragments.map(
|
|
637
|
+
(frag) => this.renderFragment(frag, { depth: depth + 2, path: [] })
|
|
638
|
+
);
|
|
639
|
+
const pluralName = pluralize.plural(groupName);
|
|
640
|
+
children.push(this.#wrapIndented(pluralName, groupChildren, depth + 1));
|
|
641
|
+
}
|
|
642
|
+
} else {
|
|
643
|
+
for (const frag of fragmentItems) {
|
|
644
|
+
children.push(
|
|
645
|
+
this.renderFragment(frag, { depth: depth + 1, path: [] })
|
|
646
|
+
);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
return this.#wrap(name, children);
|
|
650
|
+
}
|
|
651
|
+
#leafRoot(tag, value) {
|
|
652
|
+
const safe = this.#escape(value);
|
|
653
|
+
if (safe.includes("\n")) {
|
|
654
|
+
return `<${tag}>
|
|
655
|
+
${this.#indent(safe, 2)}
|
|
656
|
+
</${tag}>`;
|
|
657
|
+
}
|
|
658
|
+
return `<${tag}>${safe}</${tag}>`;
|
|
659
|
+
}
|
|
660
|
+
renderFragment(fragment2, ctx) {
|
|
661
|
+
const { name, data } = fragment2;
|
|
662
|
+
if (this.isPrimitive(data)) {
|
|
663
|
+
return this.#leaf(name, String(data), ctx.depth);
|
|
664
|
+
}
|
|
665
|
+
if (isFragment(data)) {
|
|
666
|
+
const child = this.renderFragment(data, { ...ctx, depth: ctx.depth + 1 });
|
|
667
|
+
return this.#wrapIndented(name, [child], ctx.depth);
|
|
668
|
+
}
|
|
669
|
+
if (Array.isArray(data)) {
|
|
670
|
+
return this.#renderArrayIndented(name, data, ctx.depth);
|
|
671
|
+
}
|
|
672
|
+
if (isFragmentObject(data)) {
|
|
673
|
+
const children = this.renderEntries(data, {
|
|
674
|
+
...ctx,
|
|
675
|
+
depth: ctx.depth + 1
|
|
676
|
+
});
|
|
677
|
+
return this.#wrapIndented(name, children, ctx.depth);
|
|
678
|
+
}
|
|
679
|
+
return "";
|
|
680
|
+
}
|
|
681
|
+
#renderArrayIndented(name, items, depth) {
|
|
682
|
+
const fragmentItems = items.filter(isFragment);
|
|
683
|
+
const nonFragmentItems = items.filter((item) => !isFragment(item));
|
|
684
|
+
const children = [];
|
|
685
|
+
for (const item of nonFragmentItems) {
|
|
686
|
+
if (item != null) {
|
|
687
|
+
if (isFragmentObject(item)) {
|
|
688
|
+
children.push(
|
|
689
|
+
this.#wrapIndented(
|
|
690
|
+
pluralize.singular(name),
|
|
691
|
+
this.renderEntries(item, { depth: depth + 2, path: [] }),
|
|
692
|
+
depth + 1
|
|
693
|
+
)
|
|
694
|
+
);
|
|
695
|
+
} else {
|
|
696
|
+
children.push(
|
|
697
|
+
this.#leaf(pluralize.singular(name), String(item), depth + 1)
|
|
698
|
+
);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
if (this.options.groupFragments && fragmentItems.length > 0) {
|
|
703
|
+
const groups = this.groupByName(fragmentItems);
|
|
704
|
+
for (const [groupName, groupFragments] of groups) {
|
|
705
|
+
const groupChildren = groupFragments.map(
|
|
706
|
+
(frag) => this.renderFragment(frag, { depth: depth + 2, path: [] })
|
|
707
|
+
);
|
|
708
|
+
const pluralName = pluralize.plural(groupName);
|
|
709
|
+
children.push(this.#wrapIndented(pluralName, groupChildren, depth + 1));
|
|
710
|
+
}
|
|
711
|
+
} else {
|
|
712
|
+
for (const frag of fragmentItems) {
|
|
713
|
+
children.push(
|
|
714
|
+
this.renderFragment(frag, { depth: depth + 1, path: [] })
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
return this.#wrapIndented(name, children, depth);
|
|
719
|
+
}
|
|
720
|
+
renderPrimitive(key, value, ctx) {
|
|
721
|
+
return this.#leaf(key, value, ctx.depth);
|
|
722
|
+
}
|
|
723
|
+
renderArray(key, items, ctx) {
|
|
724
|
+
if (!items.length) {
|
|
725
|
+
return "";
|
|
726
|
+
}
|
|
727
|
+
const itemTag = pluralize.singular(key);
|
|
728
|
+
const children = items.filter((item) => item != null).map((item) => {
|
|
729
|
+
if (isFragment(item)) {
|
|
730
|
+
return this.renderFragment(item, { ...ctx, depth: ctx.depth + 1 });
|
|
731
|
+
}
|
|
732
|
+
if (isFragmentObject(item)) {
|
|
733
|
+
return this.#wrapIndented(
|
|
734
|
+
itemTag,
|
|
735
|
+
this.renderEntries(item, { ...ctx, depth: ctx.depth + 2 }),
|
|
736
|
+
ctx.depth + 1
|
|
737
|
+
);
|
|
738
|
+
}
|
|
739
|
+
return this.#leaf(itemTag, String(item), ctx.depth + 1);
|
|
740
|
+
});
|
|
741
|
+
return this.#wrapIndented(key, children, ctx.depth);
|
|
742
|
+
}
|
|
743
|
+
renderObject(key, obj, ctx) {
|
|
744
|
+
const children = this.renderEntries(obj, { ...ctx, depth: ctx.depth + 1 });
|
|
745
|
+
return this.#wrapIndented(key, children, ctx.depth);
|
|
746
|
+
}
|
|
747
|
+
#escape(value) {
|
|
748
|
+
if (value == null) {
|
|
749
|
+
return "";
|
|
750
|
+
}
|
|
751
|
+
return value.replaceAll(/&/g, "&").replaceAll(/</g, "<").replaceAll(/>/g, ">").replaceAll(/"/g, """).replaceAll(/'/g, "'");
|
|
752
|
+
}
|
|
753
|
+
#indent(text, spaces) {
|
|
754
|
+
if (!text.trim()) {
|
|
755
|
+
return "";
|
|
756
|
+
}
|
|
757
|
+
const padding = " ".repeat(spaces);
|
|
758
|
+
return text.split("\n").map((line) => line.length ? padding + line : padding).join("\n");
|
|
759
|
+
}
|
|
760
|
+
#leaf(tag, value, depth) {
|
|
761
|
+
const safe = this.#escape(value);
|
|
762
|
+
const pad = " ".repeat(depth);
|
|
763
|
+
if (safe.includes("\n")) {
|
|
764
|
+
return `${pad}<${tag}>
|
|
765
|
+
${this.#indent(safe, (depth + 1) * 2)}
|
|
766
|
+
${pad}</${tag}>`;
|
|
767
|
+
}
|
|
768
|
+
return `${pad}<${tag}>${safe}</${tag}>`;
|
|
769
|
+
}
|
|
770
|
+
#wrap(tag, children) {
|
|
771
|
+
const content = children.filter(Boolean).join("\n");
|
|
772
|
+
if (!content) {
|
|
773
|
+
return "";
|
|
774
|
+
}
|
|
775
|
+
return `<${tag}>
|
|
776
|
+
${content}
|
|
777
|
+
</${tag}>`;
|
|
778
|
+
}
|
|
779
|
+
#wrapIndented(tag, children, depth) {
|
|
780
|
+
const content = children.filter(Boolean).join("\n");
|
|
781
|
+
if (!content) {
|
|
782
|
+
return "";
|
|
783
|
+
}
|
|
784
|
+
const pad = " ".repeat(depth);
|
|
785
|
+
return `${pad}<${tag}>
|
|
786
|
+
${content}
|
|
787
|
+
${pad}</${tag}>`;
|
|
788
|
+
}
|
|
789
|
+
};
|
|
790
|
+
var ContextStore = class {
|
|
791
|
+
};
|
|
792
|
+
var ContextEngine = class {
|
|
793
|
+
/** Non-message fragments (role, hints, etc.) - not persisted in graph */
|
|
794
|
+
#fragments = [];
|
|
795
|
+
/** Pending message fragments to be added to graph */
|
|
796
|
+
#pendingMessages = [];
|
|
797
|
+
#store;
|
|
798
|
+
#chatId;
|
|
799
|
+
#userId;
|
|
800
|
+
#branchName;
|
|
801
|
+
#branch = null;
|
|
802
|
+
#chatData = null;
|
|
803
|
+
#initialized = false;
|
|
804
|
+
constructor(options) {
|
|
805
|
+
if (!options.chatId) {
|
|
806
|
+
throw new Error("chatId is required");
|
|
807
|
+
}
|
|
808
|
+
if (!options.userId) {
|
|
809
|
+
throw new Error("userId is required");
|
|
810
|
+
}
|
|
811
|
+
this.#store = options.store;
|
|
812
|
+
this.#chatId = options.chatId;
|
|
813
|
+
this.#userId = options.userId;
|
|
814
|
+
this.#branchName = "main";
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Initialize the chat and branch if they don't exist.
|
|
818
|
+
*/
|
|
819
|
+
async #ensureInitialized() {
|
|
820
|
+
if (this.#initialized) {
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
this.#chatData = await this.#store.upsertChat({
|
|
824
|
+
id: this.#chatId,
|
|
825
|
+
userId: this.#userId
|
|
826
|
+
});
|
|
827
|
+
this.#branch = await this.#store.getActiveBranch(this.#chatId);
|
|
828
|
+
this.#initialized = true;
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Create a new branch from a specific message.
|
|
832
|
+
* Shared logic between rewind() and btw().
|
|
833
|
+
*/
|
|
834
|
+
async #createBranchFrom(messageId, switchTo) {
|
|
835
|
+
const branches = await this.#store.listBranches(this.#chatId);
|
|
836
|
+
const samePrefix = branches.filter(
|
|
837
|
+
(b) => b.name === this.#branchName || b.name.startsWith(`${this.#branchName}-v`)
|
|
838
|
+
);
|
|
839
|
+
const newBranchName = `${this.#branchName}-v${samePrefix.length + 1}`;
|
|
840
|
+
const newBranch = {
|
|
841
|
+
id: crypto.randomUUID(),
|
|
842
|
+
chatId: this.#chatId,
|
|
843
|
+
name: newBranchName,
|
|
844
|
+
headMessageId: messageId,
|
|
845
|
+
isActive: false,
|
|
846
|
+
createdAt: Date.now()
|
|
847
|
+
};
|
|
848
|
+
await this.#store.createBranch(newBranch);
|
|
849
|
+
if (switchTo) {
|
|
850
|
+
await this.#store.setActiveBranch(this.#chatId, newBranch.id);
|
|
851
|
+
this.#branch = { ...newBranch, isActive: true };
|
|
852
|
+
this.#branchName = newBranchName;
|
|
853
|
+
this.#pendingMessages = [];
|
|
854
|
+
}
|
|
855
|
+
const chain = await this.#store.getMessageChain(messageId);
|
|
856
|
+
return {
|
|
857
|
+
id: newBranch.id,
|
|
858
|
+
name: newBranch.name,
|
|
859
|
+
headMessageId: newBranch.headMessageId,
|
|
860
|
+
isActive: switchTo,
|
|
861
|
+
messageCount: chain.length,
|
|
862
|
+
createdAt: newBranch.createdAt
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
/**
|
|
866
|
+
* Get the current chat ID.
|
|
867
|
+
*/
|
|
868
|
+
get chatId() {
|
|
869
|
+
return this.#chatId;
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Get the current branch name.
|
|
873
|
+
*/
|
|
874
|
+
get branch() {
|
|
875
|
+
return this.#branchName;
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* Get metadata for the current chat.
|
|
879
|
+
* Returns null if the chat hasn't been initialized yet.
|
|
880
|
+
*/
|
|
881
|
+
get chat() {
|
|
882
|
+
if (!this.#chatData) {
|
|
883
|
+
return null;
|
|
884
|
+
}
|
|
885
|
+
return {
|
|
886
|
+
id: this.#chatData.id,
|
|
887
|
+
userId: this.#chatData.userId,
|
|
888
|
+
createdAt: this.#chatData.createdAt,
|
|
889
|
+
updatedAt: this.#chatData.updatedAt,
|
|
890
|
+
title: this.#chatData.title,
|
|
891
|
+
metadata: this.#chatData.metadata
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* Add fragments to the context.
|
|
896
|
+
*
|
|
897
|
+
* - Message fragments (user/assistant) are queued for persistence
|
|
898
|
+
* - Non-message fragments (role/hint) are kept in memory for system prompt
|
|
899
|
+
*/
|
|
900
|
+
set(...fragments) {
|
|
901
|
+
for (const fragment2 of fragments) {
|
|
902
|
+
if (isMessageFragment(fragment2)) {
|
|
903
|
+
this.#pendingMessages.push(fragment2);
|
|
904
|
+
} else {
|
|
905
|
+
this.#fragments.push(fragment2);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
return this;
|
|
909
|
+
}
|
|
910
|
+
// Unset a fragment by ID (not implemented yet)
|
|
911
|
+
unset(fragmentId) {
|
|
912
|
+
}
|
|
913
|
+
/**
|
|
914
|
+
* Render all fragments using the provided renderer.
|
|
915
|
+
* @internal Use resolve() instead for public API.
|
|
916
|
+
*/
|
|
917
|
+
render(renderer) {
|
|
918
|
+
return renderer.render(this.#fragments);
|
|
919
|
+
}
|
|
920
|
+
/**
|
|
921
|
+
* Resolve context into AI SDK-ready format.
|
|
922
|
+
*
|
|
923
|
+
* - Initializes chat and branch if needed
|
|
924
|
+
* - Loads message history from the graph (walking parent chain)
|
|
925
|
+
* - Separates context fragments for system prompt
|
|
926
|
+
* - Combines with pending messages
|
|
927
|
+
*
|
|
928
|
+
* @example
|
|
929
|
+
* ```ts
|
|
930
|
+
* const context = new ContextEngine({ store, chatId: 'chat-1', userId: 'user-1' })
|
|
931
|
+
* .set(role('You are helpful'), user('Hello'));
|
|
932
|
+
*
|
|
933
|
+
* const { systemPrompt, messages } = await context.resolve();
|
|
934
|
+
* await generateText({ system: systemPrompt, messages });
|
|
935
|
+
* ```
|
|
936
|
+
*/
|
|
937
|
+
async resolve(options) {
|
|
938
|
+
await this.#ensureInitialized();
|
|
939
|
+
const systemPrompt = options.renderer.render(this.#fragments);
|
|
940
|
+
const messages = [];
|
|
941
|
+
if (this.#branch?.headMessageId) {
|
|
942
|
+
const chain = await this.#store.getMessageChain(
|
|
943
|
+
this.#branch.headMessageId
|
|
944
|
+
);
|
|
945
|
+
for (const msg of chain) {
|
|
946
|
+
messages.push(message(msg.data).codec?.decode());
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
for (const fragment2 of this.#pendingMessages) {
|
|
950
|
+
const decoded = fragment2.codec.decode();
|
|
951
|
+
messages.push(decoded);
|
|
952
|
+
}
|
|
953
|
+
return { systemPrompt, messages };
|
|
954
|
+
}
|
|
955
|
+
/**
|
|
956
|
+
* Save pending messages to the graph.
|
|
957
|
+
*
|
|
958
|
+
* Each message is added as a node with parentId pointing to the previous message.
|
|
959
|
+
* The branch head is updated to point to the last message.
|
|
960
|
+
*
|
|
961
|
+
* @example
|
|
962
|
+
* ```ts
|
|
963
|
+
* context.set(user('Hello'));
|
|
964
|
+
* // AI responds...
|
|
965
|
+
* context.set(assistant('Hi there!'));
|
|
966
|
+
* await context.save(); // Persist to graph
|
|
967
|
+
* ```
|
|
968
|
+
*/
|
|
969
|
+
async save() {
|
|
970
|
+
await this.#ensureInitialized();
|
|
971
|
+
if (this.#pendingMessages.length === 0) {
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
for (let i = 0; i < this.#pendingMessages.length; i++) {
|
|
975
|
+
const fragment2 = this.#pendingMessages[i];
|
|
976
|
+
if (isLazyFragment(fragment2)) {
|
|
977
|
+
this.#pendingMessages[i] = await this.#resolveLazyFragment(fragment2);
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
let parentId = this.#branch.headMessageId;
|
|
981
|
+
const now = Date.now();
|
|
982
|
+
for (const fragment2 of this.#pendingMessages) {
|
|
983
|
+
const messageData = {
|
|
984
|
+
id: fragment2.id ?? crypto.randomUUID(),
|
|
985
|
+
chatId: this.#chatId,
|
|
986
|
+
parentId,
|
|
987
|
+
name: fragment2.name,
|
|
988
|
+
type: fragment2.type,
|
|
989
|
+
data: fragment2.codec.encode(),
|
|
990
|
+
createdAt: now
|
|
991
|
+
};
|
|
992
|
+
await this.#store.addMessage(messageData);
|
|
993
|
+
parentId = messageData.id;
|
|
994
|
+
}
|
|
995
|
+
await this.#store.updateBranchHead(this.#branch.id, parentId);
|
|
996
|
+
this.#branch.headMessageId = parentId;
|
|
997
|
+
this.#pendingMessages = [];
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* Resolve a lazy fragment by finding the appropriate ID.
|
|
1001
|
+
*/
|
|
1002
|
+
async #resolveLazyFragment(fragment2) {
|
|
1003
|
+
const lazy = fragment2[LAZY_ID];
|
|
1004
|
+
if (lazy.type === "last-assistant") {
|
|
1005
|
+
const lastId = await this.#getLastAssistantId();
|
|
1006
|
+
return assistantText(lazy.content, { id: lastId ?? crypto.randomUUID() });
|
|
1007
|
+
}
|
|
1008
|
+
throw new Error(`Unknown lazy fragment type: ${lazy.type}`);
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Find the most recent assistant message ID (pending or persisted).
|
|
1012
|
+
*/
|
|
1013
|
+
async #getLastAssistantId() {
|
|
1014
|
+
for (let i = this.#pendingMessages.length - 1; i >= 0; i--) {
|
|
1015
|
+
const msg = this.#pendingMessages[i];
|
|
1016
|
+
if (msg.name === "assistant" && !isLazyFragment(msg)) {
|
|
1017
|
+
return msg.id;
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
if (this.#branch?.headMessageId) {
|
|
1021
|
+
const chain = await this.#store.getMessageChain(
|
|
1022
|
+
this.#branch.headMessageId
|
|
1023
|
+
);
|
|
1024
|
+
for (let i = chain.length - 1; i >= 0; i--) {
|
|
1025
|
+
if (chain[i].name === "assistant") {
|
|
1026
|
+
return chain[i].id;
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
return void 0;
|
|
1031
|
+
}
|
|
1032
|
+
/**
|
|
1033
|
+
* Estimate token count and cost for the full context.
|
|
1034
|
+
*
|
|
1035
|
+
* Includes:
|
|
1036
|
+
* - System prompt fragments (role, hints, etc.)
|
|
1037
|
+
* - Persisted chat messages (from store)
|
|
1038
|
+
* - Pending messages (not yet saved)
|
|
1039
|
+
*
|
|
1040
|
+
* @param modelId - Model ID (e.g., "openai:gpt-4o", "anthropic:claude-3-5-sonnet")
|
|
1041
|
+
* @param options - Optional settings
|
|
1042
|
+
* @returns Estimate result with token counts, costs, and per-fragment breakdown
|
|
1043
|
+
*/
|
|
1044
|
+
async estimate(modelId, options = {}) {
|
|
1045
|
+
await this.#ensureInitialized();
|
|
1046
|
+
const renderer = options.renderer ?? new XmlRenderer();
|
|
1047
|
+
const registry = getModelsRegistry();
|
|
1048
|
+
await registry.load();
|
|
1049
|
+
const model = registry.get(modelId);
|
|
1050
|
+
if (!model) {
|
|
1051
|
+
throw new Error(
|
|
1052
|
+
`Model "${modelId}" not found. Call load() first or check model ID.`
|
|
1053
|
+
);
|
|
1054
|
+
}
|
|
1055
|
+
const tokenizer = registry.getTokenizer(modelId);
|
|
1056
|
+
const fragmentEstimates = [];
|
|
1057
|
+
for (const fragment2 of this.#fragments) {
|
|
1058
|
+
const rendered = renderer.render([fragment2]);
|
|
1059
|
+
const tokens = tokenizer.count(rendered);
|
|
1060
|
+
const cost = tokens / 1e6 * model.cost.input;
|
|
1061
|
+
fragmentEstimates.push({
|
|
1062
|
+
id: fragment2.id,
|
|
1063
|
+
name: fragment2.name,
|
|
1064
|
+
tokens,
|
|
1065
|
+
cost
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
1068
|
+
if (this.#branch?.headMessageId) {
|
|
1069
|
+
const chain = await this.#store.getMessageChain(
|
|
1070
|
+
this.#branch.headMessageId
|
|
1071
|
+
);
|
|
1072
|
+
for (const msg of chain) {
|
|
1073
|
+
const content = String(msg.data);
|
|
1074
|
+
const tokens = tokenizer.count(content);
|
|
1075
|
+
const cost = tokens / 1e6 * model.cost.input;
|
|
1076
|
+
fragmentEstimates.push({
|
|
1077
|
+
name: msg.name,
|
|
1078
|
+
id: msg.id,
|
|
1079
|
+
tokens,
|
|
1080
|
+
cost
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
for (const fragment2 of this.#pendingMessages) {
|
|
1085
|
+
const content = String(fragment2.data);
|
|
1086
|
+
const tokens = tokenizer.count(content);
|
|
1087
|
+
const cost = tokens / 1e6 * model.cost.input;
|
|
1088
|
+
fragmentEstimates.push({
|
|
1089
|
+
name: fragment2.name,
|
|
1090
|
+
id: fragment2.id,
|
|
1091
|
+
tokens,
|
|
1092
|
+
cost
|
|
1093
|
+
});
|
|
1094
|
+
}
|
|
1095
|
+
const totalTokens = fragmentEstimates.reduce((sum, f) => sum + f.tokens, 0);
|
|
1096
|
+
const totalCost = fragmentEstimates.reduce((sum, f) => sum + f.cost, 0);
|
|
1097
|
+
return {
|
|
1098
|
+
model: model.id,
|
|
1099
|
+
provider: model.provider,
|
|
1100
|
+
tokens: totalTokens,
|
|
1101
|
+
cost: totalCost,
|
|
1102
|
+
limits: {
|
|
1103
|
+
context: model.limit.context,
|
|
1104
|
+
output: model.limit.output,
|
|
1105
|
+
exceedsContext: totalTokens > model.limit.context
|
|
1106
|
+
},
|
|
1107
|
+
fragments: fragmentEstimates
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
/**
|
|
1111
|
+
* Rewind to a specific message by ID.
|
|
1112
|
+
*
|
|
1113
|
+
* Creates a new branch from that message, preserving the original branch.
|
|
1114
|
+
* The new branch becomes active.
|
|
1115
|
+
*
|
|
1116
|
+
* @param messageId - The message ID to rewind to
|
|
1117
|
+
* @returns The new branch info
|
|
1118
|
+
*
|
|
1119
|
+
* @example
|
|
1120
|
+
* ```ts
|
|
1121
|
+
* context.set(user('What is 2 + 2?', { id: 'q1' }));
|
|
1122
|
+
* context.set(assistant('The answer is 5.', { id: 'wrong' })); // Oops!
|
|
1123
|
+
* await context.save();
|
|
1124
|
+
*
|
|
1125
|
+
* // Rewind to the question, creates new branch
|
|
1126
|
+
* const newBranch = await context.rewind('q1');
|
|
1127
|
+
*
|
|
1128
|
+
* // Now add correct answer on new branch
|
|
1129
|
+
* context.set(assistant('The answer is 4.'));
|
|
1130
|
+
* await context.save();
|
|
1131
|
+
* ```
|
|
1132
|
+
*/
|
|
1133
|
+
async rewind(messageId) {
|
|
1134
|
+
await this.#ensureInitialized();
|
|
1135
|
+
const message2 = await this.#store.getMessage(messageId);
|
|
1136
|
+
if (!message2) {
|
|
1137
|
+
throw new Error(`Message "${messageId}" not found`);
|
|
1138
|
+
}
|
|
1139
|
+
if (message2.chatId !== this.#chatId) {
|
|
1140
|
+
throw new Error(`Message "${messageId}" belongs to a different chat`);
|
|
1141
|
+
}
|
|
1142
|
+
return this.#createBranchFrom(messageId, true);
|
|
1143
|
+
}
|
|
1144
|
+
/**
|
|
1145
|
+
* Create a checkpoint at the current position.
|
|
1146
|
+
*
|
|
1147
|
+
* A checkpoint is a named pointer to the current branch head.
|
|
1148
|
+
* Use restore() to return to this point later.
|
|
1149
|
+
*
|
|
1150
|
+
* @param name - Name for the checkpoint
|
|
1151
|
+
* @returns The checkpoint info
|
|
1152
|
+
*
|
|
1153
|
+
* @example
|
|
1154
|
+
* ```ts
|
|
1155
|
+
* context.set(user('I want to learn a new skill.'));
|
|
1156
|
+
* context.set(assistant('Would you like coding or cooking?'));
|
|
1157
|
+
* await context.save();
|
|
1158
|
+
*
|
|
1159
|
+
* // Save checkpoint before user's choice
|
|
1160
|
+
* const cp = await context.checkpoint('before-choice');
|
|
1161
|
+
* ```
|
|
1162
|
+
*/
|
|
1163
|
+
async checkpoint(name) {
|
|
1164
|
+
await this.#ensureInitialized();
|
|
1165
|
+
if (!this.#branch?.headMessageId) {
|
|
1166
|
+
throw new Error("Cannot create checkpoint: no messages in conversation");
|
|
1167
|
+
}
|
|
1168
|
+
const checkpoint = {
|
|
1169
|
+
id: crypto.randomUUID(),
|
|
1170
|
+
chatId: this.#chatId,
|
|
1171
|
+
name,
|
|
1172
|
+
messageId: this.#branch.headMessageId,
|
|
1173
|
+
createdAt: Date.now()
|
|
1174
|
+
};
|
|
1175
|
+
await this.#store.createCheckpoint(checkpoint);
|
|
1176
|
+
return {
|
|
1177
|
+
id: checkpoint.id,
|
|
1178
|
+
name: checkpoint.name,
|
|
1179
|
+
messageId: checkpoint.messageId,
|
|
1180
|
+
createdAt: checkpoint.createdAt
|
|
1181
|
+
};
|
|
1182
|
+
}
|
|
1183
|
+
/**
|
|
1184
|
+
* Restore to a checkpoint by creating a new branch from that point.
|
|
1185
|
+
*
|
|
1186
|
+
* @param name - Name of the checkpoint to restore
|
|
1187
|
+
* @returns The new branch info
|
|
1188
|
+
*
|
|
1189
|
+
* @example
|
|
1190
|
+
* ```ts
|
|
1191
|
+
* // User chose cooking, but wants to try coding path
|
|
1192
|
+
* await context.restore('before-choice');
|
|
1193
|
+
*
|
|
1194
|
+
* context.set(user('I want to learn coding.'));
|
|
1195
|
+
* context.set(assistant('Python is a great starting language!'));
|
|
1196
|
+
* await context.save();
|
|
1197
|
+
* ```
|
|
1198
|
+
*/
|
|
1199
|
+
async restore(name) {
|
|
1200
|
+
await this.#ensureInitialized();
|
|
1201
|
+
const checkpoint = await this.#store.getCheckpoint(this.#chatId, name);
|
|
1202
|
+
if (!checkpoint) {
|
|
1203
|
+
throw new Error(
|
|
1204
|
+
`Checkpoint "${name}" not found in chat "${this.#chatId}"`
|
|
1205
|
+
);
|
|
1206
|
+
}
|
|
1207
|
+
return this.rewind(checkpoint.messageId);
|
|
1208
|
+
}
|
|
1209
|
+
/**
|
|
1210
|
+
* Switch to a different branch by name.
|
|
1211
|
+
*
|
|
1212
|
+
* @param name - Branch name to switch to
|
|
1213
|
+
*
|
|
1214
|
+
* @example
|
|
1215
|
+
* ```ts
|
|
1216
|
+
* // List branches (via store)
|
|
1217
|
+
* const branches = await store.listBranches(context.chatId);
|
|
1218
|
+
* console.log(branches); // [{name: 'main', ...}, {name: 'main-v2', ...}]
|
|
1219
|
+
*
|
|
1220
|
+
* // Switch to original branch
|
|
1221
|
+
* await context.switchBranch('main');
|
|
1222
|
+
* ```
|
|
1223
|
+
*/
|
|
1224
|
+
async switchBranch(name) {
|
|
1225
|
+
await this.#ensureInitialized();
|
|
1226
|
+
const branch = await this.#store.getBranch(this.#chatId, name);
|
|
1227
|
+
if (!branch) {
|
|
1228
|
+
throw new Error(`Branch "${name}" not found in chat "${this.#chatId}"`);
|
|
1229
|
+
}
|
|
1230
|
+
await this.#store.setActiveBranch(this.#chatId, branch.id);
|
|
1231
|
+
this.#branch = { ...branch, isActive: true };
|
|
1232
|
+
this.#branchName = name;
|
|
1233
|
+
this.#pendingMessages = [];
|
|
1234
|
+
}
|
|
1235
|
+
/**
|
|
1236
|
+
* Create a parallel branch from the current position ("by the way").
|
|
1237
|
+
*
|
|
1238
|
+
* Use this when you want to fork the conversation without leaving
|
|
1239
|
+
* the current branch. Common use case: user wants to ask another
|
|
1240
|
+
* question while waiting for the model to respond.
|
|
1241
|
+
*
|
|
1242
|
+
* Unlike rewind(), this method:
|
|
1243
|
+
* - Uses the current HEAD (no messageId needed)
|
|
1244
|
+
* - Does NOT switch to the new branch
|
|
1245
|
+
* - Keeps pending messages intact
|
|
1246
|
+
*
|
|
1247
|
+
* @returns The new branch info (does not switch to it)
|
|
1248
|
+
* @throws Error if no messages exist in the conversation
|
|
1249
|
+
*
|
|
1250
|
+
* @example
|
|
1251
|
+
* ```ts
|
|
1252
|
+
* // User asked a question, model is generating...
|
|
1253
|
+
* context.set(user('What is the weather?'));
|
|
1254
|
+
* await context.save();
|
|
1255
|
+
*
|
|
1256
|
+
* // User wants to ask something else without waiting
|
|
1257
|
+
* const newBranch = await context.btw();
|
|
1258
|
+
* // newBranch = { name: 'main-v2', ... }
|
|
1259
|
+
*
|
|
1260
|
+
* // Later, switch to the new branch and add the question
|
|
1261
|
+
* await context.switchBranch(newBranch.name);
|
|
1262
|
+
* context.set(user('Also, what time is it?'));
|
|
1263
|
+
* await context.save();
|
|
1264
|
+
* ```
|
|
1265
|
+
*/
|
|
1266
|
+
async btw() {
|
|
1267
|
+
await this.#ensureInitialized();
|
|
1268
|
+
if (!this.#branch?.headMessageId) {
|
|
1269
|
+
throw new Error("Cannot create btw branch: no messages in conversation");
|
|
1270
|
+
}
|
|
1271
|
+
return this.#createBranchFrom(this.#branch.headMessageId, false);
|
|
1272
|
+
}
|
|
1273
|
+
/**
|
|
1274
|
+
* Update metadata for the current chat.
|
|
1275
|
+
*
|
|
1276
|
+
* @param updates - Partial metadata to merge (title, metadata)
|
|
1277
|
+
*
|
|
1278
|
+
* @example
|
|
1279
|
+
* ```ts
|
|
1280
|
+
* await context.updateChat({
|
|
1281
|
+
* title: 'Coding Help Session',
|
|
1282
|
+
* metadata: { tags: ['python', 'debugging'] }
|
|
1283
|
+
* });
|
|
1284
|
+
* ```
|
|
1285
|
+
*/
|
|
1286
|
+
async updateChat(updates) {
|
|
1287
|
+
await this.#ensureInitialized();
|
|
1288
|
+
const storeUpdates = {};
|
|
1289
|
+
if (updates.title !== void 0) {
|
|
1290
|
+
storeUpdates.title = updates.title;
|
|
1291
|
+
}
|
|
1292
|
+
if (updates.metadata !== void 0) {
|
|
1293
|
+
storeUpdates.metadata = {
|
|
1294
|
+
...this.#chatData?.metadata,
|
|
1295
|
+
...updates.metadata
|
|
1296
|
+
};
|
|
1297
|
+
}
|
|
1298
|
+
this.#chatData = await this.#store.updateChat(this.#chatId, storeUpdates);
|
|
1299
|
+
}
|
|
1300
|
+
/**
|
|
1301
|
+
* Consolidate context fragments (no-op for now).
|
|
1302
|
+
*
|
|
1303
|
+
* This is a placeholder for future functionality that merges context fragments
|
|
1304
|
+
* using specific rules. Currently, it does nothing.
|
|
1305
|
+
*
|
|
1306
|
+
* @experimental
|
|
1307
|
+
*/
|
|
1308
|
+
consolidate() {
|
|
1309
|
+
return void 0;
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* Extract skill path mappings from available_skills fragments.
|
|
1313
|
+
* Returns array of { host, sandbox } for mounting in sandbox filesystem.
|
|
1314
|
+
*
|
|
1315
|
+
* Reads the original `paths` configuration stored in fragment metadata
|
|
1316
|
+
* by the skills() fragment helper.
|
|
1317
|
+
*
|
|
1318
|
+
* @example
|
|
1319
|
+
* ```ts
|
|
1320
|
+
* const context = new ContextEngine({ store, chatId, userId })
|
|
1321
|
+
* .set(skills({ paths: [{ host: './skills', sandbox: '/skills' }] }));
|
|
1322
|
+
*
|
|
1323
|
+
* const mounts = context.getSkillMounts();
|
|
1324
|
+
* // [{ host: './skills', sandbox: '/skills' }]
|
|
1325
|
+
* ```
|
|
1326
|
+
*/
|
|
1327
|
+
getSkillMounts() {
|
|
1328
|
+
const mounts = [];
|
|
1329
|
+
for (const fragment2 of this.#fragments) {
|
|
1330
|
+
if (fragment2.name === "available_skills" && fragment2.metadata && Array.isArray(fragment2.metadata.paths)) {
|
|
1331
|
+
for (const mapping of fragment2.metadata.paths) {
|
|
1332
|
+
if (typeof mapping === "object" && mapping !== null && typeof mapping.host === "string" && typeof mapping.sandbox === "string") {
|
|
1333
|
+
mounts.push({ host: mapping.host, sandbox: mapping.sandbox });
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
return mounts;
|
|
1339
|
+
}
|
|
1340
|
+
/**
|
|
1341
|
+
* Inspect the full context state for debugging.
|
|
1342
|
+
* Returns a JSON-serializable object with context information.
|
|
1343
|
+
*
|
|
1344
|
+
* @param options - Inspection options (modelId and renderer required)
|
|
1345
|
+
* @returns Complete inspection data including estimates, rendered output, fragments, and graph
|
|
1346
|
+
*
|
|
1347
|
+
* @example
|
|
1348
|
+
* ```ts
|
|
1349
|
+
* const inspection = await context.inspect({
|
|
1350
|
+
* modelId: 'openai:gpt-4o',
|
|
1351
|
+
* renderer: new XmlRenderer(),
|
|
1352
|
+
* });
|
|
1353
|
+
* console.log(JSON.stringify(inspection, null, 2));
|
|
1354
|
+
*
|
|
1355
|
+
* // Or write to file for analysis
|
|
1356
|
+
* await fs.writeFile('context-debug.json', JSON.stringify(inspection, null, 2));
|
|
1357
|
+
* ```
|
|
1358
|
+
*/
|
|
1359
|
+
async inspect(options) {
|
|
1360
|
+
await this.#ensureInitialized();
|
|
1361
|
+
const { renderer } = options;
|
|
1362
|
+
const estimateResult = await this.estimate(options.modelId, { renderer });
|
|
1363
|
+
const rendered = renderer.render(this.#fragments);
|
|
1364
|
+
const persistedMessages = [];
|
|
1365
|
+
if (this.#branch?.headMessageId) {
|
|
1366
|
+
const chain = await this.#store.getMessageChain(
|
|
1367
|
+
this.#branch.headMessageId
|
|
1368
|
+
);
|
|
1369
|
+
persistedMessages.push(...chain);
|
|
1370
|
+
}
|
|
1371
|
+
const graph = await this.#store.getGraph(this.#chatId);
|
|
1372
|
+
return {
|
|
1373
|
+
estimate: estimateResult,
|
|
1374
|
+
rendered,
|
|
1375
|
+
fragments: {
|
|
1376
|
+
context: [...this.#fragments],
|
|
1377
|
+
pending: [...this.#pendingMessages],
|
|
1378
|
+
persisted: persistedMessages
|
|
1379
|
+
},
|
|
1380
|
+
graph,
|
|
1381
|
+
meta: {
|
|
1382
|
+
chatId: this.#chatId,
|
|
1383
|
+
branch: this.#branchName,
|
|
1384
|
+
timestamp: Date.now()
|
|
1385
|
+
}
|
|
1386
|
+
};
|
|
1387
|
+
}
|
|
1388
|
+
};
|
|
1389
|
+
function persona(input) {
|
|
1390
|
+
return {
|
|
1391
|
+
name: "persona",
|
|
1392
|
+
data: {
|
|
1393
|
+
name: input.name,
|
|
1394
|
+
...input.role && { role: input.role },
|
|
1395
|
+
...input.objective && { objective: input.objective },
|
|
1396
|
+
...input.tone && { tone: input.tone }
|
|
1397
|
+
}
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
function pass(part) {
|
|
1401
|
+
return { type: "pass", part };
|
|
1402
|
+
}
|
|
1403
|
+
function runGuardrailChain(part, guardrails, context) {
|
|
1404
|
+
let currentPart = part;
|
|
1405
|
+
for (const guardrail2 of guardrails) {
|
|
1406
|
+
const result = guardrail2.handle(currentPart, context);
|
|
1407
|
+
if (result.type === "fail") {
|
|
1408
|
+
return result;
|
|
1409
|
+
}
|
|
1410
|
+
currentPart = result.part;
|
|
1411
|
+
}
|
|
1412
|
+
return pass(currentPart);
|
|
1413
|
+
}
|
|
1414
|
+
var STORE_DDL = `
|
|
1415
|
+
-- Chats table
|
|
1416
|
+
-- createdAt/updatedAt: DEFAULT for insert, inline SET for updates
|
|
1417
|
+
CREATE TABLE IF NOT EXISTS chats (
|
|
1418
|
+
id TEXT PRIMARY KEY,
|
|
1419
|
+
userId TEXT NOT NULL,
|
|
1420
|
+
title TEXT,
|
|
1421
|
+
metadata TEXT,
|
|
1422
|
+
createdAt INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
|
|
1423
|
+
updatedAt INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000)
|
|
1424
|
+
);
|
|
241
1425
|
|
|
242
|
-
|
|
243
|
-
|
|
1426
|
+
CREATE INDEX IF NOT EXISTS idx_chats_updatedAt ON chats(updatedAt);
|
|
1427
|
+
CREATE INDEX IF NOT EXISTS idx_chats_userId ON chats(userId);
|
|
244
1428
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
1429
|
+
-- Messages table (nodes in the DAG)
|
|
1430
|
+
CREATE TABLE IF NOT EXISTS messages (
|
|
1431
|
+
id TEXT PRIMARY KEY,
|
|
1432
|
+
chatId TEXT NOT NULL,
|
|
1433
|
+
parentId TEXT,
|
|
1434
|
+
name TEXT NOT NULL,
|
|
1435
|
+
type TEXT,
|
|
1436
|
+
data TEXT NOT NULL,
|
|
1437
|
+
createdAt INTEGER NOT NULL,
|
|
1438
|
+
FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
|
|
1439
|
+
FOREIGN KEY (parentId) REFERENCES messages(id)
|
|
1440
|
+
);
|
|
248
1441
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
- For each table: purpose, row count, and example of what the data looks like
|
|
1442
|
+
CREATE INDEX IF NOT EXISTS idx_messages_chatId ON messages(chatId);
|
|
1443
|
+
CREATE INDEX IF NOT EXISTS idx_messages_parentId ON messages(parentId);
|
|
252
1444
|
|
|
253
|
-
|
|
254
|
-
|
|
1445
|
+
-- Branches table (pointers to head messages)
|
|
1446
|
+
CREATE TABLE IF NOT EXISTS branches (
|
|
1447
|
+
id TEXT PRIMARY KEY,
|
|
1448
|
+
chatId TEXT NOT NULL,
|
|
1449
|
+
name TEXT NOT NULL,
|
|
1450
|
+
headMessageId TEXT,
|
|
1451
|
+
isActive INTEGER NOT NULL DEFAULT 0,
|
|
1452
|
+
createdAt INTEGER NOT NULL,
|
|
1453
|
+
FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
|
|
1454
|
+
FOREIGN KEY (headMessageId) REFERENCES messages(id),
|
|
1455
|
+
UNIQUE(chatId, name)
|
|
1456
|
+
);
|
|
255
1457
|
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
1458
|
+
CREATE INDEX IF NOT EXISTS idx_branches_chatId ON branches(chatId);
|
|
1459
|
+
|
|
1460
|
+
-- Checkpoints table (pointers to message nodes)
|
|
1461
|
+
CREATE TABLE IF NOT EXISTS checkpoints (
|
|
1462
|
+
id TEXT PRIMARY KEY,
|
|
1463
|
+
chatId TEXT NOT NULL,
|
|
1464
|
+
name TEXT NOT NULL,
|
|
1465
|
+
messageId TEXT NOT NULL,
|
|
1466
|
+
createdAt INTEGER NOT NULL,
|
|
1467
|
+
FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
|
|
1468
|
+
FOREIGN KEY (messageId) REFERENCES messages(id),
|
|
1469
|
+
UNIQUE(chatId, name)
|
|
1470
|
+
);
|
|
1471
|
+
|
|
1472
|
+
CREATE INDEX IF NOT EXISTS idx_checkpoints_chatId ON checkpoints(chatId);
|
|
1473
|
+
|
|
1474
|
+
-- FTS5 virtual table for full-text search
|
|
1475
|
+
-- messageId/chatId/name are UNINDEXED (stored but not searchable, used for filtering/joining)
|
|
1476
|
+
-- Only 'content' is indexed for full-text search
|
|
1477
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
|
|
1478
|
+
messageId UNINDEXED,
|
|
1479
|
+
chatId UNINDEXED,
|
|
1480
|
+
name UNINDEXED,
|
|
1481
|
+
content,
|
|
1482
|
+
tokenize='porter unicode61'
|
|
1483
|
+
);
|
|
1484
|
+
`;
|
|
1485
|
+
var SqliteContextStore = class extends ContextStore {
|
|
1486
|
+
#db;
|
|
1487
|
+
constructor(path3) {
|
|
1488
|
+
super();
|
|
1489
|
+
this.#db = new DatabaseSync(path3);
|
|
1490
|
+
this.#db.exec("PRAGMA foreign_keys = ON");
|
|
1491
|
+
this.#db.exec(STORE_DDL);
|
|
1492
|
+
}
|
|
1493
|
+
/**
|
|
1494
|
+
* Execute a function within a transaction.
|
|
1495
|
+
* Automatically commits on success or rolls back on error.
|
|
1496
|
+
*/
|
|
1497
|
+
#useTransaction(fn) {
|
|
1498
|
+
this.#db.exec("BEGIN TRANSACTION");
|
|
1499
|
+
try {
|
|
1500
|
+
const result = fn();
|
|
1501
|
+
this.#db.exec("COMMIT");
|
|
1502
|
+
return result;
|
|
1503
|
+
} catch (error) {
|
|
1504
|
+
this.#db.exec("ROLLBACK");
|
|
1505
|
+
throw error;
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
// ==========================================================================
|
|
1509
|
+
// Chat Operations
|
|
1510
|
+
// ==========================================================================
|
|
1511
|
+
async createChat(chat) {
|
|
1512
|
+
this.#useTransaction(() => {
|
|
1513
|
+
this.#db.prepare(
|
|
1514
|
+
`INSERT INTO chats (id, userId, title, metadata)
|
|
1515
|
+
VALUES (?, ?, ?, ?)`
|
|
1516
|
+
).run(
|
|
1517
|
+
chat.id,
|
|
1518
|
+
chat.userId,
|
|
1519
|
+
chat.title ?? null,
|
|
1520
|
+
chat.metadata ? JSON.stringify(chat.metadata) : null
|
|
1521
|
+
);
|
|
1522
|
+
this.#db.prepare(
|
|
1523
|
+
`INSERT INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
|
|
1524
|
+
VALUES (?, ?, 'main', NULL, 1, ?)`
|
|
1525
|
+
).run(crypto.randomUUID(), chat.id, Date.now());
|
|
1526
|
+
});
|
|
1527
|
+
}
|
|
1528
|
+
async upsertChat(chat) {
|
|
1529
|
+
return this.#useTransaction(() => {
|
|
1530
|
+
const row = this.#db.prepare(
|
|
1531
|
+
`INSERT INTO chats (id, userId, title, metadata)
|
|
1532
|
+
VALUES (?, ?, ?, ?)
|
|
1533
|
+
ON CONFLICT(id) DO UPDATE SET id = excluded.id
|
|
1534
|
+
RETURNING *`
|
|
1535
|
+
).get(
|
|
1536
|
+
chat.id,
|
|
1537
|
+
chat.userId,
|
|
1538
|
+
chat.title ?? null,
|
|
1539
|
+
chat.metadata ? JSON.stringify(chat.metadata) : null
|
|
1540
|
+
);
|
|
1541
|
+
this.#db.prepare(
|
|
1542
|
+
`INSERT OR IGNORE INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
|
|
1543
|
+
VALUES (?, ?, 'main', NULL, 1, ?)`
|
|
1544
|
+
).run(crypto.randomUUID(), chat.id, Date.now());
|
|
1545
|
+
return {
|
|
1546
|
+
id: row.id,
|
|
1547
|
+
userId: row.userId,
|
|
1548
|
+
title: row.title ?? void 0,
|
|
1549
|
+
metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
|
|
1550
|
+
createdAt: row.createdAt,
|
|
1551
|
+
updatedAt: row.updatedAt
|
|
1552
|
+
};
|
|
1553
|
+
});
|
|
1554
|
+
}
|
|
1555
|
+
async getChat(chatId) {
|
|
1556
|
+
const row = this.#db.prepare("SELECT * FROM chats WHERE id = ?").get(chatId);
|
|
1557
|
+
if (!row) {
|
|
1558
|
+
return void 0;
|
|
1559
|
+
}
|
|
1560
|
+
return {
|
|
1561
|
+
id: row.id,
|
|
1562
|
+
userId: row.userId,
|
|
1563
|
+
title: row.title ?? void 0,
|
|
1564
|
+
metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
|
|
1565
|
+
createdAt: row.createdAt,
|
|
1566
|
+
updatedAt: row.updatedAt
|
|
1567
|
+
};
|
|
1568
|
+
}
|
|
1569
|
+
async updateChat(chatId, updates) {
|
|
1570
|
+
const setClauses = ["updatedAt = strftime('%s', 'now') * 1000"];
|
|
1571
|
+
const params = [];
|
|
1572
|
+
if (updates.title !== void 0) {
|
|
1573
|
+
setClauses.push("title = ?");
|
|
1574
|
+
params.push(updates.title ?? null);
|
|
1575
|
+
}
|
|
1576
|
+
if (updates.metadata !== void 0) {
|
|
1577
|
+
setClauses.push("metadata = ?");
|
|
1578
|
+
params.push(JSON.stringify(updates.metadata));
|
|
1579
|
+
}
|
|
1580
|
+
params.push(chatId);
|
|
1581
|
+
const row = this.#db.prepare(
|
|
1582
|
+
`UPDATE chats SET ${setClauses.join(", ")} WHERE id = ? RETURNING *`
|
|
1583
|
+
).get(...params);
|
|
1584
|
+
return {
|
|
1585
|
+
id: row.id,
|
|
1586
|
+
userId: row.userId,
|
|
1587
|
+
title: row.title ?? void 0,
|
|
1588
|
+
metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
|
|
1589
|
+
createdAt: row.createdAt,
|
|
1590
|
+
updatedAt: row.updatedAt
|
|
1591
|
+
};
|
|
1592
|
+
}
|
|
1593
|
+
async listChats(options) {
|
|
1594
|
+
const params = [];
|
|
1595
|
+
let whereClause = "";
|
|
1596
|
+
let limitClause = "";
|
|
1597
|
+
if (options?.userId) {
|
|
1598
|
+
whereClause = "WHERE c.userId = ?";
|
|
1599
|
+
params.push(options.userId);
|
|
1600
|
+
}
|
|
1601
|
+
if (options?.limit !== void 0) {
|
|
1602
|
+
limitClause = " LIMIT ?";
|
|
1603
|
+
params.push(options.limit);
|
|
1604
|
+
if (options.offset !== void 0) {
|
|
1605
|
+
limitClause += " OFFSET ?";
|
|
1606
|
+
params.push(options.offset);
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
const rows = this.#db.prepare(
|
|
1610
|
+
`SELECT
|
|
1611
|
+
c.id,
|
|
1612
|
+
c.userId,
|
|
1613
|
+
c.title,
|
|
1614
|
+
c.createdAt,
|
|
1615
|
+
c.updatedAt,
|
|
1616
|
+
COUNT(DISTINCT m.id) as messageCount,
|
|
1617
|
+
COUNT(DISTINCT b.id) as branchCount
|
|
1618
|
+
FROM chats c
|
|
1619
|
+
LEFT JOIN messages m ON m.chatId = c.id
|
|
1620
|
+
LEFT JOIN branches b ON b.chatId = c.id
|
|
1621
|
+
${whereClause}
|
|
1622
|
+
GROUP BY c.id
|
|
1623
|
+
ORDER BY c.updatedAt DESC${limitClause}`
|
|
1624
|
+
).all(...params);
|
|
1625
|
+
return rows.map((row) => ({
|
|
1626
|
+
id: row.id,
|
|
1627
|
+
userId: row.userId,
|
|
1628
|
+
title: row.title ?? void 0,
|
|
1629
|
+
messageCount: row.messageCount,
|
|
1630
|
+
branchCount: row.branchCount,
|
|
1631
|
+
createdAt: row.createdAt,
|
|
1632
|
+
updatedAt: row.updatedAt
|
|
1633
|
+
}));
|
|
1634
|
+
}
|
|
1635
|
+
async deleteChat(chatId, options) {
|
|
1636
|
+
return this.#useTransaction(() => {
|
|
1637
|
+
const messageIds = this.#db.prepare("SELECT id FROM messages WHERE chatId = ?").all(chatId);
|
|
1638
|
+
let sql = "DELETE FROM chats WHERE id = ?";
|
|
1639
|
+
const params = [chatId];
|
|
1640
|
+
if (options?.userId !== void 0) {
|
|
1641
|
+
sql += " AND userId = ?";
|
|
1642
|
+
params.push(options.userId);
|
|
1643
|
+
}
|
|
1644
|
+
const result = this.#db.prepare(sql).run(...params);
|
|
1645
|
+
if (result.changes > 0 && messageIds.length > 0) {
|
|
1646
|
+
const placeholders = messageIds.map(() => "?").join(", ");
|
|
1647
|
+
this.#db.prepare(
|
|
1648
|
+
`DELETE FROM messages_fts WHERE messageId IN (${placeholders})`
|
|
1649
|
+
).run(...messageIds.map((m) => m.id));
|
|
1650
|
+
}
|
|
1651
|
+
return result.changes > 0;
|
|
1652
|
+
});
|
|
1653
|
+
}
|
|
1654
|
+
// ==========================================================================
|
|
1655
|
+
// Message Operations (Graph Nodes)
|
|
1656
|
+
// ==========================================================================
|
|
1657
|
+
async addMessage(message2) {
|
|
1658
|
+
const existingParent = message2.parentId === message2.id ? this.#db.prepare("SELECT parentId FROM messages WHERE id = ?").get(message2.id) : void 0;
|
|
1659
|
+
const parentId = message2.parentId === message2.id ? existingParent?.parentId ?? null : message2.parentId;
|
|
1660
|
+
this.#db.prepare(
|
|
1661
|
+
`INSERT INTO messages (id, chatId, parentId, name, type, data, createdAt)
|
|
1662
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
1663
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
1664
|
+
name = excluded.name,
|
|
1665
|
+
type = excluded.type,
|
|
1666
|
+
data = excluded.data`
|
|
1667
|
+
).run(
|
|
1668
|
+
message2.id,
|
|
1669
|
+
message2.chatId,
|
|
1670
|
+
parentId,
|
|
1671
|
+
message2.name,
|
|
1672
|
+
message2.type ?? null,
|
|
1673
|
+
JSON.stringify(message2.data),
|
|
1674
|
+
message2.createdAt
|
|
1675
|
+
);
|
|
1676
|
+
const content = typeof message2.data === "string" ? message2.data : JSON.stringify(message2.data);
|
|
1677
|
+
this.#db.prepare(`DELETE FROM messages_fts WHERE messageId = ?`).run(message2.id);
|
|
1678
|
+
this.#db.prepare(
|
|
1679
|
+
`INSERT INTO messages_fts(messageId, chatId, name, content)
|
|
1680
|
+
VALUES (?, ?, ?, ?)`
|
|
1681
|
+
).run(message2.id, message2.chatId, message2.name, content);
|
|
1682
|
+
}
|
|
1683
|
+
async getMessage(messageId) {
|
|
1684
|
+
const row = this.#db.prepare("SELECT * FROM messages WHERE id = ?").get(messageId);
|
|
1685
|
+
if (!row) {
|
|
1686
|
+
return void 0;
|
|
1687
|
+
}
|
|
1688
|
+
return {
|
|
1689
|
+
id: row.id,
|
|
1690
|
+
chatId: row.chatId,
|
|
1691
|
+
parentId: row.parentId,
|
|
1692
|
+
name: row.name,
|
|
1693
|
+
type: row.type ?? void 0,
|
|
1694
|
+
data: JSON.parse(row.data),
|
|
1695
|
+
createdAt: row.createdAt
|
|
1696
|
+
};
|
|
1697
|
+
}
|
|
1698
|
+
async getMessageChain(headId) {
|
|
1699
|
+
const rows = this.#db.prepare(
|
|
1700
|
+
`WITH RECURSIVE chain AS (
|
|
1701
|
+
SELECT *, 0 as depth FROM messages WHERE id = ?
|
|
1702
|
+
UNION ALL
|
|
1703
|
+
SELECT m.*, c.depth + 1 FROM messages m
|
|
1704
|
+
INNER JOIN chain c ON m.id = c.parentId
|
|
1705
|
+
)
|
|
1706
|
+
SELECT * FROM chain
|
|
1707
|
+
ORDER BY depth DESC`
|
|
1708
|
+
).all(headId);
|
|
1709
|
+
return rows.map((row) => ({
|
|
1710
|
+
id: row.id,
|
|
1711
|
+
chatId: row.chatId,
|
|
1712
|
+
parentId: row.parentId,
|
|
1713
|
+
name: row.name,
|
|
1714
|
+
type: row.type ?? void 0,
|
|
1715
|
+
data: JSON.parse(row.data),
|
|
1716
|
+
createdAt: row.createdAt
|
|
1717
|
+
}));
|
|
1718
|
+
}
|
|
1719
|
+
async hasChildren(messageId) {
|
|
1720
|
+
const row = this.#db.prepare(
|
|
1721
|
+
"SELECT EXISTS(SELECT 1 FROM messages WHERE parentId = ?) as hasChildren"
|
|
1722
|
+
).get(messageId);
|
|
1723
|
+
return row.hasChildren === 1;
|
|
1724
|
+
}
|
|
1725
|
+
async getMessages(chatId) {
|
|
1726
|
+
const chat = await this.getChat(chatId);
|
|
1727
|
+
if (!chat) {
|
|
1728
|
+
throw new Error(`Chat "${chatId}" not found`);
|
|
1729
|
+
}
|
|
1730
|
+
const activeBranch = await this.getActiveBranch(chatId);
|
|
1731
|
+
if (!activeBranch?.headMessageId) {
|
|
1732
|
+
return [];
|
|
1733
|
+
}
|
|
1734
|
+
return this.getMessageChain(activeBranch.headMessageId);
|
|
1735
|
+
}
|
|
1736
|
+
// ==========================================================================
|
|
1737
|
+
// Branch Operations
|
|
1738
|
+
// ==========================================================================
|
|
1739
|
+
async createBranch(branch) {
|
|
1740
|
+
this.#db.prepare(
|
|
1741
|
+
`INSERT INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
|
|
1742
|
+
VALUES (?, ?, ?, ?, ?, ?)`
|
|
1743
|
+
).run(
|
|
1744
|
+
branch.id,
|
|
1745
|
+
branch.chatId,
|
|
1746
|
+
branch.name,
|
|
1747
|
+
branch.headMessageId,
|
|
1748
|
+
branch.isActive ? 1 : 0,
|
|
1749
|
+
branch.createdAt
|
|
1750
|
+
);
|
|
1751
|
+
}
|
|
1752
|
+
async getBranch(chatId, name) {
|
|
1753
|
+
const row = this.#db.prepare("SELECT * FROM branches WHERE chatId = ? AND name = ?").get(chatId, name);
|
|
1754
|
+
if (!row) {
|
|
1755
|
+
return void 0;
|
|
1756
|
+
}
|
|
1757
|
+
return {
|
|
1758
|
+
id: row.id,
|
|
1759
|
+
chatId: row.chatId,
|
|
1760
|
+
name: row.name,
|
|
1761
|
+
headMessageId: row.headMessageId,
|
|
1762
|
+
isActive: row.isActive === 1,
|
|
1763
|
+
createdAt: row.createdAt
|
|
1764
|
+
};
|
|
1765
|
+
}
|
|
1766
|
+
async getActiveBranch(chatId) {
|
|
1767
|
+
const row = this.#db.prepare("SELECT * FROM branches WHERE chatId = ? AND isActive = 1").get(chatId);
|
|
1768
|
+
if (!row) {
|
|
1769
|
+
return void 0;
|
|
1770
|
+
}
|
|
1771
|
+
return {
|
|
1772
|
+
id: row.id,
|
|
1773
|
+
chatId: row.chatId,
|
|
1774
|
+
name: row.name,
|
|
1775
|
+
headMessageId: row.headMessageId,
|
|
1776
|
+
isActive: true,
|
|
1777
|
+
createdAt: row.createdAt
|
|
1778
|
+
};
|
|
1779
|
+
}
|
|
1780
|
+
async setActiveBranch(chatId, branchId) {
|
|
1781
|
+
this.#db.prepare("UPDATE branches SET isActive = 0 WHERE chatId = ?").run(chatId);
|
|
1782
|
+
this.#db.prepare("UPDATE branches SET isActive = 1 WHERE id = ?").run(branchId);
|
|
1783
|
+
}
|
|
1784
|
+
async updateBranchHead(branchId, messageId) {
|
|
1785
|
+
this.#db.prepare("UPDATE branches SET headMessageId = ? WHERE id = ?").run(messageId, branchId);
|
|
1786
|
+
}
|
|
1787
|
+
async listBranches(chatId) {
|
|
1788
|
+
const branches = this.#db.prepare(
|
|
1789
|
+
`SELECT
|
|
1790
|
+
b.id,
|
|
1791
|
+
b.name,
|
|
1792
|
+
b.headMessageId,
|
|
1793
|
+
b.isActive,
|
|
1794
|
+
b.createdAt
|
|
1795
|
+
FROM branches b
|
|
1796
|
+
WHERE b.chatId = ?
|
|
1797
|
+
ORDER BY b.createdAt ASC`
|
|
1798
|
+
).all(chatId);
|
|
1799
|
+
const result = [];
|
|
1800
|
+
for (const branch of branches) {
|
|
1801
|
+
let messageCount = 0;
|
|
1802
|
+
if (branch.headMessageId) {
|
|
1803
|
+
const countRow = this.#db.prepare(
|
|
1804
|
+
`WITH RECURSIVE chain AS (
|
|
1805
|
+
SELECT id, parentId FROM messages WHERE id = ?
|
|
1806
|
+
UNION ALL
|
|
1807
|
+
SELECT m.id, m.parentId FROM messages m
|
|
1808
|
+
INNER JOIN chain c ON m.id = c.parentId
|
|
1809
|
+
)
|
|
1810
|
+
SELECT COUNT(*) as count FROM chain`
|
|
1811
|
+
).get(branch.headMessageId);
|
|
1812
|
+
messageCount = countRow.count;
|
|
1813
|
+
}
|
|
1814
|
+
result.push({
|
|
1815
|
+
id: branch.id,
|
|
1816
|
+
name: branch.name,
|
|
1817
|
+
headMessageId: branch.headMessageId,
|
|
1818
|
+
isActive: branch.isActive === 1,
|
|
1819
|
+
messageCount,
|
|
1820
|
+
createdAt: branch.createdAt
|
|
1821
|
+
});
|
|
1822
|
+
}
|
|
1823
|
+
return result;
|
|
1824
|
+
}
|
|
1825
|
+
// ==========================================================================
|
|
1826
|
+
// Checkpoint Operations
|
|
1827
|
+
// ==========================================================================
|
|
1828
|
+
async createCheckpoint(checkpoint) {
|
|
1829
|
+
this.#db.prepare(
|
|
1830
|
+
`INSERT INTO checkpoints (id, chatId, name, messageId, createdAt)
|
|
1831
|
+
VALUES (?, ?, ?, ?, ?)
|
|
1832
|
+
ON CONFLICT(chatId, name) DO UPDATE SET
|
|
1833
|
+
messageId = excluded.messageId,
|
|
1834
|
+
createdAt = excluded.createdAt`
|
|
1835
|
+
).run(
|
|
1836
|
+
checkpoint.id,
|
|
1837
|
+
checkpoint.chatId,
|
|
1838
|
+
checkpoint.name,
|
|
1839
|
+
checkpoint.messageId,
|
|
1840
|
+
checkpoint.createdAt
|
|
1841
|
+
);
|
|
1842
|
+
}
|
|
1843
|
+
async getCheckpoint(chatId, name) {
|
|
1844
|
+
const row = this.#db.prepare("SELECT * FROM checkpoints WHERE chatId = ? AND name = ?").get(chatId, name);
|
|
1845
|
+
if (!row) {
|
|
1846
|
+
return void 0;
|
|
1847
|
+
}
|
|
1848
|
+
return {
|
|
1849
|
+
id: row.id,
|
|
1850
|
+
chatId: row.chatId,
|
|
1851
|
+
name: row.name,
|
|
1852
|
+
messageId: row.messageId,
|
|
1853
|
+
createdAt: row.createdAt
|
|
1854
|
+
};
|
|
1855
|
+
}
|
|
1856
|
+
async listCheckpoints(chatId) {
|
|
1857
|
+
const rows = this.#db.prepare(
|
|
1858
|
+
`SELECT id, name, messageId, createdAt
|
|
1859
|
+
FROM checkpoints
|
|
1860
|
+
WHERE chatId = ?
|
|
1861
|
+
ORDER BY createdAt DESC`
|
|
1862
|
+
).all(chatId);
|
|
1863
|
+
return rows.map((row) => ({
|
|
1864
|
+
id: row.id,
|
|
1865
|
+
name: row.name,
|
|
1866
|
+
messageId: row.messageId,
|
|
1867
|
+
createdAt: row.createdAt
|
|
1868
|
+
}));
|
|
1869
|
+
}
|
|
1870
|
+
async deleteCheckpoint(chatId, name) {
|
|
1871
|
+
this.#db.prepare("DELETE FROM checkpoints WHERE chatId = ? AND name = ?").run(chatId, name);
|
|
1872
|
+
}
|
|
1873
|
+
// ==========================================================================
|
|
1874
|
+
// Search Operations
|
|
1875
|
+
// ==========================================================================
|
|
1876
|
+
async searchMessages(chatId, query, options) {
|
|
1877
|
+
const limit = options?.limit ?? 20;
|
|
1878
|
+
const roles = options?.roles;
|
|
1879
|
+
let sql = `
|
|
1880
|
+
SELECT
|
|
1881
|
+
m.id,
|
|
1882
|
+
m.chatId,
|
|
1883
|
+
m.parentId,
|
|
1884
|
+
m.name,
|
|
1885
|
+
m.type,
|
|
1886
|
+
m.data,
|
|
1887
|
+
m.createdAt,
|
|
1888
|
+
fts.rank,
|
|
1889
|
+
snippet(messages_fts, 3, '<mark>', '</mark>', '...', 32) as snippet
|
|
1890
|
+
FROM messages_fts fts
|
|
1891
|
+
JOIN messages m ON m.id = fts.messageId
|
|
1892
|
+
WHERE messages_fts MATCH ?
|
|
1893
|
+
AND fts.chatId = ?
|
|
1894
|
+
`;
|
|
1895
|
+
const params = [query, chatId];
|
|
1896
|
+
if (roles && roles.length > 0) {
|
|
1897
|
+
const placeholders = roles.map(() => "?").join(", ");
|
|
1898
|
+
sql += ` AND fts.name IN (${placeholders})`;
|
|
1899
|
+
params.push(...roles);
|
|
1900
|
+
}
|
|
1901
|
+
sql += " ORDER BY fts.rank LIMIT ?";
|
|
1902
|
+
params.push(limit);
|
|
1903
|
+
const rows = this.#db.prepare(sql).all(...params);
|
|
1904
|
+
return rows.map((row) => ({
|
|
1905
|
+
message: {
|
|
1906
|
+
id: row.id,
|
|
1907
|
+
chatId: row.chatId,
|
|
1908
|
+
parentId: row.parentId,
|
|
1909
|
+
name: row.name,
|
|
1910
|
+
type: row.type ?? void 0,
|
|
1911
|
+
data: JSON.parse(row.data),
|
|
1912
|
+
createdAt: row.createdAt
|
|
1913
|
+
},
|
|
1914
|
+
rank: row.rank,
|
|
1915
|
+
snippet: row.snippet
|
|
1916
|
+
}));
|
|
1917
|
+
}
|
|
1918
|
+
// ==========================================================================
|
|
1919
|
+
// Visualization Operations
|
|
1920
|
+
// ==========================================================================
|
|
1921
|
+
async getGraph(chatId) {
|
|
1922
|
+
const messageRows = this.#db.prepare(
|
|
1923
|
+
`SELECT id, parentId, name, data, createdAt
|
|
1924
|
+
FROM messages
|
|
1925
|
+
WHERE chatId = ?
|
|
1926
|
+
ORDER BY createdAt ASC`
|
|
1927
|
+
).all(chatId);
|
|
1928
|
+
const nodes = messageRows.map((row) => {
|
|
1929
|
+
const data = JSON.parse(row.data);
|
|
1930
|
+
const content = typeof data === "string" ? data : JSON.stringify(data);
|
|
1931
|
+
return {
|
|
1932
|
+
id: row.id,
|
|
1933
|
+
parentId: row.parentId,
|
|
1934
|
+
role: row.name,
|
|
1935
|
+
content: content.length > 50 ? content.slice(0, 50) + "..." : content,
|
|
1936
|
+
createdAt: row.createdAt
|
|
1937
|
+
};
|
|
1938
|
+
});
|
|
1939
|
+
const branchRows = this.#db.prepare(
|
|
1940
|
+
`SELECT name, headMessageId, isActive
|
|
1941
|
+
FROM branches
|
|
1942
|
+
WHERE chatId = ?
|
|
1943
|
+
ORDER BY createdAt ASC`
|
|
1944
|
+
).all(chatId);
|
|
1945
|
+
const branches = branchRows.map((row) => ({
|
|
1946
|
+
name: row.name,
|
|
1947
|
+
headMessageId: row.headMessageId,
|
|
1948
|
+
isActive: row.isActive === 1
|
|
1949
|
+
}));
|
|
1950
|
+
const checkpointRows = this.#db.prepare(
|
|
1951
|
+
`SELECT name, messageId
|
|
1952
|
+
FROM checkpoints
|
|
1953
|
+
WHERE chatId = ?
|
|
1954
|
+
ORDER BY createdAt ASC`
|
|
1955
|
+
).all(chatId);
|
|
1956
|
+
const checkpoints = checkpointRows.map((row) => ({
|
|
1957
|
+
name: row.name,
|
|
1958
|
+
messageId: row.messageId
|
|
1959
|
+
}));
|
|
1960
|
+
return {
|
|
1961
|
+
chatId,
|
|
1962
|
+
nodes,
|
|
1963
|
+
branches,
|
|
1964
|
+
checkpoints
|
|
1965
|
+
};
|
|
1966
|
+
}
|
|
1967
|
+
};
|
|
1968
|
+
var InMemoryContextStore = class extends SqliteContextStore {
|
|
1969
|
+
constructor() {
|
|
1970
|
+
super(":memory:");
|
|
1971
|
+
}
|
|
1972
|
+
};
|
|
1973
|
+
var Agent = class _Agent {
|
|
1974
|
+
#options;
|
|
1975
|
+
#guardrails = [];
|
|
1976
|
+
tools;
|
|
1977
|
+
constructor(options) {
|
|
1978
|
+
this.#options = options;
|
|
1979
|
+
this.tools = options.tools || {};
|
|
1980
|
+
this.#guardrails = options.guardrails || [];
|
|
1981
|
+
}
|
|
1982
|
+
async generate(contextVariables, config) {
|
|
1983
|
+
if (!this.#options.context) {
|
|
1984
|
+
throw new Error(`Agent ${this.#options.name} is missing a context.`);
|
|
1985
|
+
}
|
|
1986
|
+
if (!this.#options.model) {
|
|
1987
|
+
throw new Error(`Agent ${this.#options.name} is missing a model.`);
|
|
1988
|
+
}
|
|
1989
|
+
const { messages, systemPrompt } = await this.#options.context.resolve({
|
|
1990
|
+
renderer: new XmlRenderer()
|
|
1991
|
+
});
|
|
1992
|
+
return generateText({
|
|
1993
|
+
abortSignal: config?.abortSignal,
|
|
1994
|
+
providerOptions: this.#options.providerOptions,
|
|
1995
|
+
model: this.#options.model,
|
|
1996
|
+
system: systemPrompt,
|
|
1997
|
+
messages: await convertToModelMessages(messages),
|
|
1998
|
+
stopWhen: stepCountIs(25),
|
|
1999
|
+
tools: this.#options.tools,
|
|
2000
|
+
experimental_context: contextVariables,
|
|
2001
|
+
experimental_repairToolCall: repairToolCall,
|
|
2002
|
+
toolChoice: this.#options.toolChoice,
|
|
2003
|
+
onStepFinish: (step) => {
|
|
2004
|
+
const toolCall = step.toolCalls.at(-1);
|
|
2005
|
+
if (toolCall) {
|
|
2006
|
+
console.log(
|
|
2007
|
+
`Debug: ${chalk2.yellow("ToolCalled")}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`
|
|
2008
|
+
);
|
|
2009
|
+
}
|
|
269
2010
|
}
|
|
270
|
-
})
|
|
2011
|
+
});
|
|
2012
|
+
}
|
|
2013
|
+
/**
|
|
2014
|
+
* Stream a response from the agent.
|
|
2015
|
+
*
|
|
2016
|
+
* When guardrails are configured, `toUIMessageStream()` is wrapped to provide
|
|
2017
|
+
* self-correction behavior. Direct access to fullStream/textStream bypasses guardrails.
|
|
2018
|
+
*
|
|
2019
|
+
* @example
|
|
2020
|
+
* ```typescript
|
|
2021
|
+
* const stream = await agent.stream({});
|
|
2022
|
+
*
|
|
2023
|
+
* // With guardrails - use toUIMessageStream for protection
|
|
2024
|
+
* await printer.readableStream(stream.toUIMessageStream());
|
|
2025
|
+
*
|
|
2026
|
+
* // Or use printer.stdout which uses toUIMessageStream internally
|
|
2027
|
+
* await printer.stdout(stream);
|
|
2028
|
+
* ```
|
|
2029
|
+
*/
|
|
2030
|
+
async stream(contextVariables, config) {
|
|
2031
|
+
if (!this.#options.context) {
|
|
2032
|
+
throw new Error(`Agent ${this.#options.name} is missing a context.`);
|
|
2033
|
+
}
|
|
2034
|
+
if (!this.#options.model) {
|
|
2035
|
+
throw new Error(`Agent ${this.#options.name} is missing a model.`);
|
|
2036
|
+
}
|
|
2037
|
+
const result = await this.#createRawStream(contextVariables, config);
|
|
2038
|
+
if (this.#guardrails.length === 0) {
|
|
2039
|
+
return result;
|
|
2040
|
+
}
|
|
2041
|
+
return this.#wrapWithGuardrails(result, contextVariables, config);
|
|
2042
|
+
}
|
|
2043
|
+
/**
|
|
2044
|
+
* Create a raw stream without guardrail processing.
|
|
2045
|
+
*/
|
|
2046
|
+
async #createRawStream(contextVariables, config) {
|
|
2047
|
+
const { messages, systemPrompt } = await this.#options.context.resolve({
|
|
2048
|
+
renderer: new XmlRenderer()
|
|
2049
|
+
});
|
|
2050
|
+
const runId = generateId2();
|
|
2051
|
+
return streamText({
|
|
2052
|
+
abortSignal: config?.abortSignal,
|
|
2053
|
+
providerOptions: this.#options.providerOptions,
|
|
2054
|
+
model: this.#options.model,
|
|
2055
|
+
system: systemPrompt,
|
|
2056
|
+
messages: await convertToModelMessages(messages),
|
|
2057
|
+
experimental_repairToolCall: repairToolCall,
|
|
2058
|
+
stopWhen: stepCountIs(50),
|
|
2059
|
+
experimental_transform: config?.transform ?? smoothStream(),
|
|
2060
|
+
tools: this.#options.tools,
|
|
2061
|
+
experimental_context: contextVariables,
|
|
2062
|
+
toolChoice: this.#options.toolChoice,
|
|
2063
|
+
onStepFinish: (step) => {
|
|
2064
|
+
const toolCall = step.toolCalls.at(-1);
|
|
2065
|
+
if (toolCall) {
|
|
2066
|
+
console.log(
|
|
2067
|
+
`Debug: (${runId}) ${chalk2.bold.yellow("ToolCalled")}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`
|
|
2068
|
+
);
|
|
2069
|
+
}
|
|
2070
|
+
}
|
|
2071
|
+
});
|
|
2072
|
+
}
|
|
2073
|
+
/**
|
|
2074
|
+
* Wrap a StreamTextResult with guardrail protection on toUIMessageStream().
|
|
2075
|
+
*
|
|
2076
|
+
* When a guardrail fails:
|
|
2077
|
+
* 1. Accumulated text + feedback is appended as the assistant's self-correction
|
|
2078
|
+
* 2. The feedback is written to the output stream (user sees the correction)
|
|
2079
|
+
* 3. A new stream is started and the model continues from the correction
|
|
2080
|
+
*/
|
|
2081
|
+
#wrapWithGuardrails(result, contextVariables, config) {
|
|
2082
|
+
const maxRetries = config?.maxRetries ?? this.#options.maxGuardrailRetries ?? 3;
|
|
2083
|
+
const context = this.#options.context;
|
|
2084
|
+
const originalToUIMessageStream = result.toUIMessageStream.bind(result);
|
|
2085
|
+
result.toUIMessageStream = (options) => {
|
|
2086
|
+
return createUIMessageStream({
|
|
2087
|
+
generateId: generateId2,
|
|
2088
|
+
execute: async ({ writer }) => {
|
|
2089
|
+
let currentResult = result;
|
|
2090
|
+
let attempt = 0;
|
|
2091
|
+
const guardrailContext = {
|
|
2092
|
+
availableTools: Object.keys(this.tools)
|
|
2093
|
+
};
|
|
2094
|
+
while (attempt < maxRetries) {
|
|
2095
|
+
if (config?.abortSignal?.aborted) {
|
|
2096
|
+
writer.write({ type: "finish" });
|
|
2097
|
+
return;
|
|
2098
|
+
}
|
|
2099
|
+
attempt++;
|
|
2100
|
+
let accumulatedText = "";
|
|
2101
|
+
let guardrailFailed = false;
|
|
2102
|
+
let failureFeedback = "";
|
|
2103
|
+
const uiStream = currentResult === result ? originalToUIMessageStream(options) : currentResult.toUIMessageStream(options);
|
|
2104
|
+
for await (const part of uiStream) {
|
|
2105
|
+
const checkResult = runGuardrailChain(
|
|
2106
|
+
part,
|
|
2107
|
+
this.#guardrails,
|
|
2108
|
+
guardrailContext
|
|
2109
|
+
);
|
|
2110
|
+
if (checkResult.type === "fail") {
|
|
2111
|
+
guardrailFailed = true;
|
|
2112
|
+
failureFeedback = checkResult.feedback;
|
|
2113
|
+
console.log(
|
|
2114
|
+
chalk2.yellow(
|
|
2115
|
+
`[${this.#options.name}] Guardrail triggered (attempt ${attempt}/${maxRetries}): ${failureFeedback.slice(0, 50)}...`
|
|
2116
|
+
)
|
|
2117
|
+
);
|
|
2118
|
+
break;
|
|
2119
|
+
}
|
|
2120
|
+
if (checkResult.part.type === "text-delta") {
|
|
2121
|
+
accumulatedText += checkResult.part.delta;
|
|
2122
|
+
}
|
|
2123
|
+
writer.write(checkResult.part);
|
|
2124
|
+
}
|
|
2125
|
+
if (!guardrailFailed) {
|
|
2126
|
+
writer.write({ type: "finish" });
|
|
2127
|
+
return;
|
|
2128
|
+
}
|
|
2129
|
+
if (attempt >= maxRetries) {
|
|
2130
|
+
console.error(
|
|
2131
|
+
chalk2.red(
|
|
2132
|
+
`[${this.#options.name}] Guardrail retry limit (${maxRetries}) exceeded.`
|
|
2133
|
+
)
|
|
2134
|
+
);
|
|
2135
|
+
writer.write({ type: "finish" });
|
|
2136
|
+
return;
|
|
2137
|
+
}
|
|
2138
|
+
writeText(writer, failureFeedback);
|
|
2139
|
+
const selfCorrectionText = accumulatedText + " " + failureFeedback;
|
|
2140
|
+
context.set(lastAssistantMessage(selfCorrectionText));
|
|
2141
|
+
await context.save();
|
|
2142
|
+
currentResult = await this.#createRawStream(
|
|
2143
|
+
contextVariables,
|
|
2144
|
+
config
|
|
2145
|
+
);
|
|
2146
|
+
}
|
|
2147
|
+
},
|
|
2148
|
+
onError: (error) => {
|
|
2149
|
+
const message2 = error instanceof Error ? error.message : String(error);
|
|
2150
|
+
return `Stream failed: ${message2}`;
|
|
2151
|
+
}
|
|
2152
|
+
});
|
|
2153
|
+
};
|
|
2154
|
+
return result;
|
|
2155
|
+
}
|
|
2156
|
+
clone(overrides) {
|
|
2157
|
+
return new _Agent({
|
|
2158
|
+
...this.#options,
|
|
2159
|
+
...overrides
|
|
2160
|
+
});
|
|
2161
|
+
}
|
|
2162
|
+
};
|
|
2163
|
+
function agent(options) {
|
|
2164
|
+
return new Agent(options);
|
|
2165
|
+
}
|
|
2166
|
+
var repairToolCall = async ({
|
|
2167
|
+
toolCall,
|
|
2168
|
+
tools,
|
|
2169
|
+
inputSchema,
|
|
2170
|
+
error
|
|
2171
|
+
}) => {
|
|
2172
|
+
console.log(
|
|
2173
|
+
`Debug: ${chalk2.yellow("RepairingToolCall")}: ${toolCall.toolName}`,
|
|
2174
|
+
error.name
|
|
2175
|
+
);
|
|
2176
|
+
if (NoSuchToolError.isInstance(error)) {
|
|
2177
|
+
return null;
|
|
271
2178
|
}
|
|
272
|
-
|
|
2179
|
+
const tool2 = tools[toolCall.toolName];
|
|
2180
|
+
const { output } = await generateText({
|
|
2181
|
+
model: groq("openai/gpt-oss-20b"),
|
|
2182
|
+
output: Output.object({ schema: tool2.inputSchema }),
|
|
2183
|
+
prompt: [
|
|
2184
|
+
`The model tried to call the tool "${toolCall.toolName}" with the following inputs:`,
|
|
2185
|
+
JSON.stringify(toolCall.input),
|
|
2186
|
+
`The tool accepts the following schema:`,
|
|
2187
|
+
JSON.stringify(inputSchema(toolCall)),
|
|
2188
|
+
"Please fix the inputs."
|
|
2189
|
+
].join("\n")
|
|
2190
|
+
});
|
|
2191
|
+
return { ...toolCall, input: JSON.stringify(output) };
|
|
2192
|
+
};
|
|
2193
|
+
function writeText(writer, text) {
|
|
2194
|
+
const feedbackPartId = generateId2();
|
|
2195
|
+
writer.write({
|
|
2196
|
+
id: feedbackPartId,
|
|
2197
|
+
type: "text-start"
|
|
2198
|
+
});
|
|
2199
|
+
writer.write({
|
|
2200
|
+
id: feedbackPartId,
|
|
2201
|
+
type: "text-delta",
|
|
2202
|
+
delta: ` ${text}`
|
|
2203
|
+
});
|
|
2204
|
+
writer.write({
|
|
2205
|
+
id: feedbackPartId,
|
|
2206
|
+
type: "text-end"
|
|
2207
|
+
});
|
|
2208
|
+
}
|
|
2209
|
+
|
|
2210
|
+
// packages/text2sql/src/lib/adapters/groundings/report.grounding.ts
|
|
273
2211
|
var ReportGrounding = class extends AbstractGrounding {
|
|
274
2212
|
#adapter;
|
|
275
2213
|
#model;
|
|
@@ -278,7 +2216,7 @@ var ReportGrounding = class extends AbstractGrounding {
|
|
|
278
2216
|
constructor(adapter, config = {}) {
|
|
279
2217
|
super("business_context");
|
|
280
2218
|
this.#adapter = adapter;
|
|
281
|
-
this.#model = config.model ??
|
|
2219
|
+
this.#model = config.model ?? groq2("openai/gpt-oss-20b");
|
|
282
2220
|
this.#cache = config.cache;
|
|
283
2221
|
this.#forceRefresh = config.forceRefresh ?? false;
|
|
284
2222
|
}
|
|
@@ -297,16 +2235,62 @@ var ReportGrounding = class extends AbstractGrounding {
|
|
|
297
2235
|
}
|
|
298
2236
|
}
|
|
299
2237
|
async #generateReport() {
|
|
300
|
-
const
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
2238
|
+
const context = new ContextEngine({
|
|
2239
|
+
store: new InMemoryContextStore(),
|
|
2240
|
+
chatId: `report-gen-${crypto.randomUUID()}`,
|
|
2241
|
+
userId: "system"
|
|
2242
|
+
});
|
|
2243
|
+
context.set(
|
|
2244
|
+
persona({
|
|
2245
|
+
name: "db-report-agent",
|
|
2246
|
+
role: "Database analyst",
|
|
2247
|
+
objective: "Analyze the database and write a contextual report about what it represents"
|
|
2248
|
+
}),
|
|
2249
|
+
fragment(
|
|
2250
|
+
"instructions",
|
|
2251
|
+
dedent`
|
|
2252
|
+
Write a business context that helps another agent answer questions accurately.
|
|
2253
|
+
|
|
2254
|
+
For EACH table, do queries ONE AT A TIME:
|
|
2255
|
+
1. SELECT COUNT(*) to get row count
|
|
2256
|
+
2. SELECT * LIMIT 3 to see sample data
|
|
2257
|
+
|
|
2258
|
+
Then write a report with:
|
|
2259
|
+
- What business this database is for
|
|
2260
|
+
- For each table: purpose, row count, and example of what the data looks like
|
|
2261
|
+
|
|
2262
|
+
Include concrete examples like "Track prices are $0.99",
|
|
2263
|
+
"Customer names like 'Luís Gonçalves'", etc.
|
|
2264
|
+
|
|
2265
|
+
Keep it 400-600 words, conversational style.
|
|
2266
|
+
`
|
|
2267
|
+
),
|
|
2268
|
+
user(
|
|
2269
|
+
"Please analyze the database and write a contextual report about what this database represents."
|
|
2270
|
+
)
|
|
308
2271
|
);
|
|
309
|
-
|
|
2272
|
+
const adapter = this.#adapter;
|
|
2273
|
+
const reportAgent = agent({
|
|
2274
|
+
name: "db-report-agent",
|
|
2275
|
+
model: this.#model,
|
|
2276
|
+
context,
|
|
2277
|
+
tools: {
|
|
2278
|
+
query_database: tool({
|
|
2279
|
+
description: "Execute a SELECT query to explore the database and gather insights.",
|
|
2280
|
+
inputSchema: z.object({
|
|
2281
|
+
sql: z.string().describe("The SELECT query to execute"),
|
|
2282
|
+
purpose: z.string().describe(
|
|
2283
|
+
"What insight you are trying to gather with this query"
|
|
2284
|
+
)
|
|
2285
|
+
}),
|
|
2286
|
+
execute: ({ sql }) => {
|
|
2287
|
+
return adapter.execute(sql);
|
|
2288
|
+
}
|
|
2289
|
+
})
|
|
2290
|
+
}
|
|
2291
|
+
});
|
|
2292
|
+
const result = await reportAgent.generate({});
|
|
2293
|
+
return result.text;
|
|
310
2294
|
}
|
|
311
2295
|
};
|
|
312
2296
|
|