@deepagents/text2sql 0.11.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/index.d.ts +3 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +1334 -491
  4. package/dist/index.js.map +4 -4
  5. package/dist/lib/adapters/groundings/index.js +2034 -50
  6. package/dist/lib/adapters/groundings/index.js.map +4 -4
  7. package/dist/lib/adapters/groundings/report.grounding.d.ts.map +1 -1
  8. package/dist/lib/adapters/mysql/index.js +2034 -50
  9. package/dist/lib/adapters/mysql/index.js.map +4 -4
  10. package/dist/lib/adapters/postgres/index.js +2034 -50
  11. package/dist/lib/adapters/postgres/index.js.map +4 -4
  12. package/dist/lib/adapters/spreadsheet/index.js +35 -49
  13. package/dist/lib/adapters/spreadsheet/index.js.map +4 -4
  14. package/dist/lib/adapters/sqlite/index.js +2034 -50
  15. package/dist/lib/adapters/sqlite/index.js.map +4 -4
  16. package/dist/lib/adapters/sqlserver/column-stats.sqlserver.grounding.d.ts.map +1 -1
  17. package/dist/lib/adapters/sqlserver/index.js +2035 -53
  18. package/dist/lib/adapters/sqlserver/index.js.map +4 -4
  19. package/dist/lib/agents/developer.agent.d.ts.map +1 -1
  20. package/dist/lib/agents/explainer.agent.d.ts +4 -5
  21. package/dist/lib/agents/explainer.agent.d.ts.map +1 -1
  22. package/dist/lib/agents/question.agent.d.ts.map +1 -1
  23. package/dist/lib/agents/result-tools.d.ts +37 -0
  24. package/dist/lib/agents/result-tools.d.ts.map +1 -0
  25. package/dist/lib/agents/sql.agent.d.ts +1 -1
  26. package/dist/lib/agents/sql.agent.d.ts.map +1 -1
  27. package/dist/lib/agents/teachables.agent.d.ts.map +1 -1
  28. package/dist/lib/agents/text2sql.agent.d.ts +0 -21
  29. package/dist/lib/agents/text2sql.agent.d.ts.map +1 -1
  30. package/dist/lib/checkpoint.d.ts +1 -1
  31. package/dist/lib/checkpoint.d.ts.map +1 -1
  32. package/dist/lib/instructions.d.ts +9 -28
  33. package/dist/lib/instructions.d.ts.map +1 -1
  34. package/dist/lib/sql.d.ts +1 -1
  35. package/dist/lib/sql.d.ts.map +1 -1
  36. package/dist/lib/synthesis/extractors/base-contextual-extractor.d.ts +6 -7
  37. package/dist/lib/synthesis/extractors/base-contextual-extractor.d.ts.map +1 -1
  38. package/dist/lib/synthesis/extractors/last-query-extractor.d.ts.map +1 -1
  39. package/dist/lib/synthesis/extractors/segmented-context-extractor.d.ts +0 -6
  40. package/dist/lib/synthesis/extractors/segmented-context-extractor.d.ts.map +1 -1
  41. package/dist/lib/synthesis/extractors/sql-extractor.d.ts.map +1 -1
  42. package/dist/lib/synthesis/index.js +2394 -2132
  43. package/dist/lib/synthesis/index.js.map +4 -4
  44. package/dist/lib/synthesis/synthesizers/breadth-evolver.d.ts.map +1 -1
  45. package/dist/lib/synthesis/synthesizers/depth-evolver.d.ts +3 -3
  46. package/dist/lib/synthesis/synthesizers/depth-evolver.d.ts.map +1 -1
  47. package/dist/lib/synthesis/synthesizers/persona-generator.d.ts.map +1 -1
  48. package/dist/lib/synthesis/synthesizers/schema-synthesizer.d.ts +1 -1
  49. package/dist/lib/synthesis/synthesizers/schema-synthesizer.d.ts.map +1 -1
  50. package/package.json +9 -15
  51. package/dist/lib/instructions.js +0 -432
  52. package/dist/lib/instructions.js.map +0 -7
  53. package/dist/lib/teach/teachings.d.ts +0 -11
  54. package/dist/lib/teach/teachings.d.ts.map +0 -1
@@ -552,57 +552,1995 @@ var ColumnValuesGrounding = class extends AbstractGrounding {
552
552
  };
553
553
 
554
554
  // packages/text2sql/src/lib/adapters/groundings/report.grounding.ts
555
- import { groq } from "@ai-sdk/groq";
555
+ import { groq as groq2 } from "@ai-sdk/groq";
556
556
  import { tool } from "ai";
557
557
  import dedent from "dedent";
558
558
  import z from "zod";
