@deepagents/text2sql 0.13.1 → 0.15.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.
Files changed (67) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +2446 -2879
  4. package/dist/index.js.map +4 -4
  5. package/dist/lib/adapters/adapter.d.ts +2 -0
  6. package/dist/lib/adapters/adapter.d.ts.map +1 -1
  7. package/dist/lib/adapters/bigquery/bigquery.d.ts +41 -0
  8. package/dist/lib/adapters/bigquery/bigquery.d.ts.map +1 -0
  9. package/dist/lib/adapters/bigquery/constraint.bigquery.grounding.d.ts +11 -0
  10. package/dist/lib/adapters/bigquery/constraint.bigquery.grounding.d.ts.map +1 -0
  11. package/dist/lib/adapters/bigquery/index.d.ts +35 -0
  12. package/dist/lib/adapters/bigquery/index.d.ts.map +1 -0
  13. package/dist/lib/adapters/bigquery/index.js +1321 -0
  14. package/dist/lib/adapters/bigquery/index.js.map +7 -0
  15. package/dist/lib/adapters/bigquery/indexes.bigquery.grounding.d.ts +14 -0
  16. package/dist/lib/adapters/bigquery/indexes.bigquery.grounding.d.ts.map +1 -0
  17. package/dist/lib/adapters/bigquery/info.bigquery.grounding.d.ts +9 -0
  18. package/dist/lib/adapters/bigquery/info.bigquery.grounding.d.ts.map +1 -0
  19. package/dist/lib/adapters/bigquery/row-count.bigquery.grounding.d.ts +14 -0
  20. package/dist/lib/adapters/bigquery/row-count.bigquery.grounding.d.ts.map +1 -0
  21. package/dist/lib/adapters/bigquery/table.bigquery.grounding.d.ts +15 -0
  22. package/dist/lib/adapters/bigquery/table.bigquery.grounding.d.ts.map +1 -0
  23. package/dist/lib/adapters/bigquery/view.bigquery.grounding.d.ts +12 -0
  24. package/dist/lib/adapters/bigquery/view.bigquery.grounding.d.ts.map +1 -0
  25. package/dist/lib/adapters/groundings/index.js +9 -2044
  26. package/dist/lib/adapters/groundings/index.js.map +4 -4
  27. package/dist/lib/adapters/mysql/index.js +9 -2044
  28. package/dist/lib/adapters/mysql/index.js.map +4 -4
  29. package/dist/lib/adapters/postgres/column-stats.postgres.grounding.d.ts +2 -4
  30. package/dist/lib/adapters/postgres/column-stats.postgres.grounding.d.ts.map +1 -1
  31. package/dist/lib/adapters/postgres/column-values.postgres.grounding.d.ts +0 -8
  32. package/dist/lib/adapters/postgres/column-values.postgres.grounding.d.ts.map +1 -1
  33. package/dist/lib/adapters/postgres/index.js +140 -2056
  34. package/dist/lib/adapters/postgres/index.js.map +4 -4
  35. package/dist/lib/adapters/postgres/info.postgres.grounding.d.ts.map +1 -1
  36. package/dist/lib/adapters/postgres/row-count.postgres.grounding.d.ts +0 -3
  37. package/dist/lib/adapters/postgres/row-count.postgres.grounding.d.ts.map +1 -1
  38. package/dist/lib/adapters/spreadsheet/index.js +10 -35
  39. package/dist/lib/adapters/spreadsheet/index.js.map +4 -4
  40. package/dist/lib/adapters/sqlite/index.js +9 -2044
  41. package/dist/lib/adapters/sqlite/index.js.map +4 -4
  42. package/dist/lib/adapters/sqlserver/index.js +9 -2044
  43. package/dist/lib/adapters/sqlserver/index.js.map +4 -4
  44. package/dist/lib/agents/result-tools.d.ts +18 -23
  45. package/dist/lib/agents/result-tools.d.ts.map +1 -1
  46. package/dist/lib/fragments/schema.d.ts +2 -0
  47. package/dist/lib/fragments/schema.d.ts.map +1 -1
  48. package/dist/lib/fs/index.d.ts +5 -0
  49. package/dist/lib/fs/index.d.ts.map +1 -0
  50. package/dist/lib/fs/mssql/ddl.mssql-fs.d.ts +2 -0
  51. package/dist/lib/fs/mssql/ddl.mssql-fs.d.ts.map +1 -0
  52. package/dist/lib/fs/mssql/mssql-fs.d.ts +56 -0
  53. package/dist/lib/fs/mssql/mssql-fs.d.ts.map +1 -0
  54. package/dist/lib/fs/scoped-fs.d.ts +55 -0
  55. package/dist/lib/fs/scoped-fs.d.ts.map +1 -0
  56. package/dist/lib/fs/sqlite/sqlite-fs.d.ts +68 -0
  57. package/dist/lib/fs/sqlite/sqlite-fs.d.ts.map +1 -0
  58. package/dist/lib/fs/tracked-fs.d.ts +42 -0
  59. package/dist/lib/fs/tracked-fs.d.ts.map +1 -0
  60. package/dist/lib/instructions.d.ts.map +1 -1
  61. package/dist/lib/sql.d.ts +5 -6
  62. package/dist/lib/sql.d.ts.map +1 -1
  63. package/dist/lib/synthesis/index.js +223 -2088
  64. package/dist/lib/synthesis/index.js.map +4 -4
  65. package/package.json +18 -11
  66. package/dist/lib/agents/text2sql.agent.d.ts +0 -3
  67. package/dist/lib/agents/text2sql.agent.d.ts.map +0 -1
@@ -165,1968 +165,22 @@ import {
165
165
  } from "ai";
166
166
 
167
167
  // packages/text2sql/src/lib/synthesis/extractors/base-contextual-extractor.ts
