@mastra/convex 1.3.2 → 1.4.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 (44) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +28 -17
  3. package/dist/{chunk-6P3LEDHY.cjs → chunk-2KILIA33.cjs} +315 -2
  4. package/dist/chunk-2KILIA33.cjs.map +1 -0
  5. package/dist/{chunk-77UWNT5X.js → chunk-MC2EQATP.js} +315 -2
  6. package/dist/chunk-MC2EQATP.js.map +1 -0
  7. package/dist/{chunk-MC75WADX.js → chunk-QWWFHN52.js} +41 -3
  8. package/dist/chunk-QWWFHN52.js.map +1 -0
  9. package/dist/{chunk-SFRHJGSM.cjs → chunk-ZCCKLZQH.cjs} +42 -2
  10. package/dist/chunk-ZCCKLZQH.cjs.map +1 -0
  11. package/dist/docs/SKILL.md +1 -1
  12. package/dist/docs/assets/SOURCE_MAP.json +41 -33
  13. package/dist/docs/references/reference-storage-convex.md +18 -11
  14. package/dist/index.cjs +586 -44
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.js +542 -4
  17. package/dist/index.js.map +1 -1
  18. package/dist/schema.cjs +38 -30
  19. package/dist/schema.d.ts +95 -1
  20. package/dist/schema.d.ts.map +1 -1
  21. package/dist/schema.js +1 -1
  22. package/dist/server/index-map.d.ts.map +1 -1
  23. package/dist/server/index.cjs +41 -33
  24. package/dist/server/index.d.ts +1 -1
  25. package/dist/server/index.d.ts.map +1 -1
  26. package/dist/server/index.js +2 -2
  27. package/dist/server/observational-memory.d.ts +52 -0
  28. package/dist/server/observational-memory.d.ts.map +1 -0
  29. package/dist/server/storage.d.ts.map +1 -1
  30. package/dist/storage/db/index.d.ts +65 -14
  31. package/dist/storage/db/index.d.ts.map +1 -1
  32. package/dist/storage/domains/memory/index.d.ts +23 -1
  33. package/dist/storage/domains/memory/index.d.ts.map +1 -1
  34. package/dist/storage/domains/schedules/index.d.ts.map +1 -1
  35. package/dist/storage/domains/scores/index.d.ts.map +1 -1
  36. package/dist/storage/types.d.ts +133 -0
  37. package/dist/storage/types.d.ts.map +1 -1
  38. package/dist/vector/index.d.ts.map +1 -1
  39. package/dist/vector/native.d.ts.map +1 -1
  40. package/package.json +11 -11
  41. package/dist/chunk-6P3LEDHY.cjs.map +0 -1
  42. package/dist/chunk-77UWNT5X.js.map +0 -1
  43. package/dist/chunk-MC75WADX.js.map +0 -1
  44. package/dist/chunk-SFRHJGSM.cjs.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,19 +1,14 @@
1
1
  'use strict';
2
2
 
3
- var chunk6P3LEDHY_cjs = require('./chunk-6P3LEDHY.cjs');
4
- var chunkSFRHJGSM_cjs = require('./chunk-SFRHJGSM.cjs');
3
+ var chunk2KILIA33_cjs = require('./chunk-2KILIA33.cjs');
4
+ var chunkZCCKLZQH_cjs = require('./chunk-ZCCKLZQH.cjs');
5
5
  var cache = require('@mastra/core/cache');
6
6
  var storage = require('@mastra/core/storage');
7
- var crypto = require('crypto');
8
7
  var base = require('@mastra/core/base');
9
8
  var agent = require('@mastra/core/agent');
10
9
  var error = require('@mastra/core/error');
11
10
  var vector = require('@mastra/core/vector');
12
11
 
13
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
-
15
- var crypto__default = /*#__PURE__*/_interopDefault(crypto);
16
-
17
12
  // src/cache/client.ts
18
13
  var DEFAULT_CACHE_FUNCTION = "mastra/cache:handle";
19
14
  var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
@@ -281,6 +276,11 @@ var ConvexAdminClient = class {
281
276
  return result;
282
277
  }
283
278
  };
279
+
280
+ // src/storage/types.ts
281
+ var TABLE_OBSERVATIONAL_MEMORY2 = "mastra_observational_memory";
282
+
283
+ // src/storage/db/index.ts
284
284
  var LOAD_MANY_REQUEST_BATCH_SIZE = 10;
285
285
  function resolveConvexConfig(config) {
286
286
  if ("client" in config) {
@@ -337,7 +337,10 @@ var ConvexDB = class extends base.MastraBase {
337
337
  record: this.normalizeRecord(tableName, record)
338
338
  });
339
339
  }
