@mastra/libsql 1.1.0 → 1.2.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.
package/dist/index.cjs CHANGED
@@ -2041,6 +2041,21 @@ Note: This migration may take some time for large tables.
2041
2041
  };
2042
2042
 
2043
2043
  // src/storage/domains/agents/index.ts
2044
+ var SNAPSHOT_FIELDS = [
2045
+ "name",
2046
+ "description",
2047
+ "instructions",
2048
+ "model",
2049
+ "tools",
2050
+ "defaultOptions",
2051
+ "workflows",
2052
+ "agents",
2053
+ "integrationTools",
2054
+ "inputProcessors",
2055
+ "outputProcessors",
2056
+ "memory",
2057
+ "scorers"
2058
+ ];
2044
2059
  var AgentsLibSQL = class extends storage.AgentsStorage {
2045
2060
  #db;
2046
2061
  #client;
@@ -2166,6 +2181,16 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2166
2181
  }
2167
2182
  parseJson(value, fieldName) {
2168
2183
  if (!value) return void 0;
2184
+ if (value instanceof ArrayBuffer || value && value.constructor && value.constructor.name === "ArrayBuffer") {
2185
+ try {
2186
+ const decoder = new TextDecoder();
2187
+ const jsonString = decoder.decode(value);
2188
+ return JSON.parse(jsonString);
2189
+ } catch (error) {
2190
+ console.error(`Failed to parse ArrayBuffer for ${fieldName}:`, error);
2191
+ return void 0;
2192
+ }
2193
+ }
2169
2194
  if (typeof value !== "string") return value;
2170
2195
  try {
2171
2196
  return JSON.parse(value);
@@ -2243,15 +2268,6 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2243
2268
  changedFields: Object.keys(snapshotConfig),
2244
2269
  changeMessage: "Initial version"
2245
2270
  });
2246
- await this.#db.update({
2247
- tableName: storage.TABLE_AGENTS,
2248
- keys: { id: agent.id },
2249
- data: {
2250
- activeVersionId: versionId,
2251
- status: "published",
2252
- updatedAt: /* @__PURE__ */ new Date()
2253
- }
2254
- });
2255
2271
  const created = await this.getAgentById({ id: agent.id });
2256
2272
  if (!created) {
2257
2273
  throw new error.MastraError({
@@ -2290,16 +2306,57 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2290
2306
  details: { agentId: id }
2291
2307
  });
2292
2308
  }
2309
+ const metadataFields = {
2310
+ authorId: updates.authorId,
2311
+ activeVersionId: updates.activeVersionId,
2312
+ metadata: updates.metadata
2313
+ };
2314
+ const configFields = {};
2315
+ for (const field of SNAPSHOT_FIELDS) {
2316
+ if (updates[field] !== void 0) {
2317
+ configFields[field] = updates[field];
2318
+ }
2319
+ }
2320
+ if (Object.keys(configFields).length > 0) {
2321
+ const latestVersion = await this.getLatestVersion(id);
2322
+ const nextVersionNumber = latestVersion ? latestVersion.versionNumber + 1 : 1;
2323
+ if (!latestVersion) {
2324
+ throw new error.MastraError({
2325
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_AGENT", "NO_VERSION"),
2326
+ domain: error.ErrorDomain.STORAGE,
2327
+ category: error.ErrorCategory.USER,
2328
+ text: `Cannot update config fields for agent ${id} - no versions exist`,
2329
+ details: { id }
2330
+ });
2331
+ }
2332
+ const latestSnapshot = {};
2333
+ for (const field of SNAPSHOT_FIELDS) {
2334
+ if (latestVersion[field] !== void 0) {
2335
+ latestSnapshot[field] = latestVersion[field];
2336
+ }
2337
+ }
2338
+ const versionInput = {
2339
+ id: crypto.randomUUID(),
2340
+ agentId: id,
2341
+ versionNumber: nextVersionNumber,
2342
+ ...latestSnapshot,
2343
+ // Start from latest version
2344
+ ...configFields,
2345
+ // Apply updates
2346
+ changedFields: Object.keys(configFields),
2347
+ changeMessage: `Updated: ${Object.keys(configFields).join(", ")}`
2348
+ };
2349
+ await this.createVersion(versionInput);
2350
+ }
2293
2351
  const data = {
2294
2352
  updatedAt: /* @__PURE__ */ new Date()
2295
2353
  };
