@mastra/mssql 1.11.2 → 1.12.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.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
2
- import { AGENTS_SCHEMA, AGENT_VERSIONS_SCHEMA, AgentsStorage, BackgroundTasksStorage, MastraCompositeStore, MemoryStorage, ObservabilityStorage, RUN_FENCING_TABLE_SCHEMAS, RunFenceConflictError, SPAN_SCHEMA, ScoresStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, TABLE_BACKGROUND_TASKS, TABLE_MEMORY_RUN_FENCES, TABLE_MESSAGES, TABLE_RESOURCES, TABLE_SCHEMAS, TABLE_SCORERS, TABLE_SPANS, TABLE_THREADS, TABLE_WORKFLOW_DEFINITIONS, TABLE_WORKFLOW_RUN_OWNERS, TABLE_WORKFLOW_SNAPSHOT, TraceStatus, WORKFLOW_DEFINITIONS_SCHEMA, WorkflowDefinitionsStorage, WorkflowsStorage, calculatePagination, createStorageErrorId, executeRetentionPrune, getDefaultValue, isRunFenceConflictError, listTracesArgsSchema, matchesExpectedWorkflowStatus, matchesRunFence, normalizePerPage, resolveRetentionTargets, resolveRunFence, retentionCutoffMs, toTraceSpans, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
2
+ import { AGENTS_SCHEMA, AGENT_VERSIONS_SCHEMA, AgentsStorage, BackgroundTasksStorage, MastraCompositeStore, MemoryStorage, OBSERVATIONAL_MEMORY_TABLE_SCHEMA, ObservabilityStorage, RUN_FENCING_TABLE_SCHEMAS, RunFenceConflictError, SPAN_SCHEMA, ScoresStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, TABLE_BACKGROUND_TASKS, TABLE_MEMORY_RUN_FENCES, TABLE_MESSAGES, TABLE_OBSERVATIONAL_MEMORY, TABLE_RESOURCES, TABLE_SCHEMAS, TABLE_SCORERS, TABLE_SPANS, TABLE_THREADS, TABLE_WORKFLOW_DEFINITIONS, TABLE_WORKFLOW_RUN_OWNERS, TABLE_WORKFLOW_SNAPSHOT, TraceStatus, WORKFLOW_DEFINITIONS_SCHEMA, WorkflowDefinitionsStorage, WorkflowsStorage, calculatePagination, createStorageErrorId, executeRetentionPrune, getDefaultValue, isRunFenceConflictError, listTracesArgsSchema, matchesExpectedWorkflowStatus, matchesRunFence, normalizePerPage, resolveRetentionTargets, resolveRunFence, retentionCutoffMs, toTraceSpans, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
3
3
  import sql from "mssql";
4
4
  import { parseSqlIdentifier } from "@mastra/core/utils";
5
5
  import { MastraBase } from "@mastra/core/base";
6
6
  import { MessageList } from "@mastra/core/agent";
7
+ import { createHash } from "crypto";
7
8
  import { saveScorePayloadSchema } from "@mastra/core/evals";
8
9
  // src/storage/db/utils.ts
9
10
  function getSchemaName$1(schema) {
@@ -91,6 +92,25 @@ var MssqlDB = class extends MastraBase {
91
92
  "instructions",
92
93
  "other"
93
94
  ];
95
+ /**
96
+ * Observational memory text columns that hold observation text or JSON, which outgrow the
97
+ * indexable NVARCHAR(400) default.
98
+ */
99
+ OBSERVATIONAL_MEMORY_LARGE_TEXT_COLUMNS = [
100
+ "activeObservations",
101
+ "activeObservationsPendingUpdate",
102
+ "config",
103
+ "bufferedObservations",
104
+ "bufferedReflection"
105
+ ];
106
+ /** The SQL type for one column of `tableName`, applying per-table sizing. */
107
+ getColumnSqlType(tableName, columnName, def, isIndexed) {
108
+ if (tableName === TABLE_OBSERVATIONAL_MEMORY && def.type === "text") {
109
+ if (this.OBSERVATIONAL_MEMORY_LARGE_TEXT_COLUMNS.includes(columnName)) return "NVARCHAR(MAX)";
110
+ if (columnName === "lookupKey") return "NVARCHAR(450)";
111
+ }
112
+ return this.getSqlType(def.type, isIndexed, this.LARGE_DATA_COLUMNS.includes(columnName), this.COMPOSITE_INDEX_COLUMNS.includes(columnName));
113
+ }
94
114
  getSqlType(type, isPrimaryKey = false, useLargeStorage = false, useSmallStorage = false) {
95
115
  switch (type) {
96
116
  case "text":
@@ -259,9 +279,7 @@ var MssqlDB = class extends MastraBase {
259
279
  if (def.primaryKey) constraints.push("PRIMARY KEY");
260
280
  if (!def.nullable) constraints.push("NOT NULL");
261
281
  const isIndexed = !!def.primaryKey || uniqueConstraintColumns.includes(name);
262
- const useLargeStorage = this.LARGE_DATA_COLUMNS.includes(name);
263
- const useSmallStorage = this.COMPOSITE_INDEX_COLUMNS.includes(name);
264
- return `[${parsedName}] ${this.getSqlType(def.type, isIndexed, useLargeStorage, useSmallStorage)} ${constraints.join(" ")}`.trim();
282
+ return `[${parsedName}] ${this.getColumnSqlType(tableName, name, def, isIndexed)} ${constraints.join(" ")}`.trim();
265
283
  }).join(",\n");
266
284
  if (this.schemaName) await this.setupSchema();
267
285
  const checkTableRequest = this.pool.request();
@@ -545,10 +563,7 @@ MIGRATION REQUIRED: Duplicate spans detected in ${duplicateInfo.tableName}\n====
545
563
  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`);
546
564
  if (!(Array.isArray(checkResult.recordset) && checkResult.recordset.length > 0)) {
547
565
  const columnDef = schema[columnName];
548
- const useLargeStorage = this.LARGE_DATA_COLUMNS.includes(columnName);
549
- const useSmallStorage = this.COMPOSITE_INDEX_COLUMNS.includes(columnName);
550
- const isIndexed = !!columnDef.primaryKey;
551
- const sqlType = this.getSqlType(columnDef.type, isIndexed, useLargeStorage, useSmallStorage);
566
+ const sqlType = this.getColumnSqlType(tableName, columnName, columnDef, !!columnDef.primaryKey);
552
567
  const nullable = columnDef.nullable ? "" : "NOT NULL";
553
568
  const defaultValue = !columnDef.nullable ? this.getDefaultValue(columnDef.type) : "";
554
569
  const parsedColumnName = parseSqlIdentifier(columnName, "column name");
@@ -2134,6 +2149,91 @@ var BackgroundTasksMSSQL = class BackgroundTasksMSSQL extends BackgroundTasksSto
2134
2149
  return Number(result.recordset[0]?.count ?? 0);
2135
2150
  }
2136
2151
  };
2152
+ // ../../packages/_internal-core/dist/memory/index.js
2153
+ /**
2154
+ * Shared rules for observational memory lifecycle writes. Every storage adapter applies
2155
+ * these inside its own atomic section (lock, transaction, or conditional update), so the
2156
+ * decisions are identical across adapters.
2157
+ */
2158
+ /**
2159
+ * Observational memory columns that lifecycle writes depend on. Storage adapters merge these
2160
+ * into the table schema they get from `@mastra/core`, so the columns exist even when the
2161
+ * installed core predates them.
2162
+ */
2163
+ const OBSERVATIONAL_MEMORY_LIFECYCLE_COLUMNS = { supersededBy: {
2164
+ type: "text",
2165
+ nullable: true
2166
+ } };
2167
+ /** `schema` plus {@link OBSERVATIONAL_MEMORY_LIFECYCLE_COLUMNS}; `undefined` when `schema` is. */
2168
+ function withObservationalMemoryLifecycleColumns(schema) {
2169
+ return schema ? {
2170
+ ...schema,
2171
+ ...OBSERVATIONAL_MEMORY_LIFECYCLE_COLUMNS
2172
+ } : void 0;
2173
+ }
2174
+ /**
2175
+ * A buffered chunk stores `lastObservedAt = max message time + 1ms`. It is wholly covered
2176
+ * (every message it observed is already at or before the cursor) iff
2177
+ * `cursor >= chunk.lastObservedAt - 1ms`.
2178
+ */
2179
+ function isBufferedChunkCoveredByCursor(chunkLastObservedAt, cursor) {
2180
+ if (!cursor) return false;
2181
+ return new Date(cursor).getTime() >= new Date(chunkLastObservedAt).getTime() - 1;
2182
+ }
2183
+ /** The later of two cursors; `undefined` only when both are absent. */
2184
+ function maxObservationCursor(a, b) {
2185
+ if (!a) return b ? new Date(b) : void 0;
2186
+ if (!b) return new Date(a);
2187
+ return new Date(Math.max(new Date(a).getTime(), new Date(b).getTime()));
2188
+ }
2189
+ /**
2190
+ * Decide the new generation's text when a reflection built from `snapshot` commits against
2191
+ * the stored record.
2192
+ *
2193
+ * - Stored text equals the snapshot: the reflection replaces it.
2194
+ * - Stored text extends the snapshot (activation only appends): the appended tail is kept
2195
+ * after the reflection, and its tokens are added.
2196
+ * - Anything else (a non-append rewrite): `null` — the reflection must not be applied.
2197
+ */
2198
+ function planReflectionGenerationText(input) {
2199
+ const stored = input.storedObservations ?? "";
2200
+ const snapshot = input.snapshotObservations ?? "";
2201
+ if (stored === snapshot) return {
2202
+ mode: "equal",
2203
+ observations: input.reflection,
2204
+ tokenCount: input.tokenCount
2205
+ };
2206
+ if (!stored.startsWith(snapshot)) return null;
2207
+ const tail = stored.slice(snapshot.length).trimStart();
2208
+ if (!tail.trim()) return {
2209
+ mode: "equal",
2210
+ observations: input.reflection,
2211
+ tokenCount: input.tokenCount
2212
+ };
2213
+ return {
2214
+ mode: "append",
2215
+ observations: input.reflection ? `${input.reflection}\n\n${tail}` : tail,
2216
+ tokenCount: input.tokenCount + Math.max(0, (input.storedObservationTokenCount ?? 0) - (input.snapshotObservationTokenCount ?? 0))
2217
+ };
2218
+ }
2219
+ /**
2220
+ * Backs `updateActiveObservations` in adapters that implement `commitActiveObservations`.
2221
+ * Callers of `updateActiveObservations` (which resolves `void`) can't see a commit result, so a
2222
+ * write that was not applied throws instead of resolving as if it had committed.
2223
+ */
2224
+ function assertActiveObservationsApplied(result, id) {
2225
+ if (result.applied) return;
2226
+ 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`);
2227
+ }
2228
+ /**
2229
+ * Whether the stored text can still accept a reflection built from `snapshot`
2230
+ * (equal, or only appended to since).
2231
+ */
2232
+ function isAppendOnlySince(storedObservations, snapshotObservations) {
2233
+ const stored = storedObservations ?? "";
2234
+ const snapshot = snapshotObservations ?? "";
2235
+ return stored === snapshot || stored.startsWith(snapshot);
2236
+ }
2137
2237
  // src/storage/db/run-fencing.ts
2138
2238
  /**
2139
2239
  * Epoch milliseconds on the database clock. SQL Server evaluates
@@ -2142,7 +2242,7 @@ var BackgroundTasksMSSQL = class BackgroundTasksMSSQL extends BackgroundTasksSto
2142
2242
  * existing lease look longer and a new lease shorter.
2143
2243
  */
2144
2244
  const DB_NOW_MS = `DATEDIFF_BIG(MILLISECOND, '1970-01-01', SYSUTCDATETIME())`;
2145
- const ERR_DEADLOCK_VICTIM = 1205;
2245
+ const ERR_DEADLOCK_VICTIM$1 = 1205;
2146
2246
  const ERR_UNIQUE_INDEX = 2601;
2147
2247
  const ERR_PRIMARY_KEY = 2627;
2148
2248
  const MAX_CLAIM_ATTEMPTS = 5;
@@ -2206,9 +2306,666 @@ async function retryWriteRace(write) {
2206
2306
  return await write();
2207
2307
  } catch (error) {
2208
2308
  const number = error.number;
2209
- if (attempt >= MAX_CLAIM_ATTEMPTS || !(number === ERR_DEADLOCK_VICTIM || number === ERR_PRIMARY_KEY || number === ERR_UNIQUE_INDEX)) throw error;
2309
+ if (attempt >= MAX_CLAIM_ATTEMPTS || !(number === ERR_DEADLOCK_VICTIM$1 || number === ERR_PRIMARY_KEY || number === ERR_UNIQUE_INDEX)) throw error;
2310
+ }
2311
+ }
2312
+ // src/storage/domains/memory/observational-memory.ts
2313
+ /** Canonical head order: newest generation, then earliest createdAt, then lowest id. */
2314
+ const OM_HEAD_ORDER = "[generationCount] DESC, [createdAt] ASC, [id] ASC";
2315
+ /** Max `supersededBy` hops when redirecting a write aimed at a retired record. */
2316
+ const OM_MAX_HEAD_HOPS = 3;
2317
+ /** Attempts for an OM transaction chosen as a deadlock victim or timed out on a lock. */
2318
+ const OM_MAX_TRANSACTION_ATTEMPTS = 3;
2319
+ /** How long initialization waits for the per-key application lock. */
2320
+ const OM_INIT_LOCK_TIMEOUT_MS = 3e4;
2321
+ /** Deadlock victim (1205) or lock request timeout (1222): the statement can be retried. */
2322
+ const ERR_DEADLOCK_VICTIM = 1205;
2323
+ const ERR_LOCK_TIMEOUT = 1222;
2324
+ /** Case- and accent-sensitive comparison, so a group id search matches the literal text. */
2325
+ const BINARY_COLLATION = "Latin1_General_100_BIN2";
2326
+ /** Locks the primary-key row for the rest of the transaction; other writers queue behind it. */
2327
+ const ROW_LOCK = "WITH (UPDLOCK, ROWLOCK, HOLDLOCK)";
2328
+ const ID_TYPE = () => sql.NVarChar(255);
2329
+ const KEY_TYPE = () => sql.NVarChar(450);
2330
+ const TEXT_TYPE = () => sql.NVarChar(sql.MAX);
2331
+ const DATE_TYPE = () => sql.DateTime2(7);
2332
+ function isRetryableLockError(error) {
2333
+ const number = error?.number;
2334
+ return number === ERR_DEADLOCK_VICTIM || number === ERR_LOCK_TIMEOUT;
2335
+ }
2336
+ function rethrowOrWrap(error, operation, details) {
2337
+ if (error instanceof MastraError) throw error;
2338
+ throw new MastraError({
2339
+ id: createStorageErrorId("MSSQL", operation, "FAILED"),
2340
+ domain: ErrorDomain.STORAGE,
2341
+ category: ErrorCategory.THIRD_PARTY,
2342
+ details
2343
+ }, error);
2344
+ }
2345
+ function throwNotFound(id, operation) {
2346
+ throw new MastraError({
2347
+ id: createStorageErrorId("MSSQL", operation, "NOT_FOUND"),
2348
+ text: `Observational memory record not found: ${id}`,
2349
+ domain: ErrorDomain.STORAGE,
2350
+ category: ErrorCategory.THIRD_PARTY,
2351
+ details: { id }
2352
+ });
2353
+ }
2354
+ function parseJSONColumn(value) {
2355
+ if (value === null || value === void 0 || value === "") return void 0;
2356
+ if (typeof value === "string") return JSON.parse(value);
2357
+ return value;
2358
+ }
2359
+ function parseBufferedChunks(raw) {
2360
+ if (!raw) return [];
2361
+ try {
2362
+ const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
2363
+ return Array.isArray(parsed) ? parsed : [];
2364
+ } catch {
2365
+ return [];
2210
2366
  }
2211
2367
  }
2368
+ function toDate(value) {
2369
+ if (value === null || value === void 0) return void 0;
2370
+ const date = value instanceof Date ? value : new Date(value);
2371
+ return Number.isNaN(date.getTime()) ? void 0 : date;
2372
+ }
2373
+ function getObservationalMemoryKey(threadId, resourceId) {
2374
+ return threadId ? `thread:${threadId}` : `resource:${resourceId}`;
2375
+ }
2376
+ /**
2377
+ * Observational memory lifecycle on SQL Server.
2378
+ *
2379
+ * Every lifecycle write runs in one transaction that row-locks its target record by primary key
2380
+ * (`UPDLOCK, ROWLOCK, HOLDLOCK`), re-reads the stored state under that lock, and returns the real
2381
+ * outcome. A record retired by a reflection keeps a `supersededBy` pointer to its successor, so a
2382
+ * write aimed at it either reports `retired` or is redirected to the live head. Initialization is
2383
+ * serialized per key by a transaction-owned application lock, because there is no row to lock
2384
+ * before the first record exists.
2385
+ */
2386
+ var MssqlObservationalMemory = class {
2387
+ #pool;
2388
+ #schema;
2389
+ #table;
2390
+ #assertFence;
2391
+ constructor({ pool, schema, assertFence }) {
2392
+ this.#pool = pool;
2393
+ this.#schema = schema;
2394
+ this.#table = getTableName({
2395
+ indexName: TABLE_OBSERVATIONAL_MEMORY,
2396
+ schemaName: getSchemaName(schema)
2397
+ });
2398
+ this.#assertFence = assertFence;
2399
+ }
2400
+ async getObservationalMemory(threadId, resourceId) {
2401
+ try {
2402
+ 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];
2403
+ return row ? this.#parseRow(row) : null;
2404
+ } catch (error) {
2405
+ rethrowOrWrap(error, "GET_OBSERVATIONAL_MEMORY", {
2406
+ threadId,
2407
+ resourceId
2408
+ });
2409
+ }
2410
+ }
2411
+ async getObservationalMemoryHistory(threadId, resourceId, limit = 10, options) {
2412
+ try {
2413
+ const request = this.#pool.request().input("lookupKey", KEY_TYPE(), getObservationalMemoryKey(threadId, resourceId));
2414
+ const conditions = ["[lookupKey] = @lookupKey"];
2415
+ if (options?.recordId !== void 0) {
2416
+ conditions.push("[id] = @recordId");
2417
+ request.input("recordId", ID_TYPE(), options.recordId);
2418
+ }
2419
+ if (options?.from) {
2420
+ conditions.push("[createdAt] >= @from");
2421
+ request.input("from", DATE_TYPE(), options.from);
2422
+ }
2423
+ if (options?.to) {
2424
+ conditions.push("[createdAt] <= @to");
2425
+ request.input("to", DATE_TYPE(), options.to);
2426
+ }
2427
+ if (options?.groupId !== void 0) {
2428
+ request.input("groupPrefix", TEXT_TYPE(), `<observation-group id="${options.groupId}"`);
2429
+ conditions.push(`(
2430
+ CHARINDEX(@groupPrefix COLLATE ${BINARY_COLLATION}, [activeObservations] COLLATE ${BINARY_COLLATION}) > 0
2431
+ OR EXISTS (
2432
+ SELECT 1 FROM OPENJSON(CASE WHEN ISJSON([bufferedObservationChunks]) = 1 THEN [bufferedObservationChunks] END)
2433
+ WITH ([observations] NVARCHAR(MAX) '$.observations') AS chunk
2434
+ WHERE CHARINDEX(@groupPrefix COLLATE ${BINARY_COLLATION}, chunk.[observations] COLLATE ${BINARY_COLLATION}) > 0
2435
+ )
2436
+ )`);
2437
+ }
2438
+ if (options?.beforeGeneration !== void 0) {
2439
+ conditions.push("[generationCount] < @beforeGeneration");
2440
+ request.input("beforeGeneration", sql.Int, options.beforeGeneration);
2441
+ }
2442
+ if (options?.afterGeneration !== void 0) {
2443
+ conditions.push("[generationCount] > @afterGeneration");
2444
+ request.input("afterGeneration", sql.Int, options.afterGeneration);
2445
+ }
2446
+ const direction = options?.sortDirection === "ASC" ? "ASC" : "DESC";
2447
+ request.input("offset", sql.Int, Math.max(0, Math.floor(Number(options?.offset ?? 0)) || 0));
2448
+ request.input("limit", sql.Int, Math.max(1, Math.floor(Number(limit)) || 10));
2449
+ return (await request.query(`SELECT * FROM ${this.#table} WHERE ${conditions.join(" AND ")}
2450
+ ORDER BY [generationCount] ${direction}, [createdAt] ASC, [id] ASC
2451
+ OFFSET @offset ROWS FETCH NEXT @limit ROWS ONLY`)).recordset.map((row) => this.#parseRow(row));
2452
+ } catch (error) {
2453
+ rethrowOrWrap(error, "GET_OBSERVATIONAL_MEMORY_HISTORY", {
2454
+ threadId,
2455
+ resourceId,
2456
+ limit
2457
+ });
2458
+ }
2459
+ }
2460
+ async initializeObservationalMemory(input) {
2461
+ const lookupKey = getObservationalMemoryKey(input.threadId, input.resourceId);
2462
+ try {
2463
+ const existing = await this.getObservationalMemory(input.threadId, input.resourceId);
2464
+ if (existing) return existing;
2465
+ const lockName = `mastra_om_init:${this.#schema ?? "dbo"}:${createHash("sha256").update(lookupKey).digest("hex")}`;
2466
+ await this.#transaction(async (transaction) => {
2467
+ const lock = await transaction.request().input("resource", sql.NVarChar(255), lockName).input("timeout", sql.Int, OM_INIT_LOCK_TIMEOUT_MS).query(`DECLARE @result INT;
2468
+ EXEC @result = sp_getapplock @Resource = @resource, @LockMode = 'Exclusive', @LockOwner = 'Transaction', @LockTimeout = @timeout;
2469
+ SELECT @result AS result;`);
2470
+ const status = Number(lock.recordset[0]?.result);
2471
+ if (status < 0) throw new Error(`Could not acquire the observational memory initialization lock for ${lookupKey} (sp_getapplock returned ${status})`);
2472
+ 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;
2473
+ const now = /* @__PURE__ */ new Date();
2474
+ await transaction.request().input("id", ID_TYPE(), globalThis.crypto.randomUUID()).input("lookupKey", KEY_TYPE(), lookupKey).input("scope", sql.NVarChar(400), input.scope).input("resourceId", sql.NVarChar(400), input.resourceId).input("threadId", sql.NVarChar(400), input.threadId || null).input("config", TEXT_TYPE(), JSON.stringify(input.config)).input("observedTimezone", sql.NVarChar(400), input.observedTimezone || null).input("now", DATE_TYPE(), now).query(`INSERT INTO ${this.#table} (
2475
+ [id], [lookupKey], [scope], [resourceId], [threadId], [activeObservations], [originType], [config],
2476
+ [generationCount], [pendingMessageTokens], [totalTokensObserved], [observationTokenCount],
2477
+ [isObserving], [isReflecting], [isBufferingObservation], [isBufferingReflection], [lastBufferedAtTokens],
2478
+ [observedTimezone], [supersededBy], [createdAt], [updatedAt]
2479
+ ) VALUES (
2480
+ @id, @lookupKey, @scope, @resourceId, @threadId, N'', 'initial', @config,
2481
+ 0, 0, 0, 0,
2482
+ 0, 0, 0, 0, 0,
2483
+ @observedTimezone, NULL, @now, @now
2484
+ )`);
2485
+ });
2486
+ const head = await this.getObservationalMemory(input.threadId, input.resourceId);
2487
+ if (!head) throwNotFound(lookupKey, "INITIALIZE_OBSERVATIONAL_MEMORY");
2488
+ return head;
2489
+ } catch (error) {
2490
+ rethrowOrWrap(error, "INITIALIZE_OBSERVATIONAL_MEMORY", {
2491
+ threadId: input.threadId,
2492
+ resourceId: input.resourceId
2493
+ });
2494
+ }
2495
+ }
2496
+ async updateActiveObservations(input) {
2497
+ assertActiveObservationsApplied(await this.commitActiveObservations(input), input.id);
2498
+ }
2499
+ async commitActiveObservations(input) {
2500
+ try {
2501
+ return await this.#transaction(async (transaction) => {
2502
+ const row = await this.#lockRow(transaction, input.id);
2503
+ if (!row) throwNotFound(input.id, "UPDATE_ACTIVE_OBSERVATIONS");
2504
+ if (row.supersededBy) return {
2505
+ applied: false,
2506
+ reason: "retired"
2507
+ };
2508
+ if (input.expectedActiveObservations !== void 0 && input.expectedActiveObservations !== (row.activeObservations || "")) return {
2509
+ applied: false,
2510
+ reason: "conflict"
2511
+ };
2512
+ const lastObservedAt = maxObservationCursor(toDate(row.lastObservedAt), input.lastObservedAt);
2513
+ await transaction.request().input("observations", TEXT_TYPE(), input.observations).input("lastObservedAt", DATE_TYPE(), lastObservedAt).input("tokenCount", sql.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
2514
+ [activeObservations] = @observations,
2515
+ [lastObservedAt] = @lastObservedAt,
2516
+ [pendingMessageTokens] = 0,
2517
+ [observationTokenCount] = @tokenCount,
2518
+ [totalTokensObserved] = [totalTokensObserved] + @tokenCount,
2519
+ [observedMessageIds] = @observedMessageIds,
2520
+ [updatedAt] = @now
2521
+ WHERE [id] = @id`);
2522
+ return { applied: true };
2523
+ }, "commitActiveObservations");
2524
+ } catch (error) {
2525
+ rethrowOrWrap(error, "UPDATE_ACTIVE_OBSERVATIONS", { id: input.id });
2526
+ }
2527
+ }
2528
+ async createReflectionGeneration(input) {
2529
+ const { currentRecord } = input;
2530
+ try {
2531
+ return await this.#transaction(async (transaction) => {
2532
+ const row = await this.#lockRow(transaction, currentRecord.id);
2533
+ if (!row) return currentRecord;
2534
+ if (row.supersededBy) return this.#parseRow(await this.#resolveLiveRow(transaction, row));
2535
+ const stored = this.#parseRow(row);
2536
+ const plan = planReflectionGenerationText({
2537
+ storedObservations: stored.activeObservations,
2538
+ storedObservationTokenCount: stored.observationTokenCount,
2539
+ snapshotObservations: currentRecord.activeObservations,
2540
+ snapshotObservationTokenCount: currentRecord.observationTokenCount,
2541
+ reflection: input.reflection,
2542
+ tokenCount: input.tokenCount
2543
+ });
2544
+ if (!plan) return stored;
2545
+ return this.#rollOver(transaction, stored.id, plan.observations, plan.tokenCount, input.newRecordId, false);
2546
+ }, "createReflectionGeneration");
2547
+ } catch (error) {
2548
+ rethrowOrWrap(error, "CREATE_REFLECTION_GENERATION", { currentRecordId: currentRecord.id });
2549
+ }
2550
+ }
2551
+ async setReflectingFlag(id, isReflecting) {
2552
+ await this.#updateFlag(id, "isReflecting", isReflecting, "SET_REFLECTING_FLAG");
2553
+ }
2554
+ async setObservingFlag(id, isObserving) {
2555
+ await this.#updateFlag(id, "isObserving", isObserving, "SET_OBSERVING_FLAG");
2556
+ }
2557
+ async setBufferingReflectionFlag(id, isBuffering) {
2558
+ await this.#updateFlag(id, "isBufferingReflection", isBuffering, "SET_BUFFERING_REFLECTION_FLAG");
2559
+ }
2560
+ async setBufferingObservationFlag(id, isBuffering, lastBufferedAtTokens) {
2561
+ try {
2562
+ await this.#transaction(async (transaction) => {
2563
+ const row = await this.#lockRow(transaction, id);
2564
+ if (!row) throwNotFound(id, "SET_BUFFERING_OBSERVATION_FLAG");
2565
+ const target = await this.#resolveLiveRow(transaction, row);
2566
+ const request = transaction.request().input("isBuffering", sql.Bit, isBuffering).input("now", DATE_TYPE(), /* @__PURE__ */ new Date()).input("id", ID_TYPE(), target.id);
2567
+ if (lastBufferedAtTokens !== void 0) request.input("lastBufferedAtTokens", sql.Int, lastBufferedAtTokens);
2568
+ await request.query(`UPDATE ${this.#table} SET [isBufferingObservation] = @isBuffering,
2569
+ ${lastBufferedAtTokens !== void 0 ? "[lastBufferedAtTokens] = @lastBufferedAtTokens," : ""}
2570
+ [updatedAt] = @now
2571
+ WHERE [id] = @id`);
2572
+ });
2573
+ } catch (error) {
2574
+ rethrowOrWrap(error, "SET_BUFFERING_OBSERVATION_FLAG", { id });
2575
+ }
2576
+ }
2577
+ async clearObservationalMemory(threadId, resourceId) {
2578
+ try {
2579
+ await this.#pool.request().input("lookupKey", KEY_TYPE(), getObservationalMemoryKey(threadId, resourceId)).query(`DELETE FROM ${this.#table} WHERE [lookupKey] = @lookupKey`);
2580
+ } catch (error) {
2581
+ rethrowOrWrap(error, "CLEAR_OBSERVATIONAL_MEMORY", {
2582
+ threadId,
2583
+ resourceId
2584
+ });
2585
+ }
2586
+ }
2587
+ async setPendingMessageTokens(id, tokenCount) {
2588
+ try {
2589
+ await this.#transaction(async (transaction) => {
2590
+ const row = await this.#lockRow(transaction, id);
2591
+ if (!row) throwNotFound(id, "SET_PENDING_MESSAGE_TOKENS");
2592
+ const target = await this.#resolveLiveRow(transaction, row);
2593
+ await transaction.request().input("tokenCount", sql.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`);
2594
+ });
2595
+ } catch (error) {
2596
+ rethrowOrWrap(error, "SET_PENDING_MESSAGE_TOKENS", { id });
2597
+ }
2598
+ }
2599
+ async updateBufferedObservations(input) {
2600
+ await this.appendBufferedObservations(input);
2601
+ }
2602
+ async appendBufferedObservations(input) {
2603
+ const newChunk = {
2604
+ id: `ombuf-${globalThis.crypto.randomUUID()}`,
2605
+ cycleId: input.chunk.cycleId,
2606
+ observations: input.chunk.observations,
2607
+ tokenCount: input.chunk.tokenCount,
2608
+ messageIds: input.chunk.messageIds,
2609
+ messageTokens: input.chunk.messageTokens,
2610
+ lastObservedAt: input.chunk.lastObservedAt,
2611
+ createdAt: /* @__PURE__ */ new Date(),
2612
+ suggestedContinuation: input.chunk.suggestedContinuation,
2613
+ currentTask: input.chunk.currentTask,
2614
+ threadTitle: input.chunk.threadTitle,
2615
+ extractedValues: input.chunk.extractedValues,
2616
+ extractionFailures: input.chunk.extractionFailures
2617
+ };
2618
+ try {
2619
+ return await this.#transaction(async (transaction) => {
2620
+ const row = await this.#lockRow(transaction, input.id);
2621
+ if (!row) throwNotFound(input.id, "UPDATE_BUFFERED_OBSERVATIONS");
2622
+ const target = await this.#resolveLiveRow(transaction, row);
2623
+ const existingChunks = parseBufferedChunks(target.bufferedObservationChunks);
2624
+ if (existingChunks.some((existing) => existing.cycleId === input.chunk.cycleId) || isBufferedChunkCoveredByCursor(input.chunk.lastObservedAt, toDate(target.lastObservedAt))) return {
2625
+ persisted: false,
2626
+ recordId: target.id
2627
+ };
2628
+ const lastBufferedAtTime = maxObservationCursor(toDate(target.lastBufferedAtTime), input.lastBufferedAtTime ?? void 0);
2629
+ 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
2630
+ [bufferedObservationChunks] = @chunks,
2631
+ [lastBufferedAtTime] = @lastBufferedAtTime,
2632
+ [updatedAt] = @now
2633
+ WHERE [id] = @id`);
2634
+ return {
2635
+ persisted: true,
2636
+ recordId: target.id
2637
+ };
2638
+ }, "appendBufferedObservations");
2639
+ } catch (error) {
2640
+ rethrowOrWrap(error, "UPDATE_BUFFERED_OBSERVATIONS", { id: input.id });
2641
+ }
2642
+ }
2643
+ async swapBufferedToActive(input) {
2644
+ try {
2645
+ return await this.#transaction(async (transaction) => {
2646
+ const row = await this.#lockRow(transaction, input.id);
2647
+ if (!row) throwNotFound(input.id, "SWAP_BUFFERED_TO_ACTIVE");
2648
+ const emptyResult = {
2649
+ chunksActivated: 0,
2650
+ messageTokensActivated: 0,
2651
+ observationTokensActivated: 0,
2652
+ messagesActivated: 0,
2653
+ activatedCycleIds: [],
2654
+ activatedMessageIds: []
2655
+ };
2656
+ if (row.supersededBy) return {
2657
+ ...emptyResult,
2658
+ retired: true
2659
+ };
2660
+ const persistedChunks = parseBufferedChunks(row.bufferedObservationChunks);
2661
+ const refreshedWeights = new Map((Array.isArray(input.bufferedChunks) ? input.bufferedChunks : []).map((c) => [c.id, c.messageTokens]));
2662
+ const chunks = persistedChunks.map((c) => refreshedWeights.has(c.id) ? {
2663
+ ...c,
2664
+ messageTokens: refreshedWeights.get(c.id)
2665
+ } : c);
2666
+ if (chunks.length === 0) return emptyResult;
2667
+ const chunksToActivate = selectActivationBoundary(chunks, input);
2668
+ const activatedChunks = chunks.slice(0, chunksToActivate);
2669
+ const remainingChunks = persistedChunks.slice(chunksToActivate);
2670
+ const activatedContent = activatedChunks.map((c) => c.observations).join("\n\n");
2671
+ const activatedTokens = activatedChunks.reduce((sum, c) => sum + c.tokenCount, 0);
2672
+ const activatedMessageTokens = activatedChunks.reduce((sum, c) => sum + (c.messageTokens ?? 0), 0);
2673
+ const activatedMessageCount = activatedChunks.reduce((sum, c) => sum + c.messageIds.length, 0);
2674
+ const activatedCycleIds = activatedChunks.map((c) => c.cycleId).filter((cid) => !!cid);
2675
+ const activatedMessageIds = activatedChunks.flatMap((c) => c.messageIds ?? []);
2676
+ const latestChunk = activatedChunks[activatedChunks.length - 1];
2677
+ const derivedLastObservedAt = input.lastObservedAt ?? (latestChunk?.lastObservedAt ? new Date(latestChunk.lastObservedAt) : /* @__PURE__ */ new Date());
2678
+ const lastObservedAt = maxObservationCursor(toDate(row.lastObservedAt), derivedLastObservedAt);
2679
+ const existingActive = row.activeObservations || "";
2680
+ const newActive = existingActive ? `${existingActive}\n\n${activatedContent}` : activatedContent;
2681
+ const newTokenCount = Number(row.observationTokenCount || 0) + activatedTokens;
2682
+ const newPending = Math.max(0, Number(row.pendingMessageTokens || 0) - activatedMessageTokens);
2683
+ await transaction.request().input("active", TEXT_TYPE(), newActive).input("tokenCount", sql.Int, newTokenCount).input("pending", sql.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
2684
+ [activeObservations] = @active,
2685
+ [observationTokenCount] = @tokenCount,
2686
+ [pendingMessageTokens] = @pending,
2687
+ [bufferedObservationChunks] = @chunks,
2688
+ [lastObservedAt] = @lastObservedAt,
2689
+ [updatedAt] = @now
2690
+ WHERE [id] = @id`);
2691
+ return {
2692
+ chunksActivated: activatedChunks.length,
2693
+ messageTokensActivated: activatedMessageTokens,
2694
+ observationTokensActivated: activatedTokens,
2695
+ messagesActivated: activatedMessageCount,
2696
+ activatedCycleIds,
2697
+ activatedMessageIds,
2698
+ observations: activatedContent,
2699
+ perChunk: activatedChunks.map((c) => ({
2700
+ cycleId: c.cycleId ?? "",
2701
+ messageTokens: c.messageTokens ?? 0,
2702
+ observationTokens: c.tokenCount,
2703
+ messageCount: c.messageIds.length,
2704
+ observations: c.observations
2705
+ })),
2706
+ suggestedContinuation: latestChunk?.suggestedContinuation ?? void 0,
2707
+ currentTask: latestChunk?.currentTask ?? void 0
2708
+ };
2709
+ }, "swapBufferedToActive");
2710
+ } catch (error) {
2711
+ rethrowOrWrap(error, "SWAP_BUFFERED_TO_ACTIVE", { id: input.id });
2712
+ }
2713
+ }
2714
+ async updateBufferedReflection(input) {
2715
+ try {
2716
+ await this.#transaction(async (transaction) => {
2717
+ if ((await transaction.request().input("reflection", TEXT_TYPE(), input.reflection).input("tokenCount", sql.Int, input.tokenCount).input("inputTokenCount", sql.Int, input.inputTokenCount).input("lineCount", sql.Int, input.reflectedObservationLineCount).input("now", DATE_TYPE(), /* @__PURE__ */ new Date()).input("id", ID_TYPE(), input.id).query(`UPDATE ${this.#table} SET
2718
+ [bufferedReflection] = CASE
2719
+ WHEN [bufferedReflection] IS NOT NULL AND [bufferedReflection] <> N''
2720
+ THEN CONCAT([bufferedReflection], NCHAR(10), NCHAR(10), @reflection)
2721
+ ELSE @reflection
2722
+ END,
2723
+ [bufferedReflectionTokens] = COALESCE([bufferedReflectionTokens], 0) + @tokenCount,
2724
+ [bufferedReflectionInputTokens] = COALESCE([bufferedReflectionInputTokens], 0) + @inputTokenCount,
2725
+ [reflectedObservationLineCount] = @lineCount,
2726
+ [updatedAt] = @now
2727
+ WHERE [id] = @id`)).rowsAffected[0] === 0) throwNotFound(input.id, "UPDATE_BUFFERED_REFLECTION");
2728
+ }, "updateBufferedReflection");
2729
+ } catch (error) {
2730
+ rethrowOrWrap(error, "UPDATE_BUFFERED_REFLECTION", { id: input.id });
2731
+ }
2732
+ }
2733
+ async swapBufferedReflectionToActive(input) {
2734
+ const { currentRecord } = input;
2735
+ try {
2736
+ return await this.#transaction(async (transaction) => {
2737
+ const row = await this.#lockRow(transaction, currentRecord.id);
2738
+ if (!row) return currentRecord;
2739
+ if (row.supersededBy) return this.#parseRow(await this.#resolveLiveRow(transaction, row));
2740
+ const stored = this.#parseRow(row);
2741
+ const bufferedReflection = stored.bufferedReflection || "";
2742
+ if (!bufferedReflection) throw new MastraError({
2743
+ id: createStorageErrorId("MSSQL", "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", "NO_CONTENT"),
2744
+ text: "No buffered reflection to swap",
2745
+ domain: ErrorDomain.STORAGE,
2746
+ category: ErrorCategory.USER,
2747
+ details: { id: currentRecord.id }
2748
+ });
2749
+ if (!isAppendOnlySince(stored.activeObservations, currentRecord.activeObservations)) return stored;
2750
+ const reflectedLineCount = stored.reflectedObservationLineCount ?? 0;
2751
+ const unreflectedContent = (stored.activeObservations || "").split("\n").slice(reflectedLineCount).join("\n").trim();
2752
+ const newObservations = unreflectedContent ? `${bufferedReflection}\n\n${unreflectedContent}` : bufferedReflection;
2753
+ const tokenCount = input.tokenCount + Math.max(0, (stored.observationTokenCount ?? 0) - (currentRecord.observationTokenCount ?? 0));
2754
+ return this.#rollOver(transaction, stored.id, newObservations, tokenCount, input.newRecordId, true);
2755
+ }, "swapBufferedReflectionToActive");
2756
+ } catch (error) {
2757
+ rethrowOrWrap(error, "SWAP_BUFFERED_REFLECTION_TO_ACTIVE", { id: currentRecord.id });
2758
+ }
2759
+ }
2760
+ /** Inserts a fully formed record, e.g. the copy a thread clone carries over. */
2761
+ async insertObservationalMemoryRecord(record) {
2762
+ try {
2763
+ await this.#pool.request().input("id", ID_TYPE(), record.id).input("lookupKey", KEY_TYPE(), getObservationalMemoryKey(record.threadId, record.resourceId)).input("scope", sql.NVarChar(400), record.scope).input("resourceId", sql.NVarChar(400), record.resourceId).input("threadId", sql.NVarChar(400), record.threadId || null).input("activeObservations", TEXT_TYPE(), record.activeObservations || "").input("originType", sql.NVarChar(400), record.originType || "initial").input("config", TEXT_TYPE(), JSON.stringify(record.config ?? {})).input("generationCount", sql.Int, record.generationCount || 0).input("lastObservedAt", DATE_TYPE(), record.lastObservedAt ?? null).input("pendingMessageTokens", sql.Int, record.pendingMessageTokens || 0).input("totalTokensObserved", sql.Int, record.totalTokensObserved || 0).input("observationTokenCount", sql.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", sql.Int, record.bufferedReflectionTokens ?? null).input("bufferedReflectionInputTokens", sql.Int, record.bufferedReflectionInputTokens ?? null).input("reflectedObservationLineCount", sql.Int, record.reflectedObservationLineCount ?? null).input("isObserving", sql.Bit, !!record.isObserving).input("isReflecting", sql.Bit, !!record.isReflecting).input("isBufferingObservation", sql.Bit, !!record.isBufferingObservation).input("isBufferingReflection", sql.Bit, !!record.isBufferingReflection).input("lastBufferedAtTokens", sql.Int, record.lastBufferedAtTokens || 0).input("lastBufferedAtTime", DATE_TYPE(), record.lastBufferedAtTime ?? null).input("observedTimezone", sql.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} (
2764
+ [id], [lookupKey], [scope], [resourceId], [threadId], [activeObservations], [originType], [config],
2765
+ [generationCount], [lastObservedAt], [pendingMessageTokens], [totalTokensObserved], [observationTokenCount],
2766
+ [observedMessageIds], [bufferedObservationChunks], [bufferedReflection], [bufferedReflectionTokens],
2767
+ [bufferedReflectionInputTokens], [reflectedObservationLineCount],
2768
+ [isObserving], [isReflecting], [isBufferingObservation], [isBufferingReflection],
2769
+ [lastBufferedAtTokens], [lastBufferedAtTime], [observedTimezone], [metadata], [supersededBy],
2770
+ [createdAt], [updatedAt]
2771
+ ) VALUES (
2772
+ @id, @lookupKey, @scope, @resourceId, @threadId, @activeObservations, @originType, @config,
2773
+ @generationCount, @lastObservedAt, @pendingMessageTokens, @totalTokensObserved, @observationTokenCount,
2774
+ @observedMessageIds, @chunks, @bufferedReflection, @bufferedReflectionTokens,
2775
+ @bufferedReflectionInputTokens, @reflectedObservationLineCount,
2776
+ @isObserving, @isReflecting, @isBufferingObservation, @isBufferingReflection,
2777
+ @lastBufferedAtTokens, @lastBufferedAtTime, @observedTimezone, @metadata, @supersededBy,
2778
+ @createdAt, @updatedAt
2779
+ )`);
2780
+ } catch (error) {
2781
+ rethrowOrWrap(error, "INSERT_OBSERVATIONAL_MEMORY_RECORD", { id: record.id });
2782
+ }
2783
+ }
2784
+ /** Deep-merges `input.config` into the stored config under a row lock, so concurrent updates both land. */
2785
+ async updateObservationalMemoryConfig(input, merge) {
2786
+ try {
2787
+ await this.#transaction(async (transaction) => {
2788
+ const row = await this.#lockRow(transaction, input.id);
2789
+ if (!row) throwNotFound(input.id, "UPDATE_OM_CONFIG");
2790
+ const merged = merge(parseJSONColumn(row.config) ?? {}, input.config);
2791
+ 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`);
2792
+ });
2793
+ } catch (error) {
2794
+ rethrowOrWrap(error, "UPDATE_OM_CONFIG", { id: input.id });
2795
+ }
2796
+ }
2797
+ /**
2798
+ * Runs `fn` in one transaction, after checking the run fence when `fencedOperation` is given.
2799
+ * A deadlock victim or lock timeout is retried a bounded number of times; the server has
2800
+ * already rolled the transaction back.
2801
+ */
2802
+ async #transaction(fn, fencedOperation) {
2803
+ for (let attempt = 1;; attempt++) {
2804
+ const transaction = this.#pool.transaction();
2805
+ await transaction.begin();
2806
+ try {
2807
+ if (fencedOperation) await this.#assertFence(transaction, fencedOperation);
2808
+ const result = await fn(transaction);
2809
+ await transaction.commit();
2810
+ return result;
2811
+ } catch (error) {
2812
+ await transaction.rollback().catch(() => {});
2813
+ if (attempt < OM_MAX_TRANSACTION_ATTEMPTS && isRetryableLockError(error)) continue;
2814
+ throw error;
2815
+ }
2816
+ }
2817
+ }
2818
+ /** Row-locks one record by primary key for the rest of the transaction. */
2819
+ async #lockRow(transaction, id) {
2820
+ return (await transaction.request().input("id", ID_TYPE(), id).query(`SELECT * FROM ${this.#table} ${ROW_LOCK} WHERE [id] = @id`)).recordset[0] ?? null;
2821
+ }
2822
+ /**
2823
+ * The live, row-locked record a write aimed at `row` lands on: `row` itself while live,
2824
+ * otherwise the head. The head is found with a plain canonical read, then locked by primary
2825
+ * key; a head retired in between is followed through `supersededBy` (bounded).
2826
+ */
2827
+ async #resolveLiveRow(transaction, row) {
2828
+ if (!row.supersededBy) return row;
2829
+ 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;
2830
+ let current = await this.#lockRow(transaction, headId) ?? row;
2831
+ for (let hop = 0; current.supersededBy; hop++) {
2832
+ const next = hop < OM_MAX_HEAD_HOPS ? await this.#lockRow(transaction, current.supersededBy) : null;
2833
+ if (!next) throw new MastraError({
2834
+ id: createStorageErrorId("MSSQL", "RESOLVE_OBSERVATIONAL_MEMORY_HEAD", "FAILED"),
2835
+ text: `Observational memory record ${row.id} is superseded but no live head was found`,
2836
+ domain: ErrorDomain.STORAGE,
2837
+ category: ErrorCategory.THIRD_PARTY,
2838
+ details: { id: row.id }
2839
+ });
2840
+ current = next;
2841
+ }
2842
+ return current;
2843
+ }
2844
+ /**
2845
+ * Creates the next generation from the stored (live, row-locked) record and retires the stored
2846
+ * record in the same transaction. Carried columns are copied in SQL from the stored row:
2847
+ * buffered chunks move to the new generation; the cursor, buffering markers, pending tokens and
2848
+ * counters carry over; buffered reflection state does not (and is cleared on the retired row
2849
+ * after a buffered swap).
2850
+ */
2851
+ async #rollOver(transaction, storedId, observations, tokenCount, newRecordId, clearBufferedReflection) {
2852
+ const id = newRecordId ?? globalThis.crypto.randomUUID();
2853
+ const now = /* @__PURE__ */ new Date();
2854
+ await transaction.request().input("id", ID_TYPE(), id).input("observations", TEXT_TYPE(), observations).input("tokenCount", sql.Int, Math.round(tokenCount)).input("now", DATE_TYPE(), now).input("storedId", ID_TYPE(), storedId).query(`INSERT INTO ${this.#table} (
2855
+ [id], [lookupKey], [scope], [resourceId], [threadId],
2856
+ [activeObservations], [activeObservationsPendingUpdate],
2857
+ [originType], [config], [generationCount], [lastObservedAt], [lastReflectionAt],
2858
+ [pendingMessageTokens], [totalTokensObserved], [observationTokenCount], [bufferedObservationChunks],
2859
+ [isObserving], [isReflecting], [isBufferingObservation], [isBufferingReflection],
2860
+ [lastBufferedAtTokens], [lastBufferedAtTime],
2861
+ [observedTimezone], [metadata], [supersededBy], [createdAt], [updatedAt]
2862
+ )
2863
+ SELECT
2864
+ @id, [lookupKey], [scope], [resourceId], [threadId],
2865
+ @observations, NULL,
2866
+ 'reflection', [config], [generationCount] + 1, [lastObservedAt], @now,
2867
+ [pendingMessageTokens], [totalTokensObserved], @tokenCount, [bufferedObservationChunks],
2868
+ 0, 0, [isBufferingObservation], 0,
2869
+ [lastBufferedAtTokens], [lastBufferedAtTime],
2870
+ [observedTimezone], [metadata], NULL, @now, @now
2871
+ FROM ${this.#table} WHERE [id] = @storedId`);
2872
+ if ((await transaction.request().input("id", ID_TYPE(), id).input("now", DATE_TYPE(), now).input("storedId", ID_TYPE(), storedId).query(`UPDATE ${this.#table} SET
2873
+ [supersededBy] = @id,
2874
+ [bufferedObservationChunks] = NULL,
2875
+ ${clearBufferedReflection ? `[bufferedReflection] = NULL, [bufferedReflectionTokens] = NULL,
2876
+ [bufferedReflectionInputTokens] = NULL, [reflectedObservationLineCount] = NULL,` : ""}
2877
+ [updatedAt] = @now
2878
+ WHERE [id] = @storedId AND [supersededBy] IS NULL`)).rowsAffected[0] !== 1) throw new MastraError({
2879
+ id: createStorageErrorId("MSSQL", "CREATE_REFLECTION_GENERATION", "RETIRE_FAILED"),
2880
+ text: `Failed to retire observational memory record ${storedId}`,
2881
+ domain: ErrorDomain.STORAGE,
2882
+ category: ErrorCategory.THIRD_PARTY,
2883
+ details: { id: storedId }
2884
+ });
2885
+ const inserted = await this.#lockRow(transaction, id);
2886
+ if (!inserted) throwNotFound(id, "CREATE_REFLECTION_GENERATION");
2887
+ return this.#parseRow(inserted);
2888
+ }
2889
+ async #updateFlag(id, column, value, operation) {
2890
+ try {
2891
+ if ((await this.#pool.request().input("value", sql.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);
2892
+ } catch (error) {
2893
+ rethrowOrWrap(error, operation, { id });
2894
+ }
2895
+ }
2896
+ #parseRow(row) {
2897
+ return {
2898
+ id: row.id,
2899
+ scope: row.scope,
2900
+ threadId: row.threadId || null,
2901
+ resourceId: row.resourceId,
2902
+ createdAt: toDate(row.createdAt) ?? /* @__PURE__ */ new Date(),
2903
+ updatedAt: toDate(row.updatedAt) ?? /* @__PURE__ */ new Date(),
2904
+ lastObservedAt: toDate(row.lastObservedAt),
2905
+ originType: row.originType || "initial",
2906
+ generationCount: Number(row.generationCount || 0),
2907
+ activeObservations: row.activeObservations || "",
2908
+ bufferedObservationChunks: parseJSONColumn(row.bufferedObservationChunks),
2909
+ bufferedObservations: row.activeObservationsPendingUpdate || void 0,
2910
+ bufferedObservationTokens: row.bufferedObservationTokens ? Number(row.bufferedObservationTokens) : void 0,
2911
+ bufferedMessageIds: void 0,
2912
+ bufferedReflection: row.bufferedReflection || void 0,
2913
+ bufferedReflectionTokens: row.bufferedReflectionTokens ? Number(row.bufferedReflectionTokens) : void 0,
2914
+ bufferedReflectionInputTokens: row.bufferedReflectionInputTokens ? Number(row.bufferedReflectionInputTokens) : void 0,
2915
+ reflectedObservationLineCount: row.reflectedObservationLineCount ? Number(row.reflectedObservationLineCount) : void 0,
2916
+ totalTokensObserved: Number(row.totalTokensObserved || 0),
2917
+ observationTokenCount: Number(row.observationTokenCount || 0),
2918
+ pendingMessageTokens: Number(row.pendingMessageTokens || 0),
2919
+ isReflecting: !!row.isReflecting,
2920
+ isObserving: !!row.isObserving,
2921
+ isBufferingObservation: !!row.isBufferingObservation,
2922
+ isBufferingReflection: !!row.isBufferingReflection,
2923
+ lastBufferedAtTokens: Number(row.lastBufferedAtTokens || 0),
2924
+ lastBufferedAtTime: toDate(row.lastBufferedAtTime) ?? null,
2925
+ config: parseJSONColumn(row.config) ?? {},
2926
+ metadata: parseJSONColumn(row.metadata),
2927
+ observedMessageIds: parseJSONColumn(row.observedMessageIds),
2928
+ observedTimezone: row.observedTimezone || void 0,
2929
+ supersededBy: row.supersededBy ?? null
2930
+ };
2931
+ }
2932
+ };
2933
+ /**
2934
+ * How many leading chunks to activate: the chunk boundary closest to the activation target that
2935
+ * still leaves the retention floor of message tokens pending.
2936
+ */
2937
+ function selectActivationBoundary(chunks, input) {
2938
+ const retentionFloor = input.messageTokensThreshold * (1 - input.activationRatio);
2939
+ const targetMessageTokens = Math.max(0, input.currentPendingTokens - retentionFloor);
2940
+ let cumulativeMessageTokens = 0;
2941
+ let bestOverBoundary = 0;
2942
+ let bestOverTokens = 0;
2943
+ let bestUnderBoundary = 0;
2944
+ let bestUnderTokens = 0;
2945
+ for (let i = 0; i < chunks.length; i++) {
2946
+ cumulativeMessageTokens += chunks[i].messageTokens ?? 0;
2947
+ const boundary = i + 1;
2948
+ if (cumulativeMessageTokens >= targetMessageTokens) {
2949
+ if (bestOverBoundary === 0 || cumulativeMessageTokens < bestOverTokens) {
2950
+ bestOverBoundary = boundary;
2951
+ bestOverTokens = cumulativeMessageTokens;
2952
+ }
2953
+ } else if (cumulativeMessageTokens > bestUnderTokens) {
2954
+ bestUnderBoundary = boundary;
2955
+ bestUnderTokens = cumulativeMessageTokens;
2956
+ }
2957
+ }
2958
+ const maxOvershoot = retentionFloor * .95;
2959
+ const overshoot = bestOverTokens - targetMessageTokens;
2960
+ const remainingAfterOver = input.currentPendingTokens - bestOverTokens;
2961
+ const remainingAfterUnder = input.currentPendingTokens - bestUnderTokens;
2962
+ const minRemaining = Math.min(1e3, retentionFloor);
2963
+ if (input.forceMaxActivation && bestOverBoundary > 0 && remainingAfterOver >= minRemaining) return bestOverBoundary;
2964
+ if (bestOverBoundary > 0 && overshoot <= maxOvershoot && remainingAfterOver >= minRemaining) return bestOverBoundary;
2965
+ if (bestUnderBoundary > 0 && remainingAfterUnder >= minRemaining) return bestUnderBoundary;
2966
+ if (bestOverBoundary > 0) return bestOverBoundary;
2967
+ return 1;
2968
+ }
2212
2969
  // src/storage/domains/memory/index.ts
2213
2970
  function bindMssqlMetadataParams(request, params) {
2214
2971
  for (const [paramName, paramValue] of Object.entries(params)) request.input(paramName, paramValue);
@@ -2240,7 +2997,10 @@ function buildMssqlMessageMetadataFilter(metadataFilter) {
2240
2997
  }
2241
2998
  var MemoryMSSQL = class MemoryMSSQL extends MemoryStorage {
2242
2999
  supportsPartialThreadUpdate = true;
3000
+ supportsObservationalMemory = true;
3001
+ supportsObservationalMemoryHistorySearch = true;
2243
3002
  pool;
3003
+ #om;
2244
3004
  schema;
2245
3005
  db;
2246
3006
  needsConnect;
@@ -2288,6 +3048,11 @@ var MemoryMSSQL = class MemoryMSSQL extends MemoryStorage {
2288
3048
  schemaName,
2289
3049
  skipDefaultIndexes
2290
3050
  });
3051
+ this.#om = new MssqlObservationalMemory({
3052
+ pool,
3053
+ schema: schemaName,
3054
+ assertFence: (transaction, operation) => this.#assertFence(transaction, void 0, operation)
3055
+ });
2291
3056
  this.needsConnect = needsConnect;