340
- async batchInsert({ tableName, records }) {
340
+ async batchInsert({
341
+ tableName,
342
+ records
343
+ }) {
341
344
  if (records.length === 0) return;
342
345
  await this.client.callStorage({
343
346
  op: "batchInsert",
@@ -546,6 +549,67 @@ var ConvexDB = class extends base.MastraBase {
546
549
  hasMore = response.hasMore ?? false;
547
550
  }
548
551
  }
552
+ // ============================================
553
+ // Observational Memory Operations
554
+ // These always target TABLE_OBSERVATIONAL_MEMORY — the server rejects
555
+ // om* operations against any other table.
556
+ // ============================================
557
+ async omGetLatest(lookupKey) {
558
+ return this.client.callStorage({
559
+ op: "omGetLatest",
560
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
561
+ lookupKey
562
+ });
563
+ }
564
+ async omGetHistory(args) {
565
+ return this.client.callStorage({
566
+ op: "omGetHistory",
567
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
568
+ ...args
569
+ });
570
+ }
571
+ async omUpdateActive(args) {
572
+ await this.client.callStorage({
573
+ op: "omUpdateActive",
574
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
575
+ ...args
576
+ });
577
+ }
578
+ async omAppendBufferedChunk(args) {
579
+ await this.client.callStorage({
580
+ op: "omAppendBufferedChunk",
581
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
582
+ ...args
583
+ });
584
+ }
585
+ async omSwapBuffered(args) {
586
+ return this.client.callStorage({
587
+ op: "omSwapBuffered",
588
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
589
+ ...args
590
+ });
591
+ }
592
+ async omUpdateBufferedReflection(args) {
593
+ await this.client.callStorage({
594
+ op: "omUpdateBufferedReflection",
595
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
596
+ ...args
597
+ });
598
+ }
599
+ async omSwapBufferedReflection(args) {
600
+ return this.client.callStorage({
601
+ op: "omSwapBufferedReflection",
602
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
603
+ ...args
604
+ });
605
+ }
606
+ async omUpdateConfig(args) {
607
+ await this.client.callStorage({
608
+ op: "omUpdateConfig",
609
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
610
+ ...args
611
+ });
612
+ }
549
613
  normalizeRecord(tableName, record) {
550
614
  const normalized = { ...record };
551
615
  if (tableName === storage.TABLE_WORKFLOW_SNAPSHOT && !normalized.id) {
@@ -554,7 +618,7 @@ var ConvexDB = class extends base.MastraBase {
554
618
  normalized.id = workflowName ? `${workflowName}-${runId}` : runId;
555
619
  }
556
620
  if (!normalized.id) {
557
- normalized.id = crypto__default.default.randomUUID();
621
+ normalized.id = crypto.randomUUID();
558
622
  }
559
623
  for (const [key, value] of Object.entries(normalized)) {
560
624
  if (value instanceof Date) {
@@ -907,7 +971,70 @@ function parseStoredResource(record) {
907
971
  updatedAt: new Date(record.updatedAt)
908
972
  };
909
973
  }
974
+ function toISO(value) {
975
+ return value instanceof Date ? value.toISOString() : value;
976
+ }
977
+ function serializeOMChunk(chunk) {
978
+ return {
979
+ ...chunk,
980
+ lastObservedAt: toISO(chunk.lastObservedAt),
981
+ createdAt: toISO(chunk.createdAt)
982
+ };
983
+ }
984
+ function parseOMChunk(chunk) {
985
+ return {
986
+ ...chunk,
987
+ lastObservedAt: new Date(chunk.lastObservedAt),
988
+ createdAt: new Date(chunk.createdAt)
989
+ };
990
+ }
991
+ function parseStoredOMChunks(value) {
992
+ if (!value) return void 0;
993
+ const parsed = storage.safelyParseJSON(value);
994
+ if (!Array.isArray(parsed)) return void 0;
995
+ return parsed.map((chunk) => parseOMChunk(chunk));
996
+ }
997
+ function parseStoredOMRecord(doc) {
998
+ const config = storage.safelyParseJSON(doc.config);
999
+ const metadata = doc.metadata ? storage.safelyParseJSON(doc.metadata) : void 0;
1000
+ return {
1001
+ id: doc.id,
1002
+ scope: doc.scope,
1003
+ threadId: doc.threadId || null,
1004
+ resourceId: doc.resourceId,
1005
+ createdAt: new Date(doc.createdAt),
1006
+ updatedAt: new Date(doc.updatedAt),
1007
+ lastObservedAt: doc.lastObservedAt ? new Date(doc.lastObservedAt) : void 0,
1008
+ originType: doc.originType || "initial",
1009
+ generationCount: Number(doc.generationCount || 0),
1010
+ activeObservations: doc.activeObservations || "",
1011
+ bufferedObservationChunks: parseStoredOMChunks(doc.bufferedObservationChunks),
1012
+ // Deprecated fields (for backward compatibility)
1013
+ bufferedObservations: doc.activeObservationsPendingUpdate || void 0,
1014
+ bufferedObservationTokens: doc.bufferedObservationTokens ? Number(doc.bufferedObservationTokens) : void 0,
1015
+ bufferedMessageIds: void 0,
1016
+ // Use bufferedObservationChunks instead
1017
+ bufferedReflection: doc.bufferedReflection || void 0,
1018
+ bufferedReflectionTokens: doc.bufferedReflectionTokens ? Number(doc.bufferedReflectionTokens) : void 0,
1019
+ bufferedReflectionInputTokens: doc.bufferedReflectionInputTokens ? Number(doc.bufferedReflectionInputTokens) : void 0,
1020
+ reflectedObservationLineCount: doc.reflectedObservationLineCount ? Number(doc.reflectedObservationLineCount) : void 0,
1021
+ totalTokensObserved: Number(doc.totalTokensObserved || 0),
1022
+ observationTokenCount: Number(doc.observationTokenCount || 0),
1023
+ pendingMessageTokens: Number(doc.pendingMessageTokens || 0),
1024
+ isReflecting: Boolean(doc.isReflecting),
1025
+ isObserving: Boolean(doc.isObserving),
1026
+ isBufferingObservation: Boolean(doc.isBufferingObservation),
1027
+ isBufferingReflection: Boolean(doc.isBufferingReflection),
1028
+ lastBufferedAtTokens: Number(doc.lastBufferedAtTokens || 0),
1029
+ lastBufferedAtTime: doc.lastBufferedAtTime ? new Date(doc.lastBufferedAtTime) : null,
1030
+ config: config ?? {},
1031
+ metadata: metadata ?? void 0,
1032
+ observedMessageIds: doc.observedMessageIds || void 0,
1033
+ observedTimezone: doc.observedTimezone || void 0
1034
+ };
1035
+ }
910
1036
  var MemoryConvex = class extends storage.MemoryStorage {
1037
+ supportsObservationalMemory = true;
911
1038
  #db;
912
1039
  constructor(config) {
913
1040
  super();
@@ -920,6 +1047,7 @@ var MemoryConvex = class extends storage.MemoryStorage {
920
1047
  await this.#db.clearTable({ tableName: storage.TABLE_THREADS });
921
1048
  await this.#db.clearTable({ tableName: storage.TABLE_MESSAGES });
922
1049
  await this.#db.clearTable({ tableName: storage.TABLE_RESOURCES });
1050
+ await this.#db.clearTable({ tableName: TABLE_OBSERVATIONAL_MEMORY2 });
923
1051
  }
924
1052
  async getThreadById({
925
1053
  threadId,
@@ -1113,6 +1241,51 @@ var MemoryConvex = class extends storage.MemoryStorage {
1113
1241
  hasMore
1114
1242
  };
1115
1243
  }
1244
+ async listMessagesByResourceId(args) {
1245
+ const { resourceId, filter, perPage: perPageInput, page = 0, orderBy } = args;
1246
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
1247
+ const perPage = storage.normalizePerPage(perPageInput, 40);
1248
+ if (page < 0) {
1249
+ throw new error.MastraError(
1250
+ {
1251
+ id: storage.createStorageErrorId("CONVEX", "LIST_MESSAGES_BY_RESOURCE_ID", "INVALID_PAGE"),
1252
+ domain: error.ErrorDomain.STORAGE,
1253
+ category: error.ErrorCategory.USER,
1254
+ details: { page }
1255
+ },
1256
+ new Error("page must be >= 0")
1257
+ );
1258
+ }
1259
+ const maxOffset = Number.MAX_SAFE_INTEGER / 2;
1260
+ if (page * perPage > maxOffset) {
1261
+ throw new error.MastraError(
1262
+ {
1263
+ id: storage.createStorageErrorId("CONVEX", "LIST_MESSAGES_BY_RESOURCE_ID", "INVALID_PAGE"),
1264
+ domain: error.ErrorDomain.STORAGE,
1265
+ category: error.ErrorCategory.USER,
1266
+ details: { page, perPage }
1267
+ },
1268
+ new Error("page value too large")
1269
+ );
1270
+ }
1271
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1272
+ let rows = await this.#db.queryTable(storage.TABLE_MESSAGES, [{ field: "resourceId", value: resourceId }]);
1273
+ rows = storage.filterByDateRange(rows, (row) => new Date(row.createdAt), filter?.dateRange);
1274
+ rows = this._sortStoredMessages(rows, field, direction);
1275
+ const total = rows.length;
1276
+ const paginatedRows = rows.slice(offset, offset + perPage);
1277
+ const list = new agent.MessageList().add(
1278
+ paginatedRows.map((row) => this.parseStoredMessage(row)),
1279
+ "memory"
1280
+ );
1281
+ return {
1282
+ messages: list.get.all.db(),
1283
+ total,
1284
+ page,
1285
+ perPage: perPageForResponse,
1286
+ hasMore: offset + paginatedRows.length < total
1287
+ };
1288
+ }
1116
1289
  async listMessagesById({ messageIds }) {
1117
1290
  if (messageIds.length === 0) {
1118
1291
  return { messages: [] };
@@ -1252,6 +1425,16 @@ var MemoryConvex = class extends storage.MemoryStorage {
1252
1425
  });
1253
1426
  return parseStoredResource(updated);
1254
1427
  }
1428
+ _sortStoredMessages(rows, field, direction) {
1429
+ return rows.sort((a, b) => {
1430
+ const aValue = field === "createdAt" || field === "updatedAt" ? new Date(a[field]).getTime() : a[field];
1431
+ const bValue = field === "createdAt" || field === "updatedAt" ? new Date(b[field]).getTime() : b[field];
1432
+ if (typeof aValue === "number" && typeof bValue === "number") {
1433
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
1434
+ }
1435
+ return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
1436
+ });
1437
+ }
1255
1438
  _sortMessages(messages, field, direction) {
1256
1439
  return messages.sort((a, b) => {
1257
1440
  const aValue = field === "createdAt" || field === "updatedAt" ? new Date(a[field]).getTime() : a[field];
@@ -1358,6 +1541,357 @@ var MemoryConvex = class extends storage.MemoryStorage {
1358
1541
  }
1359
1542
  }
1360
1543
  }
1544
+ // ============================================
1545
+ // Observational Memory Methods
1546
+ // ============================================
1547
+ getOMKey(threadId, resourceId) {
1548
+ return threadId ? `thread:${threadId}` : `resource:${resourceId}`;
1549
+ }
1550
+ omRecordNotFound(operation, id) {
1551
+ return new error.MastraError({
1552
+ id: storage.createStorageErrorId("CONVEX", operation, "NOT_FOUND"),
1553
+ text: `Observational memory record not found: ${id}`,
1554
+ domain: error.ErrorDomain.STORAGE,
1555
+ category: error.ErrorCategory.THIRD_PARTY,
1556
+ details: { id }
1557
+ });
1558
+ }
1559
+ async getObservationalMemory(threadId, resourceId) {
1560
+ const lookupKey = this.getOMKey(threadId, resourceId);
1561
+ const doc = await this.#db.omGetLatest(lookupKey);
1562
+ return doc ? parseStoredOMRecord(doc) : null;
1563
+ }
1564
+ async getObservationalMemoryHistory(threadId, resourceId, limit = 10, options) {
1565
+ const lookupKey = this.getOMKey(threadId, resourceId);
1566
+ const docs = await this.#db.omGetHistory({
1567
+ lookupKey,
1568
+ limit,
1569
+ from: options?.from ? options.from.toISOString() : void 0,
1570
+ to: options?.to ? options.to.toISOString() : void 0,
1571
+ offset: options?.offset ?? void 0
1572
+ });
1573
+ return docs.map((doc) => parseStoredOMRecord(doc));
1574
+ }
1575
+ async initializeObservationalMemory(input) {
1576
+ const id = crypto.randomUUID();
1577
+ const now = /* @__PURE__ */ new Date();
1578
+ const lookupKey = this.getOMKey(input.threadId, input.resourceId);
1579
+ const record = {
1580
+ id,
1581
+ scope: input.scope,
1582
+ threadId: input.threadId,
1583
+ resourceId: input.resourceId,
1584
+ createdAt: now,
1585
+ updatedAt: now,
1586
+ // lastObservedAt starts undefined - all messages are "unobserved" initially
1587
+ lastObservedAt: void 0,
1588
+ originType: "initial",
1589
+ generationCount: 0,
1590
+ activeObservations: "",
1591
+ totalTokensObserved: 0,
1592
+ observationTokenCount: 0,
1593
+ pendingMessageTokens: 0,
1594
+ isReflecting: false,
1595
+ isObserving: false,
1596
+ isBufferingObservation: false,
1597
+ isBufferingReflection: false,
1598
+ lastBufferedAtTokens: 0,
1599
+ lastBufferedAtTime: null,
1600
+ config: input.config,
1601
+ observedTimezone: input.observedTimezone
1602
+ };
1603
+ await this.#db.insert({
1604
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
1605
+ record: {
1606
+ id,
1607
+ lookupKey,
1608
+ scope: input.scope,
1609
+ resourceId: input.resourceId,
1610
+ threadId: input.threadId || null,
1611
+ activeObservations: "",
1612
+ activeObservationsPendingUpdate: null,
1613
+ originType: "initial",
1614
+ config: JSON.stringify(input.config ?? {}),
1615
+ generationCount: 0,
1616
+ lastObservedAt: null,
1617
+ lastReflectionAt: null,
1618
+ pendingMessageTokens: 0,
1619
+ totalTokensObserved: 0,
1620
+ observationTokenCount: 0,
1621
+ isObserving: false,
1622
+ isReflecting: false,
1623
+ isBufferingObservation: false,
1624
+ isBufferingReflection: false,
1625
+ lastBufferedAtTokens: 0,
1626
+ lastBufferedAtTime: null,
1627
+ observedTimezone: input.observedTimezone || null,
1628
+ createdAt: now.toISOString(),
1629
+ updatedAt: now.toISOString()
1630
+ }
1631
+ });
1632
+ return record;
1633
+ }
1634
+ async insertObservationalMemoryRecord(record) {
1635
+ const lookupKey = this.getOMKey(record.threadId, record.resourceId);
1636
+ await this.#db.insert({
1637
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
1638
+ record: {
1639
+ id: record.id,
1640
+ lookupKey,
1641
+ scope: record.scope,
1642
+ resourceId: record.resourceId,
1643
+ threadId: record.threadId || null,
1644
+ activeObservations: record.activeObservations || "",
1645
+ activeObservationsPendingUpdate: null,
1646
+ originType: record.originType || "initial",
1647
+ config: JSON.stringify(record.config ?? {}),
1648
+ generationCount: record.generationCount || 0,
1649
+ lastObservedAt: record.lastObservedAt ? toISO(record.lastObservedAt) : null,
1650
+ lastReflectionAt: null,
1651
+ pendingMessageTokens: record.pendingMessageTokens || 0,
1652
+ totalTokensObserved: record.totalTokensObserved || 0,
1653
+ observationTokenCount: record.observationTokenCount || 0,
1654
+ observedMessageIds: record.observedMessageIds || null,
1655
+ bufferedObservationChunks: JSON.stringify(
1656
+ (Array.isArray(record.bufferedObservationChunks) ? record.bufferedObservationChunks : []).map(
1657
+ (chunk) => serializeOMChunk(chunk)
1658
+ )
1659
+ ),
1660
+ bufferedReflection: record.bufferedReflection || null,
1661
+ bufferedReflectionTokens: record.bufferedReflectionTokens ?? null,
1662
+ bufferedReflectionInputTokens: record.bufferedReflectionInputTokens ?? null,
1663
+ reflectedObservationLineCount: record.reflectedObservationLineCount ?? null,
1664
+ isObserving: record.isObserving || false,
1665
+ isReflecting: record.isReflecting || false,
1666
+ isBufferingObservation: record.isBufferingObservation || false,
1667
+ isBufferingReflection: record.isBufferingReflection || false,
1668
+ lastBufferedAtTokens: record.lastBufferedAtTokens || 0,
1669
+ lastBufferedAtTime: record.lastBufferedAtTime ? toISO(record.lastBufferedAtTime) : null,
1670
+ observedTimezone: record.observedTimezone || null,
1671
+ metadata: record.metadata ? JSON.stringify(record.metadata) : null,
1672
+ createdAt: toISO(record.createdAt),
1673
+ updatedAt: toISO(record.updatedAt)
1674
+ }
1675
+ });
1676
+ }
1677
+ async updateActiveObservations(input) {
1678
+ await this.#db.omUpdateActive({
1679
+ id: input.id,
1680
+ observations: input.observations,
1681
+ tokenCount: input.tokenCount,
1682
+ lastObservedAt: toISO(input.lastObservedAt),
1683
+ observedMessageIds: input.observedMessageIds ?? null,
1684
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1685
+ });
1686
+ }
1687
+ async updateBufferedObservations(input) {
1688
+ const chunk = {
1689
+ id: `ombuf-${crypto.randomUUID()}`,
1690
+ cycleId: input.chunk.cycleId,
1691
+ observations: input.chunk.observations,
1692
+ tokenCount: input.chunk.tokenCount,
1693
+ messageIds: input.chunk.messageIds,
1694
+ messageTokens: input.chunk.messageTokens,
1695
+ lastObservedAt: toISO(input.chunk.lastObservedAt),
1696
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1697
+ suggestedContinuation: input.chunk.suggestedContinuation,
1698
+ currentTask: input.chunk.currentTask,
1699
+ threadTitle: input.chunk.threadTitle,
1700
+ extractedValues: input.chunk.extractedValues,
1701
+ extractionFailures: input.chunk.extractionFailures
1702
+ };
1703
+ await this.#db.omAppendBufferedChunk({
1704
+ id: input.id,
1705
+ chunk,
1706
+ lastBufferedAtTime: input.lastBufferedAtTime ? toISO(input.lastBufferedAtTime) : void 0,
1707
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1708
+ });
1709
+ }
1710
+ async swapBufferedToActive(input) {
1711
+ return this.#db.omSwapBuffered({
1712
+ id: input.id,
1713
+ activationRatio: input.activationRatio,
1714
+ messageTokensThreshold: input.messageTokensThreshold,
1715
+ currentPendingTokens: input.currentPendingTokens,
1716
+ forceMaxActivation: input.forceMaxActivation,
1717
+ lastObservedAt: input.lastObservedAt ? toISO(input.lastObservedAt) : void 0,
1718
+ bufferedChunks: Array.isArray(input.bufferedChunks) ? input.bufferedChunks.map((chunk) => serializeOMChunk(chunk)) : void 0,
1719
+ now: (/* @__PURE__ */ new Date()).toISOString()
1720
+ });
1721
+ }
1722
+ async createReflectionGeneration(input) {
1723
+ const id = crypto.randomUUID();
1724
+ const now = /* @__PURE__ */ new Date();
1725
+ const lookupKey = this.getOMKey(input.currentRecord.threadId, input.currentRecord.resourceId);
1726
+ const record = {
1727
+ id,
1728
+ scope: input.currentRecord.scope,
1729
+ threadId: input.currentRecord.threadId,
1730
+ resourceId: input.currentRecord.resourceId,
1731
+ createdAt: now,
1732
+ updatedAt: now,
1733
+ lastObservedAt: input.currentRecord.lastObservedAt,
1734
+ originType: "reflection",
1735
+ generationCount: input.currentRecord.generationCount + 1,
1736
+ activeObservations: input.reflection,
1737
+ totalTokensObserved: input.currentRecord.totalTokensObserved,
1738
+ observationTokenCount: input.tokenCount,
1739
+ pendingMessageTokens: 0,
1740
+ isReflecting: false,
1741
+ isObserving: false,
1742
+ isBufferingObservation: false,
1743
+ isBufferingReflection: false,
1744
+ lastBufferedAtTokens: 0,
1745
+ lastBufferedAtTime: null,
1746
+ config: input.currentRecord.config,
1747
+ metadata: input.currentRecord.metadata,
1748
+ observedTimezone: input.currentRecord.observedTimezone
1749
+ };
1750
+ await this.#db.insert({
1751
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
1752
+ record: {
1753
+ id,
1754
+ lookupKey,
1755
+ scope: record.scope,
1756
+ resourceId: record.resourceId,
1757
+ threadId: record.threadId || null,
1758
+ activeObservations: input.reflection,
1759
+ activeObservationsPendingUpdate: null,
1760
+ originType: "reflection",
1761
+ config: JSON.stringify(record.config ?? {}),
1762
+ generationCount: record.generationCount,
1763
+ lastObservedAt: record.lastObservedAt ? toISO(record.lastObservedAt) : null,
1764
+ lastReflectionAt: now.toISOString(),
1765
+ pendingMessageTokens: 0,
1766
+ totalTokensObserved: record.totalTokensObserved,
1767
+ observationTokenCount: record.observationTokenCount,
1768
+ isObserving: false,
1769
+ isReflecting: false,
1770
+ isBufferingObservation: false,
1771
+ isBufferingReflection: false,
1772
+ lastBufferedAtTokens: 0,
1773
+ lastBufferedAtTime: null,
1774
+ observedTimezone: record.observedTimezone || null,
1775
+ metadata: record.metadata ? JSON.stringify(record.metadata) : null,
1776
+ createdAt: now.toISOString(),
1777
+ updatedAt: now.toISOString()
1778
+ }
1779
+ });
1780
+ return record;
1781
+ }
1782
+ async updateBufferedReflection(input) {
1783
+ await this.#db.omUpdateBufferedReflection({
1784
+ id: input.id,
1785
+ reflection: input.reflection,
1786
+ tokenCount: input.tokenCount,
1787
+ inputTokenCount: input.inputTokenCount,
1788
+ reflectedObservationLineCount: input.reflectedObservationLineCount,
1789
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1790
+ });
1791
+ }
1792
+ async swapBufferedReflectionToActive(input) {
1793
+ const { currentRecord } = input;
1794
+ const serializedCurrentRecord = {
1795
+ id: currentRecord.id,
1796
+ lookupKey: this.getOMKey(currentRecord.threadId, currentRecord.resourceId),
1797
+ scope: currentRecord.scope,
1798
+ threadId: currentRecord.threadId || null,
1799
+ resourceId: currentRecord.resourceId,
1800
+ config: JSON.stringify(currentRecord.config ?? {}),
1801
+ metadata: currentRecord.metadata ? JSON.stringify(currentRecord.metadata) : null,
1802
+ observedTimezone: currentRecord.observedTimezone || null,
1803
+ lastObservedAt: currentRecord.lastObservedAt ? toISO(currentRecord.lastObservedAt) : null,
1804
+ totalTokensObserved: currentRecord.totalTokensObserved,
1805
+ generationCount: currentRecord.generationCount
1806
+ };
1807
+ const doc = await this.#db.omSwapBufferedReflection({
1808
+ currentRecord: serializedCurrentRecord,
1809
+ newId: crypto.randomUUID(),
1810
+ tokenCount: input.tokenCount,
1811
+ now: (/* @__PURE__ */ new Date()).toISOString()
1812
+ });
1813
+ return parseStoredOMRecord(doc);
1814
+ }
1815
+ async setReflectingFlag(id, isReflecting) {
1816
+ const found = await this.#db.patch({
1817
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
1818
+ id,
1819
+ record: { isReflecting, updatedAt: /* @__PURE__ */ new Date() }
1820
+ });
1821
+ if (!found) {
1822
+ throw this.omRecordNotFound("SET_REFLECTING_FLAG", id);
1823
+ }
1824
+ }
1825
+ async setObservingFlag(id, isObserving) {
1826
+ const found = await this.#db.patch({
1827
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
1828
+ id,
1829
+ record: { isObserving, updatedAt: /* @__PURE__ */ new Date() }
1830
+ });
1831
+ if (!found) {
1832
+ throw this.omRecordNotFound("SET_OBSERVING_FLAG", id);
1833
+ }
1834
+ }
1835
+ async setBufferingObservationFlag(id, isBuffering, lastBufferedAtTokens) {
1836
+ const found = await this.#db.patch({
1837
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
1838
+ id,
1839
+ record: {
1840
+ isBufferingObservation: isBuffering,
1841
+ ...lastBufferedAtTokens !== void 0 ? { lastBufferedAtTokens } : {},
1842
+ updatedAt: /* @__PURE__ */ new Date()
1843
+ }
1844
+ });
1845
+ if (!found) {
1846
+ throw this.omRecordNotFound("SET_BUFFERING_OBSERVATION_FLAG", id);
1847
+ }
1848
+ }
1849
+ async setBufferingReflectionFlag(id, isBuffering) {
1850
+ const found = await this.#db.patch({
1851
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
1852
+ id,
1853
+ record: { isBufferingReflection: isBuffering, updatedAt: /* @__PURE__ */ new Date() }
1854
+ });
1855
+ if (!found) {
1856
+ throw this.omRecordNotFound("SET_BUFFERING_REFLECTION_FLAG", id);
1857
+ }
1858
+ }
1859
+ async setPendingMessageTokens(id, tokenCount) {
1860
+ if (typeof tokenCount !== "number" || !Number.isFinite(tokenCount) || tokenCount < 0) {
1861
+ throw new error.MastraError({
1862
+ id: storage.createStorageErrorId("CONVEX", "SET_PENDING_MESSAGE_TOKENS", "INVALID_INPUT"),
1863
+ text: `Invalid tokenCount: must be a finite non-negative number, got ${tokenCount}`,
1864
+ domain: error.ErrorDomain.STORAGE,
1865
+ category: error.ErrorCategory.USER,
1866
+ details: { id, tokenCount }
1867
+ });
1868
+ }
1869
+ const found = await this.#db.patch({
1870
+ tableName: TABLE_OBSERVATIONAL_MEMORY2,
1871
+ id,
1872
+ record: { pendingMessageTokens: tokenCount, updatedAt: /* @__PURE__ */ new Date() }
1873
+ });
1874
+ if (!found) {
1875
+ throw this.omRecordNotFound("SET_PENDING_MESSAGE_TOKENS", id);
1876
+ }
1877
+ }
1878
+ async clearObservationalMemory(threadId, resourceId) {
1879
+ const lookupKey = this.getOMKey(threadId, resourceId);
1880
+ const docs = await this.#db.queryTable(TABLE_OBSERVATIONAL_MEMORY2, [
1881
+ { field: "lookupKey", value: lookupKey }
1882
+ ]);
1883
+ await this.#db.deleteMany(
1884
+ TABLE_OBSERVATIONAL_MEMORY2,
1885
+ docs.map((doc) => doc.id)
1886
+ );
1887
+ }
1888
+ async updateObservationalMemoryConfig(input) {
1889
+ await this.#db.omUpdateConfig({
1890
+ id: input.id,
1891
+ config: JSON.stringify(input.config ?? {}),
1892
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1893
+ });
1894
+ }
1361
1895
  };