2296
- if (updates.authorId !== void 0) data.authorId = updates.authorId;
2297
- if (updates.activeVersionId !== void 0) {
2298
- data.activeVersionId = updates.activeVersionId;
2299
- data.status = "published";
2354
+ if (metadataFields.authorId !== void 0) data.authorId = metadataFields.authorId;
2355
+ if (metadataFields.activeVersionId !== void 0) {
2356
+ data.activeVersionId = metadataFields.activeVersionId;
2300
2357
  }
2301
- if (updates.metadata !== void 0) {
2302
- data.metadata = { ...existingAgent.metadata, ...updates.metadata };
2358
+ if (metadataFields.metadata !== void 0) {
2359
+ data.metadata = metadataFields.metadata;
2303
2360
  }
2304
2361
  if (Object.keys(data).length > 1) {
2305
2362
  await this.#db.update({
@@ -2406,6 +2463,88 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2406
2463
  );
2407
2464
  }
2408
2465
  }
2466
+ async listAgentsResolved(args) {
2467
+ const { page = 0, perPage: perPageInput, orderBy } = args || {};
2468
+ const { field, direction } = this.parseOrderBy(orderBy);
2469
+ if (page < 0) {
2470
+ throw new error.MastraError(
2471
+ {
2472
+ id: storage.createStorageErrorId("LIBSQL", "LIST_AGENTS_RESOLVED", "INVALID_PAGE"),
2473
+ domain: error.ErrorDomain.STORAGE,
2474
+ category: error.ErrorCategory.USER,
2475
+ details: { page }
2476
+ },
2477
+ new Error("page must be >= 0")
2478
+ );
2479
+ }
2480
+ const perPage = storage.normalizePerPage(perPageInput, 100);
2481
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
2482
+ try {
2483
+ const total = await this.#db.selectTotalCount({ tableName: storage.TABLE_AGENTS });
2484
+ if (total === 0) {
2485
+ return {
2486
+ agents: [],
2487
+ total: 0,
2488
+ page,
2489
+ perPage: perPageForResponse,
2490
+ hasMore: false
2491
+ };
2492
+ }
2493
+ const limitValue = perPageInput === false ? total : perPage;
2494
+ const agents = await this.#db.selectMany({
2495
+ tableName: storage.TABLE_AGENTS,
2496
+ orderBy: `"${field}" ${direction}`,
2497
+ limit: limitValue,
2498
+ offset
2499
+ });
2500
+ const resolvedAgents = await Promise.all(
2501
+ agents.map(async (agent) => {
2502
+ let version = null;
2503
+ if (agent.activeVersionId) {
2504
+ version = await this.getVersion(agent.activeVersionId);
2505
+ }
2506
+ if (!version) {
2507
+ version = await this.getLatestVersion(agent.id);
2508
+ }
2509
+ if (!version) {
2510
+ return agent;
2511
+ }
2512
+ return {
2513
+ ...agent,
2514
+ name: version.name,
2515
+ description: version.description,
2516
+ instructions: version.instructions,
2517
+ model: version.model,
2518
+ tools: version.tools,
2519
+ defaultOptions: version.defaultOptions,
2520
+ workflows: version.workflows,
2521
+ agents: version.agents,
2522
+ integrationTools: version.integrationTools,
2523
+ inputProcessors: version.inputProcessors,
2524
+ outputProcessors: version.outputProcessors,
2525
+ memory: version.memory,
2526
+ scorers: version.scorers
2527
+ };
2528
+ })
2529
+ );
2530
+ return {
2531
+ agents: resolvedAgents,
2532
+ total,
2533
+ page,
2534
+ perPage: perPageForResponse,
2535
+ hasMore: perPageInput === false ? false : offset + perPage < total
2536
+ };
2537
+ } catch (error$1) {
2538
+ throw new error.MastraError(
2539
+ {
2540
+ id: storage.createStorageErrorId("LIBSQL", "LIST_AGENTS_RESOLVED", "FAILED"),
2541
+ domain: error.ErrorDomain.STORAGE,
2542
+ category: error.ErrorCategory.THIRD_PARTY
2543
+ },
2544
+ error$1
2545
+ );
2546
+ }
2547
+ }
2409
2548
  // ==========================================================================
2410
2549
  // Agent Version Methods
2411
2550
  // ==========================================================================
@@ -2685,7 +2824,9 @@ var AgentsLibSQL = class extends storage.AgentsStorage {
2685
2824
  };
