@mastra/mssql 1.11.2-alpha.0 → 1.12.0-alpha.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
@@ -27,6 +27,7 @@ mssql = __toESM(mssql, 1);
27
27
  let _mastra_core_utils = require("@mastra/core/utils");
28
28
  let _mastra_core_base = require("@mastra/core/base");
29
29
  let _mastra_core_agent = require("@mastra/core/agent");
30
+ let crypto = require("crypto");
30
31
  let _mastra_core_evals = require("@mastra/core/evals");
31
32
  // src/storage/db/utils.ts
32
33
  function getSchemaName$1(schema) {
@@ -114,6 +115,25 @@ var MssqlDB = class extends _mastra_core_base.MastraBase {
114
115
  "instructions",
115
116
  "other"
116
117
  ];
118
+ /**
119
+ * Observational memory text columns that hold observation text or JSON, which outgrow the
120
+ * indexable NVARCHAR(400) default.
121
+ */
122
+ OBSERVATIONAL_MEMORY_LARGE_TEXT_COLUMNS = [
123
+ "activeObservations",
124
+ "activeObservationsPendingUpdate",
125
+ "config",
126
+ "bufferedObservations",
127
+ "bufferedReflection"
128
+ ];
129
+ /** The SQL type for one column of `tableName`, applying per-table sizing. */
130
+ getColumnSqlType(tableName, columnName, def, isIndexed) {
131
+ if (tableName === _mastra_core_storage.TABLE_OBSERVATIONAL_MEMORY && def.type === "text") {
132
+ if (this.OBSERVATIONAL_MEMORY_LARGE_TEXT_COLUMNS.includes(columnName)) return "NVARCHAR(MAX)";
133
+ if (columnName === "lookupKey") return "NVARCHAR(450)";
134
+ }
135
+ return this.getSqlType(def.type, isIndexed, this.LARGE_DATA_COLUMNS.includes(columnName), this.COMPOSITE_INDEX_COLUMNS.includes(columnName));
136
+ }
117
137
  getSqlType(type, isPrimaryKey = false, useLargeStorage = false, useSmallStorage = false) {
118
138
  switch (type) {
119
139
  case "text":
@@ -282,9 +302,7 @@ var MssqlDB = class extends _mastra_core_base.MastraBase {
282
302
  if (def.primaryKey) constraints.push("PRIMARY KEY");
283
303
  if (!def.nullable) constraints.push("NOT NULL");
284
304
  const isIndexed = !!def.primaryKey || uniqueConstraintColumns.includes(name);
285
- const useLargeStorage = this.LARGE_DATA_COLUMNS.includes(name);
286
- const useSmallStorage = this.COMPOSITE_INDEX_COLUMNS.includes(name);
287
- return `[${parsedName}] ${this.getSqlType(def.type, isIndexed, useLargeStorage, useSmallStorage)} ${constraints.join(" ")}`.trim();
305
+ return `[${parsedName}] ${this.getColumnSqlType(tableName, name, def, isIndexed)} ${constraints.join(" ")}`.trim();
288
306
  }).join(",\n");
289
307
  if (this.schemaName) await this.setupSchema();
290
308
  const checkTableRequest = this.pool.request();
@@ -568,10 +586,7 @@ MIGRATION REQUIRED: Duplicate spans detected in ${duplicateInfo.tableName}\n====
568
586
  const checkResult = await columnCheckRequest.query(`SELECT 1 AS found FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME = @tableName AND COLUMN_NAME = @columnName`);
569
587
  if (!(Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0)) {
570
588
  const columnDef = schema[columnName];
571
- const useLargeStorage = this.LARGE_DATA_COLUMNS.includes(columnName);
572
- const useSmallStorage = this.COMPOSITE_INDEX_COLUMNS.includes(columnName);
573
- const isIndexed = !!columnDef.primaryKey;
574
- const sqlType = this.getSqlType(columnDef.type, isIndexed, useLargeStorage, useSmallStorage);
589
+ const sqlType = this.getColumnSqlType(tableName, columnName, columnDef, !!columnDef.primaryKey);
575
590
  const nullable = columnDef.nullable ? "" : "NOT NULL";
576
591
  const defaultValue = !columnDef.nullable ? this.getDefaultValue(columnDef.type) : "";
577
592
  const parsedColumnName = (0, _mastra_core_utils.parseSqlIdentifier)(columnName, "column name");
@@ -2157,6 +2172,91 @@ var BackgroundTasksMSSQL = class BackgroundTasksMSSQL extends _mastra_core_stora
2157
2172
  return Number(result.recordset[0]?.count ?? 0);
2158
2173
  }
2159
2174
  };
2175
+ // ../../packages/_internal-core/dist/memory/index.js
2176
+ /**
2177
+ * Shared rules for observational memory lifecycle writes. Every storage adapter applies
2178
+ * these inside its own atomic section (lock, transaction, or conditional update), so the
2179
+ * decisions are identical across adapters.
2180
+ */
2181
+ /**
2182
+ * Observational memory columns that lifecycle writes depend on. Storage adapters merge these
2183
+ * into the table schema they get from `@mastra/core`, so the columns exist even when the
2184
+ * installed core predates them.
2185
+ */
2186
+ const OBSERVATIONAL_MEMORY_LIFECYCLE_COLUMNS = { supersededBy: {
2187
+ type: "text",
2188
+ nullable: true
2189
+ } };
2190
+ /** `schema` plus {@link OBSERVATIONAL_MEMORY_LIFECYCLE_COLUMNS}; `undefined` when `schema` is. */
2191
+ function withObservationalMemoryLifecycleColumns(schema) {
2192
+ return schema ? {
2193
+ ...schema,
2194
+ ...OBSERVATIONAL_MEMORY_LIFECYCLE_COLUMNS
2195
+ } : void 0;
2196
+ }
2197
+ /**
2198
+ * A buffered chunk stores `lastObservedAt = max message time + 1ms`. It is wholly covered
2199
+ * (every message it observed is already at or before the cursor) iff
2200
+ * `cursor >= chunk.lastObservedAt - 1ms`.
2201
+ */
2202
+ function isBufferedChunkCoveredByCursor(chunkLastObservedAt, cursor) {
2203
+ if (!cursor) return false;
2204
+ return new Date(cursor).getTime() >= new Date(chunkLastObservedAt).getTime() - 1;
2205
+ }
2206
+ /** The later of two cursors; `undefined` only when both are absent. */
2207
+ function maxObservationCursor(a, b) {
2208
+ if (!a) return b ? new Date(b) : void 0;
2209
+ if (!b) return new Date(a);
2210
+ return new Date(Math.max(new Date(a).getTime(), new Date(b).getTime()));
2211
+ }
2212
+ /**
2213
+ * Decide the new generation's text when a reflection built from `snapshot` commits against
2214
+ * the stored record.
2215
+ *
2216
+ * - Stored text equals the snapshot: the reflection replaces it.
2217
+ * - Stored text extends the snapshot (activation only appends): the appended tail is kept
2218
+ * after the reflection, and its tokens are added.
2219
+ * - Anything else (a non-append rewrite): `null` — the reflection must not be applied.
2220
+ */
2221
+ function planReflectionGenerationText(input) {
2222
+ const stored = input.storedObservations ?? "";
2223
+ const snapshot = input.snapshotObservations ?? "";
2224
+ if (stored === snapshot) return {
2225
+ mode: "equal",
2226
+ observations: input.reflection,
2227
+ tokenCount: input.tokenCount
2228
+ };
2229
+ if (!stored.startsWith(snapshot)) return null;
2230
+ const tail = stored.slice(snapshot.length).trimStart();
2231
+ if (!tail.trim()) return {
2232
+ mode: "equal",
2233
+ observations: input.reflection,
2234
+ tokenCount: input.tokenCount
2235
+ };
2236
+ return {
2237
+ mode: "append",
2238
+ observations: input.reflection ? `${input.reflection}\n\n${tail}` : tail,
2239
+ tokenCount: input.tokenCount + Math.max(0, (input.storedObservationTokenCount ?? 0) - (input.snapshotObservationTokenCount ?? 0))
2240
+ };
2241
+ }
2242
+ /**
2243
+ * Backs `updateActiveObservations` in adapters that implement `commitActiveObservations`.
2244
+ * Callers of `updateActiveObservations` (which resolves `void`) can't see a commit result, so a
2245
+ * write that was not applied throws instead of resolving as if it had committed.
2246
+ */
2247
+ function assertActiveObservationsApplied(result, id) {
2248
+ if (result.applied) return;
2249
+ throw new Error(result.reason === "retired" ? `Observational memory record ${id} was superseded by a newer generation; observations were not written` : `Observational memory record ${id} changed since the observations were composed; observations were not written`);
2250
+ }
2251
+ /**
2252
+ * Whether the stored text can still accept a reflection built from `snapshot`
2253
+ * (equal, or only appended to since).
2254
+ */
2255
+ function isAppendOnlySince(storedObservations, snapshotObservations) {
2256
+ const stored = storedObservations ?? "";
2257
+ const snapshot = snapshotObservations ?? "";
2258
+ return stored === snapshot || stored.startsWith(snapshot);
2259
+ }
2160
2260
  // src/storage/db/run-fencing.ts
2161
2261
  /**
2162
2262
  * Epoch milliseconds on the database clock. SQL Server evaluates
@@ -2165,7 +2265,7 @@ var BackgroundTasksMSSQL = class BackgroundTasksMSSQL extends _mastra_core_stora
2165
2265
  * existing lease look longer and a new lease shorter.
2166
2266
  */
2167
2267
  const DB_NOW_MS = `DATEDIFF_BIG(MILLISECOND, '1970-01-01', SYSUTCDATETIME())`;
2168
- const ERR_DEADLOCK_VICTIM = 1205;
2268
+ const ERR_DEADLOCK_VICTIM$1 = 1205;
2169
2269
  const ERR_UNIQUE_INDEX = 2601;
2170
2270
  const ERR_PRIMARY_KEY = 2627;
2171
2271
  const MAX_CLAIM_ATTEMPTS = 5;
@@ -2229,9 +2329,666 @@ async function retryWriteRace(write) {
2229
2329
  return await write();
2230
2330
  } catch (error) {
2231
2331
  const number = error.number;
2232
- if (attempt >= MAX_CLAIM_ATTEMPTS || !(number === ERR_DEADLOCK_VICTIM || number === ERR_PRIMARY_KEY || number === ERR_UNIQUE_INDEX)) throw error;
2332
+ if (attempt >= MAX_CLAIM_ATTEMPTS || !(number === ERR_DEADLOCK_VICTIM$1 || number === ERR_PRIMARY_KEY || number === ERR_UNIQUE_INDEX)) throw error;
2333
+ }
2334
+ }
2335
+ // src/storage/domains/memory/observational-memory.ts
2336
+ /** Canonical head order: newest generation, then earliest createdAt, then lowest id. */
2337
+ const OM_HEAD_ORDER = "[generationCount] DESC, [createdAt] ASC, [id] ASC";
2338
+ /** Max `supersededBy` hops when redirecting a write aimed at a retired record. */
2339
+ const OM_MAX_HEAD_HOPS = 3;
2340
+ /** Attempts for an OM transaction chosen as a deadlock victim or timed out on a lock. */
2341
+ const OM_MAX_TRANSACTION_ATTEMPTS = 3;
2342
+ /** How long initialization waits for the per-key application lock. */
2343
+ const OM_INIT_LOCK_TIMEOUT_MS = 3e4;
2344
+ /** Deadlock victim (1205) or lock request timeout (1222): the statement can be retried. */
2345
+ const ERR_DEADLOCK_VICTIM = 1205;
2346
+ const ERR_LOCK_TIMEOUT = 1222;
2347
+ /** Case- and accent-sensitive comparison, so a group id search matches the literal text. */
2348
+ const BINARY_COLLATION = "Latin1_General_100_BIN2";
2349
+ /** Locks the primary-key row for the rest of the transaction; other writers queue behind it. */
2350
+ const ROW_LOCK = "WITH (UPDLOCK, ROWLOCK, HOLDLOCK)";
2351
+ const ID_TYPE = () => mssql.default.NVarChar(255);
2352
+ const KEY_TYPE = () => mssql.default.NVarChar(450);
2353
+ const TEXT_TYPE = () => mssql.default.NVarChar(mssql.default.MAX);
2354
+ const DATE_TYPE = () => mssql.default.DateTime2(7);
2355
+ function isRetryableLockError(error) {
2356
+ const number = error?.number;
2357
+ return number === ERR_DEADLOCK_VICTIM || number === ERR_LOCK_TIMEOUT;
2358
+ }
2359
+ function rethrowOrWrap(error, operation, details) {
2360
+ if (error instanceof _mastra_core_error.MastraError) throw error;
2361
+ throw new _mastra_core_error.MastraError({
2362
+ id: (0, _mastra_core_storage.createStorageErrorId)("MSSQL", operation, "FAILED"),
2363
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2364
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
2365
+ details
2366
+ }, error);
2367
+ }
2368
+ function throwNotFound(id, operation) {
2369
+ throw new _mastra_core_error.MastraError({
2370
+ id: (0, _mastra_core_storage.createStorageErrorId)("MSSQL", operation, "NOT_FOUND"),
2371
+ text: `Observational memory record not found: ${id}`,
2372
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2373
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
2374
+ details: { id }
2375
+ });
2376
+ }
2377
+ function parseJSONColumn(value) {
2378
+ if (value === null || value === void 0 || value === "") return void 0;
2379
+ if (typeof value === "string") return JSON.parse(value);
2380
+ return value;
2381
+ }
2382
+ function parseBufferedChunks(raw) {
2383
+ if (!raw) return [];
2384
+ try {
2385
+ const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
2386
+ return Array.isArray(parsed) ? parsed : [];
2387
+ } catch {
2388
+ return [];
2233
2389
  }
2234
2390
  }
