@deepagents/text2sql 0.12.0 → 0.13.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 (29) hide show
  1. package/dist/index.js +263 -81
  2. package/dist/index.js.map +4 -4
  3. package/dist/lib/adapters/groundings/index.js +167 -11
  4. package/dist/lib/adapters/groundings/index.js.map +4 -4
  5. package/dist/lib/adapters/mysql/index.js +167 -11
  6. package/dist/lib/adapters/mysql/index.js.map +4 -4
  7. package/dist/lib/adapters/postgres/index.js +167 -11
  8. package/dist/lib/adapters/postgres/index.js.map +4 -4
  9. package/dist/lib/adapters/spreadsheet/index.js +2 -0
  10. package/dist/lib/adapters/spreadsheet/index.js.map +3 -3
  11. package/dist/lib/adapters/sqlite/index.js +167 -11
  12. package/dist/lib/adapters/sqlite/index.js.map +4 -4
  13. package/dist/lib/adapters/sqlserver/column-stats.sqlserver.grounding.d.ts.map +1 -1
  14. package/dist/lib/adapters/sqlserver/index.js +168 -14
  15. package/dist/lib/adapters/sqlserver/index.js.map +4 -4
  16. package/dist/lib/agents/result-tools.d.ts +12 -3
  17. package/dist/lib/agents/result-tools.d.ts.map +1 -1
  18. package/dist/lib/agents/sql.agent.d.ts +1 -1
  19. package/dist/lib/agents/sql.agent.d.ts.map +1 -1
  20. package/dist/lib/instructions.d.ts.map +1 -1
  21. package/dist/lib/sql.d.ts +4 -15
  22. package/dist/lib/sql.d.ts.map +1 -1
  23. package/dist/lib/synthesis/index.js +176 -10
  24. package/dist/lib/synthesis/index.js.map +4 -4
  25. package/dist/lib/synthesis/synthesizers/depth-evolver.d.ts +3 -3
  26. package/dist/lib/synthesis/synthesizers/depth-evolver.d.ts.map +1 -1
  27. package/dist/lib/synthesis/synthesizers/schema-synthesizer.d.ts +1 -1
  28. package/dist/lib/synthesis/synthesizers/schema-synthesizer.d.ts.map +1 -1
  29. package/package.json +4 -4
@@ -226,6 +226,7 @@ import z from "zod";
226
226
  import "@deepagents/agent";
227
227
 
228
228
  // packages/context/dist/index.js
229
+ import { mergeWith } from "lodash-es";
229
230
  import { encode } from "gpt-tokenizer";
230
231
  import { generateId } from "ai";
231
232
  import pluralize from "pluralize";
@@ -437,7 +438,7 @@ function message(content) {
437
438
  } : content;
438
439
  return {
439
440
  id: message2.id,
440
- name: "message",
441
+ name: message2.role,
441
442
  data: "content",
442
443
  type: "message",
443
444
  persist: true,
@@ -459,6 +460,22 @@ function assistantText(content, options) {
459
460
  parts: [{ type: "text", text: content }]
460
461
  });
461
462
  }