2686
2825
  }
2687
2826
  };
2827
+ var OM_TABLE = "mastra_observational_memory";
2688
2828
  var MemoryLibSQL = class extends storage.MemoryStorage {
2829
+ supportsObservationalMemory = true;
2689
2830
  #client;
2690
2831
  #db;
2691
2832
  constructor(config) {
@@ -2698,16 +2839,42 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
2698
2839
  await this.#db.createTable({ tableName: storage.TABLE_THREADS, schema: storage.TABLE_SCHEMAS[storage.TABLE_THREADS] });
2699
2840
  await this.#db.createTable({ tableName: storage.TABLE_MESSAGES, schema: storage.TABLE_SCHEMAS[storage.TABLE_MESSAGES] });
2700
2841
  await this.#db.createTable({ tableName: storage.TABLE_RESOURCES, schema: storage.TABLE_SCHEMAS[storage.TABLE_RESOURCES] });
2842
+ let omSchema;
2843
+ try {
2844
+ const { OBSERVATIONAL_MEMORY_TABLE_SCHEMA } = await import('@mastra/core/storage');
2845
+ omSchema = OBSERVATIONAL_MEMORY_TABLE_SCHEMA?.[OM_TABLE];
2846
+ } catch {
2847
+ }
2848
+ if (omSchema) {
2849
+ await this.#db.createTable({
2850
+ tableName: OM_TABLE,
2851
+ schema: omSchema
2852
+ });
2853
+ await this.#db.alterTable({
2854
+ tableName: OM_TABLE,
2855
+ schema: omSchema,
2856
+ ifNotExists: ["observedMessageIds", "observedTimezone"]
2857
+ });
2858
+ }
2701
2859
  await this.#db.alterTable({
2702
2860
  tableName: storage.TABLE_MESSAGES,
2703
2861
  schema: storage.TABLE_SCHEMAS[storage.TABLE_MESSAGES],
2704
2862
  ifNotExists: ["resourceId"]
2705
2863
  });
2864
+ if (omSchema) {
2865
+ await this.#client.execute({
2866
+ sql: `CREATE INDEX IF NOT EXISTS idx_om_lookup_key ON "${OM_TABLE}" ("lookupKey")`,
2867
+ args: []
2868
+ });
2869
+ }
2706
2870
  }
2707
2871
  async dangerouslyClearAll() {
2708
2872
  await this.#db.deleteData({ tableName: storage.TABLE_MESSAGES });
2709
2873
  await this.#db.deleteData({ tableName: storage.TABLE_THREADS });
2710
2874
  await this.#db.deleteData({ tableName: storage.TABLE_RESOURCES });
2875
+ {
2876
+ await this.#db.deleteData({ tableName: OM_TABLE });
2877
+ }
2711
2878
  }
2712
2879
  parseRow(row) {
2713
2880
  let content = row.content;
@@ -2935,6 +3102,126 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
2935
3102
  };
2936
3103
  }
2937
3104
  }