2391
+ function toDate(value) {
2392
+ if (value === null || value === void 0) return void 0;
2393
+ const date = value instanceof Date ? value : new Date(value);
2394
+ return Number.isNaN(date.getTime()) ? void 0 : date;
2395
+ }
2396
+ function getObservationalMemoryKey(threadId, resourceId) {
2397
+ return threadId ? `thread:${threadId}` : `resource:${resourceId}`;
2398
+ }
2399
+ /**
2400
+ * Observational memory lifecycle on SQL Server.
2401
+ *
2402
+ * Every lifecycle write runs in one transaction that row-locks its target record by primary key
2403
+ * (`UPDLOCK, ROWLOCK, HOLDLOCK`), re-reads the stored state under that lock, and returns the real
2404
+ * outcome. A record retired by a reflection keeps a `supersededBy` pointer to its successor, so a
2405
+ * write aimed at it either reports `retired` or is redirected to the live head. Initialization is
2406
+ * serialized per key by a transaction-owned application lock, because there is no row to lock
2407
+ * before the first record exists.
2408
+ */
2409
+ var MssqlObservationalMemory = class {
2410
+ #pool;
2411
+ #schema;
2412
+ #table;
2413
+ #assertFence;
2414
+ constructor({ pool, schema, assertFence }) {
2415
+ this.#pool = pool;
2416
+ this.#schema = schema;
2417
+ this.#table = getTableName({
2418
+ indexName: _mastra_core_storage.TABLE_OBSERVATIONAL_MEMORY,
2419
+ schemaName: getSchemaName(schema)
2420
+ });
2421
+ this.#assertFence = assertFence;
2422
+ }
2423
+ async getObservationalMemory(threadId, resourceId) {
2424
+ try {
2425
+ const row = (await this.#pool.request().input("lookupKey", KEY_TYPE(), getObservationalMemoryKey(threadId, resourceId)).query(`SELECT TOP 1 * FROM ${this.#table} WHERE [lookupKey] = @lookupKey ORDER BY ${OM_HEAD_ORDER}`)).recordset[0];
2426
+ return row ? this.#parseRow(row) : null;
2427
+ } catch (error) {
2428
+ rethrowOrWrap(error, "GET_OBSERVATIONAL_MEMORY", {
2429
+ threadId,
2430
+ resourceId
2431
+ });
2432
+ }
2433
+ }
2434
+ async getObservationalMemoryHistory(threadId, resourceId, limit = 10, options) {
2435
+ try {
2436
+ const request = this.#pool.request().input("lookupKey", KEY_TYPE(), getObservationalMemoryKey(threadId, resourceId));
2437
+ const conditions = ["[lookupKey] = @lookupKey"];
2438
+ if (options?.recordId !== void 0) {
2439
+ conditions.push("[id] = @recordId");
2440
+ request.input("recordId", ID_TYPE(), options.recordId);
2441
+ }
2442
+ if (options?.from) {
2443
+ conditions.push("[createdAt] >= @from");
2444
+ request.input("from", DATE_TYPE(), options.from);
2445
+ }
2446
+ if (options?.to) {
2447
+ conditions.push("[createdAt] <= @to");
2448
+ request.input("to", DATE_TYPE(), options.to);
2449
+ }
2450
+ if (options?.groupId !== void 0) {
2451
+ request.input("groupPrefix", TEXT_TYPE(), `<observation-group id="${options.groupId}"`);
2452
+ conditions.push(`(
2453
+ CHARINDEX(@groupPrefix COLLATE ${BINARY_COLLATION}, [activeObservations] COLLATE ${BINARY_COLLATION}) > 0
2454
+ OR EXISTS (
2455
+ SELECT 1 FROM OPENJSON(CASE WHEN ISJSON([bufferedObservationChunks]) = 1 THEN [bufferedObservationChunks] END)
2456
+ WITH ([observations] NVARCHAR(MAX) '$.observations') AS chunk
2457
+ WHERE CHARINDEX(@groupPrefix COLLATE ${BINARY_COLLATION}, chunk.[observations] COLLATE ${BINARY_COLLATION}) > 0
2458
+ )
2459
+ )`);
2460
+ }
2461
+ if (options?.beforeGeneration !== void 0) {
2462
+ conditions.push("[generationCount] < @beforeGeneration");
2463
+ request.input("beforeGeneration", mssql.default.Int, options.beforeGeneration);
2464
+ }
2465
+ if (options?.afterGeneration !== void 0) {
2466
+ conditions.push("[generationCount] > @afterGeneration");
2467
+ request.input("afterGeneration", mssql.default.Int, options.afterGeneration);
2468
+ }
2469
+ const direction = options?.sortDirection === "ASC" ? "ASC" : "DESC";
2470
+ request.input("offset", mssql.default.Int, Math.max(0, Math.floor(Number(options?.offset ?? 0)) || 0));
2471
+ request.input("limit", mssql.default.Int, Math.max(1, Math.floor(Number(limit)) || 10));
2472
+ return (await request.query(`SELECT * FROM ${this.#table} WHERE ${conditions.join(" AND ")}
2473
+ ORDER BY [generationCount] ${direction}, [createdAt] ASC, [id] ASC
2474
+ OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`)).recordset.map((row) => this.#parseRow(row));
2475
+ } catch (error) {
2476
+ rethrowOrWrap(error, "GET_OBSERVATIONAL_MEMORY_HISTORY", {
2477
+ threadId,
2478
+ resourceId,
2479
+ limit
2480
+ });
2481
+ }
2482
+ }
2483
+ async initializeObservationalMemory(input) {
2484
+ const lookupKey = getObservationalMemoryKey(input.threadId, input.resourceId);
2485
+ try {
2486
+ const existing = await this.getObservationalMemory(input.threadId, input.resourceId);
2487
+ if (existing) return existing;
2488
+ const lockName = `mastra_om_init:${this.#schema ?? "dbo"}:${(0, crypto.createHash)("sha256").update(lookupKey).digest("hex")}`;
2489
+ await this.#transaction(async (transaction) => {
2490
+ const lock = await transaction.request().input("resource", mssql.default.NVarChar(255), lockName).input("timeout", mssql.default.Int, OM_INIT_LOCK_TIMEOUT_MS).query(`DECLARE @result INT;
2491
+ EXEC @result = sp_getapplock @Resource = @resource, @LockMode = 'Exclusive', @LockOwner = 'Transaction', @LockTimeout = @timeout;
2492
+ SELECT @result AS result;`);
2493
+ const status = Number(lock.recordset[0]?.result);
2494
+ if (status < 0) throw new Error(`Could not acquire the observational memory initialization lock for ${lookupKey} (sp_getapplock returned ${status})`);
2495
+ if ((await transaction.request().input("lookupKey", KEY_TYPE(), lookupKey).query(`SELECT TOP 1 [id] FROM ${this.#table} WHERE [lookupKey] = @lookupKey AND [supersededBy] IS NULL`)).recordset.length > 0) return;
2496
+ const now = /* @__PURE__ */ new Date();
2497
+ await transaction.request().input("id", ID_TYPE(), globalThis.crypto.randomUUID()).input("lookupKey", KEY_TYPE(), lookupKey).input("scope", mssql.default.NVarChar(400), input.scope).input("resourceId", mssql.default.NVarChar(400), input.resourceId).input("threadId", mssql.default.NVarChar(400), input.threadId || null).input("config", TEXT_TYPE(), JSON.stringify(input.config)).input("observedTimezone", mssql.default.NVarChar(400), input.observedTimezone || null).input("now", DATE_TYPE(), now).query(`INSERT INTO ${this.#table} (
2498
+ [id], [lookupKey], [scope], [resourceId], [threadId], [activeObservations], [originType], [config],
2499
+ [generationCount], [pendingMessageTokens], [totalTokensObserved], [observationTokenCount],
2500
+ [isObserving], [isReflecting], [isBufferingObservation], [isBufferingReflection], [lastBufferedAtTokens],
2501
+ [observedTimezone], [supersededBy], [createdAt], [updatedAt]
2502
+ ) VALUES (
2503
+ @id, @lookupKey, @scope, @resourceId, @threadId, N'', 'initial', @config,
2504
+ 0, 0, 0, 0,
2505
+ 0, 0, 0, 0, 0,
2506
+ @observedTimezone, NULL, @now, @now
2507
+ )`);
2508
+ });
2509
+ const head = await this.getObservationalMemory(input.threadId, input.resourceId);
2510
+ if (!head) throwNotFound(lookupKey, "INITIALIZE_OBSERVATIONAL_MEMORY");
2511
+ return head;
2512
+ } catch (error) {
2513
+ rethrowOrWrap(error, "INITIALIZE_OBSERVATIONAL_MEMORY", {
2514
+ threadId: input.threadId,
2515
+ resourceId: input.resourceId
2516
+ });
2517
+ }
2518
+ }
2519
+ async updateActiveObservations(input) {
2520
+ assertActiveObservationsApplied(await this.commitActiveObservations(input), input.id);
2521
+ }
2522
+ async commitActiveObservations(input) {
2523
+ try {
2524
+ return await this.#transaction(async (transaction) => {
2525
+ const row = await this.#lockRow(transaction, input.id);
2526
+ if (!row) throwNotFound(input.id, "UPDATE_ACTIVE_OBSERVATIONS");
2527
+ if (row.supersededBy) return {
2528
+ applied: false,
2529
+ reason: "retired"
2530
+ };
2531
+ if (input.expectedActiveObservations !== void 0 && input.expectedActiveObservations !== (row.activeObservations || "")) return {
2532
+ applied: false,
2533
+ reason: "conflict"
2534
+ };
2535
+ const lastObservedAt = maxObservationCursor(toDate(row.lastObservedAt), input.lastObservedAt);
2536
+ await transaction.request().input("observations", TEXT_TYPE(), input.observations).input("lastObservedAt", DATE_TYPE(), lastObservedAt).input("tokenCount", mssql.default.Int, input.tokenCount).input("observedMessageIds", TEXT_TYPE(), input.observedMessageIds ? JSON.stringify(input.observedMessageIds) : null).input("now", DATE_TYPE(), /* @__PURE__ */ new Date()).input("id", ID_TYPE(), input.id).query(`UPDATE ${this.#table} SET
2537
+ [activeObservations] = @observations,
2538
+ [lastObservedAt] = @lastObservedAt,
2539
+ [pendingMessageTokens] = 0,
2540
+ [observationTokenCount] = @tokenCount,
2541
+ [totalTokensObserved] = [totalTokensObserved] + @tokenCount,
2542
+ [observedMessageIds] = @observedMessageIds,
2543
+ [updatedAt] = @now
2544
+ WHERE [id] = @id`);
2545
+ return { applied: true };
2546
+ }, "commitActiveObservations");
2547
+ } catch (error) {
2548
+ rethrowOrWrap(error, "UPDATE_ACTIVE_OBSERVATIONS", { id: input.id });
2549
+ }
2550
+ }
2551
+ async createReflectionGeneration(input) {
2552
+ const { currentRecord } = input;
2553
+ try {
2554
+ return await this.#transaction(async (transaction) => {
2555
+ const row = await this.#lockRow(transaction, currentRecord.id);
2556
+ if (!row) return currentRecord;
2557
+ if (row.supersededBy) return this.#parseRow(await this.#resolveLiveRow(transaction, row));
2558
+ const stored = this.#parseRow(row);
2559
+ const plan = planReflectionGenerationText({
2560
+ storedObservations: stored.activeObservations,
2561
+ storedObservationTokenCount: stored.observationTokenCount,
2562
+ snapshotObservations: currentRecord.activeObservations,
2563
+ snapshotObservationTokenCount: currentRecord.observationTokenCount,
2564
+ reflection: input.reflection,
2565
+ tokenCount: input.tokenCount
2566
+ });
2567
+ if (!plan) return stored;
2568
+ return this.#rollOver(transaction, stored.id, plan.observations, plan.tokenCount, input.newRecordId, false);
2569
+ }, "createReflectionGeneration");
2570
+ } catch (error) {
2571
+ rethrowOrWrap(error, "CREATE_REFLECTION_GENERATION", { currentRecordId: currentRecord.id });
2572
+ }
2573
+ }
2574
+ async setReflectingFlag(id, isReflecting) {
2575
+ await this.#updateFlag(id, "isReflecting", isReflecting, "SET_REFLECTING_FLAG");
2576
+ }
2577
+ async setObservingFlag(id, isObserving) {
2578
+ await this.#updateFlag(id, "isObserving", isObserving, "SET_OBSERVING_FLAG");
2579
+ }
2580
+ async setBufferingReflectionFlag(id, isBuffering) {
2581
+ await this.#updateFlag(id, "isBufferingReflection", isBuffering, "SET_BUFFERING_REFLECTION_FLAG");
2582
+ }
2583
+ async setBufferingObservationFlag(id, isBuffering, lastBufferedAtTokens) {
2584
+ try {
2585
+ await this.#transaction(async (transaction) => {
2586
+ const row = await this.#lockRow(transaction, id);
2587
+ if (!row) throwNotFound(id, "SET_BUFFERING_OBSERVATION_FLAG");
2588
+ const target = await this.#resolveLiveRow(transaction, row);
2589
+ const request = transaction.request().input("isBuffering", mssql.default.Bit, isBuffering).input("now", DATE_TYPE(), /* @__PURE__ */ new Date()).input("id", ID_TYPE(), target.id);
2590
+ if (lastBufferedAtTokens !== void 0) request.input("lastBufferedAtTokens", mssql.default.Int, lastBufferedAtTokens);
2591
+ await request.query(`UPDATE ${this.#table} SET [isBufferingObservation] = @isBuffering,
2592
+ ${lastBufferedAtTokens !== void 0 ? "[lastBufferedAtTokens] = @lastBufferedAtTokens," : ""}
2593
+ [updatedAt] = @now
2594
+ WHERE [id] = @id`);
2595
+ });
2596
+ } catch (error) {
2597
+ rethrowOrWrap(error, "SET_BUFFERING_OBSERVATION_FLAG", { id });
2598
+ }
2599
+ }
2600
+ async clearObservationalMemory(threadId, resourceId) {
2601
+ try {
2602
+ await this.#pool.request().input("lookupKey", KEY_TYPE(), getObservationalMemoryKey(threadId, resourceId)).query(`DELETE FROM ${this.#table} WHERE [lookupKey] = @lookupKey`);
2603
+ } catch (error) {
2604
+ rethrowOrWrap(error, "CLEAR_OBSERVATIONAL_MEMORY", {
2605
+ threadId,
2606
+ resourceId
2607
+ });
2608
+ }
2609
+ }
2610
+ async setPendingMessageTokens(id, tokenCount) {
2611
+ try {
2612
+ await this.#transaction(async (transaction) => {
2613
+ const row = await this.#lockRow(transaction, id);
2614
+ if (!row) throwNotFound(id, "SET_PENDING_MESSAGE_TOKENS");
2615
+ const target = await this.#resolveLiveRow(transaction, row);
2616
+ await transaction.request().input("tokenCount", mssql.default.Int, tokenCount).input("now", DATE_TYPE(), /* @__PURE__ */ new Date()).input("id", ID_TYPE(), target.id).query(`UPDATE ${this.#table} SET [pendingMessageTokens] = @tokenCount, [updatedAt] = @now WHERE [id] = @id`);
2617
+ });
2618
+ } catch (error) {
2619
+ rethrowOrWrap(error, "SET_PENDING_MESSAGE_TOKENS", { id });
2620
+ }
2621
+ }
2622
+ async updateBufferedObservations(input) {
2623
+ await this.appendBufferedObservations(input);
2624
+ }
2625
+ async appendBufferedObservations(input) {
2626
+ const newChunk = {
2627
+ id: `ombuf-${globalThis.crypto.randomUUID()}`,
2628
+ cycleId: input.chunk.cycleId,
2629
+ observations: input.chunk.observations,
2630
+ tokenCount: input.chunk.tokenCount,
2631
+ messageIds: input.chunk.messageIds,
2632
+ messageTokens: input.chunk.messageTokens,
2633
+ lastObservedAt: input.chunk.lastObservedAt,
2634
+ createdAt: /* @__PURE__ */ new Date(),
2635
+ suggestedContinuation: input.chunk.suggestedContinuation,
2636
+ currentTask: input.chunk.currentTask,
2637
+ threadTitle: input.chunk.threadTitle,
2638
+ extractedValues: input.chunk.extractedValues,
2639
+ extractionFailures: input.chunk.extractionFailures
2640
+ };
2641
+ try {
2642
+ return await this.#transaction(async (transaction) => {
2643
+ const row = await this.#lockRow(transaction, input.id);
2644
+ if (!row) throwNotFound(input.id, "UPDATE_BUFFERED_OBSERVATIONS");
2645
+ const target = await this.#resolveLiveRow(transaction, row);
2646
+ const existingChunks = parseBufferedChunks(target.bufferedObservationChunks);
2647
+ if (existingChunks.some((existing) => existing.cycleId === input.chunk.cycleId) || isBufferedChunkCoveredByCursor(input.chunk.lastObservedAt, toDate(target.lastObservedAt))) return {
2648
+ persisted: false,
2649
+ recordId: target.id
2650
+ };
2651
+ const lastBufferedAtTime = maxObservationCursor(toDate(target.lastBufferedAtTime), input.lastBufferedAtTime ?? void 0);
2652
+ await transaction.request().input("chunks", TEXT_TYPE(), JSON.stringify([...existingChunks, newChunk])).input("lastBufferedAtTime", DATE_TYPE(), lastBufferedAtTime ?? null).input("now", DATE_TYPE(), /* @__PURE__ */ new Date()).input("id", ID_TYPE(), target.id).query(`UPDATE ${this.#table} SET
2653
+ [bufferedObservationChunks] = @chunks,
2654
+ [lastBufferedAtTime] = @lastBufferedAtTime,
2655
+ [updatedAt] = @now
2656
+ WHERE [id] = @id`);
2657
+ return {
2658
+ persisted: true,
2659
+ recordId: target.id
2660
+ };
2661
+ }, "appendBufferedObservations");
2662
+ } catch (error) {
2663
+ rethrowOrWrap(error, "UPDATE_BUFFERED_OBSERVATIONS", { id: input.id });
2664
+ }
2665
+ }
2666
+ async swapBufferedToActive(input) {
2667
+ try {
2668
+ return await this.#transaction(async (transaction) => {
2669
+ const row = await this.#lockRow(transaction, input.id);
2670
+ if (!row) throwNotFound(input.id, "SWAP_BUFFERED_TO_ACTIVE");
2671
+ const emptyResult = {
2672
+ chunksActivated: 0,
2673
+ messageTokensActivated: 0,
2674
+ observationTokensActivated: 0,
2675
+ messagesActivated: 0,
2676
+ activatedCycleIds: [],
2677
+ activatedMessageIds: []
2678
+ };
2679
+ if (row.supersededBy) return {
2680
+ ...emptyResult,
2681
+ retired: true
2682
+ };
2683
+ const persistedChunks = parseBufferedChunks(row.bufferedObservationChunks);
2684
+ const refreshedWeights = new Map((Array.isArray(input.bufferedChunks) ? input.bufferedChunks : []).map((c) => [c.id, c.messageTokens]));
2685
+ const chunks = persistedChunks.map((c) => refreshedWeights.has(c.id) ? {
2686
+ ...c,
2687
+ messageTokens: refreshedWeights.get(c.id)
2688
+ } : c);
2689
+ if (chunks.length === 0) return emptyResult;
2690
+ const chunksToActivate = selectActivationBoundary(chunks, input);
2691
+ const activatedChunks = chunks.slice(0, chunksToActivate);
2692
+ const remainingChunks = persistedChunks.slice(chunksToActivate);
2693
+ const activatedContent = activatedChunks.map((c) => c.observations).join("\n\n");
2694
+ const activatedTokens = activatedChunks.reduce((sum, c) => sum + c.tokenCount, 0);
2695
+ const activatedMessageTokens = activatedChunks.reduce((sum, c) => sum + (c.messageTokens ?? 0), 0);
2696
+ const activatedMessageCount = activatedChunks.reduce((sum, c) => sum + c.messageIds.length, 0);
2697
+ const activatedCycleIds = activatedChunks.map((c) => c.cycleId).filter((cid) => !!cid);
2698
+ const activatedMessageIds = activatedChunks.flatMap((c) => c.messageIds ?? []);
2699
+ const latestChunk = activatedChunks[activatedChunks.length - 1];
2700
+ const derivedLastObservedAt = input.lastObservedAt ?? (latestChunk?.lastObservedAt ? new Date(latestChunk.lastObservedAt) : /* @__PURE__ */ new Date());
2701
+ const lastObservedAt = maxObservationCursor(toDate(row.lastObservedAt), derivedLastObservedAt);
2702
+ const existingActive = row.activeObservations || "";
2703
+ const newActive = existingActive ? `${existingActive}\n\n${activatedContent}` : activatedContent;
2704
+ const newTokenCount = Number(row.observationTokenCount || 0) + activatedTokens;
2705
+ const newPending = Math.max(0, Number(row.pendingMessageTokens || 0) - activatedMessageTokens);
2706
+ await transaction.request().input("active", TEXT_TYPE(), newActive).input("tokenCount", mssql.default.Int, newTokenCount).input("pending", mssql.default.Int, newPending).input("chunks", TEXT_TYPE(), remainingChunks.length > 0 ? JSON.stringify(remainingChunks) : null).input("lastObservedAt", DATE_TYPE(), lastObservedAt).input("now", DATE_TYPE(), /* @__PURE__ */ new Date()).input("id", ID_TYPE(), input.id).query(`UPDATE ${this.#table} SET
2707
+ [activeObservations] = @active,
2708
+ [observationTokenCount] = @tokenCount,
2709
+ [pendingMessageTokens] = @pending,
2710
+ [bufferedObservationChunks] = @chunks,
2711
+ [lastObservedAt] = @lastObservedAt,
2712
+ [updatedAt] = @now
2713
+ WHERE [id] = @id`);
2714
+ return {
2715
+ chunksActivated: activatedChunks.length,
2716
+ messageTokensActivated: activatedMessageTokens,
2717
+ observationTokensActivated: activatedTokens,
2718
+ messagesActivated: activatedMessageCount,
2719
+ activatedCycleIds,
2720
+ activatedMessageIds,
2721
+ observations: activatedContent,
2722
+ perChunk: activatedChunks.map((c) => ({
2723
+ cycleId: c.cycleId ?? "",
2724
+ messageTokens: c.messageTokens ?? 0,
2725
+ observationTokens: c.tokenCount,
2726
+ messageCount: c.messageIds.length,
2727
+ observations: c.observations
2728
+ })),
2729
+ suggestedContinuation: latestChunk?.suggestedContinuation ?? void 0,
2730
+ currentTask: latestChunk?.currentTask ?? void 0
2731
+ };
2732
+ }, "swapBufferedToActive");
2733
+ } catch (error) {
2734
+ rethrowOrWrap(error, "SWAP_BUFFERED_TO_ACTIVE", { id: input.id });
2735
+ }
2736
+ }
2737
+ async updateBufferedReflection(input) {
2738
+ try {
2739
+ await this.#transaction(async (transaction) => {
2740
+ if ((await transaction.request().input("reflection", TEXT_TYPE(), input.reflection).input("tokenCount", mssql.default.Int, input.tokenCount).input("inputTokenCount", mssql.default.Int, input.inputTokenCount).input("lineCount", mssql.default.Int, input.reflectedObservationLineCount).input("now", DATE_TYPE(), /* @__PURE__ */ new Date()).input("id", ID_TYPE(), input.id).query(`UPDATE ${this.#table} SET
2741
+ [bufferedReflection] = CASE
2742
+ WHEN [bufferedReflection] IS NOT NULL AND [bufferedReflection] <> N''
2743
+ THEN CONCAT([bufferedReflection], NCHAR(10), NCHAR(10), @reflection)
2744
+ ELSE @reflection
2745
+ END,
2746
+ [bufferedReflectionTokens] = COALESCE([bufferedReflectionTokens], 0) + @tokenCount,
2747
+ [bufferedReflectionInputTokens] = COALESCE([bufferedReflectionInputTokens], 0) + @inputTokenCount,
2748
+ [reflectedObservationLineCount] = @lineCount,
2749
+ [updatedAt] = @now
2750
+ WHERE [id] = @id`)).rowsAffected[0] === 0) throwNotFound(input.id, "UPDATE_BUFFERED_REFLECTION");
2751
+ }, "updateBufferedReflection");
2752
+ } catch (error) {
2753
+ rethrowOrWrap(error, "UPDATE_BUFFERED_REFLECTION", { id: input.id });
2754
+ }
2755
+ }
2756
+ async swapBufferedReflectionToActive(input) {
2757
+ const { currentRecord } = input;
2758
+ try {
2759
+ return await this.#transaction(async (transaction) => {
2760
+ const row = await this.#lockRow(transaction, currentRecord.id);
2761
+ if (!row) return currentRecord;
2762
+ if (row.supersededBy) return this.#parseRow(await this.#resolveLiveRow(transaction, row));
2763
+ const stored = this.#parseRow(row);
2764
+ const bufferedReflection = stored.bufferedReflection || "";
2765
+ if (!bufferedReflection) throw new _mastra_core_error.MastraError({
2766
+ id: (0, _mastra_core_storage.createStorageErrorId)("MSSQL", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NO_CONTENT"),
2767
+ text: "No buffered reflection to swap",
2768
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2769
+ category: _mastra_core_error.ErrorCategory.USER,
2770
+ details: { id: currentRecord.id }
2771
+ });
2772
+ if (!isAppendOnlySince(stored.activeObservations, currentRecord.activeObservations)) return stored;
2773
+ const reflectedLineCount = stored.reflectedObservationLineCount ?? 0;
2774
+ const unreflectedContent = (stored.activeObservations || "").split("\n").slice(reflectedLineCount).join("\n").trim();
2775
+ const newObservations = unreflectedContent ? `${bufferedReflection}\n\n${unreflectedContent}` : bufferedReflection;
2776
+ const tokenCount = input.tokenCount + Math.max(0, (stored.observationTokenCount ?? 0) - (currentRecord.observationTokenCount ?? 0));
2777
+ return this.#rollOver(transaction, stored.id, newObservations, tokenCount, input.newRecordId, true);
2778
+ }, "swapBufferedReflectionToActive");
2779
+ } catch (error) {
2780
+ rethrowOrWrap(error, "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", { id: currentRecord.id });
2781
+ }
2782
+ }
2783
+ /** Inserts a fully formed record, e.g. the copy a thread clone carries over. */
2784
+ async insertObservationalMemoryRecord(record) {
2785
+ try {
2786
+ await this.#pool.request().input("id", ID_TYPE(), record.id).input("lookupKey", KEY_TYPE(), getObservationalMemoryKey(record.threadId, record.resourceId)).input("scope", mssql.default.NVarChar(400), record.scope).input("resourceId", mssql.default.NVarChar(400), record.resourceId).input("threadId", mssql.default.NVarChar(400), record.threadId || null).input("activeObservations", TEXT_TYPE(), record.activeObservations || "").input("originType", mssql.default.NVarChar(400), record.originType || "initial").input("config", TEXT_TYPE(), JSON.stringify(record.config ?? {})).input("generationCount", mssql.default.Int, record.generationCount || 0).input("lastObservedAt", DATE_TYPE(), record.lastObservedAt ?? null).input("pendingMessageTokens", mssql.default.Int, record.pendingMessageTokens || 0).input("totalTokensObserved", mssql.default.Int, record.totalTokensObserved || 0).input("observationTokenCount", mssql.default.Int, record.observationTokenCount || 0).input("observedMessageIds", TEXT_TYPE(), record.observedMessageIds ? JSON.stringify(record.observedMessageIds) : null).input("chunks", TEXT_TYPE(), record.bufferedObservationChunks?.length ? JSON.stringify(record.bufferedObservationChunks) : null).input("bufferedReflection", TEXT_TYPE(), record.bufferedReflection || null).input("bufferedReflectionTokens", mssql.default.Int, record.bufferedReflectionTokens ?? null).input("bufferedReflectionInputTokens", mssql.default.Int, record.bufferedReflectionInputTokens ?? null).input("reflectedObservationLineCount", mssql.default.Int, record.reflectedObservationLineCount ?? null).input("isObserving", mssql.default.Bit, !!record.isObserving).input("isReflecting", mssql.default.Bit, !!record.isReflecting).input("isBufferingObservation", mssql.default.Bit, !!record.isBufferingObservation).input("isBufferingReflection", mssql.default.Bit, !!record.isBufferingReflection).input("lastBufferedAtTokens", mssql.default.Int, record.lastBufferedAtTokens || 0).input("lastBufferedAtTime", DATE_TYPE(), record.lastBufferedAtTime ?? null).input("observedTimezone", mssql.default.NVarChar(400), record.observedTimezone || null).input("metadata", TEXT_TYPE(), record.metadata ? JSON.stringify(record.metadata) : null).input("supersededBy", ID_TYPE(), record.supersededBy ?? null).input("createdAt", DATE_TYPE(), record.createdAt).input("updatedAt", DATE_TYPE(), record.updatedAt).query(`INSERT INTO ${this.#table} (
2787
+ [id], [lookupKey], [scope], [resourceId], [threadId], [activeObservations], [originType], [config],
2788
+ [generationCount], [lastObservedAt], [pendingMessageTokens], [totalTokensObserved], [observationTokenCount],
2789
+ [observedMessageIds], [bufferedObservationChunks], [bufferedReflection], [bufferedReflectionTokens],
2790
+ [bufferedReflectionInputTokens], [reflectedObservationLineCount],
2791
+ [isObserving], [isReflecting], [isBufferingObservation], [isBufferingReflection],
2792
+ [lastBufferedAtTokens], [lastBufferedAtTime], [observedTimezone], [metadata], [supersededBy],
2793
+ [createdAt], [updatedAt]
2794
+ ) VALUES (
2795
+ @id, @lookupKey, @scope, @resourceId, @threadId, @activeObservations, @originType, @config,
2796
+ @generationCount, @lastObservedAt, @pendingMessageTokens, @totalTokensObserved, @observationTokenCount,
2797
+ @observedMessageIds, @chunks, @bufferedReflection, @bufferedReflectionTokens,
2798
+ @bufferedReflectionInputTokens, @reflectedObservationLineCount,
2799
+ @isObserving, @isReflecting, @isBufferingObservation, @isBufferingReflection,
2800
+ @lastBufferedAtTokens, @lastBufferedAtTime, @observedTimezone, @metadata, @supersededBy,
2801
+ @createdAt, @updatedAt
2802
+ )`);
2803
+ } catch (error) {
2804
+ rethrowOrWrap(error, "INSERT_OBSERVATIONAL_MEMORY_RECORD", { id: record.id });
2805
+ }
2806
+ }
2807
+ /** Deep-merges `input.config` into the stored config under a row lock, so concurrent updates both land. */
2808
+ async updateObservationalMemoryConfig(input, merge) {
2809
+ try {
2810
+ await this.#transaction(async (transaction) => {
2811
+ const row = await this.#lockRow(transaction, input.id);
2812
+ if (!row) throwNotFound(input.id, "UPDATE_OM_CONFIG");
2813
+ const merged = merge(parseJSONColumn(row.config) ?? {}, input.config);
2814
+ await transaction.request().input("config", TEXT_TYPE(), JSON.stringify(merged)).input("now", DATE_TYPE(), /* @__PURE__ */ new Date()).input("id", ID_TYPE(), input.id).query(`UPDATE ${this.#table} SET [config] = @config, [updatedAt] = @now WHERE [id] = @id`);
2815
+ });
2816
+ } catch (error) {
2817
+ rethrowOrWrap(error, "UPDATE_OM_CONFIG", { id: input.id });
2818
+ }
2819
+ }
2820
+ /**
2821
+ * Runs `fn` in one transaction, after checking the run fence when `fencedOperation` is given.
2822
+ * A deadlock victim or lock timeout is retried a bounded number of times; the server has
2823
+ * already rolled the transaction back.
2824
+ */
2825
+ async #transaction(fn, fencedOperation) {
2826
+ for (let attempt = 1;; attempt++) {
2827
+ const transaction = this.#pool.transaction();
2828
+ await transaction.begin();
2829
+ try {
2830
+ if (fencedOperation) await this.#assertFence(transaction, fencedOperation);
2831
+ const result = await fn(transaction);
2832
+ await transaction.commit();
2833
+ return result;
2834
+ } catch (error) {
2835
+ await transaction.rollback().catch(() => {});
2836
+ if (attempt < OM_MAX_TRANSACTION_ATTEMPTS && isRetryableLockError(error)) continue;
2837
+ throw error;
2838
+ }
2839
+ }
2840
+ }
2841
+ /** Row-locks one record by primary key for the rest of the transaction. */
2842
+ async #lockRow(transaction, id) {
2843
+ return (await transaction.request().input("id", ID_TYPE(), id).query(`SELECT * FROM ${this.#table} ${ROW_LOCK} WHERE [id] = @id`)).recordset[0] ?? null;
2844
+ }
2845
+ /**
2846
+ * The live, row-locked record a write aimed at `row` lands on: `row` itself while live,
2847
+ * otherwise the head. The head is found with a plain canonical read, then locked by primary
2848
+ * key; a head retired in between is followed through `supersededBy` (bounded).
2849
+ */
2850
+ async #resolveLiveRow(transaction, row) {
2851
+ if (!row.supersededBy) return row;
2852
+ const headId = (await transaction.request().input("lookupKey", KEY_TYPE(), row.lookupKey).query(`SELECT TOP 1 [id] FROM ${this.#table} WHERE [lookupKey] = @lookupKey ORDER BY ${OM_HEAD_ORDER}`)).recordset[0]?.id ?? row.supersededBy;
2853
+ let current = await this.#lockRow(transaction, headId) ?? row;
2854
+ for (let hop = 0; current.supersededBy; hop++) {
2855
+ const next = hop < OM_MAX_HEAD_HOPS ? await this.#lockRow(transaction, current.supersededBy) : null;
2856
+ if (!next) throw new _mastra_core_error.MastraError({
2857
+ id: (0, _mastra_core_storage.createStorageErrorId)("MSSQL", "RESOLVE_OBSERVATIONAL_MEMORY_HEAD", "FAILED"),
2858
+ text: `Observational memory record ${row.id} is superseded but no live head was found`,
2859
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2860
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
2861
+ details: { id: row.id }
2862
+ });
2863
+ current = next;
2864
+ }
2865
+ return current;
2866
+ }
2867
+ /**
2868
+ * Creates the next generation from the stored (live, row-locked) record and retires the stored
2869
+ * record in the same transaction. Carried columns are copied in SQL from the stored row:
2870
+ * buffered chunks move to the new generation; the cursor, buffering markers, pending tokens and
2871
+ * counters carry over; buffered reflection state does not (and is cleared on the retired row
2872
+ * after a buffered swap).
2873
+ */
2874
+ async #rollOver(transaction, storedId, observations, tokenCount, newRecordId, clearBufferedReflection) {
2875
+ const id = newRecordId ?? globalThis.crypto.randomUUID();
2876
+ const now = /* @__PURE__ */ new Date();
2877
+ await transaction.request().input("id", ID_TYPE(), id).input("observations", TEXT_TYPE(), observations).input("tokenCount", mssql.default.Int, Math.round(tokenCount)).input("now", DATE_TYPE(), now).input("storedId", ID_TYPE(), storedId).query(`INSERT INTO ${this.#table} (
2878
+ [id], [lookupKey], [scope], [resourceId], [threadId],
2879
+ [activeObservations], [activeObservationsPendingUpdate],
2880
+ [originType], [config], [generationCount], [lastObservedAt], [lastReflectionAt],
2881
+ [pendingMessageTokens], [totalTokensObserved], [observationTokenCount], [bufferedObservationChunks],
2882
+ [isObserving], [isReflecting], [isBufferingObservation], [isBufferingReflection],
2883
+ [lastBufferedAtTokens], [lastBufferedAtTime],
2884
+ [observedTimezone], [metadata], [supersededBy], [createdAt], [updatedAt]
2885
+ )
2886
+ SELECT
2887
+ @id, [lookupKey], [scope], [resourceId], [threadId],
2888
+ @observations, NULL,
2889
+ 'reflection', [config], [generationCount] + 1, [lastObservedAt], @now,
2890
+ [pendingMessageTokens], [totalTokensObserved], @tokenCount, [bufferedObservationChunks],
2891
+ 0, 0, [isBufferingObservation], 0,
2892
+ [lastBufferedAtTokens], [lastBufferedAtTime],
2893
+ [observedTimezone], [metadata], NULL, @now, @now
2894
+ FROM ${this.#table} WHERE [id] = @storedId`);
2895
+ if ((await transaction.request().input("id", ID_TYPE(), id).input("now", DATE_TYPE(), now).input("storedId", ID_TYPE(), storedId).query(`UPDATE ${this.#table} SET
2896
+ [supersededBy] = @id,
2897
+ [bufferedObservationChunks] = NULL,
2898
+ ${clearBufferedReflection ? `[bufferedReflection] = NULL, [bufferedReflectionTokens] = NULL,
2899
+ [bufferedReflectionInputTokens] = NULL, [reflectedObservationLineCount] = NULL,` : ""}
2900
+ [updatedAt] = @now
2901
+ WHERE [id] = @storedId AND [supersededBy] IS NULL`)).rowsAffected[0] !== 1) throw new _mastra_core_error.MastraError({
2902
+ id: (0, _mastra_core_storage.createStorageErrorId)("MSSQL", "CREATE_REFLECTION_GENERATION", "RETIRE_FAILED"),
2903
+ text: `Failed to retire observational memory record ${storedId}`,
2904
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
2905
+ category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
2906
+ details: { id: storedId }
2907
+ });
2908
+ const inserted = await this.#lockRow(transaction, id);
2909
+ if (!inserted) throwNotFound(id, "CREATE_REFLECTION_GENERATION");
2910
+ return this.#parseRow(inserted);
2911
+ }
2912
+ async #updateFlag(id, column, value, operation) {
2913
+ try {
2914
+ if ((await this.#pool.request().input("value", mssql.default.Bit, value).input("now", DATE_TYPE(), /* @__PURE__ */ new Date()).input("id", ID_TYPE(), id).query(`UPDATE ${this.#table} SET [${column}] = @value, [updatedAt] = @now WHERE [id] = @id`)).rowsAffected[0] === 0) throwNotFound(id, operation);
2915
+ } catch (error) {
2916
+ rethrowOrWrap(error, operation, { id });
2917
+ }
2918
+ }
2919
+ #parseRow(row) {
2920
+ return {
2921
+ id: row.id,
2922
+ scope: row.scope,
2923
+ threadId: row.threadId || null,
2924
+ resourceId: row.resourceId,
2925
+ createdAt: toDate(row.createdAt) ?? /* @__PURE__ */ new Date(),
2926
+ updatedAt: toDate(row.updatedAt) ?? /* @__PURE__ */ new Date(),
2927
+ lastObservedAt: toDate(row.lastObservedAt),
2928
+ originType: row.originType || "initial",
2929
+ generationCount: Number(row.generationCount || 0),
2930
+ activeObservations: row.activeObservations || "",
2931
+ bufferedObservationChunks: parseJSONColumn(row.bufferedObservationChunks),
2932
+ bufferedObservations: row.activeObservationsPendingUpdate || void 0,
2933
+ bufferedObservationTokens: row.bufferedObservationTokens ? Number(row.bufferedObservationTokens) : void 0,
2934
+ bufferedMessageIds: void 0,
2935
+ bufferedReflection: row.bufferedReflection || void 0,
2936
+ bufferedReflectionTokens: row.bufferedReflectionTokens ? Number(row.bufferedReflectionTokens) : void 0,
2937
+ bufferedReflectionInputTokens: row.bufferedReflectionInputTokens ? Number(row.bufferedReflectionInputTokens) : void 0,
2938
+ reflectedObservationLineCount: row.reflectedObservationLineCount ? Number(row.reflectedObservationLineCount) : void 0,
2939
+ totalTokensObserved: Number(row.totalTokensObserved || 0),
2940
+ observationTokenCount: Number(row.observationTokenCount || 0),
2941
+ pendingMessageTokens: Number(row.pendingMessageTokens || 0),
2942
+ isReflecting: !!row.isReflecting,
2943
+ isObserving: !!row.isObserving,
2944
+ isBufferingObservation: !!row.isBufferingObservation,
2945
+ isBufferingReflection: !!row.isBufferingReflection,
2946
+ lastBufferedAtTokens: Number(row.lastBufferedAtTokens || 0),
2947
+ lastBufferedAtTime: toDate(row.lastBufferedAtTime) ?? null,
2948
+ config: parseJSONColumn(row.config) ?? {},
2949
+ metadata: parseJSONColumn(row.metadata),
2950
+ observedMessageIds: parseJSONColumn(row.observedMessageIds),
2951
+ observedTimezone: row.observedTimezone || void 0,
2952
+ supersededBy: row.supersededBy ?? null
2953
+ };
2954
+ }
2955
+ };
2956
+ /**
2957
+ * How many leading chunks to activate: the chunk boundary closest to the activation target that
2958
+ * still leaves the retention floor of message tokens pending.
2959
+ */
2960
+ function selectActivationBoundary(chunks, input) {
2961
+ const retentionFloor = input.messageTokensThreshold * (1 - input.activationRatio);
2962
+ const targetMessageTokens = Math.max(0, input.currentPendingTokens - retentionFloor);
2963
+ let cumulativeMessageTokens = 0;
2964
+ let bestOverBoundary = 0;
2965
+ let bestOverTokens = 0;
2966
+ let bestUnderBoundary = 0;
2967
+ let bestUnderTokens = 0;
2968
+ for (let i = 0; i < chunks.length; i++) {
2969
+ cumulativeMessageTokens += chunks[i].messageTokens ?? 0;
2970
+ const boundary = i + 1;
2971
+ if (cumulativeMessageTokens >= targetMessageTokens) {
2972
+ if (bestOverBoundary === 0 || cumulativeMessageTokens < bestOverTokens) {
2973
+ bestOverBoundary = boundary;
2974
+ bestOverTokens = cumulativeMessageTokens;
2975
+ }
2976
+ } else if (cumulativeMessageTokens > bestUnderTokens) {
2977
+ bestUnderBoundary = boundary;
2978
+ bestUnderTokens = cumulativeMessageTokens;
2979
+ }
2980
+ }
2981
+ const maxOvershoot = retentionFloor * .95;
2982
+ const overshoot = bestOverTokens - targetMessageTokens;
2983
+ const remainingAfterOver = input.currentPendingTokens - bestOverTokens;
2984
+ const remainingAfterUnder = input.currentPendingTokens - bestUnderTokens;
2985
+ const minRemaining = Math.min(1e3, retentionFloor);
2986
+ if (input.forceMaxActivation && bestOverBoundary > 0 && remainingAfterOver >= minRemaining) return bestOverBoundary;
2987
+ if (bestOverBoundary > 0 && overshoot <= maxOvershoot && remainingAfterOver >= minRemaining) return bestOverBoundary;
2988
+ if (bestUnderBoundary > 0 && remainingAfterUnder >= minRemaining) return bestUnderBoundary;
2989
+ if (bestOverBoundary > 0) return bestOverBoundary;
2990
+ return 1;
2991
+ }
2235
2992
  // src/storage/domains/memory/index.ts