463
+ var LAZY_ID = Symbol("lazy-id");
464
+ function isLazyFragment(fragment2) {
465
+ return LAZY_ID in fragment2;
466
+ }
467
+ function lastAssistantMessage(content) {
468
+ return {
469
+ name: "assistant",
470
+ type: "message",
471
+ persist: true,
472
+ data: "content",
473
+ [LAZY_ID]: {
474
+ type: "last-assistant",
475
+ content
476
+ }
477
+ };
478
+ }
462
479
  var ContextRenderer = class {
463
480
  options;
464
481
  constructor(options = {}) {
@@ -785,6 +802,8 @@ var ContextEngine = class {
785
802
  #branch = null;
786
803
  #chatData = null;
787
804
  #initialized = false;
805
+ /** Initial metadata to merge on first initialization */
806
+ #initialMetadata;
788
807
  constructor(options) {
789
808
  if (!options.chatId) {
790
809
  throw new Error("chatId is required");
@@ -796,6 +815,7 @@ var ContextEngine = class {
796
815
  this.#chatId = options.chatId;
797
816
  this.#userId = options.userId;
798
817
  this.#branchName = "main";
818
+ this.#initialMetadata = options.metadata;
799
819
  }
800
820
  /**
801
821
  * Initialize the chat and branch if they don't exist.
@@ -808,6 +828,15 @@ var ContextEngine = class {
808
828
  id: this.#chatId,
809
829
  userId: this.#userId
810
830
  });
831
+ if (this.#initialMetadata) {
832
+ this.#chatData = await this.#store.updateChat(this.#chatId, {
833
+ metadata: {
834
+ ...this.#chatData.metadata,
835
+ ...this.#initialMetadata
836
+ }
837
+ });
838
+ this.#initialMetadata = void 0;
839
+ }
811
840
  this.#branch = await this.#store.getActiveBranch(this.#chatId);
812
841
  this.#initialized = true;
813
842
  }
@@ -955,6 +984,12 @@ var ContextEngine = class {
955
984
  if (this.#pendingMessages.length === 0) {
956
985
  return;
957
986
  }
987
+ for (let i = 0; i < this.#pendingMessages.length; i++) {
988
+ const fragment2 = this.#pendingMessages[i];
989
+ if (isLazyFragment(fragment2)) {
990
+ this.#pendingMessages[i] = await this.#resolveLazyFragment(fragment2);
991
+ }
992
+ }
958
993
  let parentId = this.#branch.headMessageId;
959
994
  const now = Date.now();
960
995
  for (const fragment2 of this.#pendingMessages) {
@@ -974,6 +1009,39 @@ var ContextEngine = class {
974
1009
  this.#branch.headMessageId = parentId;
975
1010
  this.#pendingMessages = [];
976
1011
  }
1012
+ /**
1013
+ * Resolve a lazy fragment by finding the appropriate ID.
1014
+ */
1015
+ async #resolveLazyFragment(fragment2) {
1016
+ const lazy = fragment2[LAZY_ID];
1017
+ if (lazy.type === "last-assistant") {
1018
+ const lastId = await this.#getLastAssistantId();
1019
+ return assistantText(lazy.content, { id: lastId ?? crypto.randomUUID() });
1020
+ }
1021
+ throw new Error(`Unknown lazy fragment type: ${lazy.type}`);
1022
+ }
1023
+ /**
1024
+ * Find the most recent assistant message ID (pending or persisted).
1025
+ */
1026
+ async #getLastAssistantId() {
1027
+ for (let i = this.#pendingMessages.length - 1; i >= 0; i--) {
1028
+ const msg = this.#pendingMessages[i];
1029
+ if (msg.name === "assistant" && !isLazyFragment(msg)) {
1030
+ return msg.id;
1031
+ }
1032
+ }
1033
+ if (this.#branch?.headMessageId) {
1034
+ const chain = await this.#store.getMessageChain(
1035
+ this.#branch.headMessageId
1036
+ );
1037
+ for (let i = chain.length - 1; i >= 0; i--) {
1038
+ if (chain[i].name === "assistant") {
1039
+ return chain[i].id;
1040
+ }
1041
+ }
1042
+ }
1043
+ return void 0;
1044
+ }
977
1045
  /**
978
1046
  * Estimate token count and cost for the full context.
979
1047
  *
@@ -1242,6 +1310,36 @@ var ContextEngine = class {
1242
1310
  }
1243
1311
  this.#chatData = await this.#store.updateChat(this.#chatId, storeUpdates);
1244
1312
  }
1313
+ /**
1314
+ * Track token usage for the current chat.
1315
+ * Accumulates usage metrics in chat.metadata.usage.
1316
+ *
1317
+ * @param usage - Token usage from AI SDK (LanguageModelUsage)
1318
+ *
1319
+ * @example
1320
+ * ```ts
1321
+ * // In onFinish callback
1322
+ * const usage = await result.totalUsage;
1323
+ * await context.trackUsage(usage);
1324
+ * ```
1325
+ */
1326
+ async trackUsage(usage) {
1327
+ await this.#ensureInitialized();
1328
+ const freshChatData = await this.#store.getChat(this.#chatId);
1329
+ const currentUsage = freshChatData?.metadata?.usage ?? {};
1330
+ const updatedUsage = mergeWith(
1331
+ {},
1332
+ currentUsage,
1333
+ usage,
1334
+ (a, b) => typeof a === "number" || typeof b === "number" ? (a ?? 0) + (b ?? 0) : void 0
1335
+ );
1336
+ this.#chatData = await this.#store.updateChat(this.#chatId, {
1337
+ metadata: {
1338
+ ...freshChatData?.metadata,
1339
+ usage: updatedUsage
1340
+ }
1341
+ });
1342
+ }
1245
1343
  /**
1246
1344
  * Consolidate context fragments (no-op for now).
1247
1345
  *
@@ -1253,6 +1351,35 @@ var ContextEngine = class {
1253
1351
  consolidate() {
1254
1352
  return void 0;
1255
1353
  }
1354
+ /**
1355
+ * Extract skill path mappings from available_skills fragments.
1356
+ * Returns array of { host, sandbox } for mounting in sandbox filesystem.
1357
+ *
1358
+ * Reads the original `paths` configuration stored in fragment metadata
1359
+ * by the skills() fragment helper.
1360
+ *
1361
+ * @example
1362
+ * ```ts
1363
+ * const context = new ContextEngine({ store, chatId, userId })
1364
+ * .set(skills({ paths: [{ host: './skills', sandbox: '/skills' }] }));
1365
+ *
1366
+ * const mounts = context.getSkillMounts();
1367
+ * // [{ host: './skills', sandbox: '/skills' }]
1368
+ * ```
1369
+ */
1370
+ getSkillMounts() {
1371
+ const mounts = [];
1372
+ for (const fragment2 of this.#fragments) {
1373
+ if (fragment2.name === "available_skills" && fragment2.metadata && Array.isArray(fragment2.metadata.paths)) {
1374
+ for (const mapping of fragment2.metadata.paths) {
1375
+ if (typeof mapping === "object" && mapping !== null && typeof mapping.host === "string" && typeof mapping.sandbox === "string") {
1376
+ mounts.push({ host: mapping.host, sandbox: mapping.sandbox });
1377
+ }
1378
+ }
1379
+ }
1380
+ }
1381
+ return mounts;
1382
+ }
1256
1383
  /**
1257
1384
  * Inspect the full context state for debugging.
1258
1385
  * Returns a JSON-serializable object with context information.
@@ -1508,12 +1635,20 @@ var SqliteContextStore = class extends ContextStore {
1508
1635
  }
1509
1636
  async listChats(options) {
1510
1637
  const params = [];
1511
- let whereClause = "";
1638
+ const whereClauses = [];
1512
1639
  let limitClause = "";
1513
1640
  if (options?.userId) {
1514
- whereClause = "WHERE c.userId = ?";
1641
+ whereClauses.push("c.userId = ?");
1515
1642
  params.push(options.userId);
1516
1643
  }
1644
+ if (options?.metadata) {
1645
+ whereClauses.push(`json_extract(c.metadata, '$.' || ?) = ?`);
1646
+ params.push(options.metadata.key);
1647
+ params.push(
1648
+ typeof options.metadata.value === "boolean" ? options.metadata.value ? 1 : 0 : options.metadata.value
1649
+ );
1650
+ }
1651
+ const whereClause = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
1517
1652
  if (options?.limit !== void 0) {
1518
1653
  limitClause = " LIMIT ?";
1519
1654
  params.push(options.limit);
@@ -1527,6 +1662,7 @@ var SqliteContextStore = class extends ContextStore {
1527
1662
  c.id,
1528
1663
  c.userId,
1529
1664
  c.title,
1665
+ c.metadata,
1530
1666
  c.createdAt,
1531
1667
  c.updatedAt,
1532
1668
  COUNT(DISTINCT m.id) as messageCount,
@@ -1542,6 +1678,7 @@ var SqliteContextStore = class extends ContextStore {
1542
1678
  id: row.id,
1543
1679
  userId: row.userId,
1544
1680
  title: row.title ?? void 0,
1681
+ metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
1545
1682
  messageCount: row.messageCount,
1546
1683
  branchCount: row.branchCount,
1547
1684
  createdAt: row.createdAt,
@@ -1573,9 +1710,16 @@ var SqliteContextStore = class extends ContextStore {
1573
1710
  async addMessage(message2) {
1574
1711
  this.#db.prepare(
1575
1712
  `INSERT INTO messages (id, chatId, parentId, name, type, data, createdAt)
1576
- VALUES (?, ?, ?, ?, ?, ?, ?)
1713
+ VALUES (
1714
+ ?1,
1715
+ ?2,
1716
+ CASE WHEN ?3 = ?1 THEN (SELECT parentId FROM messages WHERE id = ?1) ELSE ?3 END,
1717
+ ?4,
1718
+ ?5,
1719
+ ?6,
1720
+ ?7
1721
+ )
1577
1722
  ON CONFLICT(id) DO UPDATE SET
1578
- parentId = excluded.parentId,
1579
1723
  name = excluded.name,
1580
1724
  type = excluded.type,
1581
1725
  data = excluded.data`
@@ -2050,13 +2194,9 @@ var Agent = class _Agent {
2050
2194
  writer.write({ type: "finish" });
2051
2195
  return;
2052
2196
  }
2053
- writer.write({
2054
- type: "text-delta",
2055
- id: generateId2(),
2056
- delta: ` ${failureFeedback}`
2057
- });
2197
+ writeText(writer, failureFeedback);
2058
2198
  const selfCorrectionText = accumulatedText + " " + failureFeedback;
2059
- context.set(assistantText(selfCorrectionText));
2199
+ context.set(lastAssistantMessage(selfCorrectionText));
2060
2200
  await context.save();
2061
2201
  currentResult = await this.#createRawStream(
2062
2202
  contextVariables,
@@ -2109,6 +2249,22 @@ var repairToolCall = async ({
2109
2249
  });
2110
2250
  return { ...toolCall, input: JSON.stringify(output) };
2111
2251
  };
2252
+ function writeText(writer, text) {
2253
+ const feedbackPartId = generateId2();
2254
+ writer.write({
2255
+ id: feedbackPartId,
2256
+ type: "text-start"
2257
+ });
2258
+ writer.write({
2259
+ id: feedbackPartId,
2260
+ type: "text-delta",
2261
+ delta: ` ${text}`
2262
+ });
2263
+ writer.write({
2264
+ id: feedbackPartId,
2265
+ type: "text-end"
2266
+ });
2267
+ }
2112
2268
 
2113
2269
  // packages/text2sql/src/lib/adapters/groundings/report.grounding.ts
2114
2270
  var ReportGrounding = class extends AbstractGrounding {