3105
+ async listMessagesByResourceId(args) {
3106
+ const { resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
3107
+ if (!resourceId || typeof resourceId !== "string" || resourceId.trim().length === 0) {
3108
+ throw new error.MastraError(
3109
+ {
3110
+ id: storage.createStorageErrorId("LIBSQL", "LIST_MESSAGES", "INVALID_QUERY"),
3111
+ domain: error.ErrorDomain.STORAGE,
3112
+ category: error.ErrorCategory.USER,
3113
+ details: { resourceId: resourceId ?? "" }
3114
+ },
3115
+ new Error("resourceId is required")
3116
+ );
3117
+ }
3118
+ if (page < 0) {
3119
+ throw new error.MastraError(
3120
+ {
3121
+ id: storage.createStorageErrorId("LIBSQL", "LIST_MESSAGES", "INVALID_PAGE"),
3122
+ domain: error.ErrorDomain.STORAGE,
3123
+ category: error.ErrorCategory.USER,
3124
+ details: { page }
3125
+ },
3126
+ new Error("page must be >= 0")
3127
+ );
3128
+ }
3129
+ const perPage = storage.normalizePerPage(perPageInput, 40);
3130
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
3131
+ try {
3132
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
3133
+ const orderByStatement = `ORDER BY "${field}" ${direction}`;
3134
+ const conditions = [];
3135
+ const queryParams = [];
3136
+ conditions.push(`"resourceId" = ?`);
3137
+ queryParams.push(resourceId);
3138
+ if (filter?.dateRange?.start) {
3139
+ const startOp = filter.dateRange.startExclusive ? ">" : ">=";
3140
+ conditions.push(`"createdAt" ${startOp} ?`);
3141
+ queryParams.push(
3142
+ filter.dateRange.start instanceof Date ? filter.dateRange.start.toISOString() : filter.dateRange.start
3143
+ );
3144
+ }
3145
+ if (filter?.dateRange?.end) {
3146
+ const endOp = filter.dateRange.endExclusive ? "<" : "<=";
3147
+ conditions.push(`"createdAt" ${endOp} ?`);
3148
+ queryParams.push(
3149
+ filter.dateRange.end instanceof Date ? filter.dateRange.end.toISOString() : filter.dateRange.end
3150
+ );
3151
+ }
3152
+ const whereClause = `WHERE ${conditions.join(" AND ")}`;
3153
+ const countResult = await this.#client.execute({
3154
+ sql: `SELECT COUNT(*) as count FROM ${storage.TABLE_MESSAGES} ${whereClause}`,
3155
+ args: queryParams
3156
+ });
3157
+ const total = Number(countResult.rows?.[0]?.count ?? 0);
3158
+ const limitValue = perPageInput === false ? total : perPage;
3159
+ const dataResult = await this.#client.execute({
3160
+ sql: `SELECT id, content, role, type, "createdAt", "resourceId", "thread_id" FROM ${storage.TABLE_MESSAGES} ${whereClause} ${orderByStatement} LIMIT ? OFFSET ?`,
3161
+ args: [...queryParams, limitValue, offset]
3162
+ });
3163
+ const messages = (dataResult.rows || []).map((row) => this.parseRow(row));
3164
+ if (total === 0 && messages.length === 0 && (!include || include.length === 0)) {
3165
+ return {
3166
+ messages: [],
3167
+ total: 0,
3168
+ page,
3169
+ perPage: perPageForResponse,
3170
+ hasMore: false
3171
+ };
3172
+ }
3173
+ const messageIds = new Set(messages.map((m) => m.id));
3174
+ if (include && include.length > 0) {
3175
+ const includeMessages = await this._getIncludedMessages({ include });
3176
+ if (includeMessages) {
3177
+ for (const includeMsg of includeMessages) {
3178
+ if (!messageIds.has(includeMsg.id)) {
3179
+ messages.push(includeMsg);
3180
+ messageIds.add(includeMsg.id);
3181
+ }
3182
+ }
3183
+ }
3184
+ }
3185
+ const list = new agent.MessageList().add(messages, "memory");
3186
+ let finalMessages = list.get.all.db();
3187
+ finalMessages = finalMessages.sort((a, b) => {
3188
+ const isDateField = field === "createdAt" || field === "updatedAt";
3189
+ const aValue = isDateField ? new Date(a[field]).getTime() : a[field];
3190
+ const bValue = isDateField ? new Date(b[field]).getTime() : b[field];
3191
+ if (typeof aValue === "number" && typeof bValue === "number") {
3192
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
3193
+ }
3194
+ return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
3195
+ });
3196
+ const hasMore = perPageInput !== false && offset + perPage < total;
3197
+ return {
3198
+ messages: finalMessages,
3199
+ total,
3200
+ page,
3201
+ perPage: perPageForResponse,
3202
+ hasMore
3203
+ };
3204
+ } catch (error$1) {
3205
+ const mastraError = new error.MastraError(
3206
+ {
3207
+ id: storage.createStorageErrorId("LIBSQL", "LIST_MESSAGES", "FAILED"),
3208
+ domain: error.ErrorDomain.STORAGE,
3209
+ category: error.ErrorCategory.THIRD_PARTY,
3210
+ details: { resourceId }
3211
+ },
3212
+ error$1
3213
+ );
3214
+ this.logger?.error?.(mastraError.toString());
3215
+ this.logger?.trackException?.(mastraError);
3216
+ return {
3217
+ messages: [],
3218
+ total: 0,
3219
+ page,
3220
+ perPage: perPageForResponse,
3221
+ hasMore: false
3222
+ };
3223
+ }
3224
+ }
2938
3225
  async saveMessages({ messages }) {
2939
3226
  if (messages.length === 0) return { messages };
2940
3227
  try {
@@ -3592,6 +3879,377 @@ var MemoryLibSQL = class extends storage.MemoryStorage {
3592
3879
  );
3593
3880
  }
3594
3881
  }
