@deepagents/text2sql 0.11.0 → 0.12.0

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