@mastra/libsql 0.0.0-knowledge-w2-20261007223745 → 0.0.0-knowledge-w2-20261008040304

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.
@@ -3,7 +3,7 @@ name: mastra-libsql
3
3
  description: Documentation for @mastra/libsql. Use when working with @mastra/libsql APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/libsql"
6
- version: "0.0.0-knowledge-w2-20261007223745"
6
+ version: "0.0.0-knowledge-w2-20261008040304"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.0.0-knowledge-w2-20261007223745",
2
+ "version": "0.0.0-knowledge-w2-20261008040304",
3
3
  "package": "@mastra/libsql",
4
4
  "exports": {},
5
5
  "modules": {}
@@ -125,7 +125,7 @@ import { agent } from './agent'
125
125
 
126
126
  const approvalClassifier = new Classifier({
127
127
  id: 'tool-approval-classifier',
128
- model: typeSafeAi.evaluationModel('jev-latest'),
128
+ model: typeSafeAi.decisionModel('jev-latest'),
129
129
  questions: {
130
130
  requiresApproval: {
131
131
  type: 'boolean',
@@ -137,7 +137,7 @@ const approvalClassifier = new Classifier({
137
137
 
138
138
  const stream = await agent.stream('Clean up old records', {
139
139
  requireToolApproval: async ({ toolName, args }) => {
140
- const result = await approvalClassifier.evaluate({
140
+ const result = await approvalClassifier.decide({
141
141
  state: {
142
142
  toolName,
143
143
  argumentNames: Object.keys(args),
@@ -149,7 +149,7 @@ const stream = await agent.stream('Clean up old records', {
149
149
  })
150
150
  ```
151
151
 
152
- The example sends argument names rather than values because the classifier forwards its state to the configured evaluation model. If the decision requires argument values, redact sensitive data first or use an evaluation model and provider that meet the protected tool's data-handling requirements.
152
+ The example sends argument names rather than values because the classifier forwards its state to the configured decision model. If the decision requires argument values, redact sensitive data first or use a decision model and provider that meet the protected tool's data-handling requirements.
153
153
 
154
154
  Returning `true` pauses the tool call for human approval. It doesn't approve or decline the call automatically. Choose a threshold that matches the risk of the tools available to the agent. If this `requireToolApproval` function throws, it defaults to requiring approval.
155
155
 
@@ -99,7 +99,7 @@ import { Agent } from '@mastra/core/agent'
99
99
  import { Memory } from '@mastra/memory'
100
100
  import { LibSQLStore } from '@mastra/libsql'
101
101
  import { PineconeVector } from '@mastra/pinecone'
102
- import { OpenAIEmbedder } from '@mastra/openai'
102
+ import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
103
103
  import { openai } from '@ai-sdk/openai'
104
104
 
105
105
  const agent = new Agent({
@@ -115,10 +115,7 @@ const agent = new Agent({
115
115
  id: 'memory-vector',
116
116
  apiKey: process.env.PINECONE_API_KEY!,
117
117
  }),
118
- embedder: new OpenAIEmbedder({
119
- model: 'text-embedding-3-small',
120
- apiKey: process.env.OPENAI_API_KEY!,
121
- }),
118
+ embedder: new ModelRouterEmbeddingModel('openai/text-embedding-3-small'),
122
119
  semanticRecall: { enabled: true }, // SemanticRecall processor automatically added
123
120
  }),
124
121
  })
@@ -411,11 +411,11 @@ PostgreSQL supports both IVFFlat and HNSW indexes. By default, Mastra creates an
411
411
 
412
412
  ```typescript
413
413
  import { Memory } from '@mastra/memory'
414
- import { PgStore, PgVector } from '@mastra/pg'
414
+ import { PostgresStore, PgVector } from '@mastra/pg'
415
415
 
416
416
  const agent = new Agent({
417
417
  memory: new Memory({
418
- storage: new PgStore({
418
+ storage: new PostgresStore({
419
419
  id: 'agent-storage',
420
420
  connectionString: process.env.DATABASE_URL,
421
421
  }),
@@ -272,6 +272,22 @@ Schema-based working memory uses **merge semantics**, meaning the agent only nee
272
272
  - **Set a field to `null` to delete it:** This explicitly removes the field from memory
273
273
  - **Arrays are replaced entirely:** When an array field is provided, it replaces the existing array (arrays aren't merged element-by-element)
274
274
 
275
+ ### Concurrent updates
276
+
277
+ With `scope: 'resource'` and a storage adapter that supports atomic merges (currently `@mastra/pg`), each merge runs inside a row-locked database transaction. Concurrent updates to different fields from separate processes are all kept. Other adapters merge in the application, which only serializes writers inside a single process.
278
+
279
+ To merge a partial update from your own code, call `memory.mergeWorkingMemory()`:
280
+
281
+ ```typescript
282
+ await memory.mergeWorkingMemory({
283
+ threadId: 'thread-1',
284
+ resourceId: 'user-123',
285
+ workingMemory: { preferences: { tone: 'formal' } },
286
+ })
287
+ ```
288
+
289
+ It throws if working memory isn't schema-based and resource-scoped, or if the storage adapter doesn't support atomic merges. Check `await memory.supportsAtomicWorkingMemoryMerge()` first if you need to fall back.
290
+
275
291
  ## Choosing between template and schema
276
292
 
277
293
  - Use a **template** (Markdown) if you want the agent to maintain memory as a free-form text block, such as a user profile or scratchpad. Templates use **replace semantics**: the agent must provide the complete memory content on each update.
@@ -101,14 +101,14 @@ export const agent = new Agent({
101
101
  import { Memory } from '@mastra/memory'
102
102
  import { Agent } from '@mastra/core/agent'
103
103
  import { ModelRouterEmbeddingModel } from '@mastra/core/llm'
104
- import { PgStore, PgVector } from '@mastra/pg'
104
+ import { PostgresStore, PgVector } from '@mastra/pg'
105
105
 
106
106
  export const agent = new Agent({
107
107
  name: 'pg-agent',
108
108
  instructions: 'You are an agent with optimized PostgreSQL memory.',
109
109
  model: 'openai/gpt-5.6-sol',
110
110
  memory: new Memory({
111
- storage: new PgStore({
111
+ storage: new PostgresStore({
112
112
  id: 'pg-agent-storage',
113
113
  connectionString: process.env.DATABASE_URL,
114
114
  }),
package/dist/index.cjs CHANGED
@@ -6748,7 +6748,7 @@ var KnowledgeLibSQL = class extends _mastra_core_storage.KnowledgeStorage {
6748
6748
  const { KnowledgeSchemaError } = await loadKnowledgeCore();
6749
6749
  const existingTables = await this.#client.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'mastra_knowledge_%'");
6750
6750
  const existingNames = new Set(existingTables.rows.map((row) => String(row.name)));
6751
- if (existingNames.size > 0 && !existingNames.has("mastra_knowledge_schema") && await this.#replaceEmptyPublishedV1()) existingNames.clear();
6751
+ if (existingNames.size > 0 && !existingNames.has("mastra_knowledge_schema") && await this.#replacePublishedV1()) existingNames.clear();
6752
6752
  if (existingNames.size > 0) {
6753
6753
  if (!existingNames.has("mastra_knowledge_schema")) throw new KnowledgeSchemaError(`Knowledge schema reset required: the existing Knowledge schema has no completion marker. ${KNOWLEDGE_RESET_GUIDANCE}`);
6754
6754
  const marker = await this.#client.execute(`SELECT version FROM ${TABLE_KNOWLEDGE_SCHEMA} WHERE id = 'canonical'`);
@@ -6834,7 +6834,7 @@ var KnowledgeLibSQL = class extends _mastra_core_storage.KnowledgeStorage {
6834
6834
  });
6835
6835
  await this.#client.batch([
6836
6836
  {
6837
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_nodes_name ON "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" (name)`,
6837
+ sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_nodes_name ON "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" (lower(name))`,
6838
6838
  args: []
6839
6839
  },
6840
6840
  {
@@ -6892,12 +6892,12 @@ var KnowledgeLibSQL = class extends _mastra_core_storage.KnowledgeStorage {
6892
6892
  });
6893
6893
  }
6894
6894
  /**
6895
- * Earlier releases created empty Knowledge tables for every app. When exactly that layout and its
6896
- * indexes are the only Knowledge objects, drop it so canonical storage can initialize; replacing it
6897
- * loses nothing. Rows, partial or unfamiliar tables, views, triggers, and extra indexes all leave the
6898
- * database untouched.
6895
+ * Knowledge v1 was experimental and its data is not migrated. When exactly the published v1 tables
6896
+ * and indexes are the only Knowledge objects, drop them, discarding any rows they hold, so canonical
6897
+ * storage can initialize. Partial or unfamiliar tables, views, triggers, and extra indexes all leave
6898
+ * the database untouched.
6899
6899
  */
6900
- async #replaceEmptyPublishedV1() {
6900
+ async #replacePublishedV1() {
6901
6901
  return this.#transaction(async (tx) => {
6902
6902
  const objects = await tx.execute("SELECT type, name FROM sqlite_master WHERE name LIKE 'mastra\\_knowledge\\_%' ESCAPE '\\' OR tbl_name LIKE 'mastra\\_knowledge\\_%' ESCAPE '\\' OR sql LIKE '%mastra\\_knowledge\\_%' ESCAPE '\\'");
6903
6903
  const tables = [];
@@ -6917,7 +6917,6 @@ var KnowledgeLibSQL = class extends _mastra_core_storage.KnowledgeStorage {
6917
6917
  columnsByTable.set(table, columns.rows.map((row) => String(row.name)));
6918
6918
  }
6919
6919
  if (!isPublishedKnowledgeV1Layout(columnsByTable)) return false;
6920
- for (const table of tables) if ((await tx.execute(`SELECT 1 FROM "${table}" LIMIT 1`)).rows.length > 0) return false;
6921
6920
  for (const table of tables) await tx.execute(`DROP TABLE "${table}"`);
6922
6921
  return true;
6923
6922
  });
@@ -7006,6 +7005,10 @@ var KnowledgeLibSQL = class extends _mastra_core_storage.KnowledgeStorage {
7006
7005
  }) : void 0)?.rows.length) continue;
7007
7006
  throw new Error(`Knowledge parent scope does not exist: ${parentAddress}`);
7008
7007
  }
7008
+ if ((await tx.execute({
7009
+ sql: `SELECT 1 FROM "mastra_knowledge_node_scopes" WHERE nodeId=? AND scopeNodeId=?`,
7010
+ args: [scopeNodeId, parentId]
7011
+ })).rows.length) continue;
7009
7012
  if ((await tx.execute({
7010
7013
  sql: `SELECT n.id FROM "mastra_knowledge_node_scopes" ns JOIN "${_mastra_core_storage.TABLE_KNOWLEDGE_NODES}" n ON n.id=ns.nodeId WHERE ns.scopeNodeId=? AND lower(n.name)=? AND n.deletedAt IS NULL AND n.id<>? LIMIT 1`,
7011
7014
  args: [
@@ -9448,6 +9451,14 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
9448
9451
  initialBackoffMs: config.initialBackoffMs
9449
9452
  });
9450
9453
  }
9454
+ /**
9455
+ * Runs a write behind the per-client write lock and retries it on transient SQLite lock
9456
+ * errors (`SQLITE_BUSY`), like the shared `LibSQLDB` writes. Each retry re-queues on the lock.
9457
+ * `fn` must be safe to rerun: a single statement, a batch, or a transaction that rolls back.
9458
+ */
9459
+ #write(operation, fn) {
9460
+ return this.#db.executeWriteOperationWithRetry(() => withClientWriteLock(this.#client, fn), operation);
9461
+ }
9451
9462
  async init() {
9452
9463
  await this.#db.createTable({
9453
9464
  tableName: _mastra_core_storage.TABLE_THREADS,
@@ -9947,13 +9958,11 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
9947
9958
  const BATCH_SIZE = 50;
9948
9959
  const messageStatements = batchStatements.slice(0, -1);
9949
9960
  const threadUpdateStatement = batchStatements[batchStatements.length - 1];
9950
- await withClientWriteLock(this.#client, async () => {
9951
- for (let i = 0; i < messageStatements.length; i += BATCH_SIZE) {
9952
- const batch = messageStatements.slice(i, i + BATCH_SIZE);
9953
- if (batch.length > 0) await this.#client.batch(batch, "write");
9954
- }
9955
- if (threadUpdateStatement) await this.#client.execute(threadUpdateStatement);
9956
- });
9961
+ for (let i = 0; i < messageStatements.length; i += BATCH_SIZE) {
9962
+ const batch = messageStatements.slice(i, i + BATCH_SIZE);
9963
+ if (batch.length > 0) await this.#write("saveMessages", () => this.#client.batch(batch, "write"));
9964
+ }
9965
+ if (threadUpdateStatement) await this.#write("saveMessages", () => this.#client.execute(threadUpdateStatement));
9957
9966
  return { messages: new _mastra_core_agent.MessageList().add(messages, "memory").get.all.db() };
9958
9967
  } catch (error) {
9959
9968
  throw new _mastra_core_error.MastraError({
@@ -10019,7 +10028,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
10019
10028
  sql: `UPDATE ${_mastra_core_storage.TABLE_THREADS} SET updatedAt = ? WHERE id = ?`,
10020
10029
  args: [now, threadId]
10021
10030
  });
10022
- await this.#client.batch(batchStatements, "write");
10031
+ await this.#write("updateMessages", () => this.#client.batch(batchStatements, "write"));
10023
10032
  return (await this.#client.execute({
10024
10033
  sql: selectSql,
10025
10034
  args: messageIds
@@ -10029,35 +10038,37 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
10029
10038
  if (!messageIds || messageIds.length === 0) return;
10030
10039
  try {
10031
10040
  const BATCH_SIZE = 100;
10032
- const threadIds = /* @__PURE__ */ new Set();
10033
- const tx = await this.#client.transaction("write");
10034
- try {
10035
- for (let i = 0; i < messageIds.length; i += BATCH_SIZE) {
10036
- const batch = messageIds.slice(i, i + BATCH_SIZE);
10037
- const placeholders = batch.map(() => "?").join(",");
10038
- (await tx.execute({
10039
- sql: `SELECT DISTINCT thread_id FROM "${_mastra_core_storage.TABLE_MESSAGES}" WHERE id IN (${placeholders})`,
10040
- args: batch
10041
- })).rows?.forEach((row) => {
10042
- if (row.thread_id) threadIds.add(row.thread_id);
10043
- });
10044
- await tx.execute({
10045
- sql: `DELETE FROM "${_mastra_core_storage.TABLE_MESSAGES}" WHERE id IN (${placeholders})`,
10046
- args: batch
10047
- });
10048
- }
10049
- if (threadIds.size > 0) {
10050
- const now = (/* @__PURE__ */ new Date()).toISOString();
10051
- for (const threadId of threadIds) await tx.execute({
10052
- sql: `UPDATE "${_mastra_core_storage.TABLE_THREADS}" SET "updatedAt" = ? WHERE id = ?`,
10053
- args: [now, threadId]
10054
- });
10041
+ await this.#write("deleteMessages", async () => {
10042
+ const threadIds = /* @__PURE__ */ new Set();
10043
+ const tx = await this.#client.transaction("write");
10044
+ try {
10045
+ for (let i = 0; i < messageIds.length; i += BATCH_SIZE) {
10046
+ const batch = messageIds.slice(i, i + BATCH_SIZE);
10047
+ const placeholders = batch.map(() => "?").join(",");
10048
+ (await tx.execute({
10049
+ sql: `SELECT DISTINCT thread_id FROM "${_mastra_core_storage.TABLE_MESSAGES}" WHERE id IN (${placeholders})`,
10050
+ args: batch
10051
+ })).rows?.forEach((row) => {
10052
+ if (row.thread_id) threadIds.add(row.thread_id);
10053
+ });
10054
+ await tx.execute({
10055
+ sql: `DELETE FROM "${_mastra_core_storage.TABLE_MESSAGES}" WHERE id IN (${placeholders})`,
10056
+ args: batch
10057
+ });
10058
+ }
10059
+ if (threadIds.size > 0) {
10060
+ const now = (/* @__PURE__ */ new Date()).toISOString();
10061
+ for (const threadId of threadIds) await tx.execute({
10062
+ sql: `UPDATE "${_mastra_core_storage.TABLE_THREADS}" SET "updatedAt" = ? WHERE id = ?`,
10063
+ args: [now, threadId]
10064
+ });
10065
+ }
10066
+ await tx.commit();
10067
+ } catch (error) {
10068
+ await tx.rollback();
10069
+ throw error;
10055
10070
  }
10056
- await tx.commit();
10057
- } catch (error) {
10058
- await tx.rollback();
10059
- throw error;
10060
- }
10071
+ });
10061
10072
  } catch (error) {
10062
10073
  throw new _mastra_core_error.MastraError({
10063
10074
  id: (0, _mastra_core_storage.createStorageErrorId)("LIBSQL", "DELETE_MESSAGES", "FAILED"),
@@ -10122,10 +10133,10 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
10122
10133
  updates.push("updatedAt = ?");
10123
10134
  values.push(updatedResource.updatedAt.toISOString());
10124
10135
  values.push(resourceId);
10125
- await this.#client.execute({
10136
+ await this.#write("updateResource", () => this.#client.execute({
10126
10137
  sql: `UPDATE ${_mastra_core_storage.TABLE_RESOURCES} SET ${updates.join(", ")} WHERE id = ?`,
10127
10138
  args: values
10128
- });
10139
+ }));
10129
10140
  return updatedResource;
10130
10141
  }
10131
10142
  async getThreadById({ threadId, resourceId }) {
@@ -10162,49 +10173,51 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
10162
10173
  */
10163
10174
  async updateThreadResourceId({ threadId, resourceId }) {
10164
10175
  try {
10165
- const tx = await this.#client.transaction("write");
10166
- try {
10167
- const row = (await tx.execute({
10168
- sql: `SELECT * FROM "${_mastra_core_storage.TABLE_THREADS}" WHERE id = ?`,
10169
- args: [threadId]
10170
- })).rows?.[0];
10171
- if (!row) throw new Error(`Thread "${threadId}" not found`);
10172
- const currentResourceId = row.resourceId;
10173
- const normalized = {
10174
- id: row.id,
10175
- resourceId: currentResourceId,
10176
- title: row.title,
10177
- metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata,
10178
- createdAt: new Date(row.createdAt),
10179
- updatedAt: new Date(row.updatedAt)
10180
- };
10181
- if (currentResourceId === resourceId) {
10176
+ return await this.#write("updateThreadResourceId", async () => {
10177
+ const tx = await this.#client.transaction("write");
10178
+ try {
10179
+ const row = (await tx.execute({
10180
+ sql: `SELECT * FROM "${_mastra_core_storage.TABLE_THREADS}" WHERE id = ?`,
10181
+ args: [threadId]
10182
+ })).rows?.[0];
10183
+ if (!row) throw new Error(`Thread "${threadId}" not found`);
10184
+ const currentResourceId = row.resourceId;
10185
+ const normalized = {
10186
+ id: row.id,
10187
+ resourceId: currentResourceId,
10188
+ title: row.title,
10189
+ metadata: typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata,
10190
+ createdAt: new Date(row.createdAt),
10191
+ updatedAt: new Date(row.updatedAt)
10192
+ };
10193
+ if (currentResourceId === resourceId) {
10194
+ await tx.commit();
10195
+ return normalized;
10196
+ }
10197
+ const now = /* @__PURE__ */ new Date();
10198
+ await tx.execute({
10199
+ sql: `UPDATE "${_mastra_core_storage.TABLE_THREADS}" SET "resourceId" = ?, "updatedAt" = ? WHERE id = ?`,
10200
+ args: [
10201
+ resourceId,
10202
+ now.toISOString(),
10203
+ threadId
10204
+ ]
10205
+ });
10206
+ await tx.execute({
10207
+ sql: `UPDATE "${_mastra_core_storage.TABLE_MESSAGES}" SET "resourceId" = ? WHERE thread_id = ?`,
10208
+ args: [resourceId, threadId]
10209
+ });
10182
10210
  await tx.commit();
10183
- return normalized;
10184
- }
10185
- const now = /* @__PURE__ */ new Date();
10186
- await tx.execute({
10187
- sql: `UPDATE "${_mastra_core_storage.TABLE_THREADS}" SET "resourceId" = ?, "updatedAt" = ? WHERE id = ?`,
10188
- args: [
10211
+ return {
10212
+ ...normalized,
10189
10213
  resourceId,
10190
- now.toISOString(),
10191
- threadId
10192
- ]
10193
- });
10194
- await tx.execute({
10195
- sql: `UPDATE "${_mastra_core_storage.TABLE_MESSAGES}" SET "resourceId" = ? WHERE thread_id = ?`,
10196
- args: [resourceId, threadId]
10197
- });
10198
- await tx.commit();
10199
- return {
10200
- ...normalized,
10201
- resourceId,
10202
- updatedAt: now
10203
- };
10204
- } catch (error) {
10205
- await tx.rollback();
10206
- throw error;
10207
- }
10214
+ updatedAt: now
10215
+ };
10216
+ } catch (error) {
10217
+ await tx.rollback();
10218
+ throw error;
10219
+ }
10220
+ });
10208
10221
  } catch (error) {
10209
10222
  throw new _mastra_core_error.MastraError({
10210
10223
  id: (0, _mastra_core_storage.createStorageErrorId)("LIBSQL", "UPDATE_THREAD_RESOURCE_ID", "FAILED"),
@@ -10366,7 +10379,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
10366
10379
  updatedAt: now
10367
10380
  };
10368
10381
  try {
10369
- await this.#client.execute({
10382
+ await this.#write("updateThread", () => this.#client.execute({
10370
10383
  sql: `UPDATE ${_mastra_core_storage.TABLE_THREADS} SET title = COALESCE(?, title), metadata = jsonb(?), updatedAt = ? WHERE id = ?`,
10371
10384
  args: [
10372
10385
  title ?? null,
@@ -10374,7 +10387,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
10374
10387
  now.toISOString(),
10375
10388
  id
10376
10389
  ]
10377
- });
10390
+ }));
10378
10391
  return updatedThread;
10379
10392
  } catch (error) {
10380
10393
  throw new _mastra_core_error.MastraError({
@@ -10388,14 +10401,14 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
10388
10401
  }
10389
10402
  async deleteThread({ threadId }) {
10390
10403
  try {
10391
- await this.#client.execute({
10404
+ await this.#write("deleteThread", () => this.#client.execute({
10392
10405
  sql: `DELETE FROM ${_mastra_core_storage.TABLE_MESSAGES} WHERE thread_id = ?`,
10393
10406
  args: [threadId]
10394
- });
10395
- await this.#client.execute({
10407
+ }));
10408
+ await this.#write("deleteThread", () => this.#client.execute({
10396
10409
  sql: `DELETE FROM ${_mastra_core_storage.TABLE_THREADS} WHERE id = ?`,
10397
10410
  args: [threadId]
10398
- });
10411
+ }));
10399
10412
  } catch (error) {
10400
10413
  throw new _mastra_core_error.MastraError({
10401
10414
  id: (0, _mastra_core_storage.createStorageErrorId)("LIBSQL", "DELETE_THREAD", "FAILED"),
@@ -10468,48 +10481,50 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
10468
10481
  createdAt: now,
10469
10482
  updatedAt: now
10470
10483
  };
10471
- const tx = await this.#client.transaction("write");
10472
- try {
10473
- await tx.execute({
10474
- sql: `INSERT INTO "${_mastra_core_storage.TABLE_THREADS}" (id, "resourceId", title, metadata, "createdAt", "updatedAt")
10475
- VALUES (?, ?, ?, jsonb(?), ?, ?)`,
10476
- args: [
10477
- newThread.id,
10478
- newThread.resourceId,
10479
- newThread.title ?? "",
10480
- JSON.stringify(newThread.metadata),
10481
- nowStr,
10482
- nowStr
10483
- ]
10484
- });
10485
- const messageIdMap = {};
10486
- const targetResourceId = resourceId || sourceThread.resourceId;
10487
- for (const sourceMsg of sourceMessages) {
10488
- const newMessageId = crypto.randomUUID();
10489
- const sourceMsgId = sourceMsg.id;
10490
- messageIdMap[sourceMsgId] = newMessageId;
10491
- const insertResult = await tx.execute({
10492
- sql: `INSERT INTO "${_mastra_core_storage.TABLE_MESSAGES}" (id, thread_id, content, role, type, "createdAt", "resourceId")
10493
- SELECT ?, ?, content, role, type, "createdAt", ?
10494
- FROM "${_mastra_core_storage.TABLE_MESSAGES}" WHERE id = ?`,
10484
+ return await this.#write("copyThread", async () => {
10485
+ const tx = await this.#client.transaction("write");
10486
+ try {
10487
+ await tx.execute({
10488
+ sql: `INSERT INTO "${_mastra_core_storage.TABLE_THREADS}" (id, "resourceId", title, metadata, "createdAt", "updatedAt")
10489
+ VALUES (?, ?, ?, jsonb(?), ?, ?)`,
10495
10490
  args: [
10496
- newMessageId,
10497
- newThreadId,
10498
- targetResourceId,
10499
- sourceMsgId
10491
+ newThread.id,
10492
+ newThread.resourceId,
10493
+ newThread.title ?? "",
10494
+ JSON.stringify(newThread.metadata),
10495
+ nowStr,
10496
+ nowStr
10500
10497
  ]
10501
10498
  });
10502
- if (insertResult.rowsAffected !== 1) throw new Error(`Failed to copy message ${sourceMsgId}: expected 1 row copied but got ${insertResult.rowsAffected}`);
10499
+ const messageIdMap = {};
10500
+ const targetResourceId = resourceId || sourceThread.resourceId;
10501
+ for (const sourceMsg of sourceMessages) {
10502
+ const newMessageId = crypto.randomUUID();
10503
+ const sourceMsgId = sourceMsg.id;
10504
+ messageIdMap[sourceMsgId] = newMessageId;
10505
+ const insertResult = await tx.execute({
10506
+ sql: `INSERT INTO "${_mastra_core_storage.TABLE_MESSAGES}" (id, thread_id, content, role, type, "createdAt", "resourceId")
10507
+ SELECT ?, ?, content, role, type, "createdAt", ?
10508
+ FROM "${_mastra_core_storage.TABLE_MESSAGES}" WHERE id = ?`,
10509
+ args: [
10510
+ newMessageId,
10511
+ newThreadId,
10512
+ targetResourceId,
10513
+ sourceMsgId
10514
+ ]
10515
+ });
10516
+ if (insertResult.rowsAffected !== 1) throw new Error(`Failed to copy message ${sourceMsgId}: expected 1 row copied but got ${insertResult.rowsAffected}`);
10517
+ }
10518
+ await tx.commit();
10519
+ return {
10520
+ thread: newThread,
10521
+ messageIdMap
10522
+ };
10523
+ } catch (error) {
10524
+ await tx.rollback();
10525
+ throw error;
10503
10526
  }
10504
- await tx.commit();
10505
- return {
10506
- thread: newThread,
10507
- messageIdMap
10508
- };
10509
- } catch (error) {
10510
- await tx.rollback();
10511
- throw error;
10512
- }
10527
+ });
10513
10528
  } catch (error) {
10514
10529
  if (error instanceof _mastra_core_error.MastraError) throw error;
10515
10530
  throw new _mastra_core_error.MastraError({
@@ -10669,7 +10684,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
10669
10684
  config: input.config,
10670
10685
  observedTimezone: input.observedTimezone
10671
10686
  };
10672
- await withClientWriteLock(this.#client, () => this.#client.execute({
10687
+ await this.#write("initializeObservationalMemory", () => this.#client.execute({
10673
10688
  sql: `INSERT INTO "${OM_TABLE}" (
10674
10689
  id, "lookupKey", scope, "resourceId", "threadId",
10675
10690
  "activeObservations", "activeObservationsPendingUpdate",
@@ -10721,7 +10736,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
10721
10736
  async insertObservationalMemoryRecord(record) {
10722
10737
  try {
10723
10738
  const lookupKey = this.getOMKey(record.threadId, record.resourceId);
10724
- await withClientWriteLock(this.#client, () => this.#client.execute({
10739
+ await this.#write("insertObservationalMemoryRecord", () => this.#client.execute({
10725
10740
  sql: `INSERT INTO "${OM_TABLE}" (
10726
10741
  id, "lookupKey", scope, "resourceId", "threadId",
10727
10742
  "activeObservations", "activeObservationsPendingUpdate",
@@ -10785,7 +10800,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
10785
10800
  try {
10786
10801
  const now = /* @__PURE__ */ new Date();
10787
10802
  const observedMessageIdsJson = input.observedMessageIds ? JSON.stringify(input.observedMessageIds) : null;
10788
- if ((await withClientWriteLock(this.#client, () => this.#client.execute({
10803
+ if ((await this.#write("updateActiveObservations", () => this.#client.execute({
10789
10804
  sql: `UPDATE "${OM_TABLE}" SET
10790
10805
  "activeObservations" = ?,
10791
10806
  "lastObservedAt" = ?,
@@ -10823,7 +10838,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
10823
10838
  }
10824
10839
  async createReflectionGeneration(input) {
10825
10840
  try {
10826
- return await withClientWriteLock(this.#client, async () => {
10841
+ return await this.#write("createReflectionGeneration", async () => {
10827
10842
  const tx = await this.#client.transaction("write");
10828
10843
  try {
10829
10844
  const record = await this.#insertReflectionGeneration(tx, input);
@@ -10919,7 +10934,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
10919
10934
  }
10920
10935
  async setReflectingFlag(id, isReflecting) {
10921
10936
  try {
10922
- if ((await withClientWriteLock(this.#client, () => this.#client.execute({
10937
+ if ((await this.#write("setReflectingFlag", () => this.#client.execute({
10923
10938
  sql: `UPDATE "${OM_TABLE}" SET "isReflecting" = ?, "updatedAt" = ? WHERE id = ?`,
10924
10939
  args: [
10925
10940
  isReflecting,
@@ -10951,7 +10966,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
10951
10966
  }
10952
10967
  async setObservingFlag(id, isObserving) {
10953
10968
  try {
10954
- if ((await withClientWriteLock(this.#client, () => this.#client.execute({
10969
+ if ((await this.#write("setObservingFlag", () => this.#client.execute({
10955
10970
  sql: `UPDATE "${OM_TABLE}" SET "isObserving" = ?, "updatedAt" = ? WHERE id = ?`,
10956
10971
  args: [
10957
10972
  isObserving,
@@ -11002,7 +11017,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
11002
11017
  id
11003
11018
  ];
11004
11019
  }
11005
- if ((await withClientWriteLock(this.#client, () => this.#client.execute({
11020
+ if ((await this.#write("setBufferingObservationFlag", () => this.#client.execute({
11006
11021
  sql,
11007
11022
  args
11008
11023
  }))).rowsAffected === 0) throw new _mastra_core_error.MastraError({
@@ -11032,7 +11047,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
11032
11047
  }
11033
11048
  async setBufferingReflectionFlag(id, isBuffering) {
11034
11049
  try {
11035
- if ((await withClientWriteLock(this.#client, () => this.#client.execute({
11050
+ if ((await this.#write("setBufferingReflectionFlag", () => this.#client.execute({
11036
11051
  sql: `UPDATE "${OM_TABLE}" SET "isBufferingReflection" = ?, "updatedAt" = ? WHERE id = ?`,
11037
11052
  args: [
11038
11053
  isBuffering,
@@ -11065,7 +11080,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
11065
11080
  async clearObservationalMemory(threadId, resourceId) {
11066
11081
  try {
11067
11082
  const lookupKey = this.getOMKey(threadId, resourceId);
11068
- await withClientWriteLock(this.#client, () => this.#client.execute({
11083
+ await this.#write("clearObservationalMemory", () => this.#client.execute({
11069
11084
  sql: `DELETE FROM "${OM_TABLE}" WHERE "lookupKey" = ?`,
11070
11085
  args: [lookupKey]
11071
11086
  }));
@@ -11083,7 +11098,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
11083
11098
  }
11084
11099
  async setPendingMessageTokens(id, tokenCount) {
11085
11100
  try {
11086
- if ((await withClientWriteLock(this.#client, () => this.#client.execute({
11101
+ if ((await this.#write("setPendingMessageTokens", () => this.#client.execute({
11087
11102
  sql: `UPDATE "${OM_TABLE}" SET
11088
11103
  "pendingMessageTokens" = ?,
11089
11104
  "updatedAt" = ?
@@ -11118,7 +11133,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
11118
11133
  }
11119
11134
  async updateObservationalMemoryConfig(input) {
11120
11135
  try {
11121
- await withClientWriteLock(this.#client, async () => {
11136
+ await this.#write("updateObservationalMemoryConfig", async () => {
11122
11137
  const tx = await this.#client.transaction("write");
11123
11138
  try {
11124
11139
  const selectResult = await tx.execute({
@@ -11162,7 +11177,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
11162
11177
  async updateBufferedObservations(input) {
11163
11178
  try {
11164
11179
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
11165
- await withClientWriteLock(this.#client, async () => {
11180
+ await this.#write("updateBufferedObservations", async () => {
11166
11181
  const tx = await this.#client.transaction("write");
11167
11182
  try {
11168
11183
  const current = await tx.execute({
@@ -11243,7 +11258,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
11243
11258
  async swapBufferedToActive(input) {
11244
11259
  try {
11245
11260
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
11246
- return await withClientWriteLock(this.#client, async () => {
11261
+ return await this.#write("swapBufferedToActive", async () => {
11247
11262
  const tx = await this.#client.transaction("write");
11248
11263
  try {
11249
11264
  const current = await tx.execute({
@@ -11392,7 +11407,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
11392
11407
  async updateBufferedReflection(input) {
11393
11408
  try {
11394
11409
  const nowStr = (/* @__PURE__ */ new Date()).toISOString();
11395
- if ((await withClientWriteLock(this.#client, () => this.#client.execute({
11410
+ if ((await this.#write("updateBufferedReflection", () => this.#client.execute({
11396
11411
  sql: `UPDATE "${OM_TABLE}" SET
11397
11412
  "bufferedReflection" = CASE
11398
11413
  WHEN "bufferedReflection" IS NOT NULL AND "bufferedReflection" != ''
@@ -11432,7 +11447,7 @@ var MemoryLibSQL = class MemoryLibSQL extends _mastra_core_storage.MemoryStorage
11432
11447
  }
11433
11448
  async swapBufferedReflectionToActive(input) {
11434
11449
  try {
11435
- return await withClientWriteLock(this.#client, async () => {
11450
+ return await this.#write("swapBufferedReflectionToActive", async () => {
11436
11451
  const tx = await this.#client.transaction("write");
11437
11452
  try {
11438
11453
  const current = await tx.execute({