3882
+ // ============================================
3883
+ // Observational Memory Methods
3884
+ // ============================================
3885
+ getOMKey(threadId, resourceId) {
3886
+ return threadId ? `thread:${threadId}` : `resource:${resourceId}`;
3887
+ }
3888
+ parseOMRow(row) {
3889
+ return {
3890
+ id: row.id,
3891
+ scope: row.scope,
3892
+ threadId: row.threadId || null,
3893
+ resourceId: row.resourceId,
3894
+ createdAt: new Date(row.createdAt),
3895
+ updatedAt: new Date(row.updatedAt),
3896
+ lastObservedAt: row.lastObservedAt ? new Date(row.lastObservedAt) : void 0,
3897
+ originType: row.originType || "initial",
3898
+ generationCount: Number(row.generationCount || 0),
3899
+ activeObservations: row.activeObservations || "",
3900
+ bufferedObservations: row.activeObservationsPendingUpdate || void 0,
3901
+ totalTokensObserved: Number(row.totalTokensObserved || 0),
3902
+ observationTokenCount: Number(row.observationTokenCount || 0),
3903
+ pendingMessageTokens: Number(row.pendingMessageTokens || 0),
3904
+ isReflecting: Boolean(row.isReflecting),
3905
+ isObserving: Boolean(row.isObserving),
3906
+ config: row.config ? JSON.parse(row.config) : {},
3907
+ metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
3908
+ observedMessageIds: row.observedMessageIds ? JSON.parse(row.observedMessageIds) : void 0,
3909
+ observedTimezone: row.observedTimezone || void 0
3910
+ };
3911
+ }
3912
+ async getObservationalMemory(threadId, resourceId) {
3913
+ try {
3914
+ const lookupKey = this.getOMKey(threadId, resourceId);
3915
+ const result = await this.#client.execute({
3916
+ // Use generationCount DESC for reliable ordering (incremented for each new record)
3917
+ sql: `SELECT * FROM "${OM_TABLE}" WHERE "lookupKey" = ? ORDER BY "generationCount" DESC LIMIT 1`,
3918
+ args: [lookupKey]
3919
+ });
3920
+ if (!result.rows || result.rows.length === 0) return null;
3921
+ return this.parseOMRow(result.rows[0]);
3922
+ } catch (error$1) {
3923
+ throw new error.MastraError(
3924
+ {
3925
+ id: storage.createStorageErrorId("LIBSQL", "GET_OBSERVATIONAL_MEMORY", "FAILED"),
3926
+ domain: error.ErrorDomain.STORAGE,
3927
+ category: error.ErrorCategory.THIRD_PARTY,
3928
+ details: { threadId, resourceId }
3929
+ },
3930
+ error$1
3931
+ );
3932
+ }
3933
+ }
3934
+ async getObservationalMemoryHistory(threadId, resourceId, limit = 10) {
3935
+ try {
3936
+ const lookupKey = this.getOMKey(threadId, resourceId);
3937
+ const result = await this.#client.execute({
3938
+ // Use generationCount DESC for reliable ordering (incremented for each new record)
3939
+ sql: `SELECT * FROM "${OM_TABLE}" WHERE "lookupKey" = ? ORDER BY "generationCount" DESC LIMIT ?`,
3940
+ args: [lookupKey, limit]
3941
+ });
3942
+ if (!result.rows) return [];
3943
+ return result.rows.map((row) => this.parseOMRow(row));
3944
+ } catch (error$1) {
3945
+ throw new error.MastraError(
3946
+ {
3947
+ id: storage.createStorageErrorId("LIBSQL", "GET_OBSERVATIONAL_MEMORY_HISTORY", "FAILED"),
3948
+ domain: error.ErrorDomain.STORAGE,
3949
+ category: error.ErrorCategory.THIRD_PARTY,
3950
+ details: { threadId, resourceId, limit }
3951
+ },
3952
+ error$1
3953
+ );
3954
+ }
3955
+ }
3956
+ async initializeObservationalMemory(input) {
3957
+ try {
3958
+ const id = crypto.randomUUID();
3959
+ const now = /* @__PURE__ */ new Date();
3960
+ const lookupKey = this.getOMKey(input.threadId, input.resourceId);
3961
+ const record = {
3962
+ id,
3963
+ scope: input.scope,
3964
+ threadId: input.threadId,
3965
+ resourceId: input.resourceId,
3966
+ createdAt: now,
3967
+ updatedAt: now,
3968
+ lastObservedAt: void 0,
3969
+ originType: "initial",
3970
+ generationCount: 0,
3971
+ activeObservations: "",
3972
+ totalTokensObserved: 0,
3973
+ observationTokenCount: 0,
3974
+ pendingMessageTokens: 0,
3975
+ isReflecting: false,
3976
+ isObserving: false,
3977
+ config: input.config,
3978
+ observedTimezone: input.observedTimezone
3979
+ };
3980
+ await this.#client.execute({
3981
+ sql: `INSERT INTO "${OM_TABLE}" (
3982
+ id, "lookupKey", scope, "resourceId", "threadId",
3983
+ "activeObservations", "activeObservationsPendingUpdate",
3984
+ "originType", config, "generationCount", "lastObservedAt", "lastReflectionAt",
3985
+ "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
3986
+ "isObserving", "isReflecting", "observedTimezone", "createdAt", "updatedAt"
3987
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3988
+ args: [
3989
+ id,
3990
+ lookupKey,
3991
+ input.scope,
3992
+ input.resourceId,
3993
+ input.threadId || null,
3994
+ "",
3995
+ null,
3996
+ "initial",
3997
+ JSON.stringify(input.config),
3998
+ 0,
3999
+ null,
4000
+ null,
4001
+ 0,
4002
+ 0,
4003
+ 0,
4004
+ false,
4005
+ false,
4006
+ input.observedTimezone || null,
4007
+ now.toISOString(),
4008
+ now.toISOString()
4009
+ ]
4010
+ });
4011
+ return record;
4012
+ } catch (error$1) {
4013
+ throw new error.MastraError(
4014
+ {
4015
+ id: storage.createStorageErrorId("LIBSQL", "INITIALIZE_OBSERVATIONAL_MEMORY", "FAILED"),
4016
+ domain: error.ErrorDomain.STORAGE,
4017
+ category: error.ErrorCategory.THIRD_PARTY,
4018
+ details: { threadId: input.threadId, resourceId: input.resourceId }
4019
+ },
4020
+ error$1
4021
+ );
4022
+ }
4023
+ }
4024
+ async updateActiveObservations(input) {
4025
+ try {
4026
+ const now = /* @__PURE__ */ new Date();
4027
+ const observedMessageIdsJson = input.observedMessageIds ? JSON.stringify(input.observedMessageIds) : null;
4028
+ const result = await this.#client.execute({
4029
+ sql: `UPDATE "${OM_TABLE}" SET
4030
+ "activeObservations" = ?,
4031
+ "lastObservedAt" = ?,
4032
+ "pendingMessageTokens" = 0,
4033
+ "observationTokenCount" = ?,
4034
+ "totalTokensObserved" = "totalTokensObserved" + ?,
4035
+ "observedMessageIds" = ?,
4036
+ "updatedAt" = ?
4037
+ WHERE id = ?`,
4038
+ args: [
4039
+ input.observations,
4040
+ input.lastObservedAt.toISOString(),
4041
+ input.tokenCount,
4042
+ input.tokenCount,
4043
+ observedMessageIdsJson,
4044
+ now.toISOString(),
4045
+ input.id
4046
+ ]
4047
+ });
4048
+ if (result.rowsAffected === 0) {
4049
+ throw new error.MastraError({
4050
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_ACTIVE_OBSERVATIONS", "NOT_FOUND"),
4051
+ text: `Observational memory record not found: ${input.id}`,
4052
+ domain: error.ErrorDomain.STORAGE,
4053
+ category: error.ErrorCategory.THIRD_PARTY,
4054
+ details: { id: input.id }
4055
+ });
4056
+ }
4057
+ } catch (error$1) {
4058
+ if (error$1 instanceof error.MastraError) {
4059
+ throw error$1;
4060
+ }
4061
+ throw new error.MastraError(
4062
+ {
4063
+ id: storage.createStorageErrorId("LIBSQL", "UPDATE_ACTIVE_OBSERVATIONS", "FAILED"),
4064
+ domain: error.ErrorDomain.STORAGE,
4065
+ category: error.ErrorCategory.THIRD_PARTY,
4066
+ details: { id: input.id }
4067
+ },
4068
+ error$1
4069
+ );
4070
+ }
4071
+ }
4072
+ async createReflectionGeneration(input) {
4073
+ try {
4074
+ const id = crypto.randomUUID();
4075
+ const now = /* @__PURE__ */ new Date();
4076
+ const lookupKey = this.getOMKey(input.currentRecord.threadId, input.currentRecord.resourceId);
4077
+ const record = {
4078
+ id,
4079
+ scope: input.currentRecord.scope,
4080
+ threadId: input.currentRecord.threadId,
4081
+ resourceId: input.currentRecord.resourceId,
4082
+ createdAt: now,
4083
+ updatedAt: now,
4084
+ lastObservedAt: input.currentRecord.lastObservedAt,
4085
+ originType: "reflection",
4086
+ generationCount: input.currentRecord.generationCount + 1,
4087
+ activeObservations: input.reflection,
4088
+ totalTokensObserved: input.currentRecord.totalTokensObserved,
4089
+ observationTokenCount: input.tokenCount,
4090
+ pendingMessageTokens: 0,
4091
+ isReflecting: false,
4092
+ isObserving: false,
4093
+ config: input.currentRecord.config,
4094
+ metadata: input.currentRecord.metadata,
4095
+ observedTimezone: input.currentRecord.observedTimezone
4096
+ };
4097
+ await this.#client.execute({
4098
+ sql: `INSERT INTO "${OM_TABLE}" (
4099
+ id, "lookupKey", scope, "resourceId", "threadId",
4100
+ "activeObservations", "activeObservationsPendingUpdate",
4101
+ "originType", config, "generationCount", "lastObservedAt", "lastReflectionAt",
4102
+ "pendingMessageTokens", "totalTokensObserved", "observationTokenCount",
4103
+ "isObserving", "isReflecting", "observedTimezone", "createdAt", "updatedAt"
4104
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
4105
+ args: [
4106
+ id,
4107
+ lookupKey,
4108
+ record.scope,
4109
+ record.resourceId,
4110
+ record.threadId || null,
4111
+ input.reflection,
4112
+ null,
4113
+ "reflection",
4114
+ JSON.stringify(record.config),
4115
+ input.currentRecord.generationCount + 1,
4116
+ record.lastObservedAt?.toISOString() || null,
4117
+ now.toISOString(),
4118
+ record.pendingMessageTokens,
4119
+ record.totalTokensObserved,
4120
+ record.observationTokenCount,
4121
+ false,
4122
+ false,
4123
+ record.observedTimezone || null,
4124
+ now.toISOString(),
4125
+ now.toISOString()
4126
+ ]
4127
+ });
4128
+ return record;
4129
+ } catch (error$1) {
4130
+ throw new error.MastraError(
4131
+ {
4132
+ id: storage.createStorageErrorId("LIBSQL", "CREATE_REFLECTION_GENERATION", "FAILED"),
4133
+ domain: error.ErrorDomain.STORAGE,
4134
+ category: error.ErrorCategory.THIRD_PARTY,
4135
+ details: { currentRecordId: input.currentRecord.id }
4136
+ },
4137
+ error$1
4138
+ );
4139
+ }
4140
+ }
4141
+ async setReflectingFlag(id, isReflecting) {
4142
+ try {
4143
+ const result = await this.#client.execute({
4144
+ sql: `UPDATE "${OM_TABLE}" SET "isReflecting" = ?, "updatedAt" = ? WHERE id = ?`,
4145
+ args: [isReflecting, (/* @__PURE__ */ new Date()).toISOString(), id]
4146
+ });
4147
+ if (result.rowsAffected === 0) {
4148
+ throw new error.MastraError({
4149
+ id: storage.createStorageErrorId("LIBSQL", "SET_REFLECTING_FLAG", "NOT_FOUND"),
4150
+ text: `Observational memory record not found: ${id}`,
4151
+ domain: error.ErrorDomain.STORAGE,
4152
+ category: error.ErrorCategory.THIRD_PARTY,
4153
+ details: { id, isReflecting }
4154
+ });
4155
+ }
4156
+ } catch (error$1) {
4157
+ if (error$1 instanceof error.MastraError) {
4158
+ throw error$1;
4159
+ }
4160
+ throw new error.MastraError(
4161
+ {
4162
+ id: storage.createStorageErrorId("LIBSQL", "SET_REFLECTING_FLAG", "FAILED"),
4163
+ domain: error.ErrorDomain.STORAGE,
4164
+ category: error.ErrorCategory.THIRD_PARTY,
4165
+ details: { id, isReflecting }
4166
+ },
4167
+ error$1
4168
+ );
4169
+ }
4170
+ }
4171
+ async setObservingFlag(id, isObserving) {
4172
+ try {
4173
+ const result = await this.#client.execute({
4174
+ sql: `UPDATE "${OM_TABLE}" SET "isObserving" = ?, "updatedAt" = ? WHERE id = ?`,
4175
+ args: [isObserving, (/* @__PURE__ */ new Date()).toISOString(), id]
4176
+ });
4177
+ if (result.rowsAffected === 0) {
4178
+ throw new error.MastraError({
4179
+ id: storage.createStorageErrorId("LIBSQL", "SET_OBSERVING_FLAG", "NOT_FOUND"),
4180
+ text: `Observational memory record not found: ${id}`,
4181
+ domain: error.ErrorDomain.STORAGE,
4182
+ category: error.ErrorCategory.THIRD_PARTY,
4183
+ details: { id, isObserving }
4184
+ });
4185
+ }
4186
+ } catch (error$1) {
4187
+ if (error$1 instanceof error.MastraError) {
4188
+ throw error$1;
4189
+ }
4190
+ throw new error.MastraError(
4191
+ {
4192
+ id: storage.createStorageErrorId("LIBSQL", "SET_OBSERVING_FLAG", "FAILED"),
4193
+ domain: error.ErrorDomain.STORAGE,
4194
+ category: error.ErrorCategory.THIRD_PARTY,
4195
+ details: { id, isObserving }
4196
+ },
4197
+ error$1
4198
+ );
4199
+ }
4200
+ }
4201
+ async clearObservationalMemory(threadId, resourceId) {
4202
+ try {
4203
+ const lookupKey = this.getOMKey(threadId, resourceId);
4204
+ await this.#client.execute({
4205
+ sql: `DELETE FROM "${OM_TABLE}" WHERE "lookupKey" = ?`,
4206
+ args: [lookupKey]
4207
+ });
4208
+ } catch (error$1) {
4209
+ throw new error.MastraError(
4210
+ {
4211
+ id: storage.createStorageErrorId("LIBSQL", "CLEAR_OBSERVATIONAL_MEMORY", "FAILED"),
4212
+ domain: error.ErrorDomain.STORAGE,
4213
+ category: error.ErrorCategory.THIRD_PARTY,
4214
+ details: { threadId, resourceId }
4215
+ },
4216
+ error$1
4217
+ );
4218
+ }
4219
+ }
4220
+ async addPendingMessageTokens(id, tokenCount) {
4221
+ try {
4222
+ const result = await this.#client.execute({
4223
+ sql: `UPDATE "${OM_TABLE}" SET
4224
+ "pendingMessageTokens" = "pendingMessageTokens" + ?,
4225
+ "updatedAt" = ?
4226
+ WHERE id = ?`,
4227
+ args: [tokenCount, (/* @__PURE__ */ new Date()).toISOString(), id]
4228
+ });
4229
+ if (result.rowsAffected === 0) {
4230
+ throw new error.MastraError({
4231
+ id: storage.createStorageErrorId("LIBSQL", "ADD_PENDING_MESSAGE_TOKENS", "NOT_FOUND"),
4232
+ text: `Observational memory record not found: ${id}`,
4233
+ domain: error.ErrorDomain.STORAGE,
4234
+ category: error.ErrorCategory.THIRD_PARTY,
4235
+ details: { id, tokenCount }
4236
+ });
4237
+ }
4238
+ } catch (error$1) {
4239
+ if (error$1 instanceof error.MastraError) {
4240
+ throw error$1;
4241
+ }
4242
+ throw new error.MastraError(
4243
+ {
4244
+ id: storage.createStorageErrorId("LIBSQL", "ADD_PENDING_MESSAGE_TOKENS", "FAILED"),
4245
+ domain: error.ErrorDomain.STORAGE,
4246
+ category: error.ErrorCategory.THIRD_PARTY,
4247
+ details: { id, tokenCount }
4248
+ },
4249
+ error$1
4250
+ );
4251
+ }
4252
+ }
3595
4253
  };
3596
4254
  var ObservabilityLibSQL = class extends storage.ObservabilityStorage {
3597
4255
  #db;