2292
3057
  this.skipDefaultIndexes = skipDefaultIndexes;
2293
3058
  this.indexes = indexes?.filter((idx) => MemoryMSSQL.MANAGED_TABLES.includes(idx.table));
@@ -2313,9 +3078,31 @@ var MemoryMSSQL = class MemoryMSSQL extends MemoryStorage {
2313
3078
  tableName: TABLE_MEMORY_RUN_FENCES,
2314
3079
  schema: RUN_FENCING_TABLE_SCHEMAS[TABLE_MEMORY_RUN_FENCES]
2315
3080
  });
3081
+ await this.#initObservationalMemoryTable();
2316
3082
  await this.createDefaultIndexes();
2317
3083
  await this.createCustomIndexes();
2318
3084
  }
3085
+ /** Creates or upgrades the observational memory table and its head-lookup index. */
3086
+ async #initObservationalMemoryTable() {
3087
+ const schema = withObservationalMemoryLifecycleColumns(OBSERVATIONAL_MEMORY_TABLE_SCHEMA[TABLE_OBSERVATIONAL_MEMORY]);
3088
+ if (!schema) return;
3089
+ const tableName = TABLE_OBSERVATIONAL_MEMORY;
3090
+ await this.db.createTable({
3091
+ tableName,
3092
+ schema
3093
+ });
3094
+ await this.db.alterTable({
3095
+ tableName,
3096
+ schema,
3097
+ ifNotExists: Object.keys(schema)
3098
+ });
3099
+ if (this.skipDefaultIndexes) return;
3100
+ await this.db.createIndex({
3101
+ name: "mastra_om_lookupkey_generation_idx",
3102
+ table: tableName,
3103
+ columns: ["lookupKey", "generationCount DESC"]
3104
+ });
3105
+ }
2319
3106
  supportsRunFencing() {
2320
3107
  return true;
2321
3108
  }