2236
2993
  function bindMssqlMetadataParams(request, params) {
2237
2994
  for (const [paramName, paramValue] of Object.entries(params)) request.input(paramName, paramValue);
@@ -2263,7 +3020,10 @@ function buildMssqlMessageMetadataFilter(metadataFilter) {
2263
3020
  }
2264
3021
  var MemoryMSSQL = class MemoryMSSQL extends _mastra_core_storage.MemoryStorage {
2265
3022
  supportsPartialThreadUpdate = true;
3023
+ supportsObservationalMemory = true;
3024
+ supportsObservationalMemoryHistorySearch = true;
2266
3025
  pool;
3026
+ #om;
2267
3027
  schema;
2268
3028
  db;
2269
3029
  needsConnect;
@@ -2311,6 +3071,11 @@ var MemoryMSSQL = class MemoryMSSQL extends _mastra_core_storage.MemoryStorage {
2311
3071
  schemaName,
2312
3072
  skipDefaultIndexes
2313
3073
  });
3074
+ this.#om = new MssqlObservationalMemory({
3075
+ pool,
3076
+ schema: schemaName,
3077
+ assertFence: (transaction, operation) => this.#assertFence(transaction, void 0, operation)
3078
+ });
2314
3079
  this.needsConnect = needsConnect;