168
- import { groq as groq2 } from "@ai-sdk/groq";
169
- import {
170
- getToolOrDynamicToolName,
171
- isTextUIPart,
172
- isToolOrDynamicToolUIPart
173
- } from "ai";
174
- import dedent from "dedent";
175
- import z from "zod";
176
-
177
- // packages/context/dist/index.js
178
- import { mergeWith } from "lodash-es";
179
- import { encode } from "gpt-tokenizer";
180
- import { generateId } from "ai";
181
- import pluralize from "pluralize";
182
- import { titlecase } from "stringcase";
183
- import chalk from "chalk";
184
- import { defineCommand } from "just-bash";
185
- import spawn from "nano-spawn";
186
- import "bash-tool";
187
- import spawn2 from "nano-spawn";
188
- import {
189
- createBashTool
190
- } from "bash-tool";
191
- import YAML from "yaml";
192
- import { DatabaseSync } from "node:sqlite";
193
- import { groq } from "@ai-sdk/groq";
194
- import {
195
- NoSuchToolError,
196
- Output,
197
- convertToModelMessages,
198
- createUIMessageStream,
199
- generateId as generateId2,
200
- generateText,
201
- smoothStream,
202
- stepCountIs,
203
- streamText
204
- } from "ai";
205
- import chalk2 from "chalk";
206
- import "zod";
207
- import "@deepagents/agent";
208
- var defaultTokenizer = {
209
- encode(text) {
210
- return encode(text);
211
- },
212
- count(text) {
213
- return encode(text).length;
214
- }
215
- };
216
- var ModelsRegistry = class {
217
- #cache = /* @__PURE__ */ new Map();
218
- #loaded = false;
219
- #tokenizers = /* @__PURE__ */ new Map();
220
- #defaultTokenizer = defaultTokenizer;
221
- /**
222
- * Load models data from models.dev API
223
- */
224
- async load() {
225
- if (this.#loaded) return;
226
- const response = await fetch("https://models.dev/api.json");
227
- if (!response.ok) {
228
- throw new Error(`Failed to fetch models: ${response.statusText}`);
229
- }
230
- const data = await response.json();
231
- for (const [providerId, provider] of Object.entries(data)) {
232
- for (const [modelId, model] of Object.entries(provider.models)) {
233
- const info = {
234
- id: model.id,
235
- name: model.name,
236
- family: model.family,
237
- cost: model.cost,
238
- limit: model.limit,
239
- provider: providerId
240
- };
241
- this.#cache.set(`${providerId}:${modelId}`, info);
242
- }
243
- }
244
- this.#loaded = true;
245
- }
246
- /**
247
- * Get model info by ID
248
- * @param modelId - Model ID (e.g., "openai:gpt-4o")
249
- */
250
- get(modelId) {
251
- return this.#cache.get(modelId);
252
- }
253
- /**
254
- * Check if a model exists in the registry
255
- */
256
- has(modelId) {
257
- return this.#cache.has(modelId);
258
- }
259
- /**
260
- * List all available model IDs
261
- */
262
- list() {
263
- return [...this.#cache.keys()];
264
- }
265
- /**
266
- * Register a custom tokenizer for specific model families
267
- * @param family - Model family name (e.g., "llama", "claude")
268
- * @param tokenizer - Tokenizer implementation
269
- */
270
- registerTokenizer(family, tokenizer) {
271
- this.#tokenizers.set(family, tokenizer);
272
- }
273
- /**
274
- * Set the default tokenizer used when no family-specific tokenizer is registered
275
- */
276
- setDefaultTokenizer(tokenizer) {
277
- this.#defaultTokenizer = tokenizer;
278
- }
279
- /**
280
- * Get the appropriate tokenizer for a model
281
- */
282
- getTokenizer(modelId) {
283
- const model = this.get(modelId);
284
- if (model) {
285
- const familyTokenizer = this.#tokenizers.get(model.family);
286
- if (familyTokenizer) {
287
- return familyTokenizer;
288
- }
289
- }
290
- return this.#defaultTokenizer;
291
- }
292
- /**
293
- * Estimate token count and cost for given text and model
294
- * @param modelId - Model ID to use for pricing (e.g., "openai:gpt-4o")
295
- * @param input - Input text (prompt)
296
- */
297
- estimate(modelId, input) {
298
- const model = this.get(modelId);
299
- if (!model) {
300
- throw new Error(
301
- `Model "${modelId}" not found. Call load() first or check model ID.`
302
- );
303
- }
304
- const tokenizer = this.getTokenizer(modelId);
305
- const tokens = tokenizer.count(input);
306
- const cost = tokens / 1e6 * model.cost.input;
307
- return {
308
- model: model.id,
309
- provider: model.provider,
310
- tokens,
311
- cost,
312
- limits: {
313
- context: model.limit.context,
314
- output: model.limit.output,
315
- exceedsContext: tokens > model.limit.context
316
- },
317
- fragments: []
318
- };
319
- }
320
- };
321
- var _registry = null;
322
- function getModelsRegistry() {
323
- if (!_registry) {
324
- _registry = new ModelsRegistry();
325
- }
326
- return _registry;
327
- }
328
- function isFragment(data) {
329
- return typeof data === "object" && data !== null && "name" in data && "data" in data && typeof data.name === "string";
330
- }
331
- function isFragmentObject(data) {
332
- return typeof data === "object" && data !== null && !Array.isArray(data) && !isFragment(data);
333
- }
334
- function isMessageFragment(fragment2) {
335
- return fragment2.type === "message";
336
- }
337
- function fragment(name, ...children) {
338
- return {
339
- name,
340
- data: children
341
- };
342
- }
343
- function user(content) {
344
- const message2 = typeof content === "string" ? {
345
- id: generateId(),
346
- role: "user",
347
- parts: [{ type: "text", text: content }]
348
- } : content;
349
- return {
350
- id: message2.id,
351
- name: "user",
352
- data: "content",
353
- type: "message",
354
- persist: true,
355
- codec: {
356
- decode() {
357
- return message2;
358
- },
359
- encode() {
360
- return message2;
361
- }
362
- }
363
- };
364
- }
365
- function assistant(message2) {
366
- return {
367
- id: message2.id,
368
- name: "assistant",
369
- data: "content",
370
- type: "message",
371
- persist: true,
372
- codec: {
373
- decode() {
374
- return message2;
375
- },
376
- encode() {
377
- return message2;
378
- }
379
- }
380
- };
381
- }
382
- function message(content) {
383
- const message2 = typeof content === "string" ? {
384
- id: generateId(),
385
- role: "user",
386
- parts: [{ type: "text", text: content }]
387
- } : content;
388
- return {
389
- id: message2.id,
390
- name: message2.role,
391
- data: "content",
392
- type: "message",
393
- persist: true,
394
- codec: {
395
- decode() {
396
- return message2;
397
- },
398
- encode() {
399
- return message2;
400
- }
401
- }
402
- };
403
- }
404
- function assistantText(content, options) {
405
- const id = options?.id ?? crypto.randomUUID();
406
- return assistant({
407
- id,
408
- role: "assistant",
409
- parts: [{ type: "text", text: content }]
410
- });
411
- }
412
- var LAZY_ID = Symbol("lazy-id");
413
- function isLazyFragment(fragment2) {
414
- return LAZY_ID in fragment2;
415
- }
416
- var ContextRenderer = class {
417
- options;
418
- constructor(options = {}) {
419
- this.options = options;
420
- }
421
- /**
422
- * Check if data is a primitive (string, number, boolean).
423
- */
424
- isPrimitive(data) {
425
- return typeof data === "string" || typeof data === "number" || typeof data === "boolean";
426
- }
427
- /**
428
- * Group fragments by name for groupFragments option.
429
- */
430
- groupByName(fragments) {
431
- const groups = /* @__PURE__ */ new Map();
432
- for (const fragment2 of fragments) {
433
- const existing = groups.get(fragment2.name) ?? [];
434
- existing.push(fragment2);
435
- groups.set(fragment2.name, existing);
436
- }
437
- return groups;
438
- }
439
- /**
440
- * Remove null/undefined from fragments and fragment data recursively.
441
- * This protects renderers from nullish values and ensures they are ignored
442
- * consistently across all output formats.
443
- */
444
- sanitizeFragments(fragments) {
445
- const sanitized = [];
446
- for (const fragment2 of fragments) {
447
- const cleaned = this.sanitizeFragment(fragment2, /* @__PURE__ */ new WeakSet());
448
- if (cleaned) {
449
- sanitized.push(cleaned);
450
- }
451
- }
452
- return sanitized;
453
- }
454
- sanitizeFragment(fragment2, seen) {
455
- const data = this.sanitizeData(fragment2.data, seen);
456
- if (data == null) {
457
- return null;
458
- }
459
- return {
460
- ...fragment2,
461
- data
462
- };
463
- }
464
- sanitizeData(data, seen) {
465
- if (data == null) {
466
- return void 0;
467
- }
468
- if (isFragment(data)) {
469
- return this.sanitizeFragment(data, seen) ?? void 0;
470
- }
471
- if (Array.isArray(data)) {
472
- if (seen.has(data)) {
473
- return void 0;
474
- }
475
- seen.add(data);
476
- const cleaned = [];
477
- for (const item of data) {
478
- const sanitizedItem = this.sanitizeData(item, seen);
479
- if (sanitizedItem != null) {
480
- cleaned.push(sanitizedItem);
481
- }
482
- }
483
- return cleaned;
484
- }
485
- if (isFragmentObject(data)) {
486
- if (seen.has(data)) {
487
- return void 0;
488
- }
489
- seen.add(data);
490
- const cleaned = {};
491
- for (const [key, value] of Object.entries(data)) {
492
- const sanitizedValue = this.sanitizeData(value, seen);
493
- if (sanitizedValue != null) {
494
- cleaned[key] = sanitizedValue;
495
- }
496
- }
497
- return cleaned;
498
- }
499
- return data;
500
- }
501
- /**
502
- * Template method - dispatches value to appropriate handler.
503
- */
504
- renderValue(key, value, ctx) {
505
- if (value == null) {
506
- return "";
507
- }
508
- if (isFragment(value)) {
509
- return this.renderFragment(value, ctx);
510
- }
511
- if (Array.isArray(value)) {
512
- return this.renderArray(key, value, ctx);
513
- }
514
- if (isFragmentObject(value)) {
515
- return this.renderObject(key, value, ctx);
516
- }
517
- return this.renderPrimitive(key, String(value), ctx);
518
- }
519
- /**
520
- * Render all entries of an object.
521
- */
522
- renderEntries(data, ctx) {
523
- return Object.entries(data).map(([key, value]) => this.renderValue(key, value, ctx)).filter(Boolean);
524
- }
525
- };
526
- var XmlRenderer = class extends ContextRenderer {
527
- render(fragments) {
528
- const sanitized = this.sanitizeFragments(fragments);
529
- return sanitized.map((f) => this.#renderTopLevel(f)).filter(Boolean).join("\n");
530
- }
531
- #renderTopLevel(fragment2) {
532
- if (this.isPrimitive(fragment2.data)) {
533
- return this.#leafRoot(fragment2.name, String(fragment2.data));
534
- }
535
- if (Array.isArray(fragment2.data)) {
536
- return this.#renderArray(fragment2.name, fragment2.data, 0);
537
- }
538
- if (isFragment(fragment2.data)) {
539
- const child = this.renderFragment(fragment2.data, { depth: 1, path: [] });
540
- return this.#wrap(fragment2.name, [child]);
541
- }
542
- if (isFragmentObject(fragment2.data)) {
543
- return this.#wrap(
544
- fragment2.name,
545
- this.renderEntries(fragment2.data, { depth: 1, path: [] })
546
- );
547
- }
548
- return "";
549
- }
550
- #renderArray(name, items, depth) {
551
- const fragmentItems = items.filter(isFragment);
552
- const nonFragmentItems = items.filter((item) => !isFragment(item));
553
- const children = [];
554
- for (const item of nonFragmentItems) {
555
- if (item != null) {
556
- if (isFragmentObject(item)) {
557
- children.push(
558
- this.#wrapIndented(
559
- pluralize.singular(name),
560
- this.renderEntries(item, { depth: depth + 2, path: [] }),
561
- depth + 1
562
- )
563
- );
564
- } else {
565
- children.push(
566
- this.#leaf(pluralize.singular(name), String(item), depth + 1)
567
- );
568
- }
569
- }
570
- }
571
- if (this.options.groupFragments && fragmentItems.length > 0) {
572
- const groups = this.groupByName(fragmentItems);
573
- for (const [groupName, groupFragments] of groups) {
574
- const groupChildren = groupFragments.map(
575
- (frag) => this.renderFragment(frag, { depth: depth + 2, path: [] })
576
- );
577
- const pluralName = pluralize.plural(groupName);
578
- children.push(this.#wrapIndented(pluralName, groupChildren, depth + 1));
579
- }
580
- } else {
581
- for (const frag of fragmentItems) {
582
- children.push(
583
- this.renderFragment(frag, { depth: depth + 1, path: [] })
584
- );
585
- }
586
- }
587
- return this.#wrap(name, children);
588
- }
589
- #leafRoot(tag, value) {
590
- const safe = this.#escape(value);
591
- if (safe.includes("\n")) {
592
- return `<${tag}>
593
- ${this.#indent(safe, 2)}
594
- </${tag}>`;
595
- }
596
- return `<${tag}>${safe}</${tag}>`;
597
- }
598
- renderFragment(fragment2, ctx) {
599
- const { name, data } = fragment2;
600
- if (this.isPrimitive(data)) {
601
- return this.#leaf(name, String(data), ctx.depth);
602
- }
603
- if (isFragment(data)) {
604
- const child = this.renderFragment(data, { ...ctx, depth: ctx.depth + 1 });
605
- return this.#wrapIndented(name, [child], ctx.depth);
606
- }
607
- if (Array.isArray(data)) {
608
- return this.#renderArrayIndented(name, data, ctx.depth);
609
- }
610
- if (isFragmentObject(data)) {
611
- const children = this.renderEntries(data, {
612
- ...ctx,
613
- depth: ctx.depth + 1
614
- });
615
- return this.#wrapIndented(name, children, ctx.depth);
616
- }
617
- return "";
618
- }
619
- #renderArrayIndented(name, items, depth) {
620
- const fragmentItems = items.filter(isFragment);
621
- const nonFragmentItems = items.filter((item) => !isFragment(item));
622
- const children = [];
623
- for (const item of nonFragmentItems) {
624
- if (item != null) {
625
- if (isFragmentObject(item)) {
626
- children.push(
627
- this.#wrapIndented(
628
- pluralize.singular(name),
629
- this.renderEntries(item, { depth: depth + 2, path: [] }),
630
- depth + 1
631
- )
632
- );
633
- } else {
634
- children.push(
635
- this.#leaf(pluralize.singular(name), String(item), depth + 1)
636
- );
637
- }
638
- }
639
- }
640
- if (this.options.groupFragments && fragmentItems.length > 0) {
641
- const groups = this.groupByName(fragmentItems);
642
- for (const [groupName, groupFragments] of groups) {
643
- const groupChildren = groupFragments.map(
644
- (frag) => this.renderFragment(frag, { depth: depth + 2, path: [] })
645
- );
646
- const pluralName = pluralize.plural(groupName);
647
- children.push(this.#wrapIndented(pluralName, groupChildren, depth + 1));
648
- }
649
- } else {
650
- for (const frag of fragmentItems) {
651
- children.push(
652
- this.renderFragment(frag, { depth: depth + 1, path: [] })
653
- );
654
- }
655
- }
656
- return this.#wrapIndented(name, children, depth);
657
- }
658
- renderPrimitive(key, value, ctx) {
659
- return this.#leaf(key, value, ctx.depth);
660
- }
661
- renderArray(key, items, ctx) {
662
- if (!items.length) {
663
- return "";
664
- }
665
- const itemTag = pluralize.singular(key);
666
- const children = items.filter((item) => item != null).map((item) => {
667
- if (isFragment(item)) {
668
- return this.renderFragment(item, { ...ctx, depth: ctx.depth + 1 });
669
- }
670
- if (isFragmentObject(item)) {
671
- return this.#wrapIndented(
672
- itemTag,
673
- this.renderEntries(item, { ...ctx, depth: ctx.depth + 2 }),
674
- ctx.depth + 1
675
- );
676
- }
677
- return this.#leaf(itemTag, String(item), ctx.depth + 1);
678
- });
679
- return this.#wrapIndented(key, children, ctx.depth);
680
- }
681
- renderObject(key, obj, ctx) {
682
- const children = this.renderEntries(obj, { ...ctx, depth: ctx.depth + 1 });
683
- return this.#wrapIndented(key, children, ctx.depth);
684
- }
685
- #escape(value) {
686
- if (value == null) {
687
- return "";
688
- }
689
- return value.replaceAll(/&/g, "&amp;").replaceAll(/</g, "&lt;").replaceAll(/>/g, "&gt;").replaceAll(/"/g, "&quot;").replaceAll(/'/g, "&apos;");
690
- }
691
- #indent(text, spaces) {
692
- if (!text.trim()) {
693
- return "";
694
- }
695
- const padding = " ".repeat(spaces);
696
- return text.split("\n").map((line) => line.length ? padding + line : padding).join("\n");
697
- }
698
- #leaf(tag, value, depth) {
699
- const safe = this.#escape(value);
700
- const pad = " ".repeat(depth);
701
- if (safe.includes("\n")) {
702
- return `${pad}<${tag}>
703
- ${this.#indent(safe, (depth + 1) * 2)}
704
- ${pad}</${tag}>`;
705
- }
706
- return `${pad}<${tag}>${safe}</${tag}>`;
707
- }
708
- #wrap(tag, children) {
709
- const content = children.filter(Boolean).join("\n");
710
- if (!content) {
711
- return "";
712
- }
713
- return `<${tag}>
714
- ${content}
715
- </${tag}>`;
716
- }
717
- #wrapIndented(tag, children, depth) {
718
- const content = children.filter(Boolean).join("\n");
719
- if (!content) {
720
- return "";
721
- }
722
- const pad = " ".repeat(depth);
723
- return `${pad}<${tag}>
724
- ${content}
725
- ${pad}</${tag}>`;
726
- }
727
- };
728
- var ContextStore = class {
729
- };
730
- var ContextEngine = class {
731
- /** Non-message fragments (role, hints, etc.) - not persisted in graph */
732
- #fragments = [];
733
- /** Pending message fragments to be added to graph */
734
- #pendingMessages = [];
735
- #store;
736
- #chatId;
737
- #userId;
738
- #branchName;
739
- #branch = null;
740
- #chatData = null;
741
- #initialized = false;
742
- /** Initial metadata to merge on first initialization */
743
- #initialMetadata;
744
- constructor(options) {
745
- if (!options.chatId) {
746
- throw new Error("chatId is required");
747
- }
748
- if (!options.userId) {
749
- throw new Error("userId is required");
750
- }
751
- this.#store = options.store;
752
- this.#chatId = options.chatId;
753
- this.#userId = options.userId;
754
- this.#branchName = "main";
755
- this.#initialMetadata = options.metadata;
756
- }
757
- /**
758
- * Initialize the chat and branch if they don't exist.
759
- */
760
- async #ensureInitialized() {
761
- if (this.#initialized) {
762
- return;
763
- }
764
- this.#chatData = await this.#store.upsertChat({
765
- id: this.#chatId,
766
- userId: this.#userId
767
- });
768
- if (this.#initialMetadata) {
769
- this.#chatData = await this.#store.updateChat(this.#chatId, {
770
- metadata: {
771
- ...this.#chatData.metadata,
772
- ...this.#initialMetadata
773
- }
774
- });
775
- this.#initialMetadata = void 0;
776
- }
777
- this.#branch = await this.#store.getActiveBranch(this.#chatId);
778
- this.#initialized = true;
779
- }
780
- /**
781
- * Create a new branch from a specific message.
782
- * Shared logic between rewind() and btw().
783
- */
784
- async #createBranchFrom(messageId, switchTo) {
785
- const branches = await this.#store.listBranches(this.#chatId);
786
- const samePrefix = branches.filter(
787
- (b) => b.name === this.#branchName || b.name.startsWith(`${this.#branchName}-v`)
788
- );
789
- const newBranchName = `${this.#branchName}-v${samePrefix.length + 1}`;
790
- const newBranch = {
791
- id: crypto.randomUUID(),
792
- chatId: this.#chatId,
793
- name: newBranchName,
794
- headMessageId: messageId,
795
- isActive: false,
796
- createdAt: Date.now()
797
- };
798
- await this.#store.createBranch(newBranch);
799
- if (switchTo) {
800
- await this.#store.setActiveBranch(this.#chatId, newBranch.id);
801
- this.#branch = { ...newBranch, isActive: true };
802
- this.#branchName = newBranchName;
803
- this.#pendingMessages = [];
804
- }
805
- const chain = await this.#store.getMessageChain(messageId);
806
- return {
807
- id: newBranch.id,
808
- name: newBranch.name,
809
- headMessageId: newBranch.headMessageId,
810
- isActive: switchTo,
811
- messageCount: chain.length,
812
- createdAt: newBranch.createdAt
813
- };
814
- }
815
- /**
816
- * Get the current chat ID.
817
- */
818
- get chatId() {
819
- return this.#chatId;
820
- }
821
- /**
822
- * Get the current branch name.
823
- */
824
- get branch() {
825
- return this.#branchName;
826
- }
827
- /**
828
- * Get metadata for the current chat.
829
- * Returns null if the chat hasn't been initialized yet.
830
- */
831
- get chat() {
832
- if (!this.#chatData) {
833
- return null;
834
- }
835
- return {
836
- id: this.#chatData.id,
837
- userId: this.#chatData.userId,
838
- createdAt: this.#chatData.createdAt,
839
- updatedAt: this.#chatData.updatedAt,
840
- title: this.#chatData.title,
841
- metadata: this.#chatData.metadata
842
- };
843
- }
844
- /**
845
- * Add fragments to the context.
846
- *
847
- * - Message fragments (user/assistant) are queued for persistence
848
- * - Non-message fragments (role/hint) are kept in memory for system prompt
849
- */
850
- set(...fragments) {
851
- for (const fragment2 of fragments) {
852
- if (isMessageFragment(fragment2)) {
853
- this.#pendingMessages.push(fragment2);
854
- } else {
855
- this.#fragments.push(fragment2);
856
- }
857
- }
858
- return this;
859
- }
860
- // Unset a fragment by ID (not implemented yet)
861
- unset(fragmentId) {
862
- }
863
- /**
864
- * Render all fragments using the provided renderer.
865
- * @internal Use resolve() instead for public API.
866
- */
867
- render(renderer) {
868
- return renderer.render(this.#fragments);
869
- }
870
- /**
871
- * Resolve context into AI SDK-ready format.
872
- *
873
- * - Initializes chat and branch if needed
874
- * - Loads message history from the graph (walking parent chain)
875
- * - Separates context fragments for system prompt
876
- * - Combines with pending messages
877
- *
878
- * @example
879
- * ```ts
880
- * const context = new ContextEngine({ store, chatId: 'chat-1', userId: 'user-1' })
881
- * .set(role('You are helpful'), user('Hello'));
882
- *
883
- * const { systemPrompt, messages } = await context.resolve();
884
- * await generateText({ system: systemPrompt, messages });
885
- * ```
886
- */
887
- async resolve(options) {
888
- await this.#ensureInitialized();
889
- const systemPrompt = options.renderer.render(this.#fragments);
890
- const messages = [];
891
- if (this.#branch?.headMessageId) {
892
- const chain = await this.#store.getMessageChain(
893
- this.#branch.headMessageId
894
- );
895
- for (const msg of chain) {
896
- messages.push(message(msg.data).codec?.decode());
897
- }
898
- }
899
- for (const fragment2 of this.#pendingMessages) {
900
- const decoded = fragment2.codec.decode();
901
- messages.push(decoded);
902
- }
903
- return { systemPrompt, messages };
904
- }
905
- /**
906
- * Save pending messages to the graph.
907
- *
908
- * Each message is added as a node with parentId pointing to the previous message.
909
- * The branch head is updated to point to the last message.
910
- *
911
- * @example
912
- * ```ts
913
- * context.set(user('Hello'));
914
- * // AI responds...
915
- * context.set(assistant('Hi there!'));
916
- * await context.save(); // Persist to graph
917
- * ```
918
- */
919
- async save() {
920
- await this.#ensureInitialized();
921
- if (this.#pendingMessages.length === 0) {
922
- return;
923
- }
924
- for (let i = 0; i < this.#pendingMessages.length; i++) {
925
- const fragment2 = this.#pendingMessages[i];
926
- if (isLazyFragment(fragment2)) {
927
- this.#pendingMessages[i] = await this.#resolveLazyFragment(fragment2);
928
- }
929
- }
930
- let parentId = this.#branch.headMessageId;
931
- const now = Date.now();
932
- for (const fragment2 of this.#pendingMessages) {
933
- const messageData = {
934
- id: fragment2.id ?? crypto.randomUUID(),
935
- chatId: this.#chatId,
936
- parentId,
937
- name: fragment2.name,
938
- type: fragment2.type,
939
- data: fragment2.codec.encode(),
940
- createdAt: now
941
- };
942
- await this.#store.addMessage(messageData);
943
- parentId = messageData.id;
944
- }
945
- await this.#store.updateBranchHead(this.#branch.id, parentId);
946
- this.#branch.headMessageId = parentId;
947
- this.#pendingMessages = [];
948
- }
949
- /**
950
- * Resolve a lazy fragment by finding the appropriate ID.
951
- */
952
- async #resolveLazyFragment(fragment2) {
953
- const lazy = fragment2[LAZY_ID];
954
- if (lazy.type === "last-assistant") {
955
- const lastId = await this.#getLastAssistantId();
956
- return assistantText(lazy.content, { id: lastId ?? crypto.randomUUID() });
957
- }
958
- throw new Error(`Unknown lazy fragment type: ${lazy.type}`);
959
- }
960
- /**
961
- * Find the most recent assistant message ID (pending or persisted).
962
- */
963
- async #getLastAssistantId() {
964
- for (let i = this.#pendingMessages.length - 1; i >= 0; i--) {
965
- const msg = this.#pendingMessages[i];
966
- if (msg.name === "assistant" && !isLazyFragment(msg)) {
967
- return msg.id;
968
- }
969
- }
970
- if (this.#branch?.headMessageId) {
971
- const chain = await this.#store.getMessageChain(
972
- this.#branch.headMessageId
973
- );
974
- for (let i = chain.length - 1; i >= 0; i--) {
975
- if (chain[i].name === "assistant") {
976
- return chain[i].id;
977
- }
978
- }
979
- }
980
- return void 0;
981
- }
982
- /**
983
- * Estimate token count and cost for the full context.
984
- *
985
- * Includes:
986
- * - System prompt fragments (role, hints, etc.)
987
- * - Persisted chat messages (from store)
988
- * - Pending messages (not yet saved)
989
- *
990
- * @param modelId - Model ID (e.g., "openai:gpt-4o", "anthropic:claude-3-5-sonnet")
991
- * @param options - Optional settings
992
- * @returns Estimate result with token counts, costs, and per-fragment breakdown
993
- */
994
- async estimate(modelId, options = {}) {
995
- await this.#ensureInitialized();
996
- const renderer = options.renderer ?? new XmlRenderer();
997
- const registry = getModelsRegistry();
998
- await registry.load();
999
- const model = registry.get(modelId);
1000
- if (!model) {
1001
- throw new Error(
1002
- `Model "${modelId}" not found. Call load() first or check model ID.`
1003
- );
1004
- }
1005
- const tokenizer = registry.getTokenizer(modelId);
1006
- const fragmentEstimates = [];
1007
- for (const fragment2 of this.#fragments) {
1008
- const rendered = renderer.render([fragment2]);
1009
- const tokens = tokenizer.count(rendered);
1010
- const cost = tokens / 1e6 * model.cost.input;
1011
- fragmentEstimates.push({
1012
- id: fragment2.id,
1013
- name: fragment2.name,
1014
- tokens,
1015
- cost
1016
- });
1017
- }
1018
- if (this.#branch?.headMessageId) {
1019
- const chain = await this.#store.getMessageChain(
1020
- this.#branch.headMessageId
1021
- );
1022
- for (const msg of chain) {
1023
- const content = String(msg.data);
1024
- const tokens = tokenizer.count(content);
1025
- const cost = tokens / 1e6 * model.cost.input;
1026
- fragmentEstimates.push({
1027
- name: msg.name,
1028
- id: msg.id,
1029
- tokens,
1030
- cost
1031
- });
1032
- }
1033
- }
1034
- for (const fragment2 of this.#pendingMessages) {
1035
- const content = String(fragment2.data);
1036
- const tokens = tokenizer.count(content);
1037
- const cost = tokens / 1e6 * model.cost.input;
1038
- fragmentEstimates.push({
1039
- name: fragment2.name,
1040
- id: fragment2.id,
1041
- tokens,
1042
- cost
1043
- });
1044
- }
1045
- const totalTokens = fragmentEstimates.reduce((sum, f) => sum + f.tokens, 0);
1046
- const totalCost = fragmentEstimates.reduce((sum, f) => sum + f.cost, 0);
1047
- return {
1048
- model: model.id,
1049
- provider: model.provider,
1050
- tokens: totalTokens,
1051
- cost: totalCost,
1052
- limits: {
1053
- context: model.limit.context,
1054
- output: model.limit.output,
1055
- exceedsContext: totalTokens > model.limit.context
1056
- },
1057
- fragments: fragmentEstimates
1058
- };
1059
- }
1060
- /**
1061
- * Rewind to a specific message by ID.
1062
- *
1063
- * Creates a new branch from that message, preserving the original branch.
1064
- * The new branch becomes active.
1065
- *
1066
- * @param messageId - The message ID to rewind to
1067
- * @returns The new branch info
1068
- *
1069
- * @example
1070
- * ```ts
1071
- * context.set(user('What is 2 + 2?', { id: 'q1' }));
1072
- * context.set(assistant('The answer is 5.', { id: 'wrong' })); // Oops!
1073
- * await context.save();
1074
- *
1075
- * // Rewind to the question, creates new branch
1076
- * const newBranch = await context.rewind('q1');
1077
- *
1078
- * // Now add correct answer on new branch
1079
- * context.set(assistant('The answer is 4.'));
1080
- * await context.save();
1081
- * ```
1082
- */
1083
- async rewind(messageId) {
1084
- await this.#ensureInitialized();
1085
- const message2 = await this.#store.getMessage(messageId);
1086
- if (!message2) {
1087
- throw new Error(`Message "${messageId}" not found`);
1088
- }
1089
- if (message2.chatId !== this.#chatId) {
1090
- throw new Error(`Message "${messageId}" belongs to a different chat`);
1091
- }
1092
- return this.#createBranchFrom(messageId, true);
1093
- }
1094
- /**
1095
- * Create a checkpoint at the current position.
1096
- *
1097
- * A checkpoint is a named pointer to the current branch head.
1098
- * Use restore() to return to this point later.
1099
- *
1100
- * @param name - Name for the checkpoint
1101
- * @returns The checkpoint info
1102
- *
1103
- * @example
1104
- * ```ts
1105
- * context.set(user('I want to learn a new skill.'));
1106
- * context.set(assistant('Would you like coding or cooking?'));
1107
- * await context.save();
1108
- *
1109
- * // Save checkpoint before user's choice
1110
- * const cp = await context.checkpoint('before-choice');
1111
- * ```
1112
- */
1113
- async checkpoint(name) {
1114
- await this.#ensureInitialized();
1115
- if (!this.#branch?.headMessageId) {
1116
- throw new Error("Cannot create checkpoint: no messages in conversation");
1117
- }
1118
- const checkpoint = {
1119
- id: crypto.randomUUID(),
1120
- chatId: this.#chatId,
1121
- name,
1122
- messageId: this.#branch.headMessageId,
1123
- createdAt: Date.now()
1124
- };
1125
- await this.#store.createCheckpoint(checkpoint);
1126
- return {
1127
- id: checkpoint.id,
1128
- name: checkpoint.name,
1129
- messageId: checkpoint.messageId,
1130
- createdAt: checkpoint.createdAt
1131
- };
1132
- }
1133
- /**
1134
- * Restore to a checkpoint by creating a new branch from that point.
1135
- *
1136
- * @param name - Name of the checkpoint to restore
1137
- * @returns The new branch info
1138
- *
1139
- * @example
1140
- * ```ts
1141
- * // User chose cooking, but wants to try coding path
1142
- * await context.restore('before-choice');
1143
- *
1144
- * context.set(user('I want to learn coding.'));
1145
- * context.set(assistant('Python is a great starting language!'));
1146
- * await context.save();
1147
- * ```
1148
- */
1149
- async restore(name) {
1150
- await this.#ensureInitialized();
1151
- const checkpoint = await this.#store.getCheckpoint(this.#chatId, name);
1152
- if (!checkpoint) {
1153
- throw new Error(
1154
- `Checkpoint "${name}" not found in chat "${this.#chatId}"`
1155
- );
1156
- }
1157
- return this.rewind(checkpoint.messageId);
1158
- }
1159
- /**
1160
- * Switch to a different branch by name.
1161
- *
1162
- * @param name - Branch name to switch to
1163
- *
1164
- * @example
1165
- * ```ts
1166
- * // List branches (via store)
1167
- * const branches = await store.listBranches(context.chatId);
1168
- * console.log(branches); // [{name: 'main', ...}, {name: 'main-v2', ...}]
1169
- *
1170
- * // Switch to original branch
1171
- * await context.switchBranch('main');
1172
- * ```
1173
- */
1174
- async switchBranch(name) {
1175
- await this.#ensureInitialized();
1176
- const branch = await this.#store.getBranch(this.#chatId, name);
1177
- if (!branch) {
1178
- throw new Error(`Branch "${name}" not found in chat "${this.#chatId}"`);
1179
- }
1180
- await this.#store.setActiveBranch(this.#chatId, branch.id);
1181
- this.#branch = { ...branch, isActive: true };
1182
- this.#branchName = name;
1183
- this.#pendingMessages = [];
1184
- }
1185
- /**
1186
- * Create a parallel branch from the current position ("by the way").
1187
- *
1188
- * Use this when you want to fork the conversation without leaving
1189
- * the current branch. Common use case: user wants to ask another
1190
- * question while waiting for the model to respond.
1191
- *
1192
- * Unlike rewind(), this method:
1193
- * - Uses the current HEAD (no messageId needed)
1194
- * - Does NOT switch to the new branch
1195
- * - Keeps pending messages intact
1196
- *
1197
- * @returns The new branch info (does not switch to it)
1198
- * @throws Error if no messages exist in the conversation
1199
- *
1200
- * @example
1201
- * ```ts
1202
- * // User asked a question, model is generating...
1203
- * context.set(user('What is the weather?'));
1204
- * await context.save();
1205
- *
1206
- * // User wants to ask something else without waiting
1207
- * const newBranch = await context.btw();
1208
- * // newBranch = { name: 'main-v2', ... }
1209
- *
1210
- * // Later, switch to the new branch and add the question
1211
- * await context.switchBranch(newBranch.name);
1212
- * context.set(user('Also, what time is it?'));
1213
- * await context.save();
1214
- * ```
1215
- */
1216
- async btw() {
1217
- await this.#ensureInitialized();
1218
- if (!this.#branch?.headMessageId) {
1219
- throw new Error("Cannot create btw branch: no messages in conversation");
1220
- }
1221
- return this.#createBranchFrom(this.#branch.headMessageId, false);
1222
- }
1223
- /**
1224
- * Update metadata for the current chat.
1225
- *
1226
- * @param updates - Partial metadata to merge (title, metadata)
1227
- *
1228
- * @example
1229
- * ```ts
1230
- * await context.updateChat({
1231
- * title: 'Coding Help Session',
1232
- * metadata: { tags: ['python', 'debugging'] }
1233
- * });
1234
- * ```
1235
- */
1236
- async updateChat(updates) {
1237
- await this.#ensureInitialized();
1238
- const storeUpdates = {};
1239
- if (updates.title !== void 0) {
1240
- storeUpdates.title = updates.title;
1241
- }
1242
- if (updates.metadata !== void 0) {
1243
- storeUpdates.metadata = {
1244
- ...this.#chatData?.metadata,
1245
- ...updates.metadata
1246
- };
1247
- }
1248
- this.#chatData = await this.#store.updateChat(this.#chatId, storeUpdates);
1249
- }
1250
- /**
1251
- * Track token usage for the current chat.
1252
- * Accumulates usage metrics in chat.metadata.usage.
1253
- *
1254
- * @param usage - Token usage from AI SDK (LanguageModelUsage)
1255
- *
1256
- * @example
1257
- * ```ts
1258
- * // In onFinish callback
1259
- * const usage = await result.totalUsage;
1260
- * await context.trackUsage(usage);
1261
- * ```
1262
- */
1263
- async trackUsage(usage) {
1264
- await this.#ensureInitialized();
1265
- const freshChatData = await this.#store.getChat(this.#chatId);
1266
- const currentUsage = freshChatData?.metadata?.usage ?? {};
1267
- const updatedUsage = mergeWith(
1268
- {},
1269
- currentUsage,
1270
- usage,
1271
- (a, b) => typeof a === "number" || typeof b === "number" ? (a ?? 0) + (b ?? 0) : void 0
1272
- );
1273
- this.#chatData = await this.#store.updateChat(this.#chatId, {
1274
- metadata: {
1275
- ...freshChatData?.metadata,
1276
- usage: updatedUsage
1277
- }
1278
- });
1279
- }
1280
- /**
1281
- * Consolidate context fragments (no-op for now).
1282
- *
1283
- * This is a placeholder for future functionality that merges context fragments
1284
- * using specific rules. Currently, it does nothing.
1285
- *
1286
- * @experimental
1287
- */
1288
- consolidate() {
1289
- return void 0;
1290
- }
1291
- /**
1292
- * Extract skill path mappings from available_skills fragments.
1293
- * Returns array of { host, sandbox } for mounting in sandbox filesystem.
1294
- *
1295
- * Reads the original `paths` configuration stored in fragment metadata
1296
- * by the skills() fragment helper.
1297
- *
1298
- * @example
1299
- * ```ts
1300
- * const context = new ContextEngine({ store, chatId, userId })
1301
- * .set(skills({ paths: [{ host: './skills', sandbox: '/skills' }] }));
1302
- *
1303
- * const mounts = context.getSkillMounts();
1304
- * // [{ host: './skills', sandbox: '/skills' }]
1305
- * ```
1306
- */
1307
- getSkillMounts() {
1308
- const mounts = [];
1309
- for (const fragment2 of this.#fragments) {
1310
- if (fragment2.name === "available_skills" && fragment2.metadata && Array.isArray(fragment2.metadata.paths)) {
1311
- for (const mapping of fragment2.metadata.paths) {
1312
- if (typeof mapping === "object" && mapping !== null && typeof mapping.host === "string" && typeof mapping.sandbox === "string") {
1313
- mounts.push({ host: mapping.host, sandbox: mapping.sandbox });
1314
- }
1315
- }
1316
- }
1317
- }
1318
- return mounts;
1319
- }
1320
- /**
1321
- * Inspect the full context state for debugging.
1322
- * Returns a JSON-serializable object with context information.
1323
- *
1324
- * @param options - Inspection options (modelId and renderer required)
1325
- * @returns Complete inspection data including estimates, rendered output, fragments, and graph
1326
- *
1327
- * @example
1328
- * ```ts
1329
- * const inspection = await context.inspect({
1330
- * modelId: 'openai:gpt-4o',
1331
- * renderer: new XmlRenderer(),
1332
- * });
1333
- * console.log(JSON.stringify(inspection, null, 2));
1334
- *
1335
- * // Or write to file for analysis
1336
- * await fs.writeFile('context-debug.json', JSON.stringify(inspection, null, 2));
1337
- * ```
1338
- */
1339
- async inspect(options) {
1340
- await this.#ensureInitialized();
1341
- const { renderer } = options;
1342
- const estimateResult = await this.estimate(options.modelId, { renderer });
1343
- const rendered = renderer.render(this.#fragments);
1344
- const persistedMessages = [];
1345
- if (this.#branch?.headMessageId) {
1346
- const chain = await this.#store.getMessageChain(
1347
- this.#branch.headMessageId
1348
- );
1349
- persistedMessages.push(...chain);
1350
- }
1351
- const graph = await this.#store.getGraph(this.#chatId);
1352
- return {
1353
- estimate: estimateResult,
1354
- rendered,
1355
- fragments: {
1356
- context: [...this.#fragments],
1357
- pending: [...this.#pendingMessages],
1358
- persisted: persistedMessages
1359
- },
1360
- graph,
1361
- meta: {
1362
- chatId: this.#chatId,
1363
- branch: this.#branchName,
1364
- timestamp: Date.now()
1365
- }
1366
- };
1367
- }
1368
- };
1369
- function term(name, definition) {
1370
- return {
1371
- name: "term",
1372
- data: { name, definition }
1373
- };
1374
- }
1375
- function hint(text) {
1376
- return {
1377
- name: "hint",
1378
- data: text
1379
- };
1380
- }
1381
- function guardrail(input) {
1382
- return {
1383
- name: "guardrail",
1384
- data: {
1385
- rule: input.rule,
1386
- ...input.reason && { reason: input.reason },
1387
- ...input.action && { action: input.action }
1388
- }
1389
- };
1390
- }
1391
- function explain(input) {
1392
- return {
1393
- name: "explain",
1394
- data: {
1395
- concept: input.concept,
1396
- explanation: input.explanation,
1397
- ...input.therefore && { therefore: input.therefore }
1398
- }
1399
- };
1400
- }
1401
- function example(input) {
1402
- return {
1403
- name: "example",
1404
- data: {
1405
- question: input.question,
1406
- answer: input.answer,
1407
- ...input.note && { note: input.note }
1408
- }
1409
- };
1410
- }
1411
- function clarification(input) {
1412
- return {
1413
- name: "clarification",
1414
- data: {
1415
- when: input.when,
1416
- ask: input.ask,
1417
- reason: input.reason
1418
- }
1419
- };
1420
- }
1421
- function workflow(input) {
1422
- return {
1423
- name: "workflow",
1424
- data: {
1425
- task: input.task,
1426
- steps: input.steps,
1427
- ...input.triggers?.length && { triggers: input.triggers },
1428
- ...input.notes && { notes: input.notes }
1429
- }
1430
- };
1431
- }
1432
- function quirk(input) {
1433
- return {
1434
- name: "quirk",
1435
- data: {
1436
- issue: input.issue,
1437
- workaround: input.workaround
1438
- }
1439
- };
1440
- }
1441
- function styleGuide(input) {
1442
- return {
1443
- name: "styleGuide",
1444
- data: {
1445
- prefer: input.prefer,
1446
- ...input.never && { never: input.never },
1447
- ...input.always && { always: input.always }
1448
- }
1449
- };
1450
- }
1451
- function analogy(input) {
1452
- return {
1453
- name: "analogy",
1454
- data: {
1455
- concepts: input.concepts,
1456
- relationship: input.relationship,
1457
- ...input.insight && { insight: input.insight },
1458
- ...input.therefore && { therefore: input.therefore },
1459
- ...input.pitfall && { pitfall: input.pitfall }
1460
- }
1461
- };
1462
- }
1463
- function persona(input) {
1464
- return {
1465
- name: "persona",
1466
- data: {
1467
- name: input.name,
1468
- ...input.role && { role: input.role },
1469
- ...input.objective && { objective: input.objective },
1470
- ...input.tone && { tone: input.tone }
1471
- }
1472
- };
1473
- }
1474
- var STORE_DDL = `
1475
- -- Chats table
1476
- -- createdAt/updatedAt: DEFAULT for insert, inline SET for updates
1477
- CREATE TABLE IF NOT EXISTS chats (
1478
- id TEXT PRIMARY KEY,
1479
- userId TEXT NOT NULL,
1480
- title TEXT,
1481
- metadata TEXT,
1482
- createdAt INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
1483
- updatedAt INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000)
1484
- );
1485
-
1486
- CREATE INDEX IF NOT EXISTS idx_chats_updatedAt ON chats(updatedAt);
1487
- CREATE INDEX IF NOT EXISTS idx_chats_userId ON chats(userId);
1488
-
1489
- -- Messages table (nodes in the DAG)
1490
- CREATE TABLE IF NOT EXISTS messages (
1491
- id TEXT PRIMARY KEY,
1492
- chatId TEXT NOT NULL,
1493
- parentId TEXT,
1494
- name TEXT NOT NULL,
1495
- type TEXT,
1496
- data TEXT NOT NULL,
1497
- createdAt INTEGER NOT NULL,
1498
- FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
1499
- FOREIGN KEY (parentId) REFERENCES messages(id)
1500
- );
1501
-
1502
- CREATE INDEX IF NOT EXISTS idx_messages_chatId ON messages(chatId);
1503
- CREATE INDEX IF NOT EXISTS idx_messages_parentId ON messages(parentId);
1504
-
1505
- -- Branches table (pointers to head messages)
1506
- CREATE TABLE IF NOT EXISTS branches (
1507
- id TEXT PRIMARY KEY,
1508
- chatId TEXT NOT NULL,
1509
- name TEXT NOT NULL,
1510
- headMessageId TEXT,
1511
- isActive INTEGER NOT NULL DEFAULT 0,
1512
- createdAt INTEGER NOT NULL,
1513
- FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
1514
- FOREIGN KEY (headMessageId) REFERENCES messages(id),
1515
- UNIQUE(chatId, name)
1516
- );
1517
-
1518
- CREATE INDEX IF NOT EXISTS idx_branches_chatId ON branches(chatId);
1519
-
1520
- -- Checkpoints table (pointers to message nodes)
1521
- CREATE TABLE IF NOT EXISTS checkpoints (
1522
- id TEXT PRIMARY KEY,
1523
- chatId TEXT NOT NULL,
1524
- name TEXT NOT NULL,
1525
- messageId TEXT NOT NULL,
1526
- createdAt INTEGER NOT NULL,
1527
- FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
1528
- FOREIGN KEY (messageId) REFERENCES messages(id),
1529
- UNIQUE(chatId, name)
1530
- );
1531
-
1532
- CREATE INDEX IF NOT EXISTS idx_checkpoints_chatId ON checkpoints(chatId);
1533
-
1534
- -- FTS5 virtual table for full-text search
1535
- -- messageId/chatId/name are UNINDEXED (stored but not searchable, used for filtering/joining)
1536
- -- Only 'content' is indexed for full-text search
1537
- CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
1538
- messageId UNINDEXED,
1539
- chatId UNINDEXED,
1540
- name UNINDEXED,
1541
- content,
1542
- tokenize='porter unicode61'
1543
- );
1544
- `;
1545
- var SqliteContextStore = class extends ContextStore {
1546
- #db;
1547
- constructor(path3) {
1548
- super();
1549
- this.#db = new DatabaseSync(path3);
1550
- this.#db.exec("PRAGMA foreign_keys = ON");
1551
- this.#db.exec(STORE_DDL);
1552
- }
1553
- /**
1554
- * Execute a function within a transaction.
1555
- * Automatically commits on success or rolls back on error.
1556
- */
1557
- #useTransaction(fn) {
1558
- this.#db.exec("BEGIN TRANSACTION");
1559
- try {
1560
- const result = fn();
1561
- this.#db.exec("COMMIT");
1562
- return result;
1563
- } catch (error) {
1564
- this.#db.exec("ROLLBACK");
1565
- throw error;
1566
- }
1567
- }
1568
- // ==========================================================================
1569
- // Chat Operations
1570
- // ==========================================================================
1571
- async createChat(chat) {
1572
- this.#useTransaction(() => {
1573
- this.#db.prepare(
1574
- `INSERT INTO chats (id, userId, title, metadata)
1575
- VALUES (?, ?, ?, ?)`
1576
- ).run(
1577
- chat.id,
1578
- chat.userId,
1579
- chat.title ?? null,
1580
- chat.metadata ? JSON.stringify(chat.metadata) : null
1581
- );
1582
- this.#db.prepare(
1583
- `INSERT INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
1584
- VALUES (?, ?, 'main', NULL, 1, ?)`
1585
- ).run(crypto.randomUUID(), chat.id, Date.now());
1586
- });
1587
- }
1588
- async upsertChat(chat) {
1589
- return this.#useTransaction(() => {
1590
- const row = this.#db.prepare(
1591
- `INSERT INTO chats (id, userId, title, metadata)
1592
- VALUES (?, ?, ?, ?)
1593
- ON CONFLICT(id) DO UPDATE SET id = excluded.id
1594
- RETURNING *`
1595
- ).get(
1596
- chat.id,
1597
- chat.userId,
1598
- chat.title ?? null,
1599
- chat.metadata ? JSON.stringify(chat.metadata) : null
1600
- );
1601
- this.#db.prepare(
1602
- `INSERT OR IGNORE INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
1603
- VALUES (?, ?, 'main', NULL, 1, ?)`
1604
- ).run(crypto.randomUUID(), chat.id, Date.now());
1605
- return {
1606
- id: row.id,
1607
- userId: row.userId,
1608
- title: row.title ?? void 0,
1609
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
1610
- createdAt: row.createdAt,
1611
- updatedAt: row.updatedAt
1612
- };
1613
- });
1614
- }
1615
- async getChat(chatId) {
1616
- const row = this.#db.prepare("SELECT * FROM chats WHERE id = ?").get(chatId);
1617
- if (!row) {
1618
- return void 0;
1619
- }
1620
- return {
1621
- id: row.id,
1622
- userId: row.userId,
1623
- title: row.title ?? void 0,
1624
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
1625
- createdAt: row.createdAt,
1626
- updatedAt: row.updatedAt
1627
- };
1628
- }
1629
- async updateChat(chatId, updates) {
1630
- const setClauses = ["updatedAt = strftime('%s', 'now') * 1000"];
1631
- const params = [];
1632
- if (updates.title !== void 0) {
1633
- setClauses.push("title = ?");
1634
- params.push(updates.title ?? null);
1635
- }
1636
- if (updates.metadata !== void 0) {
1637
- setClauses.push("metadata = ?");
1638
- params.push(JSON.stringify(updates.metadata));
1639
- }
1640
- params.push(chatId);
1641
- const row = this.#db.prepare(
1642
- `UPDATE chats SET ${setClauses.join(", ")} WHERE id = ? RETURNING *`
1643
- ).get(...params);
1644
- return {
1645
- id: row.id,
1646
- userId: row.userId,
1647
- title: row.title ?? void 0,
1648
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
1649
- createdAt: row.createdAt,
1650
- updatedAt: row.updatedAt
1651
- };
1652
- }
1653
- async listChats(options) {
1654
- const params = [];
1655
- const whereClauses = [];
1656
- let limitClause = "";
1657
- if (options?.userId) {
1658
- whereClauses.push("c.userId = ?");
1659
- params.push(options.userId);
1660
- }
1661
- if (options?.metadata) {
1662
- whereClauses.push(`json_extract(c.metadata, '$.' || ?) = ?`);
1663
- params.push(options.metadata.key);
1664
- params.push(
1665
- typeof options.metadata.value === "boolean" ? options.metadata.value ? 1 : 0 : options.metadata.value
1666
- );
1667
- }
1668
- const whereClause = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
1669
- if (options?.limit !== void 0) {
1670
- limitClause = " LIMIT ?";
1671
- params.push(options.limit);
1672
- if (options.offset !== void 0) {
1673
- limitClause += " OFFSET ?";
1674
- params.push(options.offset);
1675
- }
1676
- }
1677
- const rows = this.#db.prepare(
1678
- `SELECT
1679
- c.id,
1680
- c.userId,
1681
- c.title,
1682
- c.metadata,
1683
- c.createdAt,
1684
- c.updatedAt,
1685
- COUNT(DISTINCT m.id) as messageCount,
1686
- COUNT(DISTINCT b.id) as branchCount
1687
- FROM chats c
1688
- LEFT JOIN messages m ON m.chatId = c.id
1689
- LEFT JOIN branches b ON b.chatId = c.id
1690
- ${whereClause}
1691
- GROUP BY c.id
1692
- ORDER BY c.updatedAt DESC${limitClause}`
1693
- ).all(...params);
1694
- return rows.map((row) => ({
1695
- id: row.id,
1696
- userId: row.userId,
1697
- title: row.title ?? void 0,
1698
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
1699
- messageCount: row.messageCount,
1700
- branchCount: row.branchCount,
1701
- createdAt: row.createdAt,
1702
- updatedAt: row.updatedAt
1703
- }));
1704
- }
1705
- async deleteChat(chatId, options) {
1706
- return this.#useTransaction(() => {
1707
- const messageIds = this.#db.prepare("SELECT id FROM messages WHERE chatId = ?").all(chatId);
1708
- let sql = "DELETE FROM chats WHERE id = ?";
1709
- const params = [chatId];
1710
- if (options?.userId !== void 0) {
1711
- sql += " AND userId = ?";
1712
- params.push(options.userId);
1713
- }
1714
- const result = this.#db.prepare(sql).run(...params);
1715
- if (result.changes > 0 && messageIds.length > 0) {
1716
- const placeholders = messageIds.map(() => "?").join(", ");
1717
- this.#db.prepare(
1718
- `DELETE FROM messages_fts WHERE messageId IN (${placeholders})`
1719
- ).run(...messageIds.map((m) => m.id));
1720
- }
1721
- return result.changes > 0;
1722
- });
1723
- }
1724
- // ==========================================================================
1725
- // Message Operations (Graph Nodes)
1726
- // ==========================================================================
1727
- async addMessage(message2) {
1728
- this.#db.prepare(
1729
- `INSERT INTO messages (id, chatId, parentId, name, type, data, createdAt)
1730
- VALUES (
1731
- ?1,
1732
- ?2,
1733
- CASE WHEN ?3 = ?1 THEN (SELECT parentId FROM messages WHERE id = ?1) ELSE ?3 END,
1734
- ?4,
1735
- ?5,
1736
- ?6,
1737
- ?7
1738
- )
1739
- ON CONFLICT(id) DO UPDATE SET
1740
- name = excluded.name,
1741
- type = excluded.type,
1742
- data = excluded.data`
1743
- ).run(
1744
- message2.id,
1745
- message2.chatId,
1746
- message2.parentId,
1747
- message2.name,
1748
- message2.type ?? null,
1749
- JSON.stringify(message2.data),
1750
- message2.createdAt
1751
- );
1752
- const content = typeof message2.data === "string" ? message2.data : JSON.stringify(message2.data);
1753
- this.#db.prepare(`DELETE FROM messages_fts WHERE messageId = ?`).run(message2.id);
1754
- this.#db.prepare(
1755
- `INSERT INTO messages_fts(messageId, chatId, name, content)
1756
- VALUES (?, ?, ?, ?)`
1757
- ).run(message2.id, message2.chatId, message2.name, content);
1758
- }
1759
- async getMessage(messageId) {
1760
- const row = this.#db.prepare("SELECT * FROM messages WHERE id = ?").get(messageId);
1761
- if (!row) {
1762
- return void 0;
1763
- }
1764
- return {
1765
- id: row.id,
1766
- chatId: row.chatId,
1767
- parentId: row.parentId,
1768
- name: row.name,
1769
- type: row.type ?? void 0,
1770
- data: JSON.parse(row.data),
1771
- createdAt: row.createdAt
1772
- };
1773
- }
1774
- async getMessageChain(headId) {
1775
- const rows = this.#db.prepare(
1776
- `WITH RECURSIVE chain AS (
1777
- SELECT *, 0 as depth FROM messages WHERE id = ?
1778
- UNION ALL
1779
- SELECT m.*, c.depth + 1 FROM messages m
1780
- INNER JOIN chain c ON m.id = c.parentId
1781
- )
1782
- SELECT * FROM chain
1783
- ORDER BY depth DESC`
1784
- ).all(headId);
1785
- return rows.map((row) => ({
1786
- id: row.id,
1787
- chatId: row.chatId,
1788
- parentId: row.parentId,
1789
- name: row.name,
1790
- type: row.type ?? void 0,
1791
- data: JSON.parse(row.data),
1792
- createdAt: row.createdAt
1793
- }));
1794
- }
1795
- async hasChildren(messageId) {
1796
- const row = this.#db.prepare(
1797
- "SELECT EXISTS(SELECT 1 FROM messages WHERE parentId = ?) as hasChildren"
1798
- ).get(messageId);
1799
- return row.hasChildren === 1;
1800
- }
1801
- async getMessages(chatId) {
1802
- const chat = await this.getChat(chatId);
1803
- if (!chat) {
1804
- throw new Error(`Chat "${chatId}" not found`);
1805
- }
1806
- const activeBranch = await this.getActiveBranch(chatId);
1807
- if (!activeBranch?.headMessageId) {
1808
- return [];
1809
- }
1810
- return this.getMessageChain(activeBranch.headMessageId);
1811
- }
1812
- // ==========================================================================
1813
- // Branch Operations
1814
- // ==========================================================================
1815
- async createBranch(branch) {
1816
- this.#db.prepare(
1817
- `INSERT INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
1818
- VALUES (?, ?, ?, ?, ?, ?)`
1819
- ).run(
1820
- branch.id,
1821
- branch.chatId,
1822
- branch.name,
1823
- branch.headMessageId,
1824
- branch.isActive ? 1 : 0,
1825
- branch.createdAt
1826
- );
1827
- }
1828
- async getBranch(chatId, name) {
1829
- const row = this.#db.prepare("SELECT * FROM branches WHERE chatId = ? AND name = ?").get(chatId, name);
1830
- if (!row) {
1831
- return void 0;
1832
- }
1833
- return {
1834
- id: row.id,
1835
- chatId: row.chatId,
1836
- name: row.name,
1837
- headMessageId: row.headMessageId,
1838
- isActive: row.isActive === 1,
1839
- createdAt: row.createdAt
1840
- };
1841
- }
1842
- async getActiveBranch(chatId) {
1843
- const row = this.#db.prepare("SELECT * FROM branches WHERE chatId = ? AND isActive = 1").get(chatId);
1844
- if (!row) {
1845
- return void 0;
1846
- }
1847
- return {
1848
- id: row.id,
1849
- chatId: row.chatId,
1850
- name: row.name,
1851
- headMessageId: row.headMessageId,
1852
- isActive: true,
1853
- createdAt: row.createdAt
1854
- };
1855
- }
1856
- async setActiveBranch(chatId, branchId) {
1857
- this.#db.prepare("UPDATE branches SET isActive = 0 WHERE chatId = ?").run(chatId);
1858
- this.#db.prepare("UPDATE branches SET isActive = 1 WHERE id = ?").run(branchId);
1859
- }
1860
- async updateBranchHead(branchId, messageId) {
1861
- this.#db.prepare("UPDATE branches SET headMessageId = ? WHERE id = ?").run(messageId, branchId);
1862
- }
1863
- async listBranches(chatId) {
1864
- const branches = this.#db.prepare(
1865
- `SELECT
1866
- b.id,
1867
- b.name,
1868
- b.headMessageId,
1869
- b.isActive,
1870
- b.createdAt
1871
- FROM branches b
1872
- WHERE b.chatId = ?
1873
- ORDER BY b.createdAt ASC`
1874
- ).all(chatId);
1875
- const result = [];
1876
- for (const branch of branches) {
1877
- let messageCount = 0;
1878
- if (branch.headMessageId) {
1879
- const countRow = this.#db.prepare(
1880
- `WITH RECURSIVE chain AS (
1881
- SELECT id, parentId FROM messages WHERE id = ?
1882
- UNION ALL
1883
- SELECT m.id, m.parentId FROM messages m
1884
- INNER JOIN chain c ON m.id = c.parentId
1885
- )
1886
- SELECT COUNT(*) as count FROM chain`
1887
- ).get(branch.headMessageId);
1888
- messageCount = countRow.count;
1889
- }
1890
- result.push({
1891
- id: branch.id,
1892
- name: branch.name,
1893
- headMessageId: branch.headMessageId,
1894
- isActive: branch.isActive === 1,
1895
- messageCount,
1896
- createdAt: branch.createdAt
1897
- });
1898
- }
1899
- return result;
1900
- }
1901
- // ==========================================================================
1902
- // Checkpoint Operations
1903
- // ==========================================================================
1904
- async createCheckpoint(checkpoint) {
1905
- this.#db.prepare(
1906
- `INSERT INTO checkpoints (id, chatId, name, messageId, createdAt)
1907
- VALUES (?, ?, ?, ?, ?)
1908
- ON CONFLICT(chatId, name) DO UPDATE SET
1909
- messageId = excluded.messageId,
1910
- createdAt = excluded.createdAt`
1911
- ).run(
1912
- checkpoint.id,
1913
- checkpoint.chatId,
1914
- checkpoint.name,
1915
- checkpoint.messageId,
1916
- checkpoint.createdAt
1917
- );
1918
- }
1919
- async getCheckpoint(chatId, name) {
1920
- const row = this.#db.prepare("SELECT * FROM checkpoints WHERE chatId = ? AND name = ?").get(chatId, name);
1921
- if (!row) {
1922
- return void 0;
1923
- }
1924
- return {
1925
- id: row.id,
1926
- chatId: row.chatId,
1927
- name: row.name,
1928
- messageId: row.messageId,
1929
- createdAt: row.createdAt
1930
- };
1931
- }
1932
- async listCheckpoints(chatId) {
1933
- const rows = this.#db.prepare(
1934
- `SELECT id, name, messageId, createdAt
1935
- FROM checkpoints
1936
- WHERE chatId = ?
1937
- ORDER BY createdAt DESC`
1938
- ).all(chatId);
1939
- return rows.map((row) => ({
1940
- id: row.id,
1941
- name: row.name,
1942
- messageId: row.messageId,
1943
- createdAt: row.createdAt
1944
- }));
1945
- }
1946
- async deleteCheckpoint(chatId, name) {
1947
- this.#db.prepare("DELETE FROM checkpoints WHERE chatId = ? AND name = ?").run(chatId, name);
1948
- }
1949
- // ==========================================================================
1950
- // Search Operations
1951
- // ==========================================================================
1952
- async searchMessages(chatId, query, options) {
1953
- const limit = options?.limit ?? 20;
1954
- const roles = options?.roles;
1955
- let sql = `
1956
- SELECT
1957
- m.id,
1958
- m.chatId,
1959
- m.parentId,
1960
- m.name,
1961
- m.type,
1962
- m.data,
1963
- m.createdAt,
1964
- fts.rank,
1965
- snippet(messages_fts, 3, '<mark>', '</mark>', '...', 32) as snippet
1966
- FROM messages_fts fts
1967
- JOIN messages m ON m.id = fts.messageId
1968
- WHERE messages_fts MATCH ?
1969
- AND fts.chatId = ?
1970
- `;
1971
- const params = [query, chatId];
1972
- if (roles && roles.length > 0) {
1973
- const placeholders = roles.map(() => "?").join(", ");
1974
- sql += ` AND fts.name IN (${placeholders})`;
1975
- params.push(...roles);
1976
- }
1977
- sql += " ORDER BY fts.rank LIMIT ?";
1978
- params.push(limit);
1979
- const rows = this.#db.prepare(sql).all(...params);
1980
- return rows.map((row) => ({
1981
- message: {
1982
- id: row.id,
1983
- chatId: row.chatId,
1984
- parentId: row.parentId,
1985
- name: row.name,
1986
- type: row.type ?? void 0,
1987
- data: JSON.parse(row.data),
1988
- createdAt: row.createdAt
1989
- },
1990
- rank: row.rank,
1991
- snippet: row.snippet
1992
- }));
1993
- }
1994
- // ==========================================================================
1995
- // Visualization Operations
1996
- // ==========================================================================
1997
- async getGraph(chatId) {
1998
- const messageRows = this.#db.prepare(
1999
- `SELECT id, parentId, name, data, createdAt
2000
- FROM messages
2001
- WHERE chatId = ?
2002
- ORDER BY createdAt ASC`
2003
- ).all(chatId);
2004
- const nodes = messageRows.map((row) => {
2005
- const data = JSON.parse(row.data);
2006
- const content = typeof data === "string" ? data : JSON.stringify(data);
2007
- return {
2008
- id: row.id,
2009
- parentId: row.parentId,
2010
- role: row.name,
2011
- content: content.length > 50 ? content.slice(0, 50) + "..." : content,
2012
- createdAt: row.createdAt
2013
- };
2014
- });
2015
- const branchRows = this.#db.prepare(
2016
- `SELECT name, headMessageId, isActive
2017
- FROM branches
2018
- WHERE chatId = ?
2019
- ORDER BY createdAt ASC`
2020
- ).all(chatId);
2021
- const branches = branchRows.map((row) => ({
2022
- name: row.name,
2023
- headMessageId: row.headMessageId,
2024
- isActive: row.isActive === 1
2025
- }));
2026
- const checkpointRows = this.#db.prepare(
2027
- `SELECT name, messageId
2028
- FROM checkpoints
2029
- WHERE chatId = ?
2030
- ORDER BY createdAt ASC`
2031
- ).all(chatId);
2032
- const checkpoints = checkpointRows.map((row) => ({
2033
- name: row.name,
2034
- messageId: row.messageId
2035
- }));
2036
- return {
2037
- chatId,
2038
- nodes,
2039
- branches,
2040
- checkpoints
2041
- };
2042
- }
2043
- };
2044
- var InMemoryContextStore = class extends SqliteContextStore {
2045
- constructor() {
2046
- super(":memory:");
2047
- }
2048
- };
2049
- function structuredOutput(options) {
2050
- return {
2051
- async generate(contextVariables, config) {
2052
- if (!options.context) {
2053
- throw new Error(`structuredOutput is missing a context.`);
2054
- }
2055
- if (!options.model) {
2056
- throw new Error(`structuredOutput is missing a model.`);
2057
- }
2058
- const { messages, systemPrompt } = await options.context.resolve({
2059
- renderer: new XmlRenderer()
2060
- });
2061
- const result = await generateText({
2062
- abortSignal: config?.abortSignal,
2063
- providerOptions: options.providerOptions,
2064
- model: options.model,
2065
- system: systemPrompt,
2066
- messages: await convertToModelMessages(messages),
2067
- stopWhen: stepCountIs(25),
2068
- experimental_repairToolCall: repairToolCall,
2069
- experimental_context: contextVariables,
2070
- output: Output.object({ schema: options.schema }),
2071
- tools: options.tools
2072
- });
2073
- return result.output;
2074
- },
2075
- async stream(contextVariables, config) {
2076
- if (!options.context) {
2077
- throw new Error(`structuredOutput is missing a context.`);
2078
- }
2079
- if (!options.model) {
2080
- throw new Error(`structuredOutput is missing a model.`);
2081
- }
2082
- const { messages, systemPrompt } = await options.context.resolve({
2083
- renderer: new XmlRenderer()
2084
- });
2085
- return streamText({
2086
- abortSignal: config?.abortSignal,
2087
- providerOptions: options.providerOptions,
2088
- model: options.model,
2089
- system: systemPrompt,
2090
- experimental_repairToolCall: repairToolCall,
2091
- messages: await convertToModelMessages(messages),
2092
- stopWhen: stepCountIs(50),
2093
- experimental_transform: config?.transform ?? smoothStream(),
2094
- experimental_context: contextVariables,
2095
- output: Output.object({ schema: options.schema }),
2096
- tools: options.tools
2097
- });
2098
- }
2099
- };
2100
- }
2101
- var repairToolCall = async ({
2102
- toolCall,
2103
- tools,
2104
- inputSchema,
2105
- error
2106
- }) => {
2107
- console.log(
2108
- `Debug: ${chalk2.yellow("RepairingToolCall")}: ${toolCall.toolName}`,
2109
- error.name
2110
- );
2111
- if (NoSuchToolError.isInstance(error)) {
2112
- return null;
2113
- }
2114
- const tool = tools[toolCall.toolName];
2115
- const { output } = await generateText({
2116
- model: groq("openai/gpt-oss-20b"),
2117
- output: Output.object({ schema: tool.inputSchema }),
2118
- prompt: [
2119
- `The model tried to call the tool "${toolCall.toolName}" with the following inputs:`,
2120
- JSON.stringify(toolCall.input),
2121
- `The tool accepts the following schema:`,
2122
- JSON.stringify(inputSchema(toolCall)),
2123
- "Please fix the inputs."
2124
- ].join("\n")
2125
- });
2126
- return { ...toolCall, input: JSON.stringify(output) };
2127
- };
2128
-
2129
- // packages/text2sql/src/lib/synthesis/extractors/base-contextual-extractor.ts
168
+ import { groq } from "@ai-sdk/groq";
169
+ import {
170
+ getToolOrDynamicToolName,
171
+ isTextUIPart,
172
+ isToolOrDynamicToolUIPart
173
+ } from "ai";
174
+ import dedent from "dedent";
175
+ import z from "zod";
176
+ import {
177
+ ContextEngine,
178
+ InMemoryContextStore,
179
+ fragment,
180
+ persona,
181
+ structuredOutput,
182
+ user
183
+ } from "@deepagents/context";
2130
184
  var contextResolverSchema = z.object({
2131
185
  question: z.string().describe(
2132
186
  "A standalone natural language question that the SQL query answers"
@@ -2173,14 +227,14 @@ async function resolveContext(params) {
2173
227
  user("Generate a standalone question for this SQL query.")
2174
228
  );
2175
229
  const resolverOutput = structuredOutput({
2176
- model: groq2("openai/gpt-oss-20b"),
230
+ model: groq("openai/gpt-oss-20b"),
2177
231
  context,
2178
232
  schema: contextResolverSchema
2179
233
  });
2180
234
  return resolverOutput.generate();
2181
235
  }
2182
- function getMessageText(message2) {
2183
- const textParts = message2.parts.filter(isTextUIPart).map((part) => part.text);
236
+ function getMessageText(message) {
237
+ const textParts = message.parts.filter(isTextUIPart).map((part) => part.text);
2184
238
  return textParts.join(" ").trim();
2185
239
  }
2186
240
  function formatConversation(messages) {
@@ -2217,24 +271,24 @@ var BaseContextualExtractor = class extends PairProducer {
2217
271
  * Core extraction loop - iterates through messages and calls hooks.
2218
272
  */
2219
273
  async extractSqlsWithContext(toolName, includeFailures) {
2220
- for (const message2 of this.messages) {
2221
- if (message2.role === "user") {
2222
- const text = getMessageText(message2);
274
+ for (const message of this.messages) {
275
+ if (message.role === "user") {
276
+ const text = getMessageText(message);
2223
277
  if (text) {
2224
278
  await this.onUserMessage(text);
2225
279
  }
2226
280
  continue;
2227
281
  }
2228
- if (message2.role === "assistant") {
2229
- await this.extractFromAssistant(message2, toolName, includeFailures);
282
+ if (message.role === "assistant") {
283
+ await this.extractFromAssistant(message, toolName, includeFailures);
2230
284
  }
2231
285
  }
2232
286
  }
2233
287
  /**
2234
288
  * Extract SQL from assistant message parts.
2235
289
  */
2236
- async extractFromAssistant(message2, toolName, includeFailures) {
2237
- for (const part of message2.parts) {
290
+ async extractFromAssistant(message, toolName, includeFailures) {
291
+ for (const part of message.parts) {
2238
292
  if (!isToolOrDynamicToolUIPart(part)) {
2239
293
  continue;
2240
294
  }
@@ -2263,9 +317,9 @@ var BaseContextualExtractor = class extends PairProducer {
2263
317
  conversationContext: snapshot
2264
318
  });
2265
319
  }
2266
- const assistantText2 = getMessageText(message2);
2267
- if (assistantText2) {
2268
- this.context.push(`Assistant: ${assistantText2}`);
320
+ const assistantText = getMessageText(message);
321
+ if (assistantText) {
322
+ this.context.push(`Assistant: ${assistantText}`);
2269
323
  }
2270
324
  }
2271
325
  /**
@@ -2310,13 +364,13 @@ var MessageExtractor = class extends PairProducer {
2310
364
  async *produce() {
2311
365
  const { includeFailures = false, toolName = "db_query" } = this.#options;
2312
366
  let lastUserMessage = null;
2313
- for (const message2 of this.#messages) {
2314
- if (message2.role === "user") {
2315
- lastUserMessage = message2;
367
+ for (const message of this.#messages) {
368
+ if (message.role === "user") {
369
+ lastUserMessage = message;
2316
370
  continue;
2317
371
  }
2318
- if (message2.role === "assistant" && lastUserMessage) {
2319
- for (const part of message2.parts) {
372
+ if (message.role === "assistant" && lastUserMessage) {
373
+ for (const part of message.parts) {
2320
374
  if (!isToolOrDynamicToolUIPart2(part)) {
2321
375
  continue;
2322
376
  }
@@ -2353,9 +407,17 @@ var MessageExtractor = class extends PairProducer {
2353
407
  };
2354
408
 
2355
409
  // packages/text2sql/src/lib/synthesis/extractors/sql-extractor.ts
2356
- import { groq as groq3 } from "@ai-sdk/groq";
410
+ import { groq as groq2 } from "@ai-sdk/groq";
2357
411
  import dedent2 from "dedent";
2358
412
  import z2 from "zod";
413
+ import {
414
+ ContextEngine as ContextEngine2,
415
+ InMemoryContextStore as InMemoryContextStore2,
416
+ fragment as fragment2,
417
+ persona as persona2,
418
+ structuredOutput as structuredOutput2,
419
+ user as user2
420
+ } from "@deepagents/context";
2359
421
  var outputSchema = z2.object({
2360
422
  question: z2.string().describe("A natural language question that the SQL query answers")
2361
423
  });
@@ -2390,20 +452,20 @@ var SqlExtractor = class extends PairProducer {
2390
452
  continue;
2391
453
  }
2392
454
  }
2393
- const context = new ContextEngine({
2394
- store: new InMemoryContextStore(),
455
+ const context = new ContextEngine2({
456
+ store: new InMemoryContextStore2(),
2395
457
  chatId: `sql-to-question-${crypto.randomUUID()}`,
2396
458
  userId: "system"
2397
459
  });
2398
460
  context.set(
2399
- persona({
461
+ persona2({
2400
462
  name: "sql_to_question",
2401
463
  role: "You are an expert at understanding SQL queries and generating clear, natural language questions that describe what the query retrieves.",
2402
464
  objective: "Generate clear, natural language questions that describe what SQL queries retrieve"
2403
465
  }),
2404
- fragment("database_schema", introspection),
2405
- fragment("sql", sql),
2406
- fragment(
466
+ fragment2("database_schema", introspection),
467
+ fragment2("sql", sql),
468
+ fragment2(
2407
469
  "task",
2408
470
  dedent2`
2409
471
  Given the database schema and the SQL query above, generate a single
@@ -2414,7 +476,7 @@ var SqlExtractor = class extends PairProducer {
2414
476
  4. Is concise but complete
2415
477
  `
2416
478
  ),
2417
- fragment(
479
+ fragment2(
2418
480
  "examples",
2419
481
  dedent2`
2420
482
  SQL: SELECT COUNT(*) FROM customers WHERE region = 'NY'
@@ -2427,10 +489,10 @@ var SqlExtractor = class extends PairProducer {
2427
489
  Question: "Which customers have never placed an order?"
2428
490
  `
2429
491
  ),
2430
- user("Generate a natural language question for this SQL query.")
492
+ user2("Generate a natural language question for this SQL query.")
2431
493
  );
2432
- const sqlToQuestionOutput = structuredOutput({
2433
- model: groq3("openai/gpt-oss-20b"),
494
+ const sqlToQuestionOutput = structuredOutput2({
495
+ model: groq2("openai/gpt-oss-20b"),
2434
496
  context,
2435
497
  schema: outputSchema
2436
498
  });
@@ -2490,28 +552,36 @@ var WindowedContextExtractor = class extends BaseContextualExtractor {
2490
552
  };
2491
553
 
2492
554
  // packages/text2sql/src/lib/synthesis/extractors/segmented-context-extractor.ts
2493
- import { groq as groq4 } from "@ai-sdk/groq";
555
+ import { groq as groq3 } from "@ai-sdk/groq";
2494
556
  import dedent3 from "dedent";
2495
557
  import z3 from "zod";
558
+ import {
559
+ ContextEngine as ContextEngine3,
560
+ InMemoryContextStore as InMemoryContextStore3,
561
+ fragment as fragment3,
562
+ persona as persona3,
563
+ structuredOutput as structuredOutput3,
564
+ user as user3
565
+ } from "@deepagents/context";
2496
566
  var topicChangeSchema = z3.object({
2497
567
  isTopicChange: z3.boolean().describe("Whether the new message represents a topic change"),
2498
568
  reason: z3.string().describe("Brief explanation for the decision")
2499
569
  });
2500
570
  async function detectTopicChange(params) {
2501
- const context = new ContextEngine({
2502
- store: new InMemoryContextStore(),
571
+ const context = new ContextEngine3({
572
+ store: new InMemoryContextStore3(),
2503
573
  chatId: `topic-change-${crypto.randomUUID()}`,
2504
574
  userId: "system"
2505
575
  });
2506
576
  context.set(
2507
- persona({
577
+ persona3({
2508
578
  name: "topic_change_detector",
2509
579
  role: "You are an expert at understanding conversational flow and detecting topic changes.",
2510
580
  objective: "Detect significant topic changes in database conversations"
2511
581
  }),
2512
- fragment("conversation_context", params.context || "(no prior context)"),
2513
- fragment("new_message", params.newMessage),
2514
- fragment(
582
+ fragment3("conversation_context", params.context || "(no prior context)"),
583
+ fragment3("new_message", params.newMessage),
584
+ fragment3(
2515
585
  "task",
2516
586
  dedent3`
2517
587
  Determine if the new message represents a significant topic change from the
@@ -2526,7 +596,7 @@ async function detectTopicChange(params) {
2526
596
  - Requests for more details on the same topic
2527
597
  `
2528
598
  ),
2529
- fragment(
599
+ fragment3(
2530
600
  "examples",
2531
601
  dedent3`
2532
602
  Context: "Show me customers in NY" → "Sort by revenue"
@@ -2542,10 +612,10 @@ async function detectTopicChange(params) {
2542
612
  Decision: Topic change (products → orders/sales)
2543
613
  `
2544
614
  ),
2545
- user("Determine if this is a topic change.")
615
+ user3("Determine if this is a topic change.")
2546
616
  );
2547
- const topicOutput = structuredOutput({
2548
- model: groq4("openai/gpt-oss-20b"),
617
+ const topicOutput = structuredOutput3({
618
+ model: groq3("openai/gpt-oss-20b"),
2549
619
  context,
2550
620
  schema: topicChangeSchema
2551
621
  });
@@ -2645,10 +715,19 @@ var LastQueryExtractor = class extends BaseContextualExtractor {
2645
715
  import pLimit from "p-limit";
2646
716
 
2647
717
  // packages/text2sql/src/lib/agents/question.agent.ts
2648
- import { groq as groq5 } from "@ai-sdk/groq";
718
+ import { groq as groq4 } from "@ai-sdk/groq";
2649
719
  import dedent4 from "dedent";
2650
720
  import z4 from "zod";
2651
721
  import "@deepagents/agent";
722
+ import {
723
+ ContextEngine as ContextEngine4,
724
+ InMemoryContextStore as InMemoryContextStore4,
725
+ fragment as fragment4,
726
+ guardrail,
727
+ persona as persona4,
728
+ structuredOutput as structuredOutput4,
729
+ user as user4
730
+ } from "@deepagents/context";
2652
731
  var complexityInstructions = {
2653
732
  simple: dedent4`
2654
733
  Generate simple questions that require:
@@ -2692,24 +771,24 @@ var outputSchema2 = z4.object({
2692
771
  });
2693
772
  async function generateQuestions(params) {
2694
773
  const { introspection, complexity, count, prompt, model } = params;
2695
- const context = new ContextEngine({
2696
- store: new InMemoryContextStore(),
774
+ const context = new ContextEngine4({
775
+ store: new InMemoryContextStore4(),
2697
776
  chatId: `question-gen-${crypto.randomUUID()}`,
2698
777
  userId: "system"
2699
778
  });
2700
779
  context.set(
2701
- persona({
780
+ persona4({
2702
781
  name: "question_generator",
2703
782
  role: "You are a synthetic data generator specializing in creating realistic natural language questions that users might ask about a database.",
2704
783
  objective: "Generate diverse, realistic natural language questions that match the specified complexity level"
2705
784
  }),
2706
- fragment("database_schema", introspection || ""),
2707
- fragment(
785
+ fragment4("database_schema", introspection || ""),
786
+ fragment4(
2708
787
  "complexity",
2709
788
  { level: complexity },
2710
789
  complexityInstructions[complexity]
2711
790
  ),
2712
- fragment(
791
+ fragment4(
2713
792
  "task",
2714
793
  dedent4`
2715
794
  Generate exactly ${count} natural language questions at the "${complexity}" complexity level.
@@ -2735,12 +814,12 @@ async function generateQuestions(params) {
2735
814
  guardrail({
2736
815
  rule: "All questions must match the specified complexity level"
2737
816
  }),
2738
- user(
817
+ user4(
2739
818
  prompt ?? `Generate ${count} questions at ${complexity} complexity given db schema.`
2740
819
  )
2741
820
  );
2742
- const questionOutput = structuredOutput({
2743
- model: model ?? groq5("openai/gpt-oss-20b"),
821
+ const questionOutput = structuredOutput4({
822
+ model: model ?? groq4("openai/gpt-oss-20b"),
2744
823
  context,
2745
824
  schema: outputSchema2
2746
825
  });
@@ -2748,7 +827,7 @@ async function generateQuestions(params) {
2748
827
  }
2749
828
 
2750
829
  // packages/text2sql/src/lib/agents/sql.agent.ts
2751
- import { groq as groq6 } from "@ai-sdk/groq";
830
+ import { groq as groq5 } from "@ai-sdk/groq";
2752
831
  import {
2753
832
  APICallError,
2754
833
  JSONParseError,
@@ -2764,6 +843,13 @@ import { createWriteStream } from "node:fs";
2764
843
  import pRetry from "p-retry";
2765
844
  import z5 from "zod";
2766
845
  import "@deepagents/agent";
846
+ import {
847
+ ContextEngine as ContextEngine5,
848
+ InMemoryContextStore as InMemoryContextStore5,
849
+ persona as persona5,
850
+ structuredOutput as structuredOutput5,
851
+ user as user5
852
+ } from "@deepagents/context";
2767
853
  var logger = new Console({
2768
854
  stdout: createWriteStream("./sql-agent.log", { flags: "a" }),
2769
855
  stderr: createWriteStream("./sql-agent-error.log", { flags: "a" }),
@@ -2777,8 +863,8 @@ function extractSql(output) {
2777
863
  var marker = Symbol("SQLValidationError");
2778
864
  var SQLValidationError = class _SQLValidationError extends Error {
2779
865
  [marker];
2780
- constructor(message2) {
2781
- super(message2);
866
+ constructor(message) {
867
+ super(message);
2782
868
  this.name = "SQLValidationError";
2783
869
  this[marker] = true;
2784
870
  }
@@ -2787,8 +873,8 @@ var SQLValidationError = class _SQLValidationError extends Error {
2787
873
  }
2788
874
  };
2789
875
  var UnanswerableSQLError = class _UnanswerableSQLError extends Error {
2790
- constructor(message2) {
2791
- super(message2);
876
+ constructor(message) {
877
+ super(message);
2792
878
  this.name = "UnanswerableSQLError";
2793
879
  }
2794
880
  static isInstance(error) {
@@ -2799,13 +885,13 @@ async function toSql(options) {
2799
885
  const { maxRetries = 3 } = options;
2800
886
  return withRetry(
2801
887
  async (attemptNumber, errors, attempts) => {
2802
- const context = new ContextEngine({
2803
- store: new InMemoryContextStore(),
888
+ const context = new ContextEngine5({
889
+ store: new InMemoryContextStore5(),
2804
890
  chatId: `sql-gen-${crypto.randomUUID()}`,
2805
891
  userId: "system"
2806
892
  });
2807
893
  context.set(
2808
- persona({
894
+ persona5({
2809
895
  name: "Freya",
2810
896
  role: "You are an expert SQL query generator. You translate natural language questions into precise, efficient SQL queries based on the provided database schema.",
2811
897
  objective: "Translate natural language questions into precise, efficient SQL queries"
@@ -2815,21 +901,21 @@ async function toSql(options) {
2815
901
  );
2816
902
  if (errors.length) {
2817
903
  context.set(
2818
- user(options.input),
2819
- user(
904
+ user5(options.input),
905
+ user5(
2820
906
  `<validation_error>Your previous SQL query had the following error: ${errors.at(-1)?.message}. Please fix the query.</validation_error>`
2821
907
  )
2822
908
  );
2823
909
  } else {
2824
- context.set(user(options.input));
910
+ context.set(user5(options.input));
2825
911
  }
2826
912
  const temperature = RETRY_TEMPERATURES[attemptNumber - 1] ?? RETRY_TEMPERATURES[RETRY_TEMPERATURES.length - 1];
2827
- const baseModel = options.model ?? groq6("openai/gpt-oss-20b");
913
+ const baseModel = options.model ?? groq5("openai/gpt-oss-20b");
2828
914
  const model = wrapLanguageModel({
2829
915
  model: baseModel,
2830
916
  middleware: defaultSettingsMiddleware({ settings: { temperature } })
2831
917
  });
2832
- const sqlOutput = structuredOutput({
918
+ const sqlOutput = structuredOutput5({
2833
919
  model,
2834
920
  context,
2835
921
  schema: z5.union([
@@ -2943,12 +1029,12 @@ var SchemaSynthesizer = class extends PairProducer {
2943
1029
  async *produce() {
2944
1030
  const introspection = "";
2945
1031
  const combinations = this.#personas.flatMap(
2946
- (persona2) => this.#complexities.map((complexity) => ({ persona: persona2, complexity }))
1032
+ (persona8) => this.#complexities.map((complexity) => ({ persona: persona8, complexity }))
2947
1033
  );
2948
- for (const { persona: persona2, complexity } of combinations) {
1034
+ for (const { persona: persona8, complexity } of combinations) {
2949
1035
  const pairs = await this.#processCombination(
2950
1036
  introspection,
2951
- persona2,
1037
+ persona8,
2952
1038
  complexity
2953
1039
  );
2954
1040
  if (pairs.length) {
@@ -2960,8 +1046,8 @@ var SchemaSynthesizer = class extends PairProducer {
2960
1046
  * Processes a single persona × complexity combination by generating questions
2961
1047
  * and converting each to SQL in parallel.
2962
1048
  */
2963
- async #processCombination(introspection, persona2, complexity) {
2964
- const personaContext = persona2 ? `As ${persona2.role}, ${persona2.perspective}
1049
+ async #processCombination(introspection, persona8, complexity) {
1050
+ const personaContext = persona8 ? `As ${persona8.role}, ${persona8.perspective}
2965
1051
 
2966
1052
  Generate questions this persona would ask.` : void 0;
2967
1053
  const prompt = personaContext ? `${personaContext}
@@ -3013,11 +1099,20 @@ Generate ${this.options.count} questions at ${complexity} complexity.` : void 0;
3013
1099
  };
3014
1100
 
3015
1101
  // packages/text2sql/src/lib/synthesis/synthesizers/breadth-evolver.ts
3016
- import { groq as groq7 } from "@ai-sdk/groq";
1102
+ import { groq as groq6 } from "@ai-sdk/groq";
3017
1103
  import dedent5 from "dedent";
3018
1104
  import pLimit2 from "p-limit";
3019
1105
  import z6 from "zod";
3020
1106
  import "@deepagents/agent";
1107
+ import {
1108
+ ContextEngine as ContextEngine6,
1109
+ InMemoryContextStore as InMemoryContextStore6,
1110
+ fragment as fragment5,
1111
+ guardrail as guardrail2,
1112
+ persona as personaFragment,
1113
+ structuredOutput as structuredOutput6,
1114
+ user as user6
1115
+ } from "@deepagents/context";
3021
1116
 
3022
1117
  // packages/text2sql/src/lib/synthesis/synthesizers/styles.ts
3023
1118
  var ALL_STYLES = [
@@ -3059,8 +1154,8 @@ var paraphraserOutputSchema = z6.object({
3059
1154
  ).min(1).describe("List of paraphrased questions that would produce the same SQL")
3060
1155
  });
3061
1156
  async function paraphraseQuestion(params) {
3062
- const context = new ContextEngine({
3063
- store: new InMemoryContextStore(),
1157
+ const context = new ContextEngine6({
1158
+ store: new InMemoryContextStore6(),
3064
1159
  chatId: `paraphraser-${crypto.randomUUID()}`,
3065
1160
  userId: "system"
3066
1161
  });
@@ -3083,20 +1178,20 @@ async function paraphraseQuestion(params) {
3083
1178
  </communication_styles>
3084
1179
  ` : "";
3085
1180
  context.set(
3086
- persona({
1181
+ personaFragment({
3087
1182
  name: "question_paraphraser",
3088
1183
  role: "You are a linguistic expert specializing in paraphrasing database questions. Your task is to generate alternative phrasings of questions that preserve the exact same semantic meaning - they must all produce the identical SQL query.",
3089
1184
  objective: "Generate paraphrased versions of questions that preserve exact semantic meaning and produce identical SQL"
3090
1185
  }),
3091
- fragment("original_question", params.question),
3092
- fragment(
1186
+ fragment5("original_question", params.question),
1187
+ fragment5(
3093
1188
  "reference_sql",
3094
1189
  params.sql,
3095
1190
  "This SQL shows what the question is really asking - all paraphrases must ask for exactly this"
3096
1191
  ),
3097
- ...personaInstruction ? [fragment("persona", personaInstruction)] : [],
3098
- ...styleInstruction ? [fragment("communication_styles", styleInstruction)] : [],
3099
- fragment(
1192
+ ...personaInstruction ? [fragment5("persona", personaInstruction)] : [],
1193
+ ...styleInstruction ? [fragment5("communication_styles", styleInstruction)] : [],
1194
+ fragment5(
3100
1195
  "task",
3101
1196
  dedent5`
3102
1197
  Generate exactly ${params.count} paraphrased versions of the original question.
@@ -3110,22 +1205,22 @@ async function paraphraseQuestion(params) {
3110
1205
  ${params.persona?.styles?.length ? "6. Apply the specified communication styles to create diverse phrasings" : ""}
3111
1206
  `
3112
1207
  ),
3113
- guardrail({ rule: "NEVER change what data is being requested" }),
3114
- guardrail({
1208
+ guardrail2({ rule: "NEVER change what data is being requested" }),
1209
+ guardrail2({
3115
1210
  rule: "NEVER add filters, aggregations, or conditions not in the original"
3116
1211
  }),
3117
- guardrail({
1212
+ guardrail2({
3118
1213
  rule: "NEVER remove any specificity from the original question"
3119
1214
  }),
3120
- guardrail({
1215
+ guardrail2({
3121
1216
  rule: "All paraphrases must be answerable by the exact same SQL query"
3122
1217
  }),
3123
- user(
1218
+ user6(
3124
1219
  `Paraphrase this question ${params.count} times: "${params.question}"`
3125
1220
  )
3126
1221
  );
3127
- const paraphraserOutput = structuredOutput({
3128
- model: params.model ?? groq7("openai/gpt-oss-20b"),
1222
+ const paraphraserOutput = structuredOutput6({
1223
+ model: params.model ?? groq6("openai/gpt-oss-20b"),
3129
1224
  context,
3130
1225
  schema: paraphraserOutputSchema
3131
1226
  });
@@ -3173,13 +1268,22 @@ var BreadthEvolver = class extends PairProducer {
3173
1268
  };
3174
1269
 
3175
1270
  // packages/text2sql/src/lib/synthesis/synthesizers/depth-evolver.ts
3176
- import { groq as groq8 } from "@ai-sdk/groq";
1271
+ import { groq as groq7 } from "@ai-sdk/groq";
3177
1272
  import { NoObjectGeneratedError as NoObjectGeneratedError2, NoOutputGeneratedError as NoOutputGeneratedError2 } from "ai";
3178
1273
  import dedent6 from "dedent";
3179
1274
  import pLimit3 from "p-limit";
3180
1275
  import pRetry2 from "p-retry";
3181
1276
  import z7 from "zod";
3182
1277
  import "@deepagents/agent";
1278
+ import {
1279
+ ContextEngine as ContextEngine7,
1280
+ InMemoryContextStore as InMemoryContextStore7,
1281
+ fragment as fragment6,
1282
+ guardrail as guardrail3,
1283
+ persona as persona6,
1284
+ structuredOutput as structuredOutput7,
1285
+ user as user7
1286
+ } from "@deepagents/context";
3183
1287
  var techniqueInstructions = {
3184
1288
  "add-aggregation": dedent6`
3185
1289
  Add aggregation requirements to the question.
@@ -3226,30 +1330,30 @@ var evolverOutputSchema = z7.object({
3226
1330
  evolvedQuestion: z7.string().describe("The evolved, more complex version of the original question")
3227
1331
  });
3228
1332
  async function evolveQuestion(params) {
3229
- const context = new ContextEngine({
3230
- store: new InMemoryContextStore(),
1333
+ const context = new ContextEngine7({
1334
+ store: new InMemoryContextStore7(),
3231
1335
  chatId: `evolver-${crypto.randomUUID()}`,
3232
1336
  userId: "system"
3233
1337
  });
3234
1338
  context.set(
3235
- persona({
1339
+ persona6({
3236
1340
  name: "question_evolver",
3237
1341
  role: "You are an expert at evolving simple database questions into more complex ones. Your task is to take a basic question and transform it into a more sophisticated version that requires advanced SQL techniques to answer.",
3238
1342
  objective: "Transform simple questions into complex versions requiring advanced SQL techniques"
3239
1343
  }),
3240
- fragment("original_question", params.question),
3241
- fragment(
1344
+ fragment6("original_question", params.question),
1345
+ fragment6(
3242
1346
  "original_sql",
3243
1347
  params.sql,
3244
1348
  "(This shows what the original question required)"
3245
1349
  ),
3246
- fragment("database_schema", params.schema),
3247
- fragment(
1350
+ fragment6("database_schema", params.schema),
1351
+ fragment6(
3248
1352
  "technique",
3249
1353
  { name: params.technique },
3250
1354
  params.techniqueInstruction
3251
1355
  ),
3252
- fragment(
1356
+ fragment6(
3253
1357
  "task",
3254
1358
  dedent6`
3255
1359
  Evolve the original question using the "${params.technique}" technique.
@@ -3263,22 +1367,22 @@ async function evolveQuestion(params) {
3263
1367
  6. The evolved question should build upon the original topic/domain
3264
1368
  `
3265
1369
  ),
3266
- guardrail({
1370
+ guardrail3({
3267
1371
  rule: "The evolved question MUST require more complex SQL than the original"
3268
1372
  }),
3269
- guardrail({
1373
+ guardrail3({
3270
1374
  rule: "Do not ask for data that does not exist in the schema"
3271
1375
  }),
3272
- guardrail({
1376
+ guardrail3({
3273
1377
  rule: "Keep the question grounded in the same domain as the original"
3274
1378
  }),
3275
- guardrail({ rule: "Make sure the question is clear and unambiguous" }),
3276
- user(
1379
+ guardrail3({ rule: "Make sure the question is clear and unambiguous" }),
1380
+ user7(
3277
1381
  `Evolve this question using "${params.technique}": "${params.question}"`
3278
1382
  )
3279
1383
  );
3280
- const evolverOutput = structuredOutput({
3281
- model: params.model ?? groq8("openai/gpt-oss-20b"),
1384
+ const evolverOutput = structuredOutput7({
1385
+ model: params.model ?? groq7("openai/gpt-oss-20b"),
3282
1386
  context,
3283
1387
  schema: evolverOutputSchema
3284
1388
  });
@@ -3395,10 +1499,20 @@ async function withRetry2(computation) {
3395
1499
  }
3396
1500
 
3397
1501
  // packages/text2sql/src/lib/synthesis/synthesizers/persona-generator.ts
3398
- import { groq as groq9 } from "@ai-sdk/groq";
1502
+ import { groq as groq8 } from "@ai-sdk/groq";
3399
1503
  import dedent7 from "dedent";
3400
1504
  import z8 from "zod";
3401
1505
  import "@deepagents/agent";
1506
+ import {
1507
+ ContextEngine as ContextEngine8,
1508
+ InMemoryContextStore as InMemoryContextStore8,
1509
+ XmlRenderer,
1510
+ fragment as fragment7,
1511
+ guardrail as guardrail4,
1512
+ persona as personaFragment2,
1513
+ structuredOutput as structuredOutput8,
1514
+ user as user8
1515
+ } from "@deepagents/context";
3402
1516
  var outputSchema3 = z8.object({
3403
1517
  personas: z8.array(
3404
1518
  z8.object({
@@ -3415,19 +1529,19 @@ var outputSchema3 = z8.object({
3415
1529
  async function generatePersonas(schemaFragments, options) {
3416
1530
  const schema = new XmlRenderer().render(schemaFragments);
3417
1531
  const count = options?.count ?? 5;
3418
- const context = new ContextEngine({
3419
- store: new InMemoryContextStore(),
1532
+ const context = new ContextEngine8({
1533
+ store: new InMemoryContextStore8(),
3420
1534
  chatId: `persona-gen-${crypto.randomUUID()}`,
3421
1535
  userId: "system"
3422
1536
  });
3423
1537
  context.set(
3424
- persona({
1538
+ personaFragment2({
3425
1539
  name: "persona_generator",
3426
1540
  role: "You are an expert at understanding database schemas and inferring who would use them.",
3427
1541
  objective: "Generate realistic personas representing users who would query this database"
3428
1542
  }),
3429
- fragment("database_schema", schema),
3430
- fragment(
1543
+ fragment7("database_schema", schema),
1544
+ fragment7(
3431
1545
  "task",
3432
1546
  dedent7`
3433
1547
  Analyze the database schema and generate realistic personas representing
@@ -3460,7 +1574,7 @@ async function generatePersonas(schemaFragments, options) {
3460
1574
  - Styles should match how this persona would naturally communicate
3461
1575
  `
3462
1576
  ),
3463
- fragment(
1577
+ fragment7(
3464
1578
  "example",
3465
1579
  dedent7`
3466
1580
  For an e-commerce schema with orders, customers, products tables:
@@ -3478,21 +1592,21 @@ async function generatePersonas(schemaFragments, options) {
3478
1592
  }
3479
1593
  `
3480
1594
  ),
3481
- guardrail({
1595
+ guardrail4({
3482
1596
  rule: "Only generate personas relevant to the actual schema provided"
3483
1597
  }),
3484
- guardrail({
1598
+ guardrail4({
3485
1599
  rule: "Do not invent tables or data that do not exist in the schema"
3486
1600
  }),
3487
- guardrail({
1601
+ guardrail4({
3488
1602
  rule: "Ensure perspectives are specific to the domain, not generic"
3489
1603
  }),
3490
- user(
1604
+ user8(
3491
1605
  `Generate exactly ${count} distinct personas who would query this database.`
3492
1606
  )
3493
1607
  );
3494
- const personaOutput = structuredOutput({
3495
- model: options?.model ?? groq9("openai/gpt-oss-20b"),
1608
+ const personaOutput = structuredOutput8({
1609
+ model: options?.model ?? groq8("openai/gpt-oss-20b"),
3496
1610
  context,
3497
1611
  schema: outputSchema3
3498
1612
  });
@@ -3500,11 +1614,32 @@ async function generatePersonas(schemaFragments, options) {
3500
1614
  return output.personas;
3501
1615
  }
3502
1616
 
1617
+ // packages/text2sql/src/lib/synthesis/synthesizers/teachings-generator.ts
1618
+ import { XmlRenderer as XmlRenderer2 } from "@deepagents/context";
1619
+
3503
1620
  // packages/text2sql/src/lib/agents/teachables.agent.ts
3504
- import { groq as groq10 } from "@ai-sdk/groq";
1621
+ import { groq as groq9 } from "@ai-sdk/groq";
3505
1622
  import dedent8 from "dedent";
3506
1623
  import z9 from "zod";
3507
1624
  import "@deepagents/agent";
1625
+ import {
1626
+ ContextEngine as ContextEngine9,
1627
+ InMemoryContextStore as InMemoryContextStore9,
1628
+ analogy,
1629
+ clarification,
1630
+ example,
1631
+ explain,
1632
+ fragment as fragment8,
1633
+ guardrail as guardrail5,
1634
+ hint,
1635
+ persona as persona7,
1636
+ quirk,
1637
+ structuredOutput as structuredOutput9,
1638
+ styleGuide,
1639
+ term,
1640
+ user as user9,
1641
+ workflow
1642
+ } from "@deepagents/context";
3508
1643
  var outputSchema4 = z9.object({
3509
1644
  terms: z9.array(z9.object({ name: z9.string(), definition: z9.string() })).optional().describe("Domain terminology definitions"),
3510
1645
  hints: z9.array(z9.object({ text: z9.string() })).optional().describe("Helpful hints for SQL generation"),
@@ -3557,20 +1692,20 @@ var outputSchema4 = z9.object({
3557
1692
  ).optional().describe("Concept analogies")
3558
1693
  });
3559
1694
  async function toTeachings(input, options) {
3560
- const context = new ContextEngine({
3561
- store: new InMemoryContextStore(),
1695
+ const context = new ContextEngine9({
1696
+ store: new InMemoryContextStore9(),
3562
1697
  chatId: `teachables-gen-${crypto.randomUUID()}`,
3563
1698
  userId: "system"
3564
1699
  });
3565
1700
  context.set(
3566
- persona({
1701
+ persona7({
3567
1702
  name: "teachables-author",
3568
1703
  role: 'You design "fragments" for a Text2SQL system. Fragments become structured XML instructions.',
3569
1704
  objective: "Choose only high-impact items that improve accuracy, safety, or clarity for this database"
3570
1705
  }),
3571
- fragment("database_schema", input.schema),
3572
- ...input.context ? [fragment("additional_context", input.context)] : [],
3573
- fragment(
1706
+ fragment8("database_schema", input.schema),
1707
+ ...input.context ? [fragment8("additional_context", input.context)] : [],
1708
+ fragment8(
3574
1709
  "output_structure",
3575
1710
  dedent8`
3576
1711
  Output a JSON object with these optional arrays (include only relevant ones):
@@ -3586,7 +1721,7 @@ async function toTeachings(input, options) {
3586
1721
  - analogies: [{ concepts: string[], relationship: string, insight?: string, therefore?: string, pitfall?: string }]
3587
1722
  `
3588
1723
  ),
3589
- fragment(
1724
+ fragment8(
3590
1725
  "task",
3591
1726
  dedent8`
3592
1727
  1. Analyze the schema to infer domain, relationships, and sensitive columns.
@@ -3598,12 +1733,12 @@ async function toTeachings(input, options) {
3598
1733
  4. Only include categories that are relevant to this schema.
3599
1734
  `
3600
1735
  ),
3601
- user(
1736
+ user9(
3602
1737
  `Analyze this database schema and generate fragments that will help an AI generate accurate SQL queries.`
3603
1738
  )
3604
1739
  );
3605
- const teachablesOutput = structuredOutput({
3606
- model: options?.model ?? groq10("openai/gpt-oss-20b"),
1740
+ const teachablesOutput = structuredOutput9({
1741
+ model: options?.model ?? groq9("openai/gpt-oss-20b"),
3607
1742
  context,
3608
1743
  schema: outputSchema4
3609
1744
  });
@@ -3613,7 +1748,7 @@ async function toTeachings(input, options) {
3613
1748
  result.hints?.forEach((h) => fragments.push(hint(h.text)));
3614
1749
  result.guardrails?.forEach(
3615
1750
  (g) => fragments.push(
3616
- guardrail({ rule: g.rule, reason: g.reason, action: g.action })
1751
+ guardrail5({ rule: g.rule, reason: g.reason, action: g.action })
3617
1752
  )
3618
1753
  );
3619
1754
  result.explains?.forEach(
@@ -3669,7 +1804,7 @@ async function toTeachings(input, options) {
3669
1804
 
3670
1805
  // packages/text2sql/src/lib/synthesis/synthesizers/teachings-generator.ts
3671
1806
  async function generateTeachings(schemaFragments, options) {
3672
- const schema = new XmlRenderer().render(schemaFragments);
1807
+ const schema = new XmlRenderer2().render(schemaFragments);
3673
1808
  const maxRetries = options?.maxRetries ?? 3;
3674
1809
  let lastError;
3675
1810
  for (let attempt = 0; attempt < maxRetries; attempt++) {