@@ -2434,6 +3221,7 @@ var MemoryMSSQL = class MemoryMSSQL extends MemoryStorage {
2434
3221
  await this.db.clearTable({ tableName: TABLE_THREADS });
2435
3222
  await this.db.clearTable({ tableName: TABLE_RESOURCES });
2436
3223
  await this.db.clearTable({ tableName: TABLE_MEMORY_RUN_FENCES });
3224
+ await this.db.clearTable({ tableName: TABLE_OBSERVATIONAL_MEMORY });
2437
3225
  }
2438
3226
  async getThreadById({ threadId, resourceId }) {
2439
3227
  try {
@@ -2906,8 +3694,7 @@ var MemoryMSSQL = class MemoryMSSQL extends MemoryStorage {
2906
3694
  }
2907
3695
  }
2908
3696
  async listMessages(args) {
2909
- const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
2910
- const metadataFilter = validateStorageMetadataFilter(filter?.metadata);
3697
+ const { threadId } = args;
2911
3698
  const threadIds = Array.isArray(threadId) ? threadId : [threadId];
2912
3699
  if (threadIds.length === 0 || threadIds.some((id) => !id.trim())) throw new MastraError({
2913
3700
  id: createStorageErrorId("MSSQL", "LIST_MESSAGES", "INVALID_THREAD_ID"),
@@ -2915,13 +3702,30 @@ var MemoryMSSQL = class MemoryMSSQL extends MemoryStorage {
2915
3702
  category: ErrorCategory.THIRD_PARTY,
2916
3703
  details: { threadId: Array.isArray(threadId) ? threadId.join(",") : threadId }
2917
3704
  }, /* @__PURE__ */ new Error("threadId must be a non-empty string or array of non-empty strings"));
3705
+ return this.#queryMessages(args, threadIds);
3706
+ }
3707
+ /** Lists a resource's messages across all of its threads (used by resource-scoped observational memory). */
3708
+ async listMessagesByResourceId(args) {
3709
+ const { resourceId } = args;
3710
+ if (!resourceId || typeof resourceId !== "string" || resourceId.trim().length === 0) throw new MastraError({
3711
+ id: createStorageErrorId("MSSQL", "LIST_MESSAGES", "INVALID_QUERY"),
3712
+ domain: ErrorDomain.STORAGE,
3713
+ category: ErrorCategory.USER,
3714
+ details: { resourceId: resourceId ?? "" }
3715
+ }, /* @__PURE__ */ new Error("resourceId is required"));
3716
+ return this.#queryMessages(args, null);
3717
+ }
3718
+ /** One page of messages from `threadIds`, or from every thread of `resourceId` when `threadIds` is null. */
3719
+ async #queryMessages(args, threadIds) {
3720
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
3721
+ const metadataFilter = validateStorageMetadataFilter(filter?.metadata);
2918
3722
  if (page < 0) throw new MastraError({
2919
3723
  id: createStorageErrorId("MSSQL", "LIST_MESSAGES", "INVALID_PAGE"),
2920
3724
  domain: ErrorDomain.STORAGE,
2921
3725
  category: ErrorCategory.USER,
2922
3726
  text: "Page number must be non-negative",
2923
3727
  details: {
2924
- threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
3728
+ threadId: Array.isArray(threadId) ? threadId.join(",") : threadId ?? "",
2925
3729
  page
2926
3730
  }
2927
3731
  });
@@ -2936,7 +3740,7 @@ var MemoryMSSQL = class MemoryMSSQL extends MemoryStorage {
2936
3740
  });
2937
3741
  const baseQuery = `SELECT seq_id, id, content, role, type, [createdAt], thread_id AS threadId, resourceId FROM ${tableName}`;
2938
3742
  const { sql: preparedWhereClause = "", params: whereParams } = prepareWhereClause({
2939
- thread_id: threadIds.length === 1 ? threadIds[0] : { $in: threadIds },
3743
+ ...threadIds ? { thread_id: threadIds.length === 1 ? threadIds[0] : { $in: threadIds } } : {},
2940
3744
  ...resourceId ? { resourceId } : {},
2941
3745
  ...buildDateRangeFilter(filter?.dateRange, "createdAt")
2942
3746
  }, TABLE_SCHEMAS[TABLE_MESSAGES]);
@@ -3017,23 +3821,23 @@ var MemoryMSSQL = class MemoryMSSQL extends MemoryStorage {
3017
3821
  const seqB = seqById.get(b.id);
3018
3822
  return seqA != null && seqB != null ? (seqA - seqB) * mult : a.id.localeCompare(b.id);
3019
3823
  });