2315
3080
  this.skipDefaultIndexes = skipDefaultIndexes;
2316
3081
  this.indexes = indexes?.filter((idx) => MemoryMSSQL.MANAGED_TABLES.includes(idx.table));
@@ -2336,9 +3101,31 @@ var MemoryMSSQL = class MemoryMSSQL extends _mastra_core_storage.MemoryStorage {
2336
3101
  tableName: _mastra_core_storage.TABLE_MEMORY_RUN_FENCES,
2337
3102
  schema: _mastra_core_storage.RUN_FENCING_TABLE_SCHEMAS[_mastra_core_storage.TABLE_MEMORY_RUN_FENCES]
2338
3103
  });
3104
+ await this.#initObservationalMemoryTable();
2339
3105
  await this.createDefaultIndexes();
2340
3106
  await this.createCustomIndexes();
2341
3107
  }
3108
+ /** Creates or upgrades the observational memory table and its head-lookup index. */
3109
+ async #initObservationalMemoryTable() {
3110
+ const schema = withObservationalMemoryLifecycleColumns(_mastra_core_storage.OBSERVATIONAL_MEMORY_TABLE_SCHEMA[_mastra_core_storage.TABLE_OBSERVATIONAL_MEMORY]);
3111
+ if (!schema) return;
3112
+ const tableName = _mastra_core_storage.TABLE_OBSERVATIONAL_MEMORY;
3113
+ await this.db.createTable({
3114
+ tableName,
3115
+ schema
3116
+ });
3117
+ await this.db.alterTable({
3118
+ tableName,
3119
+ schema,
3120
+ ifNotExists: Object.keys(schema)
3121
+ });
3122
+ if (this.skipDefaultIndexes) return;
3123
+ await this.db.createIndex({
3124
+ name: "mastra_om_lookupkey_generation_idx",
3125
+ table: tableName,
3126
+ columns: ["lookupKey", "generationCount DESC"]
3127
+ });
3128
+ }
2342
3129
  supportsRunFencing() {
2343
3130
  return true;
2344
3131
  }