1362
1896
  var SCHEDULE_LIST_LIMIT = 8e3;
1363
1897
  function serializeJson2(value) {
@@ -1423,7 +1957,7 @@ function recordToSchedule(record) {
1423
1957
  }
1424
1958
  function triggerToRecord(trigger) {
1425
1959
  return {
1426
- id: trigger.id ?? crypto__default.default.randomUUID(),
1960
+ id: trigger.id ?? crypto.randomUUID(),
1427
1961
  schedule_id: trigger.scheduleId,
1428
1962
  run_id: trigger.runId,
1429
1963
  scheduled_fire_at: trigger.scheduledFireAt,
@@ -1623,7 +2157,7 @@ var ScoresConvex = class extends storage.ScoresStorage {
1623
2157
  const now = /* @__PURE__ */ new Date();
1624
2158
  const record = {
1625
2159
  ...score,
1626
- id: crypto__default.default.randomUUID(),
2160
+ id: crypto.randomUUID(),
1627
2161
  createdAt: now.toISOString(),
1628
2162
  updatedAt: now.toISOString()
1629
2163
  };
@@ -1947,7 +2481,7 @@ var ConvexVector = class extends vector.MastraVector {
1947
2481
  };
1948
2482
  }
1949
2483
  async upsert({ indexName, vectors, ids, metadata }) {
1950
- const vectorIds = ids ?? vectors.map(() => crypto__default.default.randomUUID());
2484
+ const vectorIds = ids ?? vectors.map(() => crypto.randomUUID());
1951
2485
  const records = vectors.map((vector, i) => ({
1952
2486
  id: vectorIds[i],
1953
2487
  embedding: vector,
@@ -2299,7 +2833,7 @@ var ConvexNativeVector = class extends vector.MastraVector {
2299
2833
  if (metadata && !metadata.every(isMetadataRecord)) {
2300
2834
  throw new Error("ConvexNativeVector.upsert: metadata entries must be objects when provided");
2301
2835
  }
2302
- const vectorIds = ids ?? vectors.map(() => crypto__default.default.randomUUID());
2836
+ const vectorIds = ids ?? vectors.map(() => crypto.randomUUID());
2303
2837
  if (new Set(vectorIds).size !== vectorIds.length) {
2304
2838
  throw new Error("ConvexNativeVector.upsert: ids must be unique");
2305
2839
  }
@@ -2452,127 +2986,135 @@ var ConvexNativeVector = class extends vector.MastraVector {
2452
2986
 
2453
2987
  Object.defineProperty(exports, "mastraCache", {
2454
2988
  enumerable: true,
2455
- get: function () { return chunk6P3LEDHY_cjs.mastraCache; }
2989
+ get: function () { return chunk2KILIA33_cjs.mastraCache; }
2456
2990
  });
2457
2991
  Object.defineProperty(exports, "mastraNativeVectorAction", {
2458
2992
  enumerable: true,
2459
- get: function () { return chunk6P3LEDHY_cjs.mastraNativeVectorAction; }
2993
+ get: function () { return chunk2KILIA33_cjs.mastraNativeVectorAction; }
2460
2994
  });
2461
2995
  Object.defineProperty(exports, "mastraNativeVectorMutation", {
2462
2996
  enumerable: true,
2463
- get: function () { return chunk6P3LEDHY_cjs.mastraNativeVectorMutation; }
2997
+ get: function () { return chunk2KILIA33_cjs.mastraNativeVectorMutation; }
2464
2998
  });
2465
2999
  Object.defineProperty(exports, "mastraNativeVectorQuery", {
2466
3000
  enumerable: true,
2467
- get: function () { return chunk6P3LEDHY_cjs.mastraNativeVectorQuery; }
3001
+ get: function () { return chunk2KILIA33_cjs.mastraNativeVectorQuery; }
2468
3002
  });
2469
3003
  Object.defineProperty(exports, "mastraStorage", {
2470
3004
  enumerable: true,
2471
- get: function () { return chunk6P3LEDHY_cjs.mastraStorage; }
3005
+ get: function () { return chunk2KILIA33_cjs.mastraStorage; }
2472
3006
  });
2473
3007
  Object.defineProperty(exports, "TABLE_BACKGROUND_TASKS", {
2474
3008
  enumerable: true,
2475
- get: function () { return chunkSFRHJGSM_cjs.TABLE_BACKGROUND_TASKS; }
3009
+ get: function () { return chunkZCCKLZQH_cjs.TABLE_BACKGROUND_TASKS; }
2476
3010
  });
2477
3011
  Object.defineProperty(exports, "TABLE_CHANNEL_CONFIG", {
2478
3012
  enumerable: true,
2479
- get: function () { return chunkSFRHJGSM_cjs.TABLE_CHANNEL_CONFIG; }
3013
+ get: function () { return chunkZCCKLZQH_cjs.TABLE_CHANNEL_CONFIG; }
2480
3014
  });
2481
3015
  Object.defineProperty(exports, "TABLE_CHANNEL_INSTALLATIONS", {
2482
3016
  enumerable: true,
2483
- get: function () { return chunkSFRHJGSM_cjs.TABLE_CHANNEL_INSTALLATIONS; }
3017
+ get: function () { return chunkZCCKLZQH_cjs.TABLE_CHANNEL_INSTALLATIONS; }
2484
3018
  });
2485
3019
  Object.defineProperty(exports, "TABLE_MESSAGES", {
2486
3020
  enumerable: true,
2487
- get: function () { return chunkSFRHJGSM_cjs.TABLE_MESSAGES; }
3021
+ get: function () { return chunkZCCKLZQH_cjs.TABLE_MESSAGES; }
3022
+ });
3023
+ Object.defineProperty(exports, "TABLE_OBSERVATIONAL_MEMORY", {
3024
+ enumerable: true,
3025
+ get: function () { return chunkZCCKLZQH_cjs.TABLE_OBSERVATIONAL_MEMORY; }
2488
3026
  });
2489
3027
  Object.defineProperty(exports, "TABLE_RESOURCES", {
2490
3028
  enumerable: true,
2491
- get: function () { return chunkSFRHJGSM_cjs.TABLE_RESOURCES; }
3029
+ get: function () { return chunkZCCKLZQH_cjs.TABLE_RESOURCES; }
2492
3030
  });
2493
3031
  Object.defineProperty(exports, "TABLE_SCHEDULES", {
2494
3032
  enumerable: true,
2495
- get: function () { return chunkSFRHJGSM_cjs.TABLE_SCHEDULES; }
3033
+ get: function () { return chunkZCCKLZQH_cjs.TABLE_SCHEDULES; }
2496
3034
  });
2497
3035
  Object.defineProperty(exports, "TABLE_SCHEDULE_TRIGGERS", {
2498
3036
  enumerable: true,
2499
- get: function () { return chunkSFRHJGSM_cjs.TABLE_SCHEDULE_TRIGGERS; }
3037
+ get: function () { return chunkZCCKLZQH_cjs.TABLE_SCHEDULE_TRIGGERS; }
2500
3038
  });
2501
3039
  Object.defineProperty(exports, "TABLE_SCORERS", {
2502
3040
  enumerable: true,
2503
- get: function () { return chunkSFRHJGSM_cjs.TABLE_SCORERS; }
3041
+ get: function () { return chunkZCCKLZQH_cjs.TABLE_SCORERS; }
2504
3042
  });
2505
3043
  Object.defineProperty(exports, "TABLE_THREADS", {
2506
3044
  enumerable: true,
2507
- get: function () { return chunkSFRHJGSM_cjs.TABLE_THREADS; }
3045
+ get: function () { return chunkZCCKLZQH_cjs.TABLE_THREADS; }
2508
3046
  });
2509
3047
  Object.defineProperty(exports, "TABLE_WORKFLOW_SNAPSHOT", {
2510
3048
  enumerable: true,
2511
- get: function () { return chunkSFRHJGSM_cjs.TABLE_WORKFLOW_SNAPSHOT; }
3049
+ get: function () { return chunkZCCKLZQH_cjs.TABLE_WORKFLOW_SNAPSHOT; }
2512
3050
  });
2513
3051
  Object.defineProperty(exports, "defineMastraNativeVectorTable", {
2514
3052
  enumerable: true,
2515
- get: function () { return chunkSFRHJGSM_cjs.defineMastraNativeVectorTable; }
3053
+ get: function () { return chunkZCCKLZQH_cjs.defineMastraNativeVectorTable; }
2516
3054
  });
2517
3055
  Object.defineProperty(exports, "mastraBackgroundTasksTable", {
2518
3056
  enumerable: true,
2519
- get: function () { return chunkSFRHJGSM_cjs.mastraBackgroundTasksTable; }
3057
+ get: function () { return chunkZCCKLZQH_cjs.mastraBackgroundTasksTable; }
2520
3058
  });
2521
3059
  Object.defineProperty(exports, "mastraCacheListItemsTable", {
2522
3060
  enumerable: true,
2523
- get: function () { return chunkSFRHJGSM_cjs.mastraCacheListItemsTable; }
3061
+ get: function () { return chunkZCCKLZQH_cjs.mastraCacheListItemsTable; }
2524
3062
  });
2525
3063
  Object.defineProperty(exports, "mastraCacheTable", {
2526
3064
  enumerable: true,
2527
- get: function () { return chunkSFRHJGSM_cjs.mastraCacheTable; }
3065
+ get: function () { return chunkZCCKLZQH_cjs.mastraCacheTable; }
2528
3066
  });
2529
3067
  Object.defineProperty(exports, "mastraChannelConfigTable", {
2530
3068
  enumerable: true,
2531
- get: function () { return chunkSFRHJGSM_cjs.mastraChannelConfigTable; }
3069
+ get: function () { return chunkZCCKLZQH_cjs.mastraChannelConfigTable; }
2532
3070
  });
2533
3071
  Object.defineProperty(exports, "mastraChannelInstallationsTable", {
2534
3072
  enumerable: true,
2535
- get: function () { return chunkSFRHJGSM_cjs.mastraChannelInstallationsTable; }
3073
+ get: function () { return chunkZCCKLZQH_cjs.mastraChannelInstallationsTable; }
2536
3074
  });
2537
3075
  Object.defineProperty(exports, "mastraDocumentsTable", {
2538
3076
  enumerable: true,
2539
- get: function () { return chunkSFRHJGSM_cjs.mastraDocumentsTable; }
3077
+ get: function () { return chunkZCCKLZQH_cjs.mastraDocumentsTable; }
2540
3078
  });
2541
3079
  Object.defineProperty(exports, "mastraMessagesTable", {
2542
3080
  enumerable: true,
2543
- get: function () { return chunkSFRHJGSM_cjs.mastraMessagesTable; }
3081
+ get: function () { return chunkZCCKLZQH_cjs.mastraMessagesTable; }
3082
+ });
3083
+ Object.defineProperty(exports, "mastraObservationalMemoryTable", {
3084
+ enumerable: true,
3085
+ get: function () { return chunkZCCKLZQH_cjs.mastraObservationalMemoryTable; }
2544
3086
  });
2545
3087
  Object.defineProperty(exports, "mastraResourcesTable", {
2546
3088
  enumerable: true,
2547
- get: function () { return chunkSFRHJGSM_cjs.mastraResourcesTable; }
3089
+ get: function () { return chunkZCCKLZQH_cjs.mastraResourcesTable; }
2548
3090
  });
2549
3091
  Object.defineProperty(exports, "mastraScheduleTriggersTable", {
2550
3092
  enumerable: true,
2551
- get: function () { return chunkSFRHJGSM_cjs.mastraScheduleTriggersTable; }
3093
+ get: function () { return chunkZCCKLZQH_cjs.mastraScheduleTriggersTable; }
2552
3094
  });
2553
3095
  Object.defineProperty(exports, "mastraSchedulesTable", {
2554
3096
  enumerable: true,
2555
- get: function () { return chunkSFRHJGSM_cjs.mastraSchedulesTable; }
3097
+ get: function () { return chunkZCCKLZQH_cjs.mastraSchedulesTable; }
2556
3098
  });
2557
3099
  Object.defineProperty(exports, "mastraScoresTable", {
2558
3100
  enumerable: true,
2559
- get: function () { return chunkSFRHJGSM_cjs.mastraScoresTable; }
3101
+ get: function () { return chunkZCCKLZQH_cjs.mastraScoresTable; }
2560
3102
  });
2561
3103
  Object.defineProperty(exports, "mastraThreadsTable", {
2562
3104
  enumerable: true,
2563
- get: function () { return chunkSFRHJGSM_cjs.mastraThreadsTable; }
3105
+ get: function () { return chunkZCCKLZQH_cjs.mastraThreadsTable; }
2564
3106
  });
2565
3107
  Object.defineProperty(exports, "mastraVectorIndexesTable", {
2566
3108
  enumerable: true,
2567
- get: function () { return chunkSFRHJGSM_cjs.mastraVectorIndexesTable; }
3109
+ get: function () { return chunkZCCKLZQH_cjs.mastraVectorIndexesTable; }
2568
3110
  });
2569
3111
  Object.defineProperty(exports, "mastraVectorsTable", {
2570
3112
  enumerable: true,
2571
- get: function () { return chunkSFRHJGSM_cjs.mastraVectorsTable; }
3113
+ get: function () { return chunkZCCKLZQH_cjs.mastraVectorsTable; }
2572
3114
  });
2573
3115
  Object.defineProperty(exports, "mastraWorkflowSnapshotsTable", {
2574
3116
  enumerable: true,
2575
- get: function () { return chunkSFRHJGSM_cjs.mastraWorkflowSnapshotsTable; }
3117
+ get: function () { return chunkZCCKLZQH_cjs.mastraWorkflowSnapshotsTable; }
2576
3118
  });
2577
3119
  exports.ConvexCacheClient = ConvexCacheClient;
2578
3120
  exports.ConvexNativeVector = ConvexNativeVector;