3020
- const threadIdSet = new Set(threadIds);
3824
+ const threadIdSet = new Set(threadIds ?? []);
3021
3825
  const returnedThreadMessageCount = finalMessages.filter((m) => m.threadId && threadIdSet.has(m.threadId)).length;
3022
3826
  return {
3023
3827
  messages: finalMessages,
3024
3828
  total,
3025
3829
  page,
3026
3830
  perPage: perPageForResponse,
3027
- hasMore: metadataFilter ? perPageInput !== false && offset + primaryPageCount < total : perPageInput !== false && returnedThreadMessageCount < total && offset + perPage < total
3831
+ hasMore: metadataFilter || !threadIds ? perPageInput !== false && offset + primaryPageCount < total : perPageInput !== false && returnedThreadMessageCount < total && offset + perPage < total
3028
3832
  };
3029
3833
  } catch (error) {
3030
3834
  if (error instanceof MastraError && error.category === ErrorCategory.USER) throw error;
3031
3835
  const mastraError = new MastraError({
3032
- id: createStorageErrorId("MSSQL", "LIST_MESSAGES", "FAILED"),
3836
+ id: createStorageErrorId("MSSQL", threadIds ? "LIST_MESSAGES" : "LIST_MESSAGES_BY_RESOURCE_ID", "FAILED"),
3033
3837
  domain: ErrorDomain.STORAGE,
3034
3838
  category: ErrorCategory.THIRD_PARTY,
3035
3839
  details: {
3036
- threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
3840
+ threadId: Array.isArray(threadId) ? threadId.join(",") : threadId ?? "",
3037
3841
  resourceId: resourceId ?? ""
3038
3842
  }
3039
3843
  }, error);
@@ -3368,6 +4172,63 @@ var MemoryMSSQL = class MemoryMSSQL extends MemoryStorage {
3368
4172
  throw mastraError;
3369
4173
  }
3370
4174
  }