@@ -2457,6 +3244,7 @@ var MemoryMSSQL = class MemoryMSSQL extends _mastra_core_storage.MemoryStorage {
2457
3244
  await this.db.clearTable({ tableName: _mastra_core_storage.TABLE_THREADS });
2458
3245
  await this.db.clearTable({ tableName: _mastra_core_storage.TABLE_RESOURCES });
2459
3246
  await this.db.clearTable({ tableName: _mastra_core_storage.TABLE_MEMORY_RUN_FENCES });
3247
+ await this.db.clearTable({ tableName: _mastra_core_storage.TABLE_OBSERVATIONAL_MEMORY });
2460
3248
  }
2461
3249
  async getThreadById({ threadId, resourceId }) {
2462
3250
  try {
@@ -2929,8 +3717,7 @@ var MemoryMSSQL = class MemoryMSSQL extends _mastra_core_storage.MemoryStorage {
2929
3717
  }
2930
3718
  }
2931
3719
  async listMessages(args) {
2932
- const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
2933
- const metadataFilter = (0, _mastra_core_storage.validateStorageMetadataFilter)(filter?.metadata);
3720
+ const { threadId } = args;
2934
3721
  const threadIds = Array.isArray(threadId) ? threadId : [threadId];
2935
3722
  if (threadIds.length === 0 || threadIds.some((id) => !id.trim())) throw new _mastra_core_error.MastraError({
2936
3723
  id: (0, _mastra_core_storage.createStorageErrorId)("MSSQL", "LIST_MESSAGES", "INVALID_THREAD_ID"),
@@ -2938,13 +3725,30 @@ var MemoryMSSQL = class MemoryMSSQL extends _mastra_core_storage.MemoryStorage {
2938
3725
  category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
2939
3726
  details: { threadId: Array.isArray(threadId) ? threadId.join(",") : threadId }
2940
3727
  }, /* @__PURE__ */ new Error("threadId must be a non-empty string or array of non-empty strings"));
3728
+ return this.#queryMessages(args, threadIds);
3729
+ }
3730
+ /** Lists a resource's messages across all of its threads (used by resource-scoped observational memory). */
3731
+ async listMessagesByResourceId(args) {
3732
+ const { resourceId } = args;
3733
+ if (!resourceId || typeof resourceId !== "string" || resourceId.trim().length === 0) throw new _mastra_core_error.MastraError({
3734
+ id: (0, _mastra_core_storage.createStorageErrorId)("MSSQL", "LIST_MESSAGES", "INVALID_QUERY"),
3735
+ domain: _mastra_core_error.ErrorDomain.STORAGE,
3736
+ category: _mastra_core_error.ErrorCategory.USER,
3737
+ details: { resourceId: resourceId ?? "" }
3738
+ }, /* @__PURE__ */ new Error("resourceId is required"));
3739
+ return this.#queryMessages(args, null);
3740
+ }
3741
+ /** One page of messages from `threadIds`, or from every thread of `resourceId` when `threadIds` is null. */
3742
+ async #queryMessages(args, threadIds) {
3743
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
3744
+ const metadataFilter = (0, _mastra_core_storage.validateStorageMetadataFilter)(filter?.metadata);
2941
3745
  if (page < 0) throw new _mastra_core_error.MastraError({
2942
3746
  id: (0, _mastra_core_storage.createStorageErrorId)("MSSQL", "LIST_MESSAGES", "INVALID_PAGE"),
2943
3747
  domain: _mastra_core_error.ErrorDomain.STORAGE,
2944
3748
  category: _mastra_core_error.ErrorCategory.USER,
2945
3749
  text: "Page number must be non-negative",
2946
3750
  details: {
2947
- threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
3751
+ threadId: Array.isArray(threadId) ? threadId.join(",") : threadId ?? "",
2948
3752
  page
2949
3753
  }
2950
3754
  });
@@ -2959,7 +3763,7 @@ var MemoryMSSQL = class MemoryMSSQL extends _mastra_core_storage.MemoryStorage {
2959
3763
  });
2960
3764
  const baseQuery = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId FROM ${tableName}`;
2961
3765
  const { sql: preparedWhereClause = "", params: whereParams } = prepareWhereClause({
2962
- thread_id: threadIds.length === 1 ? threadIds[0] : { $in: threadIds },
3766
+ ...threadIds ? { thread_id: threadIds.length === 1 ? threadIds[0] : { $in: threadIds } } : {},
2963
3767
  ...resourceId ? { resourceId } : {},
2964
3768
  ...buildDateRangeFilter(filter?.dateRange, "createdAt")
2965
3769
  }, _mastra_core_storage.TABLE_SCHEMAS[_mastra_core_storage.TABLE_MESSAGES]);
@@ -3040,23 +3844,23 @@ var MemoryMSSQL = class MemoryMSSQL extends _mastra_core_storage.MemoryStorage {
3040
3844
  const seqB = seqById.get(b.id);
3041
3845
  return seqA != null && seqB != null ? (seqA - seqB) * mult : a.id.localeCompare(b.id);
3042
3846
  });
3043
- const threadIdSet = new Set(threadIds);
3847
+ const threadIdSet = new Set(threadIds ?? []);
3044
3848
  const returnedThreadMessageCount = finalMessages.filter((m) => m.threadId && threadIdSet.has(m.threadId)).length;
3045
3849
  return {
3046
3850
  messages: finalMessages,
3047
3851
  total,
3048
3852
  page,
3049
3853
  perPage: perPageForResponse,
3050
- hasMore: metadataFilter ? perPageInput !== false && offset + primaryPageCount < total : perPageInput !== false && returnedThreadMessageCount < total && offset + perPage < total
3854
+ hasMore: metadataFilter || !threadIds ? perPageInput !== false && offset + primaryPageCount < total : perPageInput !== false && returnedThreadMessageCount < total && offset + perPage < total
3051
3855
  };
3052
3856
  } catch (error) {
3053
3857
  if (error instanceof _mastra_core_error.MastraError && error.category === _mastra_core_error.ErrorCategory.USER) throw error;
3054
3858
  const mastraError = new _mastra_core_error.MastraError({
3055
- id: (0, _mastra_core_storage.createStorageErrorId)("MSSQL", "LIST_MESSAGES", "FAILED"),
3859
+ id: (0, _mastra_core_storage.createStorageErrorId)("MSSQL", threadIds ? "LIST_MESSAGES" : "LIST_MESSAGES_BY_RESOURCE_ID", "FAILED"),
3056
3860
  domain: _mastra_core_error.ErrorDomain.STORAGE,
3057
3861
  category: _mastra_core_error.ErrorCategory.THIRD_PARTY,
3058
3862
  details: {
3059
- threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
3863
+ threadId: Array.isArray(threadId) ? threadId.join(",") : threadId ?? "",
3060
3864
  resourceId: resourceId ?? ""
3061
3865
  }
3062
3866
  }, error);
@@ -3391,6 +4195,63 @@ var MemoryMSSQL = class MemoryMSSQL extends _mastra_core_storage.MemoryStorage {
3391
4195
  throw mastraError;
3392
4196
  }
3393
4197
  }
4198
+ getObservationalMemory(threadId, resourceId) {
4199
+ return this.#om.getObservationalMemory(threadId, resourceId);
4200
+ }
4201
+ getObservationalMemoryHistory(threadId, resourceId, limit, options) {
4202
+ return this.#om.getObservationalMemoryHistory(threadId, resourceId, limit, options);
4203
+ }
4204
+ initializeObservationalMemory(input) {
4205
+ return this.#om.initializeObservationalMemory(input);
4206
+ }
4207
+ updateActiveObservations(input) {
4208
+ return this.#om.updateActiveObservations(input);
4209
+ }
4210
+ commitActiveObservations(input) {
4211
+ return this.#om.commitActiveObservations(input);
4212
+ }
4213
+ updateBufferedObservations(input) {
4214
+ return this.#om.updateBufferedObservations(input);
4215
+ }
4216
+ appendBufferedObservations(input) {
4217
+ return this.#om.appendBufferedObservations(input);
4218
+ }
4219
+ swapBufferedToActive(input) {
4220
+ return this.#om.swapBufferedToActive(input);
4221
+ }
4222
+ createReflectionGeneration(input) {
4223
+ return this.#om.createReflectionGeneration(input);
4224
+ }
4225
+ updateBufferedReflection(input) {
4226
+ return this.#om.updateBufferedReflection(input);
4227
+ }
4228
+ swapBufferedReflectionToActive(input) {
4229
+ return this.#om.swapBufferedReflectionToActive(input);
4230
+ }
4231
+ setReflectingFlag(id, isReflecting) {
4232
+ return this.#om.setReflectingFlag(id, isReflecting);
4233
+ }
4234
+ setObservingFlag(id, isObserving) {
4235
+ return this.#om.setObservingFlag(id, isObserving);
4236
+ }
4237
+ setBufferingObservationFlag(id, isBuffering, lastBufferedAtTokens) {
4238
+ return this.#om.setBufferingObservationFlag(id, isBuffering, lastBufferedAtTokens);
4239
+ }
4240
+ setBufferingReflectionFlag(id, isBuffering) {
4241
+ return this.#om.setBufferingReflectionFlag(id, isBuffering);
4242
+ }
4243
+ clearObservationalMemory(threadId, resourceId) {
4244
+ return this.#om.clearObservationalMemory(threadId, resourceId);
4245
+ }
4246
+ setPendingMessageTokens(id, tokenCount) {
4247
+ return this.#om.setPendingMessageTokens(id, tokenCount);
4248
+ }
4249
+ insertObservationalMemoryRecord(record) {
4250
+ return this.#om.insertObservationalMemoryRecord(record);
4251
+ }
4252
+ updateObservationalMemoryConfig(input) {
4253
+ return this.#om.updateObservationalMemoryConfig(input, (target, source) => this.deepMergeConfig(target, source));
4254
+ }
3394
4255
  };
3395
4256
  // src/storage/domains/observability/index.ts
3396
4257
  var ObservabilityMSSQL = class ObservabilityMSSQL extends _mastra_core_storage.ObservabilityStorage {