559
+ import "@deepagents/agent";
560
+
561
+ // packages/context/dist/index.js
562
+ import { encode } from "gpt-tokenizer";
563
+ import { generateId } from "ai";
564
+ import pluralize from "pluralize";
565
+ import { titlecase } from "stringcase";
566
+ import chalk from "chalk";
567
+ import { defineCommand } from "just-bash";
568
+ import spawn from "nano-spawn";
569
+ import "bash-tool";
570
+ import spawn2 from "nano-spawn";
571
+ import {
572
+ createBashTool
573
+ } from "bash-tool";
574
+ import YAML from "yaml";
575
+ import { DatabaseSync } from "node:sqlite";
576
+ import { groq } from "@ai-sdk/groq";
559
577
  import {
560
- agent,
561
- generate,
562
- toState,
563
- user
564
- } from "@deepagents/agent";
565
- var reportAgent = agent({
566
- name: "db-report-agent",
567
- model: groq("openai/gpt-oss-20b"),
568
- prompt: () => dedent`
569
- <identity>
570
- You are a database analyst expert. Your job is to understand what
571
- a database represents and provide business context about it.
572
- You have READ-ONLY access to the database.
573
- </identity>
578
+ NoSuchToolError,
579
+ Output,
580
+ convertToModelMessages,
581
+ createUIMessageStream,
582
+ generateId as generateId2,
583
+ generateText,
584
+ smoothStream,
585
+ stepCountIs,
586
+ streamText
587
+ } from "ai";
588
+ import chalk2 from "chalk";
589
+ import "zod";
590
+ import "@deepagents/agent";
591
+ var defaultTokenizer = {
592
+ encode(text) {
593
+ return encode(text);
594
+ },
595
+ count(text) {
596
+ return encode(text).length;
597
+ }
598
+ };
599
+ var ModelsRegistry = class {
600
+ #cache = /* @__PURE__ */ new Map();
601
+ #loaded = false;
602
+ #tokenizers = /* @__PURE__ */ new Map();
603
+ #defaultTokenizer = defaultTokenizer;
604
+ /**
605
+ * Load models data from models.dev API
606
+ */
607
+ async load() {
608
+ if (this.#loaded) return;
609
+ const response = await fetch("https://models.dev/api.json");
610
+ if (!response.ok) {
611
+ throw new Error(`Failed to fetch models: ${response.statusText}`);
612
+ }
613
+ const data = await response.json();
614
+ for (const [providerId, provider] of Object.entries(data)) {
615
+ for (const [modelId, model] of Object.entries(provider.models)) {
616
+ const info2 = {
617
+ id: model.id,
618
+ name: model.name,
619
+ family: model.family,
620
+ cost: model.cost,
621
+ limit: model.limit,
622
+ provider: providerId
623
+ };
624
+ this.#cache.set(`${providerId}:${modelId}`, info2);
625
+ }
626
+ }
627
+ this.#loaded = true;
628
+ }
629
+ /**
630
+ * Get model info by ID
631
+ * @param modelId - Model ID (e.g., "openai:gpt-4o")
632
+ */
633
+ get(modelId) {
634
+ return this.#cache.get(modelId);
635
+ }
636
+ /**
637
+ * Check if a model exists in the registry
638
+ */
639
+ has(modelId) {
640
+ return this.#cache.has(modelId);
641
+ }
642
+ /**
643
+ * List all available model IDs
644
+ */
645
+ list() {
646
+ return [...this.#cache.keys()];
647
+ }
648
+ /**
649
+ * Register a custom tokenizer for specific model families
650
+ * @param family - Model family name (e.g., "llama", "claude")
651
+ * @param tokenizer - Tokenizer implementation
652
+ */
653
+ registerTokenizer(family, tokenizer) {
654
+ this.#tokenizers.set(family, tokenizer);
655
+ }
656
+ /**
657
+ * Set the default tokenizer used when no family-specific tokenizer is registered
658
+ */
659
+ setDefaultTokenizer(tokenizer) {
660
+ this.#defaultTokenizer = tokenizer;
661
+ }
662
+ /**
663
+ * Get the appropriate tokenizer for a model
664
+ */
665
+ getTokenizer(modelId) {
666
+ const model = this.get(modelId);
667
+ if (model) {
668
+ const familyTokenizer = this.#tokenizers.get(model.family);
669
+ if (familyTokenizer) {
670
+ return familyTokenizer;
671
+ }
672
+ }
673
+ return this.#defaultTokenizer;
674
+ }
675
+ /**
676
+ * Estimate token count and cost for given text and model
677
+ * @param modelId - Model ID to use for pricing (e.g., "openai:gpt-4o")
678
+ * @param input - Input text (prompt)
679
+ */
680
+ estimate(modelId, input) {
681
+ const model = this.get(modelId);
682
+ if (!model) {
683
+ throw new Error(
684
+ `Model "${modelId}" not found. Call load() first or check model ID.`
685
+ );
686
+ }
687
+ const tokenizer = this.getTokenizer(modelId);
688
+ const tokens = tokenizer.count(input);
689
+ const cost = tokens / 1e6 * model.cost.input;
690
+ return {
691
+ model: model.id,
692
+ provider: model.provider,
693
+ tokens,
694
+ cost,
695
+ limits: {
696
+ context: model.limit.context,
697
+ output: model.limit.output,
698
+ exceedsContext: tokens > model.limit.context
699
+ },
700
+ fragments: []
701
+ };
702
+ }
703
+ };
704
+ var _registry = null;
705
+ function getModelsRegistry() {
706
+ if (!_registry) {
707
+ _registry = new ModelsRegistry();
708
+ }
709
+ return _registry;
710
+ }
711
+ function isFragment(data) {
712
+ return typeof data === "object" && data !== null && "name" in data && "data" in data && typeof data.name === "string";
713
+ }
714
+ function isFragmentObject(data) {
715
+ return typeof data === "object" && data !== null && !Array.isArray(data) && !isFragment(data);
716
+ }
717
+ function isMessageFragment(fragment2) {
718
+ return fragment2.type === "message";
719
+ }
720
+ function fragment(name, ...children) {
721
+ return {
722
+ name,
723
+ data: children
724
+ };
725
+ }
726
+ function user(content) {
727
+ const message2 = typeof content === "string" ? {
728
+ id: generateId(),
729
+ role: "user",
730
+ parts: [{ type: "text", text: content }]
731
+ } : content;
732
+ return {
733
+ id: message2.id,
734
+ name: "user",
735
+ data: "content",
736
+ type: "message",
737
+ persist: true,
738
+ codec: {
739
+ decode() {
740
+ return message2;
741
+ },
742
+ encode() {
743
+ return message2;
744
+ }
745
+ }
746
+ };
747
+ }
748
+ function assistant(message2) {
749
+ return {
750
+ id: message2.id,
751
+ name: "assistant",
752
+ data: "content",
753
+ type: "message",
754
+ persist: true,
755
+ codec: {
756
+ decode() {
757
+ return message2;
758
+ },
759
+ encode() {
760
+ return message2;
761
+ }
762
+ }
763
+ };
764
+ }
765
+ function message(content) {
766
+ const message2 = typeof content === "string" ? {
767
+ id: generateId(),
768
+ role: "user",
769
+ parts: [{ type: "text", text: content }]
770
+ } : content;
771
+ return {
772
+ id: message2.id,
773
+ name: message2.role,
774
+ data: "content",
775
+ type: "message",
776
+ persist: true,
777
+ codec: {
778
+ decode() {
779
+ return message2;
780
+ },
781
+ encode() {
782
+ return message2;
783
+ }
784
+ }
785
+ };
786
+ }
787
+ function assistantText(content, options) {
788
+ const id = options?.id ?? crypto.randomUUID();
789
+ return assistant({
790
+ id,
791
+ role: "assistant",
792
+ parts: [{ type: "text", text: content }]
793
+ });
794
+ }
795
+ var LAZY_ID = Symbol("lazy-id");
796
+ function isLazyFragment(fragment2) {
797
+ return LAZY_ID in fragment2;
798
+ }
799
+ function lastAssistantMessage(content) {
800
+ return {
801
+ name: "assistant",
802
+ type: "message",
803
+ persist: true,
804
+ data: "content",
805
+ [LAZY_ID]: {
806
+ type: "last-assistant",
807
+ content
808
+ }
809
+ };
810
+ }
811
+ var ContextRenderer = class {
812
+ options;
813
+ constructor(options = {}) {
814
+ this.options = options;
815
+ }
816
+ /**
817
+ * Check if data is a primitive (string, number, boolean).
818
+ */
819
+ isPrimitive(data) {
820
+ return typeof data === "string" || typeof data === "number" || typeof data === "boolean";
821
+ }
822
+ /**
823
+ * Group fragments by name for groupFragments option.
824
+ */
825
+ groupByName(fragments) {
826
+ const groups = /* @__PURE__ */ new Map();
827
+ for (const fragment2 of fragments) {
828
+ const existing = groups.get(fragment2.name) ?? [];
829
+ existing.push(fragment2);
830
+ groups.set(fragment2.name, existing);
831
+ }
832
+ return groups;
833
+ }
834
+ /**
835
+ * Remove null/undefined from fragments and fragment data recursively.
836
+ * This protects renderers from nullish values and ensures they are ignored
837
+ * consistently across all output formats.
838
+ */
839
+ sanitizeFragments(fragments) {
840
+ const sanitized = [];
841
+ for (const fragment2 of fragments) {
842
+ const cleaned = this.sanitizeFragment(fragment2, /* @__PURE__ */ new WeakSet());
843
+ if (cleaned) {
844
+ sanitized.push(cleaned);
845
+ }
846
+ }
847
+ return sanitized;
848
+ }
849
+ sanitizeFragment(fragment2, seen) {
850
+ const data = this.sanitizeData(fragment2.data, seen);
851
+ if (data == null) {
852
+ return null;
853
+ }
854
+ return {
855
+ ...fragment2,
856
+ data
857
+ };
858
+ }
859
+ sanitizeData(data, seen) {
860
+ if (data == null) {
861
+ return void 0;
862
+ }
863
+ if (isFragment(data)) {
864
+ return this.sanitizeFragment(data, seen) ?? void 0;
865
+ }
866
+ if (Array.isArray(data)) {
867
+ if (seen.has(data)) {
868
+ return void 0;
869
+ }
870
+ seen.add(data);
871
+ const cleaned = [];
872
+ for (const item of data) {
873
+ const sanitizedItem = this.sanitizeData(item, seen);
874
+ if (sanitizedItem != null) {
875
+ cleaned.push(sanitizedItem);
876
+ }
877
+ }
878
+ return cleaned;
879
+ }
880
+ if (isFragmentObject(data)) {
881
+ if (seen.has(data)) {
882
+ return void 0;
883
+ }
884
+ seen.add(data);
885
+ const cleaned = {};
886
+ for (const [key, value] of Object.entries(data)) {
887
+ const sanitizedValue = this.sanitizeData(value, seen);
888
+ if (sanitizedValue != null) {
889
+ cleaned[key] = sanitizedValue;
890
+ }
891
+ }
892
+ return cleaned;
893
+ }
894
+ return data;
895
+ }
896
+ /**
897
+ * Template method - dispatches value to appropriate handler.
898
+ */
899
+ renderValue(key, value, ctx) {
900
+ if (value == null) {
901
+ return "";
902
+ }
903
+ if (isFragment(value)) {
904
+ return this.renderFragment(value, ctx);
905
+ }
906
+ if (Array.isArray(value)) {
907
+ return this.renderArray(key, value, ctx);
908
+ }
909
+ if (isFragmentObject(value)) {
910
+ return this.renderObject(key, value, ctx);
911
+ }
912
+ return this.renderPrimitive(key, String(value), ctx);
913
+ }
914
+ /**
915
+ * Render all entries of an object.
916
+ */
917
+ renderEntries(data, ctx) {
918
+ return Object.entries(data).map(([key, value]) => this.renderValue(key, value, ctx)).filter(Boolean);
919
+ }
920
+ };
921
+ var XmlRenderer = class extends ContextRenderer {
922
+ render(fragments) {
923
+ const sanitized = this.sanitizeFragments(fragments);
924
+ return sanitized.map((f) => this.#renderTopLevel(f)).filter(Boolean).join("\n");
925
+ }
926
+ #renderTopLevel(fragment2) {
927
+ if (this.isPrimitive(fragment2.data)) {
928
+ return this.#leafRoot(fragment2.name, String(fragment2.data));
929
+ }
930
+ if (Array.isArray(fragment2.data)) {
931
+ return this.#renderArray(fragment2.name, fragment2.data, 0);
932
+ }
933
+ if (isFragment(fragment2.data)) {
934
+ const child = this.renderFragment(fragment2.data, { depth: 1, path: [] });
935
+ return this.#wrap(fragment2.name, [child]);
936
+ }
937
+ if (isFragmentObject(fragment2.data)) {
938
+ return this.#wrap(
939
+ fragment2.name,
940
+ this.renderEntries(fragment2.data, { depth: 1, path: [] })
941
+ );
942
+ }
943
+ return "";
944
+ }
945
+ #renderArray(name, items, depth) {
946
+ const fragmentItems = items.filter(isFragment);
947
+ const nonFragmentItems = items.filter((item) => !isFragment(item));
948
+ const children = [];
949
+ for (const item of nonFragmentItems) {
950
+ if (item != null) {
951
+ if (isFragmentObject(item)) {
952
+ children.push(
953
+ this.#wrapIndented(
954
+ pluralize.singular(name),
955
+ this.renderEntries(item, { depth: depth + 2, path: [] }),
956
+ depth + 1
957
+ )
958
+ );
959
+ } else {
960
+ children.push(
961
+ this.#leaf(pluralize.singular(name), String(item), depth + 1)
962
+ );
963
+ }
964
+ }
965
+ }
966
+ if (this.options.groupFragments && fragmentItems.length > 0) {
967
+ const groups = this.groupByName(fragmentItems);
968
+ for (const [groupName, groupFragments] of groups) {
969
+ const groupChildren = groupFragments.map(
970
+ (frag) => this.renderFragment(frag, { depth: depth + 2, path: [] })
971
+ );
972
+ const pluralName = pluralize.plural(groupName);
973
+ children.push(this.#wrapIndented(pluralName, groupChildren, depth + 1));
974
+ }
975
+ } else {
976
+ for (const frag of fragmentItems) {
977
+ children.push(
978
+ this.renderFragment(frag, { depth: depth + 1, path: [] })
979
+ );
980
+ }
981
+ }
982
+ return this.#wrap(name, children);
983
+ }
984
+ #leafRoot(tag, value) {
985
+ const safe = this.#escape(value);
986
+ if (safe.includes("\n")) {
987
+ return `<${tag}>
988
+ ${this.#indent(safe, 2)}
989
+ </${tag}>`;
990
+ }
991
+ return `<${tag}>${safe}</${tag}>`;
992
+ }
993
+ renderFragment(fragment2, ctx) {
994
+ const { name, data } = fragment2;
995
+ if (this.isPrimitive(data)) {
996
+ return this.#leaf(name, String(data), ctx.depth);
997
+ }
998
+ if (isFragment(data)) {
999
+ const child = this.renderFragment(data, { ...ctx, depth: ctx.depth + 1 });
1000
+ return this.#wrapIndented(name, [child], ctx.depth);
1001
+ }
1002
+ if (Array.isArray(data)) {
1003
+ return this.#renderArrayIndented(name, data, ctx.depth);
1004
+ }
1005
+ if (isFragmentObject(data)) {
1006
+ const children = this.renderEntries(data, {
1007
+ ...ctx,
1008
+ depth: ctx.depth + 1
1009
+ });
1010
+ return this.#wrapIndented(name, children, ctx.depth);
1011
+ }
1012
+ return "";
1013
+ }
1014
+ #renderArrayIndented(name, items, depth) {
1015
+ const fragmentItems = items.filter(isFragment);
1016
+ const nonFragmentItems = items.filter((item) => !isFragment(item));
1017
+ const children = [];
1018
+ for (const item of nonFragmentItems) {
1019
+ if (item != null) {
1020
+ if (isFragmentObject(item)) {
1021
+ children.push(
1022
+ this.#wrapIndented(
1023
+ pluralize.singular(name),
1024
+ this.renderEntries(item, { depth: depth + 2, path: [] }),
1025
+ depth + 1
1026
+ )
1027
+ );
1028
+ } else {
1029
+ children.push(
1030
+ this.#leaf(pluralize.singular(name), String(item), depth + 1)
1031
+ );
1032
+ }
1033
+ }
1034
+ }
1035
+ if (this.options.groupFragments && fragmentItems.length > 0) {
1036
+ const groups = this.groupByName(fragmentItems);
1037
+ for (const [groupName, groupFragments] of groups) {
1038
+ const groupChildren = groupFragments.map(
1039
+ (frag) => this.renderFragment(frag, { depth: depth + 2, path: [] })
1040
+ );
1041
+ const pluralName = pluralize.plural(groupName);
1042
+ children.push(this.#wrapIndented(pluralName, groupChildren, depth + 1));
1043
+ }
1044
+ } else {
1045
+ for (const frag of fragmentItems) {
1046
+ children.push(
1047
+ this.renderFragment(frag, { depth: depth + 1, path: [] })
1048
+ );
1049
+ }
1050
+ }
1051
+ return this.#wrapIndented(name, children, depth);
1052
+ }
1053
+ renderPrimitive(key, value, ctx) {
1054
+ return this.#leaf(key, value, ctx.depth);
1055
+ }
1056
+ renderArray(key, items, ctx) {
1057
+ if (!items.length) {
1058
+ return "";
1059
+ }
1060
+ const itemTag = pluralize.singular(key);
1061
+ const children = items.filter((item) => item != null).map((item) => {
1062
+ if (isFragment(item)) {
1063
+ return this.renderFragment(item, { ...ctx, depth: ctx.depth + 1 });
1064
+ }
1065
+ if (isFragmentObject(item)) {
1066
+ return this.#wrapIndented(
1067
+ itemTag,
1068
+ this.renderEntries(item, { ...ctx, depth: ctx.depth + 2 }),
1069
+ ctx.depth + 1
1070
+ );
1071
+ }
1072
+ return this.#leaf(itemTag, String(item), ctx.depth + 1);
1073
+ });
1074
+ return this.#wrapIndented(key, children, ctx.depth);
1075
+ }
1076
+ renderObject(key, obj, ctx) {
1077
+ const children = this.renderEntries(obj, { ...ctx, depth: ctx.depth + 1 });
1078
+ return this.#wrapIndented(key, children, ctx.depth);
1079
+ }
1080
+ #escape(value) {
1081
+ if (value == null) {
1082
+ return "";
1083
+ }
1084
+ return value.replaceAll(/&/g, "&amp;").replaceAll(/</g, "&lt;").replaceAll(/>/g, "&gt;").replaceAll(/"/g, "&quot;").replaceAll(/'/g, "&apos;");
1085
+ }
1086
+ #indent(text, spaces) {
1087
+ if (!text.trim()) {
1088
+ return "";
1089
+ }
1090
+ const padding = " ".repeat(spaces);
1091
+ return text.split("\n").map((line) => line.length ? padding + line : padding).join("\n");
1092
+ }
1093
+ #leaf(tag, value, depth) {
1094
+ const safe = this.#escape(value);
1095
+ const pad = " ".repeat(depth);
1096
+ if (safe.includes("\n")) {
1097
+ return `${pad}<${tag}>
1098
+ ${this.#indent(safe, (depth + 1) * 2)}
1099
+ ${pad}</${tag}>`;
1100
+ }
1101
+ return `${pad}<${tag}>${safe}</${tag}>`;
1102
+ }
1103
+ #wrap(tag, children) {
1104
+ const content = children.filter(Boolean).join("\n");
1105
+ if (!content) {
1106
+ return "";
1107
+ }
1108
+ return `<${tag}>
1109
+ ${content}
1110
+ </${tag}>`;
1111
+ }
1112
+ #wrapIndented(tag, children, depth) {
1113
+ const content = children.filter(Boolean).join("\n");
1114
+ if (!content) {
1115
+ return "";
1116
+ }
1117
+ const pad = " ".repeat(depth);
1118
+ return `${pad}<${tag}>
1119
+ ${content}
1120
+ ${pad}</${tag}>`;
1121
+ }
1122
+ };
1123
+ var ContextStore = class {
1124
+ };
1125
+ var ContextEngine = class {
1126
+ /** Non-message fragments (role, hints, etc.) - not persisted in graph */
1127
+ #fragments = [];
1128
+ /** Pending message fragments to be added to graph */
1129
+ #pendingMessages = [];
1130
+ #store;
1131
+ #chatId;
1132
+ #userId;
1133
+ #branchName;
1134
+ #branch = null;
1135
+ #chatData = null;
1136
+ #initialized = false;
1137
+ constructor(options) {
1138
+ if (!options.chatId) {
1139
+ throw new Error("chatId is required");
1140
+ }
1141
+ if (!options.userId) {
1142
+ throw new Error("userId is required");
1143
+ }
1144
+ this.#store = options.store;
1145
+ this.#chatId = options.chatId;
1146
+ this.#userId = options.userId;
1147
+ this.#branchName = "main";
1148
+ }
1149
+ /**
1150
+ * Initialize the chat and branch if they don't exist.
1151
+ */
1152
+ async #ensureInitialized() {
1153
+ if (this.#initialized) {
1154
+ return;
1155
+ }
1156
+ this.#chatData = await this.#store.upsertChat({
1157
+ id: this.#chatId,
1158
+ userId: this.#userId
1159
+ });
1160
+ this.#branch = await this.#store.getActiveBranch(this.#chatId);
1161
+ this.#initialized = true;
1162
+ }
1163
+ /**
1164
+ * Create a new branch from a specific message.
1165
+ * Shared logic between rewind() and btw().
1166
+ */
1167
+ async #createBranchFrom(messageId, switchTo) {
1168
+ const branches = await this.#store.listBranches(this.#chatId);
1169
+ const samePrefix = branches.filter(
1170
+ (b) => b.name === this.#branchName || b.name.startsWith(`${this.#branchName}-v`)
1171
+ );
1172
+ const newBranchName = `${this.#branchName}-v${samePrefix.length + 1}`;
1173
+ const newBranch = {
1174
+ id: crypto.randomUUID(),
1175
+ chatId: this.#chatId,
1176
+ name: newBranchName,
1177
+ headMessageId: messageId,
1178
+ isActive: false,
1179
+ createdAt: Date.now()
1180
+ };
1181
+ await this.#store.createBranch(newBranch);
1182
+ if (switchTo) {
1183
+ await this.#store.setActiveBranch(this.#chatId, newBranch.id);
1184
+ this.#branch = { ...newBranch, isActive: true };
1185
+ this.#branchName = newBranchName;
1186
+ this.#pendingMessages = [];
1187
+ }
1188
+ const chain = await this.#store.getMessageChain(messageId);
1189
+ return {
1190
+ id: newBranch.id,
1191
+ name: newBranch.name,
1192
+ headMessageId: newBranch.headMessageId,
1193
+ isActive: switchTo,
1194
+ messageCount: chain.length,
1195
+ createdAt: newBranch.createdAt
1196
+ };
1197
+ }
1198
+ /**
1199
+ * Get the current chat ID.
1200
+ */
1201
+ get chatId() {
1202
+ return this.#chatId;
1203
+ }
1204
+ /**
1205
+ * Get the current branch name.
1206
+ */
1207
+ get branch() {
1208
+ return this.#branchName;
1209
+ }
1210
+ /**
1211
+ * Get metadata for the current chat.
1212
+ * Returns null if the chat hasn't been initialized yet.
1213
+ */
1214
+ get chat() {
1215
+ if (!this.#chatData) {
1216
+ return null;
1217
+ }
1218
+ return {
1219
+ id: this.#chatData.id,
1220
+ userId: this.#chatData.userId,
1221
+ createdAt: this.#chatData.createdAt,
1222
+ updatedAt: this.#chatData.updatedAt,
1223
+ title: this.#chatData.title,
1224
+ metadata: this.#chatData.metadata
1225
+ };
1226
+ }
1227
+ /**
1228
+ * Add fragments to the context.
1229
+ *
1230
+ * - Message fragments (user/assistant) are queued for persistence
1231
+ * - Non-message fragments (role/hint) are kept in memory for system prompt
1232
+ */
1233
+ set(...fragments) {
1234
+ for (const fragment2 of fragments) {
1235
+ if (isMessageFragment(fragment2)) {
1236
+ this.#pendingMessages.push(fragment2);
1237
+ } else {
1238
+ this.#fragments.push(fragment2);
1239
+ }
1240
+ }
1241
+ return this;
1242
+ }
1243
+ // Unset a fragment by ID (not implemented yet)
1244
+ unset(fragmentId) {
1245
+ }
1246
+ /**
1247
+ * Render all fragments using the provided renderer.
1248
+ * @internal Use resolve() instead for public API.
1249
+ */
1250
+ render(renderer) {
1251
+ return renderer.render(this.#fragments);
1252
+ }
1253
+ /**
1254
+ * Resolve context into AI SDK-ready format.
1255
+ *
1256
+ * - Initializes chat and branch if needed
1257
+ * - Loads message history from the graph (walking parent chain)
1258
+ * - Separates context fragments for system prompt
1259
+ * - Combines with pending messages
1260
+ *
1261
+ * @example
1262
+ * ```ts
1263
+ * const context = new ContextEngine({ store, chatId: 'chat-1', userId: 'user-1' })
1264
+ * .set(role('You are helpful'), user('Hello'));
1265
+ *
1266
+ * const { systemPrompt, messages } = await context.resolve();
1267
+ * await generateText({ system: systemPrompt, messages });
1268
+ * ```
1269
+ */
1270
+ async resolve(options) {
1271
+ await this.#ensureInitialized();
1272
+ const systemPrompt = options.renderer.render(this.#fragments);
1273
+ const messages = [];
1274
+ if (this.#branch?.headMessageId) {
1275
+ const chain = await this.#store.getMessageChain(
1276
+ this.#branch.headMessageId
1277
+ );
1278
+ for (const msg of chain) {
1279
+ messages.push(message(msg.data).codec?.decode());
1280
+ }
1281
+ }
1282
+ for (const fragment2 of this.#pendingMessages) {
1283
+ const decoded = fragment2.codec.decode();
1284
+ messages.push(decoded);
1285
+ }
1286
+ return { systemPrompt, messages };
1287
+ }
1288
+ /**
1289
+ * Save pending messages to the graph.
1290
+ *
1291
+ * Each message is added as a node with parentId pointing to the previous message.
1292
+ * The branch head is updated to point to the last message.
1293
+ *
1294
+ * @example
1295
+ * ```ts
1296
+ * context.set(user('Hello'));
1297
+ * // AI responds...
1298
+ * context.set(assistant('Hi there!'));
1299
+ * await context.save(); // Persist to graph
1300
+ * ```
1301
+ */
1302
+ async save() {
1303
+ await this.#ensureInitialized();
1304
+ if (this.#pendingMessages.length === 0) {
1305
+ return;
1306
+ }
1307
+ for (let i = 0; i < this.#pendingMessages.length; i++) {
1308
+ const fragment2 = this.#pendingMessages[i];
1309
+ if (isLazyFragment(fragment2)) {
1310
+ this.#pendingMessages[i] = await this.#resolveLazyFragment(fragment2);
1311
+ }
1312
+ }
1313
+ let parentId = this.#branch.headMessageId;
1314
+ const now = Date.now();
1315
+ for (const fragment2 of this.#pendingMessages) {
1316
+ const messageData = {
1317
+ id: fragment2.id ?? crypto.randomUUID(),
1318
+ chatId: this.#chatId,
1319
+ parentId,
1320
+ name: fragment2.name,
1321
+ type: fragment2.type,
1322
+ data: fragment2.codec.encode(),
1323
+ createdAt: now
1324
+ };
1325
+ await this.#store.addMessage(messageData);
1326
+ parentId = messageData.id;
1327
+ }
1328
+ await this.#store.updateBranchHead(this.#branch.id, parentId);
1329
+ this.#branch.headMessageId = parentId;
1330
+ this.#pendingMessages = [];
1331
+ }
1332
+ /**
1333
+ * Resolve a lazy fragment by finding the appropriate ID.
1334
+ */
1335
+ async #resolveLazyFragment(fragment2) {
1336
+ const lazy = fragment2[LAZY_ID];
1337
+ if (lazy.type === "last-assistant") {
1338
+ const lastId = await this.#getLastAssistantId();
1339
+ return assistantText(lazy.content, { id: lastId ?? crypto.randomUUID() });
1340
+ }
1341
+ throw new Error(`Unknown lazy fragment type: ${lazy.type}`);
1342
+ }
1343
+ /**
1344
+ * Find the most recent assistant message ID (pending or persisted).
1345
+ */
1346
+ async #getLastAssistantId() {
1347
+ for (let i = this.#pendingMessages.length - 1; i >= 0; i--) {
1348
+ const msg = this.#pendingMessages[i];
1349
+ if (msg.name === "assistant" && !isLazyFragment(msg)) {
1350
+ return msg.id;
1351
+ }
1352
+ }
1353
+ if (this.#branch?.headMessageId) {
1354
+ const chain = await this.#store.getMessageChain(
1355
+ this.#branch.headMessageId
1356
+ );
1357
+ for (let i = chain.length - 1; i >= 0; i--) {
1358
+ if (chain[i].name === "assistant") {
1359
+ return chain[i].id;
1360
+ }
1361
+ }
1362
+ }
1363
+ return void 0;
1364
+ }
1365
+ /**
1366
+ * Estimate token count and cost for the full context.
1367
+ *
1368
+ * Includes:
1369
+ * - System prompt fragments (role, hints, etc.)
1370
+ * - Persisted chat messages (from store)
1371
+ * - Pending messages (not yet saved)
1372
+ *
1373
+ * @param modelId - Model ID (e.g., "openai:gpt-4o", "anthropic:claude-3-5-sonnet")
1374
+ * @param options - Optional settings
1375
+ * @returns Estimate result with token counts, costs, and per-fragment breakdown
1376
+ */
1377
+ async estimate(modelId, options = {}) {
1378
+ await this.#ensureInitialized();
1379
+ const renderer = options.renderer ?? new XmlRenderer();
1380
+ const registry = getModelsRegistry();
1381
+ await registry.load();
1382
+ const model = registry.get(modelId);
1383
+ if (!model) {
1384
+ throw new Error(
1385
+ `Model "${modelId}" not found. Call load() first or check model ID.`
1386
+ );
1387
+ }
1388
+ const tokenizer = registry.getTokenizer(modelId);
1389
+ const fragmentEstimates = [];
1390
+ for (const fragment2 of this.#fragments) {
1391
+ const rendered = renderer.render([fragment2]);
1392
+ const tokens = tokenizer.count(rendered);
1393
+ const cost = tokens / 1e6 * model.cost.input;
1394
+ fragmentEstimates.push({
1395
+ id: fragment2.id,
1396
+ name: fragment2.name,
1397
+ tokens,
1398
+ cost
1399
+ });
1400
+ }
1401
+ if (this.#branch?.headMessageId) {
1402
+ const chain = await this.#store.getMessageChain(
1403
+ this.#branch.headMessageId
1404
+ );
1405
+ for (const msg of chain) {
1406
+ const content = String(msg.data);
1407
+ const tokens = tokenizer.count(content);
1408
+ const cost = tokens / 1e6 * model.cost.input;
1409
+ fragmentEstimates.push({
1410
+ name: msg.name,
1411
+ id: msg.id,
1412
+ tokens,
1413
+ cost
1414
+ });
1415
+ }
1416
+ }
1417
+ for (const fragment2 of this.#pendingMessages) {
1418
+ const content = String(fragment2.data);
1419
+ const tokens = tokenizer.count(content);
1420
+ const cost = tokens / 1e6 * model.cost.input;
1421
+ fragmentEstimates.push({
1422
+ name: fragment2.name,
1423
+ id: fragment2.id,
1424
+ tokens,
1425
+ cost
1426
+ });
1427
+ }
1428
+ const totalTokens = fragmentEstimates.reduce((sum, f) => sum + f.tokens, 0);
1429
+ const totalCost = fragmentEstimates.reduce((sum, f) => sum + f.cost, 0);
1430
+ return {
1431
+ model: model.id,
1432
+ provider: model.provider,
1433
+ tokens: totalTokens,
1434
+ cost: totalCost,
1435
+ limits: {
1436
+ context: model.limit.context,
1437
+ output: model.limit.output,
1438
+ exceedsContext: totalTokens > model.limit.context
1439
+ },
1440
+ fragments: fragmentEstimates
1441
+ };
1442
+ }
1443
+ /**
1444
+ * Rewind to a specific message by ID.
1445
+ *
1446
+ * Creates a new branch from that message, preserving the original branch.
1447
+ * The new branch becomes active.
1448
+ *
1449
+ * @param messageId - The message ID to rewind to
1450
+ * @returns The new branch info
1451
+ *
1452
+ * @example
1453
+ * ```ts
1454
+ * context.set(user('What is 2 + 2?', { id: 'q1' }));
1455
+ * context.set(assistant('The answer is 5.', { id: 'wrong' })); // Oops!
1456
+ * await context.save();
1457
+ *
1458
+ * // Rewind to the question, creates new branch
1459
+ * const newBranch = await context.rewind('q1');
1460
+ *
1461
+ * // Now add correct answer on new branch
1462
+ * context.set(assistant('The answer is 4.'));
1463
+ * await context.save();
1464
+ * ```
1465
+ */
1466
+ async rewind(messageId) {
1467
+ await this.#ensureInitialized();
1468
+ const message2 = await this.#store.getMessage(messageId);
1469
+ if (!message2) {
1470
+ throw new Error(`Message "${messageId}" not found`);
1471
+ }
1472
+ if (message2.chatId !== this.#chatId) {
1473
+ throw new Error(`Message "${messageId}" belongs to a different chat`);
1474
+ }
1475
+ return this.#createBranchFrom(messageId, true);
1476
+ }
1477
+ /**
1478
+ * Create a checkpoint at the current position.
1479
+ *
1480
+ * A checkpoint is a named pointer to the current branch head.
1481
+ * Use restore() to return to this point later.
1482
+ *
1483
+ * @param name - Name for the checkpoint
1484
+ * @returns The checkpoint info
1485
+ *
1486
+ * @example
1487
+ * ```ts
1488
+ * context.set(user('I want to learn a new skill.'));
1489
+ * context.set(assistant('Would you like coding or cooking?'));
1490
+ * await context.save();
1491
+ *
1492
+ * // Save checkpoint before user's choice
1493
+ * const cp = await context.checkpoint('before-choice');
1494
+ * ```
1495
+ */
1496
+ async checkpoint(name) {
1497
+ await this.#ensureInitialized();
1498
+ if (!this.#branch?.headMessageId) {
1499
+ throw new Error("Cannot create checkpoint: no messages in conversation");
1500
+ }
1501
+ const checkpoint = {
1502
+ id: crypto.randomUUID(),
1503
+ chatId: this.#chatId,
1504
+ name,
1505
+ messageId: this.#branch.headMessageId,
1506
+ createdAt: Date.now()
1507
+ };
1508
+ await this.#store.createCheckpoint(checkpoint);
1509
+ return {
1510
+ id: checkpoint.id,
1511
+ name: checkpoint.name,
1512
+ messageId: checkpoint.messageId,
1513
+ createdAt: checkpoint.createdAt
1514
+ };
1515
+ }
1516
+ /**
1517
+ * Restore to a checkpoint by creating a new branch from that point.
1518
+ *
1519
+ * @param name - Name of the checkpoint to restore
1520
+ * @returns The new branch info
1521
+ *
1522
+ * @example
1523
+ * ```ts
1524
+ * // User chose cooking, but wants to try coding path
1525
+ * await context.restore('before-choice');
1526
+ *
1527
+ * context.set(user('I want to learn coding.'));
1528
+ * context.set(assistant('Python is a great starting language!'));
1529
+ * await context.save();
1530
+ * ```
1531
+ */
1532
+ async restore(name) {
1533
+ await this.#ensureInitialized();
1534
+ const checkpoint = await this.#store.getCheckpoint(this.#chatId, name);
1535
+ if (!checkpoint) {
1536
+ throw new Error(
1537
+ `Checkpoint "${name}" not found in chat "${this.#chatId}"`
1538
+ );
1539
+ }
1540
+ return this.rewind(checkpoint.messageId);
1541
+ }
1542
+ /**
1543
+ * Switch to a different branch by name.
1544
+ *
1545
+ * @param name - Branch name to switch to
1546
+ *
1547
+ * @example
1548
+ * ```ts
1549
+ * // List branches (via store)
1550
+ * const branches = await store.listBranches(context.chatId);
1551
+ * console.log(branches); // [{name: 'main', ...}, {name: 'main-v2', ...}]
1552
+ *
1553
+ * // Switch to original branch
1554
+ * await context.switchBranch('main');
1555
+ * ```
1556
+ */
1557
+ async switchBranch(name) {
1558
+ await this.#ensureInitialized();
1559
+ const branch = await this.#store.getBranch(this.#chatId, name);
1560
+ if (!branch) {
1561
+ throw new Error(`Branch "${name}" not found in chat "${this.#chatId}"`);
1562
+ }
1563
+ await this.#store.setActiveBranch(this.#chatId, branch.id);
1564
+ this.#branch = { ...branch, isActive: true };
1565
+ this.#branchName = name;
1566
+ this.#pendingMessages = [];
1567
+ }
1568
+ /**
1569
+ * Create a parallel branch from the current position ("by the way").
1570
+ *
1571
+ * Use this when you want to fork the conversation without leaving
1572
+ * the current branch. Common use case: user wants to ask another
1573
+ * question while waiting for the model to respond.
1574
+ *
1575
+ * Unlike rewind(), this method:
1576
+ * - Uses the current HEAD (no messageId needed)
1577
+ * - Does NOT switch to the new branch
1578
+ * - Keeps pending messages intact
1579
+ *
1580
+ * @returns The new branch info (does not switch to it)
1581
+ * @throws Error if no messages exist in the conversation
1582
+ *
1583
+ * @example
1584
+ * ```ts
1585
+ * // User asked a question, model is generating...
1586
+ * context.set(user('What is the weather?'));
1587
+ * await context.save();
1588
+ *
1589
+ * // User wants to ask something else without waiting
1590
+ * const newBranch = await context.btw();
1591
+ * // newBranch = { name: 'main-v2', ... }
1592
+ *
1593
+ * // Later, switch to the new branch and add the question
1594
+ * await context.switchBranch(newBranch.name);
1595
+ * context.set(user('Also, what time is it?'));
1596
+ * await context.save();
1597
+ * ```
1598
+ */
1599
+ async btw() {
1600
+ await this.#ensureInitialized();
1601
+ if (!this.#branch?.headMessageId) {
1602
+ throw new Error("Cannot create btw branch: no messages in conversation");
1603
+ }
1604
+ return this.#createBranchFrom(this.#branch.headMessageId, false);
1605
+ }
1606
+ /**
1607
+ * Update metadata for the current chat.
1608
+ *
1609
+ * @param updates - Partial metadata to merge (title, metadata)
1610
+ *
1611
+ * @example
1612
+ * ```ts
1613
+ * await context.updateChat({
1614
+ * title: 'Coding Help Session',
1615
+ * metadata: { tags: ['python', 'debugging'] }
1616
+ * });
1617
+ * ```
1618
+ */
1619
+ async updateChat(updates) {
1620
+ await this.#ensureInitialized();
1621
+ const storeUpdates = {};
1622
+ if (updates.title !== void 0) {
1623
+ storeUpdates.title = updates.title;
1624
+ }
1625
+ if (updates.metadata !== void 0) {
1626
+ storeUpdates.metadata = {
1627
+ ...this.#chatData?.metadata,
1628
+ ...updates.metadata
1629
+ };
1630
+ }
1631
+ this.#chatData = await this.#store.updateChat(this.#chatId, storeUpdates);
1632
+ }
1633
+ /**
1634
+ * Consolidate context fragments (no-op for now).
1635
+ *
1636
+ * This is a placeholder for future functionality that merges context fragments
1637
+ * using specific rules. Currently, it does nothing.
1638
+ *
1639
+ * @experimental
1640
+ */
1641
+ consolidate() {
1642
+ return void 0;
1643
+ }
1644
+ /**
1645
+ * Extract skill path mappings from available_skills fragments.
1646
+ * Returns array of { host, sandbox } for mounting in sandbox filesystem.
1647
+ *
1648
+ * Reads the original `paths` configuration stored in fragment metadata
1649
+ * by the skills() fragment helper.
1650
+ *
1651
+ * @example
1652
+ * ```ts
1653
+ * const context = new ContextEngine({ store, chatId, userId })
1654
+ * .set(skills({ paths: [{ host: './skills', sandbox: '/skills' }] }));
1655
+ *
1656
+ * const mounts = context.getSkillMounts();
1657
+ * // [{ host: './skills', sandbox: '/skills' }]
1658
+ * ```
1659
+ */
1660
+ getSkillMounts() {
1661
+ const mounts = [];
1662
+ for (const fragment2 of this.#fragments) {
1663
+ if (fragment2.name === "available_skills" && fragment2.metadata && Array.isArray(fragment2.metadata.paths)) {
1664
+ for (const mapping of fragment2.metadata.paths) {
1665
+ if (typeof mapping === "object" && mapping !== null && typeof mapping.host === "string" && typeof mapping.sandbox === "string") {
1666
+ mounts.push({ host: mapping.host, sandbox: mapping.sandbox });
1667
+ }
1668
+ }
1669
+ }
1670
+ }
1671
+ return mounts;
1672
+ }
1673
+ /**
1674
+ * Inspect the full context state for debugging.
1675
+ * Returns a JSON-serializable object with context information.
1676
+ *
1677
+ * @param options - Inspection options (modelId and renderer required)
1678
+ * @returns Complete inspection data including estimates, rendered output, fragments, and graph
1679
+ *
1680
+ * @example
1681
+ * ```ts
1682
+ * const inspection = await context.inspect({
1683
+ * modelId: 'openai:gpt-4o',
1684
+ * renderer: new XmlRenderer(),
1685
+ * });
1686
+ * console.log(JSON.stringify(inspection, null, 2));
1687
+ *
1688
+ * // Or write to file for analysis
1689
+ * await fs.writeFile('context-debug.json', JSON.stringify(inspection, null, 2));
1690
+ * ```
1691
+ */
1692
+ async inspect(options) {
1693
+ await this.#ensureInitialized();
1694
+ const { renderer } = options;
1695
+ const estimateResult = await this.estimate(options.modelId, { renderer });
1696
+ const rendered = renderer.render(this.#fragments);
1697
+ const persistedMessages = [];
1698
+ if (this.#branch?.headMessageId) {
1699
+ const chain = await this.#store.getMessageChain(
1700
+ this.#branch.headMessageId
1701
+ );
1702
+ persistedMessages.push(...chain);
1703
+ }
1704
+ const graph = await this.#store.getGraph(this.#chatId);
1705
+ return {
1706
+ estimate: estimateResult,
1707
+ rendered,
1708
+ fragments: {
1709
+ context: [...this.#fragments],
1710
+ pending: [...this.#pendingMessages],
1711
+ persisted: persistedMessages
1712
+ },
1713
+ graph,
1714
+ meta: {
1715
+ chatId: this.#chatId,
1716
+ branch: this.#branchName,
1717
+ timestamp: Date.now()
1718
+ }
1719
+ };
1720
+ }
1721
+ };
1722
+ function persona(input) {
1723
+ return {
1724
+ name: "persona",
1725
+ data: {
1726
+ name: input.name,
1727
+ ...input.role && { role: input.role },
1728
+ ...input.objective && { objective: input.objective },
1729
+ ...input.tone && { tone: input.tone }
1730
+ }
1731
+ };
1732
+ }
1733
+ function pass(part) {
1734
+ return { type: "pass", part };
1735
+ }
1736
+ function runGuardrailChain(part, guardrails, context) {
1737
+ let currentPart = part;
1738
+ for (const guardrail2 of guardrails) {
1739
+ const result = guardrail2.handle(currentPart, context);
1740
+ if (result.type === "fail") {
1741
+ return result;
1742
+ }
1743
+ currentPart = result.part;
1744
+ }
1745
+ return pass(currentPart);
1746
+ }
1747
+ var STORE_DDL = `
1748
+ -- Chats table
1749
+ -- createdAt/updatedAt: DEFAULT for insert, inline SET for updates
1750
+ CREATE TABLE IF NOT EXISTS chats (
1751
+ id TEXT PRIMARY KEY,
1752
+ userId TEXT NOT NULL,
1753
+ title TEXT,
1754
+ metadata TEXT,
1755
+ createdAt INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
1756
+ updatedAt INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000)
1757
+ );
574
1758
 
575
- <instructions>
576
- Write a business context that helps another agent answer questions accurately.
1759
+ CREATE INDEX IF NOT EXISTS idx_chats_updatedAt ON chats(updatedAt);
1760
+ CREATE INDEX IF NOT EXISTS idx_chats_userId ON chats(userId);
577
1761
 
578
- For EACH table, do queries ONE AT A TIME:
579
- 1. SELECT COUNT(*) to get row count
580
- 2. SELECT * LIMIT 3 to see sample data
1762
+ -- Messages table (nodes in the DAG)
1763
+ CREATE TABLE IF NOT EXISTS messages (
1764
+ id TEXT PRIMARY KEY,
1765
+ chatId TEXT NOT NULL,
1766
+ parentId TEXT,
1767
+ name TEXT NOT NULL,
1768
+ type TEXT,
1769
+ data TEXT NOT NULL,
1770
+ createdAt INTEGER NOT NULL,
1771
+ FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
1772
+ FOREIGN KEY (parentId) REFERENCES messages(id)
1773
+ );
581
1774
 
582
- Then write a report with:
583
- - What business this database is for
584
- - For each table: purpose, row count, and example of what the data looks like
1775
+ CREATE INDEX IF NOT EXISTS idx_messages_chatId ON messages(chatId);
1776
+ CREATE INDEX IF NOT EXISTS idx_messages_parentId ON messages(parentId);
585
1777
 
586
- Include concrete examples like "Track prices are $0.99",
587
- "Customer names like 'Luís Gonçalves'", etc.
1778
+ -- Branches table (pointers to head messages)
1779
+ CREATE TABLE IF NOT EXISTS branches (
1780
+ id TEXT PRIMARY KEY,
1781
+ chatId TEXT NOT NULL,
1782
+ name TEXT NOT NULL,
1783
+ headMessageId TEXT,
1784
+ isActive INTEGER NOT NULL DEFAULT 0,
1785
+ createdAt INTEGER NOT NULL,
1786
+ FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
1787
+ FOREIGN KEY (headMessageId) REFERENCES messages(id),
1788
+ UNIQUE(chatId, name)
1789
+ );
588
1790
 
589
- Keep it 400-600 words, conversational style.
590
- </instructions>
591
- `,
592
- tools: {
593
- query_database: tool({
594
- description: "Execute a SELECT query to explore the database and gather insights.",
595
- inputSchema: z.object({
596
- sql: z.string().describe("The SELECT query to execute"),
597
- purpose: z.string().describe("What insight you are trying to gather with this query")
598
- }),
599
- execute: ({ sql }, options) => {
600
- const state = toState(options);
601
- return state.adapter.execute(sql);
1791
+ CREATE INDEX IF NOT EXISTS idx_branches_chatId ON branches(chatId);
1792
+
1793
+ -- Checkpoints table (pointers to message nodes)
1794
+ CREATE TABLE IF NOT EXISTS checkpoints (
1795
+ id TEXT PRIMARY KEY,
1796
+ chatId TEXT NOT NULL,
1797
+ name TEXT NOT NULL,
1798
+ messageId TEXT NOT NULL,
1799
+ createdAt INTEGER NOT NULL,
1800
+ FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
1801
+ FOREIGN KEY (messageId) REFERENCES messages(id),
1802
+ UNIQUE(chatId, name)
1803
+ );
1804
+
1805
+ CREATE INDEX IF NOT EXISTS idx_checkpoints_chatId ON checkpoints(chatId);
1806
+
1807
+ -- FTS5 virtual table for full-text search
1808
+ -- messageId/chatId/name are UNINDEXED (stored but not searchable, used for filtering/joining)
1809
+ -- Only 'content' is indexed for full-text search
1810
+ CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
1811
+ messageId UNINDEXED,
1812
+ chatId UNINDEXED,
1813
+ name UNINDEXED,
1814
+ content,
1815
+ tokenize='porter unicode61'
1816
+ );
1817
+ `;
1818
+ var SqliteContextStore = class extends ContextStore {
1819
+ #db;
1820
+ constructor(path3) {
1821
+ super();
1822
+ this.#db = new DatabaseSync(path3);
1823
+ this.#db.exec("PRAGMA foreign_keys = ON");
1824
+ this.#db.exec(STORE_DDL);
1825
+ }
1826
+ /**
1827
+ * Execute a function within a transaction.
1828
+ * Automatically commits on success or rolls back on error.
1829
+ */
1830
+ #useTransaction(fn) {
1831
+ this.#db.exec("BEGIN TRANSACTION");
1832
+ try {
1833
+ const result = fn();
1834
+ this.#db.exec("COMMIT");
1835
+ return result;
1836
+ } catch (error) {
1837
+ this.#db.exec("ROLLBACK");
1838
+ throw error;
1839
+ }
1840
+ }
1841
+ // ==========================================================================
1842
+ // Chat Operations
1843
+ // ==========================================================================
1844
+ async createChat(chat) {
1845
+ this.#useTransaction(() => {
1846
+ this.#db.prepare(
1847
+ `INSERT INTO chats (id, userId, title, metadata)
1848
+ VALUES (?, ?, ?, ?)`
1849
+ ).run(
1850
+ chat.id,
1851
+ chat.userId,
1852
+ chat.title ?? null,
1853
+ chat.metadata ? JSON.stringify(chat.metadata) : null
1854
+ );
1855
+ this.#db.prepare(
1856
+ `INSERT INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
1857
+ VALUES (?, ?, 'main', NULL, 1, ?)`
1858
+ ).run(crypto.randomUUID(), chat.id, Date.now());
1859
+ });
1860
+ }
1861
+ async upsertChat(chat) {
1862
+ return this.#useTransaction(() => {
1863
+ const row = this.#db.prepare(
1864
+ `INSERT INTO chats (id, userId, title, metadata)
1865
+ VALUES (?, ?, ?, ?)
1866
+ ON CONFLICT(id) DO UPDATE SET id = excluded.id
1867
+ RETURNING *`
1868
+ ).get(
1869
+ chat.id,
1870
+ chat.userId,
1871
+ chat.title ?? null,
1872
+ chat.metadata ? JSON.stringify(chat.metadata) : null
1873
+ );
1874
+ this.#db.prepare(
1875
+ `INSERT OR IGNORE INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
1876
+ VALUES (?, ?, 'main', NULL, 1, ?)`
1877
+ ).run(crypto.randomUUID(), chat.id, Date.now());
1878
+ return {
1879
+ id: row.id,
1880
+ userId: row.userId,
1881
+ title: row.title ?? void 0,
1882
+ metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
1883
+ createdAt: row.createdAt,
1884
+ updatedAt: row.updatedAt
1885
+ };
1886
+ });
1887
+ }
1888
+ async getChat(chatId) {
1889
+ const row = this.#db.prepare("SELECT * FROM chats WHERE id = ?").get(chatId);
1890
+ if (!row) {
1891
+ return void 0;
1892
+ }
1893
+ return {
1894
+ id: row.id,
1895
+ userId: row.userId,
1896
+ title: row.title ?? void 0,
1897
+ metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
1898
+ createdAt: row.createdAt,
1899
+ updatedAt: row.updatedAt
1900
+ };
1901
+ }
1902
+ async updateChat(chatId, updates) {
1903
+ const setClauses = ["updatedAt = strftime('%s', 'now') * 1000"];
1904
+ const params = [];
1905
+ if (updates.title !== void 0) {
1906
+ setClauses.push("title = ?");
1907
+ params.push(updates.title ?? null);
1908
+ }
1909
+ if (updates.metadata !== void 0) {
1910
+ setClauses.push("metadata = ?");
1911
+ params.push(JSON.stringify(updates.metadata));
1912
+ }
1913
+ params.push(chatId);
1914
+ const row = this.#db.prepare(
1915
+ `UPDATE chats SET ${setClauses.join(", ")} WHERE id = ? RETURNING *`
1916
+ ).get(...params);
1917
+ return {
1918
+ id: row.id,
1919
+ userId: row.userId,
1920
+ title: row.title ?? void 0,
1921
+ metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
1922
+ createdAt: row.createdAt,
1923
+ updatedAt: row.updatedAt
1924
+ };
1925
+ }
1926
+ async listChats(options) {
1927
+ const params = [];
1928
+ let whereClause = "";
1929
+ let limitClause = "";
1930
+ if (options?.userId) {
1931
+ whereClause = "WHERE c.userId = ?";
1932
+ params.push(options.userId);
1933
+ }
1934
+ if (options?.limit !== void 0) {
1935
+ limitClause = " LIMIT ?";
1936
+ params.push(options.limit);
1937
+ if (options.offset !== void 0) {
1938
+ limitClause += " OFFSET ?";
1939
+ params.push(options.offset);
1940
+ }
1941
+ }
1942
+ const rows = this.#db.prepare(
1943
+ `SELECT
1944
+ c.id,
1945
+ c.userId,
1946
+ c.title,
1947
+ c.createdAt,
1948
+ c.updatedAt,
1949
+ COUNT(DISTINCT m.id) as messageCount,
1950
+ COUNT(DISTINCT b.id) as branchCount
1951
+ FROM chats c
1952
+ LEFT JOIN messages m ON m.chatId = c.id
1953
+ LEFT JOIN branches b ON b.chatId = c.id
1954
+ ${whereClause}
1955
+ GROUP BY c.id
1956
+ ORDER BY c.updatedAt DESC${limitClause}`
1957
+ ).all(...params);
1958
+ return rows.map((row) => ({
1959
+ id: row.id,
1960
+ userId: row.userId,
1961
+ title: row.title ?? void 0,
1962
+ messageCount: row.messageCount,
1963
+ branchCount: row.branchCount,
1964
+ createdAt: row.createdAt,
1965
+ updatedAt: row.updatedAt
1966
+ }));
1967
+ }
1968
+ async deleteChat(chatId, options) {
1969
+ return this.#useTransaction(() => {
1970
+ const messageIds = this.#db.prepare("SELECT id FROM messages WHERE chatId = ?").all(chatId);
1971
+ let sql = "DELETE FROM chats WHERE id = ?";
1972
+ const params = [chatId];
1973
+ if (options?.userId !== void 0) {
1974
+ sql += " AND userId = ?";
1975
+ params.push(options.userId);
1976
+ }
1977
+ const result = this.#db.prepare(sql).run(...params);
1978
+ if (result.changes > 0 && messageIds.length > 0) {
1979
+ const placeholders = messageIds.map(() => "?").join(", ");
1980
+ this.#db.prepare(
1981
+ `DELETE FROM messages_fts WHERE messageId IN (${placeholders})`
1982
+ ).run(...messageIds.map((m) => m.id));
1983
+ }
1984
+ return result.changes > 0;
1985
+ });
1986
+ }
1987
+ // ==========================================================================
1988
+ // Message Operations (Graph Nodes)
1989
+ // ==========================================================================
1990
+ async addMessage(message2) {
1991
+ const existingParent = message2.parentId === message2.id ? this.#db.prepare("SELECT parentId FROM messages WHERE id = ?").get(message2.id) : void 0;
1992
+ const parentId = message2.parentId === message2.id ? existingParent?.parentId ?? null : message2.parentId;
1993
+ this.#db.prepare(
1994
+ `INSERT INTO messages (id, chatId, parentId, name, type, data, createdAt)
1995
+ VALUES (?, ?, ?, ?, ?, ?, ?)
1996
+ ON CONFLICT(id) DO UPDATE SET
1997
+ name = excluded.name,
1998
+ type = excluded.type,
1999
+ data = excluded.data`
2000
+ ).run(
2001
+ message2.id,
2002
+ message2.chatId,
2003
+ parentId,
2004
+ message2.name,
2005
+ message2.type ?? null,
2006
+ JSON.stringify(message2.data),
2007
+ message2.createdAt
2008
+ );
2009
+ const content = typeof message2.data === "string" ? message2.data : JSON.stringify(message2.data);
2010
+ this.#db.prepare(`DELETE FROM messages_fts WHERE messageId = ?`).run(message2.id);
2011
+ this.#db.prepare(
2012
+ `INSERT INTO messages_fts(messageId, chatId, name, content)
2013
+ VALUES (?, ?, ?, ?)`
2014
+ ).run(message2.id, message2.chatId, message2.name, content);
2015
+ }
2016
+ async getMessage(messageId) {
2017
+ const row = this.#db.prepare("SELECT * FROM messages WHERE id = ?").get(messageId);
2018
+ if (!row) {
2019
+ return void 0;
2020
+ }
2021
+ return {
2022
+ id: row.id,
2023
+ chatId: row.chatId,
2024
+ parentId: row.parentId,
2025
+ name: row.name,
2026
+ type: row.type ?? void 0,
2027
+ data: JSON.parse(row.data),
2028
+ createdAt: row.createdAt
2029
+ };
2030
+ }
2031
+ async getMessageChain(headId) {
2032
+ const rows = this.#db.prepare(
2033
+ `WITH RECURSIVE chain AS (
2034
+ SELECT *, 0 as depth FROM messages WHERE id = ?
2035
+ UNION ALL
2036
+ SELECT m.*, c.depth + 1 FROM messages m
2037
+ INNER JOIN chain c ON m.id = c.parentId
2038
+ )
2039
+ SELECT * FROM chain
2040
+ ORDER BY depth DESC`
2041
+ ).all(headId);
2042
+ return rows.map((row) => ({
2043
+ id: row.id,
2044
+ chatId: row.chatId,
2045
+ parentId: row.parentId,
2046
+ name: row.name,
2047
+ type: row.type ?? void 0,
2048
+ data: JSON.parse(row.data),
2049
+ createdAt: row.createdAt
2050
+ }));
2051
+ }
2052
+ async hasChildren(messageId) {
2053
+ const row = this.#db.prepare(
2054
+ "SELECT EXISTS(SELECT 1 FROM messages WHERE parentId = ?) as hasChildren"
2055
+ ).get(messageId);
2056
+ return row.hasChildren === 1;
2057
+ }
2058
+ async getMessages(chatId) {
2059
+ const chat = await this.getChat(chatId);
2060
+ if (!chat) {
2061
+ throw new Error(`Chat "${chatId}" not found`);
2062
+ }
2063
+ const activeBranch = await this.getActiveBranch(chatId);
2064
+ if (!activeBranch?.headMessageId) {
2065
+ return [];
2066
+ }
2067
+ return this.getMessageChain(activeBranch.headMessageId);
2068
+ }
2069
+ // ==========================================================================
2070
+ // Branch Operations
2071
+ // ==========================================================================
2072
+ async createBranch(branch) {
2073
+ this.#db.prepare(
2074
+ `INSERT INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
2075
+ VALUES (?, ?, ?, ?, ?, ?)`
2076
+ ).run(
2077
+ branch.id,
2078
+ branch.chatId,
2079
+ branch.name,
2080
+ branch.headMessageId,
2081
+ branch.isActive ? 1 : 0,
2082
+ branch.createdAt
2083
+ );
2084
+ }
2085
+ async getBranch(chatId, name) {
2086
+ const row = this.#db.prepare("SELECT * FROM branches WHERE chatId = ? AND name = ?").get(chatId, name);
2087
+ if (!row) {
2088
+ return void 0;
2089
+ }
2090
+ return {
2091
+ id: row.id,
2092
+ chatId: row.chatId,
2093
+ name: row.name,
2094
+ headMessageId: row.headMessageId,
2095
+ isActive: row.isActive === 1,
2096
+ createdAt: row.createdAt
2097
+ };
2098
+ }
2099
+ async getActiveBranch(chatId) {
2100
+ const row = this.#db.prepare("SELECT * FROM branches WHERE chatId = ? AND isActive = 1").get(chatId);
2101
+ if (!row) {
2102
+ return void 0;
2103
+ }
2104
+ return {
2105
+ id: row.id,
2106
+ chatId: row.chatId,
2107
+ name: row.name,
2108
+ headMessageId: row.headMessageId,
2109
+ isActive: true,
2110
+ createdAt: row.createdAt
2111
+ };
2112
+ }
2113
+ async setActiveBranch(chatId, branchId) {
2114
+ this.#db.prepare("UPDATE branches SET isActive = 0 WHERE chatId = ?").run(chatId);
2115
+ this.#db.prepare("UPDATE branches SET isActive = 1 WHERE id = ?").run(branchId);
2116
+ }
2117
+ async updateBranchHead(branchId, messageId) {
2118
+ this.#db.prepare("UPDATE branches SET headMessageId = ? WHERE id = ?").run(messageId, branchId);
2119
+ }
2120
+ async listBranches(chatId) {
2121
+ const branches = this.#db.prepare(
2122
+ `SELECT
2123
+ b.id,
2124
+ b.name,
2125
+ b.headMessageId,
2126
+ b.isActive,
2127
+ b.createdAt
2128
+ FROM branches b
2129
+ WHERE b.chatId = ?
2130
+ ORDER BY b.createdAt ASC`
2131
+ ).all(chatId);
2132
+ const result = [];
2133
+ for (const branch of branches) {
2134
+ let messageCount = 0;
2135
+ if (branch.headMessageId) {
2136
+ const countRow = this.#db.prepare(
2137
+ `WITH RECURSIVE chain AS (
2138
+ SELECT id, parentId FROM messages WHERE id = ?
2139
+ UNION ALL
2140
+ SELECT m.id, m.parentId FROM messages m
2141
+ INNER JOIN chain c ON m.id = c.parentId
2142
+ )
2143
+ SELECT COUNT(*) as count FROM chain`
2144
+ ).get(branch.headMessageId);
2145
+ messageCount = countRow.count;
602
2146
  }
603
- })
2147
+ result.push({
2148
+ id: branch.id,
2149
+ name: branch.name,
2150
+ headMessageId: branch.headMessageId,
2151
+ isActive: branch.isActive === 1,
2152
+ messageCount,
2153
+ createdAt: branch.createdAt
2154
+ });
2155
+ }
2156
+ return result;
2157
+ }
2158
+ // ==========================================================================
2159
+ // Checkpoint Operations
2160
+ // ==========================================================================
2161
+ async createCheckpoint(checkpoint) {
2162
+ this.#db.prepare(
2163
+ `INSERT INTO checkpoints (id, chatId, name, messageId, createdAt)
2164
+ VALUES (?, ?, ?, ?, ?)
2165
+ ON CONFLICT(chatId, name) DO UPDATE SET
2166
+ messageId = excluded.messageId,
2167
+ createdAt = excluded.createdAt`
2168
+ ).run(
2169
+ checkpoint.id,
2170
+ checkpoint.chatId,
2171
+ checkpoint.name,
2172
+ checkpoint.messageId,
2173
+ checkpoint.createdAt
2174
+ );
2175
+ }
2176
+ async getCheckpoint(chatId, name) {
2177
+ const row = this.#db.prepare("SELECT * FROM checkpoints WHERE chatId = ? AND name = ?").get(chatId, name);
2178
+ if (!row) {
2179
+ return void 0;
2180
+ }
2181
+ return {
2182
+ id: row.id,
2183
+ chatId: row.chatId,
2184
+ name: row.name,
2185
+ messageId: row.messageId,
2186
+ createdAt: row.createdAt
2187
+ };
604
2188
  }
605
- });
2189
+ async listCheckpoints(chatId) {
2190
+ const rows = this.#db.prepare(
2191
+ `SELECT id, name, messageId, createdAt
2192
+ FROM checkpoints
2193
+ WHERE chatId = ?
2194
+ ORDER BY createdAt DESC`
2195
+ ).all(chatId);
2196
+ return rows.map((row) => ({
2197
+ id: row.id,
2198
+ name: row.name,
2199
+ messageId: row.messageId,
2200
+ createdAt: row.createdAt
2201
+ }));
2202
+ }
2203
+ async deleteCheckpoint(chatId, name) {
2204
+ this.#db.prepare("DELETE FROM checkpoints WHERE chatId = ? AND name = ?").run(chatId, name);
2205
+ }
2206
+ // ==========================================================================
2207
+ // Search Operations
2208
+ // ==========================================================================
2209
+ async searchMessages(chatId, query, options) {
2210
+ const limit = options?.limit ?? 20;
2211
+ const roles = options?.roles;
2212
+ let sql = `
2213
+ SELECT
2214
+ m.id,
2215
+ m.chatId,
2216
+ m.parentId,
2217
+ m.name,
2218
+ m.type,
2219
+ m.data,
2220
+ m.createdAt,
2221
+ fts.rank,
2222
+ snippet(messages_fts, 3, '<mark>', '</mark>', '...', 32) as snippet
2223
+ FROM messages_fts fts
2224
+ JOIN messages m ON m.id = fts.messageId
2225
+ WHERE messages_fts MATCH ?
2226
+ AND fts.chatId = ?
2227
+ `;
2228
+ const params = [query, chatId];
2229
+ if (roles && roles.length > 0) {
2230
+ const placeholders = roles.map(() => "?").join(", ");
2231
+ sql += ` AND fts.name IN (${placeholders})`;
2232
+ params.push(...roles);
2233
+ }
2234
+ sql += " ORDER BY fts.rank LIMIT ?";
2235
+ params.push(limit);
2236
+ const rows = this.#db.prepare(sql).all(...params);
2237
+ return rows.map((row) => ({
2238
+ message: {
2239
+ id: row.id,
2240
+ chatId: row.chatId,
2241
+ parentId: row.parentId,
2242
+ name: row.name,
2243
+ type: row.type ?? void 0,
2244
+ data: JSON.parse(row.data),
2245
+ createdAt: row.createdAt
2246
+ },
2247
+ rank: row.rank,
2248
+ snippet: row.snippet
2249
+ }));
2250
+ }
2251
+ // ==========================================================================
2252
+ // Visualization Operations
2253
+ // ==========================================================================
2254
+ async getGraph(chatId) {
2255
+ const messageRows = this.#db.prepare(
2256
+ `SELECT id, parentId, name, data, createdAt
2257
+ FROM messages
2258
+ WHERE chatId = ?
2259
+ ORDER BY createdAt ASC`
2260
+ ).all(chatId);
2261
+ const nodes = messageRows.map((row) => {
2262
+ const data = JSON.parse(row.data);
2263
+ const content = typeof data === "string" ? data : JSON.stringify(data);
2264
+ return {
2265
+ id: row.id,
2266
+ parentId: row.parentId,
2267
+ role: row.name,
2268
+ content: content.length > 50 ? content.slice(0, 50) + "..." : content,
2269
+ createdAt: row.createdAt
2270
+ };
2271
+ });
2272
+ const branchRows = this.#db.prepare(
2273
+ `SELECT name, headMessageId, isActive
2274
+ FROM branches
2275
+ WHERE chatId = ?
2276
+ ORDER BY createdAt ASC`
2277
+ ).all(chatId);
2278
+ const branches = branchRows.map((row) => ({
2279
+ name: row.name,
2280
+ headMessageId: row.headMessageId,
2281
+ isActive: row.isActive === 1
2282
+ }));
2283
+ const checkpointRows = this.#db.prepare(
2284
+ `SELECT name, messageId
2285
+ FROM checkpoints
2286
+ WHERE chatId = ?
2287
+ ORDER BY createdAt ASC`
2288
+ ).all(chatId);
2289
+ const checkpoints = checkpointRows.map((row) => ({
2290
+ name: row.name,
2291
+ messageId: row.messageId
2292
+ }));
2293
+ return {
2294
+ chatId,
2295
+ nodes,
2296
+ branches,
2297
+ checkpoints
2298
+ };
2299
+ }
2300
+ };
2301
+ var InMemoryContextStore = class extends SqliteContextStore {
2302
+ constructor() {
2303
+ super(":memory:");
2304
+ }
2305
+ };
2306
+ var Agent = class _Agent {
2307
+ #options;
2308
+ #guardrails = [];
2309
+ tools;
2310
+ constructor(options) {
2311
+ this.#options = options;
2312
+ this.tools = options.tools || {};
2313
+ this.#guardrails = options.guardrails || [];
2314
+ }
2315
+ async generate(contextVariables, config) {
2316
+ if (!this.#options.context) {
2317
+ throw new Error(`Agent ${this.#options.name} is missing a context.`);
2318
+ }
2319
+ if (!this.#options.model) {
2320
+ throw new Error(`Agent ${this.#options.name} is missing a model.`);
2321
+ }
2322
+ const { messages, systemPrompt } = await this.#options.context.resolve({
2323
+ renderer: new XmlRenderer()
2324
+ });
2325
+ return generateText({
2326
+ abortSignal: config?.abortSignal,
2327
+ providerOptions: this.#options.providerOptions,
2328
+ model: this.#options.model,
2329
+ system: systemPrompt,
2330
+ messages: await convertToModelMessages(messages),
2331
+ stopWhen: stepCountIs(25),
2332
+ tools: this.#options.tools,
2333
+ experimental_context: contextVariables,
2334
+ experimental_repairToolCall: repairToolCall,
2335
+ toolChoice: this.#options.toolChoice,
2336
+ onStepFinish: (step) => {
2337
+ const toolCall = step.toolCalls.at(-1);
2338
+ if (toolCall) {
2339
+ console.log(
2340
+ `Debug: ${chalk2.yellow("ToolCalled")}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`
2341
+ );
2342
+ }
2343
+ }
2344
+ });
2345
+ }
2346
+ /**
2347
+ * Stream a response from the agent.
2348
+ *
2349
+ * When guardrails are configured, `toUIMessageStream()` is wrapped to provide
2350
+ * self-correction behavior. Direct access to fullStream/textStream bypasses guardrails.
2351
+ *
2352
+ * @example
2353
+ * ```typescript
2354
+ * const stream = await agent.stream({});
2355
+ *
2356
+ * // With guardrails - use toUIMessageStream for protection
2357
+ * await printer.readableStream(stream.toUIMessageStream());
2358
+ *
2359
+ * // Or use printer.stdout which uses toUIMessageStream internally
2360
+ * await printer.stdout(stream);
2361
+ * ```
2362
+ */
2363
+ async stream(contextVariables, config) {
2364
+ if (!this.#options.context) {
2365
+ throw new Error(`Agent ${this.#options.name} is missing a context.`);
2366
+ }
2367
+ if (!this.#options.model) {
2368
+ throw new Error(`Agent ${this.#options.name} is missing a model.`);
2369
+ }
2370
+ const result = await this.#createRawStream(contextVariables, config);
2371
+ if (this.#guardrails.length === 0) {
2372
+ return result;
2373
+ }
2374
+ return this.#wrapWithGuardrails(result, contextVariables, config);
2375
+ }
2376
+ /**
2377
+ * Create a raw stream without guardrail processing.
2378
+ */
2379
+ async #createRawStream(contextVariables, config) {
2380
+ const { messages, systemPrompt } = await this.#options.context.resolve({
2381
+ renderer: new XmlRenderer()
2382
+ });
2383
+ const runId = generateId2();
2384
+ return streamText({
2385
+ abortSignal: config?.abortSignal,
2386
+ providerOptions: this.#options.providerOptions,
2387
+ model: this.#options.model,
2388
+ system: systemPrompt,
2389
+ messages: await convertToModelMessages(messages),
2390
+ experimental_repairToolCall: repairToolCall,
2391
+ stopWhen: stepCountIs(50),
2392
+ experimental_transform: config?.transform ?? smoothStream(),
2393
+ tools: this.#options.tools,
2394
+ experimental_context: contextVariables,
2395
+ toolChoice: this.#options.toolChoice,
2396
+ onStepFinish: (step) => {
2397
+ const toolCall = step.toolCalls.at(-1);
2398
+ if (toolCall) {
2399
+ console.log(
2400
+ `Debug: (${runId}) ${chalk2.bold.yellow("ToolCalled")}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`
2401
+ );
2402
+ }
2403
+ }
2404
+ });
2405
+ }
2406
+ /**
2407
+ * Wrap a StreamTextResult with guardrail protection on toUIMessageStream().
2408
+ *
2409
+ * When a guardrail fails:
2410
+ * 1. Accumulated text + feedback is appended as the assistant's self-correction
2411
+ * 2. The feedback is written to the output stream (user sees the correction)
2412
+ * 3. A new stream is started and the model continues from the correction
2413
+ */
2414
+ #wrapWithGuardrails(result, contextVariables, config) {
2415
+ const maxRetries = config?.maxRetries ?? this.#options.maxGuardrailRetries ?? 3;
2416
+ const context = this.#options.context;
2417
+ const originalToUIMessageStream = result.toUIMessageStream.bind(result);
2418
+ result.toUIMessageStream = (options) => {
2419
+ return createUIMessageStream({
2420
+ generateId: generateId2,
2421
+ execute: async ({ writer }) => {
2422
+ let currentResult = result;
2423
+ let attempt = 0;
2424
+ const guardrailContext = {
2425
+ availableTools: Object.keys(this.tools)
2426
+ };
2427
+ while (attempt < maxRetries) {
2428
+ if (config?.abortSignal?.aborted) {
2429
+ writer.write({ type: "finish" });
2430
+ return;
2431
+ }
2432
+ attempt++;
2433
+ let accumulatedText = "";
2434
+ let guardrailFailed = false;
2435
+ let failureFeedback = "";
2436
+ const uiStream = currentResult === result ? originalToUIMessageStream(options) : currentResult.toUIMessageStream(options);
2437
+ for await (const part of uiStream) {
2438
+ const checkResult = runGuardrailChain(
2439
+ part,
2440
+ this.#guardrails,
2441
+ guardrailContext
2442
+ );
2443
+ if (checkResult.type === "fail") {
2444
+ guardrailFailed = true;
2445
+ failureFeedback = checkResult.feedback;
2446
+ console.log(
2447
+ chalk2.yellow(
2448
+ `[${this.#options.name}] Guardrail triggered (attempt ${attempt}/${maxRetries}): ${failureFeedback.slice(0, 50)}...`
2449
+ )
2450
+ );
2451
+ break;
2452
+ }
2453
+ if (checkResult.part.type === "text-delta") {
2454
+ accumulatedText += checkResult.part.delta;
2455
+ }
2456
+ writer.write(checkResult.part);
2457
+ }
2458
+ if (!guardrailFailed) {
2459
+ writer.write({ type: "finish" });
2460
+ return;
2461
+ }
2462
+ if (attempt >= maxRetries) {
2463
+ console.error(
2464
+ chalk2.red(
2465
+ `[${this.#options.name}] Guardrail retry limit (${maxRetries}) exceeded.`
2466
+ )
2467
+ );
2468
+ writer.write({ type: "finish" });
2469
+ return;
2470
+ }
2471
+ writeText(writer, failureFeedback);
2472
+ const selfCorrectionText = accumulatedText + " " + failureFeedback;
2473
+ context.set(lastAssistantMessage(selfCorrectionText));
2474
+ await context.save();
2475
+ currentResult = await this.#createRawStream(
2476
+ contextVariables,
2477
+ config
2478
+ );
2479
+ }
2480
+ },
2481
+ onError: (error) => {
2482
+ const message2 = error instanceof Error ? error.message : String(error);
2483
+ return `Stream failed: ${message2}`;
2484
+ }
2485
+ });
2486
+ };
2487
+ return result;
2488
+ }
2489
+ clone(overrides) {
2490
+ return new _Agent({
2491
+ ...this.#options,
2492
+ ...overrides
2493
+ });
2494
+ }
2495
+ };
2496
+ function agent(options) {
2497
+ return new Agent(options);
2498
+ }
2499
+ var repairToolCall = async ({
2500
+ toolCall,
2501
+ tools,
2502
+ inputSchema,
2503
+ error
2504
+ }) => {
2505
+ console.log(
2506
+ `Debug: ${chalk2.yellow("RepairingToolCall")}: ${toolCall.toolName}`,
2507
+ error.name
2508
+ );
2509
+ if (NoSuchToolError.isInstance(error)) {
2510
+ return null;
2511
+ }
2512
+ const tool2 = tools[toolCall.toolName];
2513
+ const { output } = await generateText({
2514
+ model: groq("openai/gpt-oss-20b"),
2515
+ output: Output.object({ schema: tool2.inputSchema }),
2516
+ prompt: [
2517
+ `The model tried to call the tool "${toolCall.toolName}" with the following inputs:`,
2518
+ JSON.stringify(toolCall.input),
2519
+ `The tool accepts the following schema:`,
2520
+ JSON.stringify(inputSchema(toolCall)),
2521
+ "Please fix the inputs."
2522
+ ].join("\n")
2523
+ });
2524
+ return { ...toolCall, input: JSON.stringify(output) };
2525
+ };
2526
+ function writeText(writer, text) {
2527
+ const feedbackPartId = generateId2();
2528
+ writer.write({
2529
+ id: feedbackPartId,
2530
+ type: "text-start"
2531
+ });
2532
+ writer.write({
2533
+ id: feedbackPartId,
2534
+ type: "text-delta",
2535
+ delta: ` ${text}`
2536
+ });
2537
+ writer.write({
2538
+ id: feedbackPartId,
2539
+ type: "text-end"
2540
+ });
2541
+ }
2542
+
2543
+ // packages/text2sql/src/lib/adapters/groundings/report.grounding.ts
606
2544
  var ReportGrounding = class extends AbstractGrounding {
607
2545
  #adapter;
608
2546
  #model;
@@ -611,7 +2549,7 @@ var ReportGrounding = class extends AbstractGrounding {
611
2549
  constructor(adapter, config = {}) {
612
2550
  super("business_context");
613
2551
  this.#adapter = adapter;
614
- this.#model = config.model ?? groq("openai/gpt-oss-20b");
2552
+ this.#model = config.model ?? groq2("openai/gpt-oss-20b");
615
2553
  this.#cache = config.cache;
616
2554
  this.#forceRefresh = config.forceRefresh ?? false;
617
2555
  }
@@ -630,16 +2568,62 @@ var ReportGrounding = class extends AbstractGrounding {
630
2568
  }
631
2569
  }
632
2570
  async #generateReport() {
633
- const { text } = await generate(
634
- reportAgent.clone({ model: this.#model }),
635
- [
636
- user(
637
- "Please analyze the database and write a contextual report about what this database represents."
638
- )
639
- ],
640
- { adapter: this.#adapter }
2571
+ const context = new ContextEngine({
2572
+ store: new InMemoryContextStore(),
2573
+ chatId: `report-gen-${crypto.randomUUID()}`,
2574
+ userId: "system"
2575
+ });
2576
+ context.set(
2577
+ persona({
2578
+ name: "db-report-agent",
2579
+ role: "Database analyst",
2580
+ objective: "Analyze the database and write a contextual report about what it represents"
2581
+ }),
2582
+ fragment(
2583
+ "instructions",
2584
+ dedent`
2585
+ Write a business context that helps another agent answer questions accurately.
2586
+
2587
+ For EACH table, do queries ONE AT A TIME:
2588
+ 1. SELECT COUNT(*) to get row count
2589
+ 2. SELECT * LIMIT 3 to see sample data
2590
+
2591
+ Then write a report with:
2592
+ - What business this database is for
2593
+ - For each table: purpose, row count, and example of what the data looks like
2594
+
2595
+ Include concrete examples like "Track prices are $0.99",
2596
+ "Customer names like 'Luís Gonçalves'", etc.
2597
+
2598
+ Keep it 400-600 words, conversational style.
2599
+ `
2600
+ ),
2601
+ user(
2602
+ "Please analyze the database and write a contextual report about what this database represents."
2603
+ )
641
2604
  );
642
- return text;
2605
+ const adapter = this.#adapter;
2606
+ const reportAgent = agent({
2607
+ name: "db-report-agent",
2608
+ model: this.#model,
2609
+ context,
2610
+ tools: {
2611
+ query_database: tool({
2612
+ description: "Execute a SELECT query to explore the database and gather insights.",
2613
+ inputSchema: z.object({
2614
+ sql: z.string().describe("The SELECT query to execute"),
2615
+ purpose: z.string().describe(
2616
+ "What insight you are trying to gather with this query"
2617
+ )
2618
+ }),
2619
+ execute: ({ sql }) => {
2620
+ return adapter.execute(sql);
2621
+ }
2622
+ })
2623
+ }
2624
+ });
2625
+ const result = await reportAgent.generate({});
2626
+ return result.text;
643
2627
  }
644
2628
  };
645
2629