4175
+ getObservationalMemory(threadId, resourceId) {
4176
+ return this.#om.getObservationalMemory(threadId, resourceId);
4177
+ }
4178
+ getObservationalMemoryHistory(threadId, resourceId, limit, options) {
4179
+ return this.#om.getObservationalMemoryHistory(threadId, resourceId, limit, options);
4180
+ }
4181
+ initializeObservationalMemory(input) {
4182
+ return this.#om.initializeObservationalMemory(input);
4183
+ }
4184
+ updateActiveObservations(input) {
4185
+ return this.#om.updateActiveObservations(input);
4186
+ }
4187
+ commitActiveObservations(input) {
4188
+ return this.#om.commitActiveObservations(input);
4189
+ }
4190
+ updateBufferedObservations(input) {
4191
+ return this.#om.updateBufferedObservations(input);
4192
+ }
4193
+ appendBufferedObservations(input) {
4194
+ return this.#om.appendBufferedObservations(input);
4195
+ }
4196
+ swapBufferedToActive(input) {
4197
+ return this.#om.swapBufferedToActive(input);
4198
+ }
4199
+ createReflectionGeneration(input) {
4200
+ return this.#om.createReflectionGeneration(input);
4201
+ }
4202
+ updateBufferedReflection(input) {
4203
+ return this.#om.updateBufferedReflection(input);
4204
+ }
4205
+ swapBufferedReflectionToActive(input) {
4206
+ return this.#om.swapBufferedReflectionToActive(input);
4207
+ }
4208
+ setReflectingFlag(id, isReflecting) {
4209
+ return this.#om.setReflectingFlag(id, isReflecting);
4210
+ }
4211
+ setObservingFlag(id, isObserving) {
4212
+ return this.#om.setObservingFlag(id, isObserving);
4213
+ }
4214
+ setBufferingObservationFlag(id, isBuffering, lastBufferedAtTokens) {
4215
+ return this.#om.setBufferingObservationFlag(id, isBuffering, lastBufferedAtTokens);
4216
+ }
4217
+ setBufferingReflectionFlag(id, isBuffering) {
4218
+ return this.#om.setBufferingReflectionFlag(id, isBuffering);
4219
+ }
4220
+ clearObservationalMemory(threadId, resourceId) {
4221
+ return this.#om.clearObservationalMemory(threadId, resourceId);
4222
+ }
4223
+ setPendingMessageTokens(id, tokenCount) {
4224
+ return this.#om.setPendingMessageTokens(id, tokenCount);
4225
+ }
4226
+ insertObservationalMemoryRecord(record) {
4227
+ return this.#om.insertObservationalMemoryRecord(record);
4228
+ }
4229
+ updateObservationalMemoryConfig(input) {
4230
+ return this.#om.updateObservationalMemoryConfig(input, (target, source) => this.deepMergeConfig(target, source));
4231
+ }
3371
4232
  };
3372
4233
  // src/storage/domains/observability/index.ts
3373
4234
  var ObservabilityMSSQL = class ObservabilityMSSQL extends ObservabilityStorage {