@mastra/memory 1.25.1-alpha.0 → 1.26.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.
@@ -1,30 +1,30 @@
1
1
  //#region \0rolldown/runtime.js
2
2
  var __create$1 = Object.create;
3
- var __defProp$4 = Object.defineProperty;
3
+ var __defProp$3 = Object.defineProperty;
4
4
  var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames$1 = Object.getOwnPropertyNames;
6
6
  var __getProtoOf$1 = Object.getPrototypeOf;
7
7
  var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
8
8
  var __exportAll = (all, no_symbols) => {
9
9
  let target = {};
10
- for (var name in all) __defProp$4(target, name, {
10
+ for (var name in all) __defProp$3(target, name, {
11
11
  get: all[name],
12
12
  enumerable: true
13
13
  });
14
- if (!no_symbols) __defProp$4(target, Symbol.toStringTag, { value: "Module" });
14
+ if (!no_symbols) __defProp$3(target, Symbol.toStringTag, { value: "Module" });
15
15
  return target;
16
16
  };
17
17
  var __copyProps$1 = (to, from, except, desc) => {
18
18
  if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames$1(from), i = 0, n = keys.length, key; i < n; i++) {
19
19
  key = keys[i];
20
- if (!__hasOwnProp$1.call(to, key) && key !== except) __defProp$4(to, key, {
20
+ if (!__hasOwnProp$1.call(to, key) && key !== except) __defProp$3(to, key, {
21
21
  get: ((k) => from[k]).bind(null, key),
22
22
  enumerable: !(desc = __getOwnPropDesc$1(from, key)) || desc.enumerable
23
23
  });
24
24
  }
25
25
  return to;
26
26
  };
27
- var __toESM$1 = (mod, isNodeMode, target) => (target = mod != null ? __create$1(__getProtoOf$1(mod)) : {}, __copyProps$1(isNodeMode || !mod || !mod.__esModule ? __defProp$4(target, "default", {
27
+ var __toESM$1 = (mod, isNodeMode, target) => (target = mod != null ? __create$1(__getProtoOf$1(mod)) : {}, __copyProps$1(isNodeMode || !mod || !mod.__esModule ? __defProp$3(target, "default", {
28
28
  value: mod,
29
29
  enumerable: true
30
30
  }) : target, mod));
@@ -201,9 +201,9 @@ Error message: ${getErrorMessage$4(cause)}`,
201
201
  _a13$5 = symbol13$5;
202
202
  var TypeValidationError$2 = _TypeValidationError;
203
203
  //#endregion
204
- //#region ../_vendored/ai_v4/dist/dist-e6zV1w-k.js
204
+ //#region ../_vendored/ai_v4/dist/index.js
205
205
  var __create = Object.create;
206
- var __defProp$3 = Object.defineProperty;
206
+ var __defProp$1$1 = Object.defineProperty;
207
207
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
208
208
  var __getOwnPropNames = Object.getOwnPropertyNames;
209
209
  var __getProtoOf = Object.getPrototypeOf;
@@ -212,14 +212,14 @@ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).expor
212
212
  var __copyProps = (to, from, except, desc) => {
213
213
  if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
214
214
  key = keys[i];
215
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp$3(to, key, {
215
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp$1$1(to, key, {
216
216
  get: ((k) => from[k]).bind(null, key),
217
217
  enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
218
218
  });
219
219
  }
220
220
  return to;
221
221
  };
222
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp$3(target, "default", {
222
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp$1$1(target, "default", {
223
223
  value: mod,
224
224
  enumerable: true
225
225
  }) : target, mod));
@@ -433,8 +433,6 @@ function safeParseJSON$2({ text, schema }) {
433
433
  }
434
434
  }
435
435
  var { btoa: btoa$2, atob: atob$2 } = globalThis;
436
- //#endregion
437
- //#region ../_vendored/ai_v4/dist/index.js
438
436
  const ignoreOverride$2 = Symbol("Let zodToJsonSchema decide on which parser to use");
439
437
  const defaultOptions$2 = {
440
438
  name: void 0,
@@ -3736,7 +3734,7 @@ function trimStartOfStream() {
3736
3734
  };
3737
3735
  }
3738
3736
  //#endregion
3739
- //#region ../_vendored/ai_v5/dist/dist-Qv-F35RT.js
3737
+ //#region ../_vendored/ai_v5/dist/dist-BuEMdYEn.js
3740
3738
  var marker$1$4 = "vercel.ai.error";
3741
3739
  var symbol$1$3 = Symbol.for(marker$1$4);
3742
3740
  var _a$1$3;
@@ -4286,6 +4284,26 @@ async function cancelResponseBody$1(response) {
4286
4284
  await ((_a2 = response.body) == null ? void 0 : _a2.cancel());
4287
4285
  } catch (e) {}
4288
4286
  }
4287
+ var initialGlobalFetch$1 = globalThis.fetch;
4288
+ isNodeDefaultFetch$1(initialGlobalFetch$1);
4289
+ function isNodeDefaultFetch$1(fetch) {
4290
+ const source = Function.prototype.toString.call(fetch);
4291
+ return source.includes("internal/deps/undici") || source.includes("lazy loading of undici");
4292
+ }
4293
+ function getCurrentModulePath$1() {
4294
+ const originalPrepareStackTrace = Error.prepareStackTrace;
4295
+ try {
4296
+ Error.prepareStackTrace = (_error, callSites) => callSites;
4297
+ const error = /* @__PURE__ */ new Error("Capture current module path");
4298
+ Error.captureStackTrace(error, getCurrentModulePath$1);
4299
+ const [caller] = error.stack;
4300
+ const fileName = caller == null ? void 0 : caller.getFileName();
4301
+ if (fileName == null) throw new Error("Unable to determine the current module path");
4302
+ return fileName;
4303
+ } finally {
4304
+ Error.prepareStackTrace = originalPrepareStackTrace;
4305
+ }
4306
+ }
4289
4307
  var DEFAULT_MAX_DOWNLOAD_SIZE$1 = 2 * 1024 * 1024 * 1024;
4290
4308
  async function readResponseWithSizeLimit$1({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE$1 }) {
4291
4309
  const contentLength = response.headers.get("content-length");
@@ -4395,11 +4413,11 @@ function withUserAgentSuffix$1(headers, ...userAgentSuffixParts) {
4395
4413
  normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
4396
4414
  return Object.fromEntries(normalizedHeaders.entries());
4397
4415
  }
4398
- var VERSION$4 = "3.0.30";
4416
+ var VERSION$4 = "3.0.31";
4399
4417
  var getOriginalFetch$1 = () => globalThis.fetch;
4400
- var getFromApi$1 = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch$1() }) => {
4418
+ var getFromApi$1 = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch$1() }) => {
4401
4419
  try {
4402
- const response = await fetch2(url, {
4420
+ const response = await fetch(url, {
4403
4421
  method: "GET",
4404
4422
  headers: withUserAgentSuffix$1(headers, `ai-sdk/provider-utils/${VERSION$4}`, getRuntimeEnvironmentUserAgent$1()),
4405
4423
  signal: abortSignal
@@ -4625,7 +4643,7 @@ function parseJsonEventStream$1({ stream, schema }) {
4625
4643
  } }));
4626
4644
  }
4627
4645
  var getOriginalFetch2$1 = () => globalThis.fetch;
4628
- var postJsonToApi$1 = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }) => postToApi$1({
4646
+ var postJsonToApi$1 = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => postToApi$1({
4629
4647
  url,
4630
4648
  headers: {
4631
4649
  "Content-Type": "application/json",
@@ -4638,11 +4656,11 @@ var postJsonToApi$1 = async ({ url, headers, body, failedResponseHandler, succes
4638
4656
  failedResponseHandler,
4639
4657
  successfulResponseHandler,
4640
4658
  abortSignal,
4641
- fetch: fetch2
4659
+ fetch
4642
4660
  });
4643
- var postToApi$1 = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch2$1() }) => {
4661
+ var postToApi$1 = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch2$1() }) => {
4644
4662
  try {
4645
- const response = await fetch2(url, {
4663
+ const response = await fetch(url, {
4646
4664
  method: "POST",
4647
4665
  headers: withUserAgentSuffix$1(headers, `ai-sdk/provider-utils/${VERSION$4}`, getRuntimeEnvironmentUserAgent$1()),
4648
4666
  body: body.content,
@@ -6704,7 +6722,7 @@ async function getVercelRequestId$1() {
6704
6722
  var _a10;
6705
6723
  return (_a10 = getContext$1().headers) == null ? void 0 : _a10["x-vercel-id"];
6706
6724
  }
6707
- var VERSION$2$2 = "2.0.115";
6725
+ var VERSION$2$2 = "2.0.125";
6708
6726
  var AI_GATEWAY_PROTOCOL_VERSION$1 = "0.0.1";
6709
6727
  function createGatewayProvider$1(options = {}) {
6710
6728
  var _a10, _b10;
@@ -7738,7 +7756,7 @@ function getGlobalProvider$1() {
7738
7756
  var _a16;
7739
7757
  return (_a16 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a16 : gateway$1;
7740
7758
  }
7741
- var VERSION$5 = "5.0.216";
7759
+ var VERSION$5 = "5.0.226";
7742
7760
  var dataContentSchema$1 = zod_v4.z.union([
7743
7761
  zod_v4.z.string(),
7744
7762
  zod_v4.z.instanceof(Uint8Array),
@@ -8604,7 +8622,7 @@ var object$1 = ({ schema: inputSchema }) => {
8604
8622
  };
8605
8623
  };
8606
8624
  //#endregion
8607
- //#region ../_vendored/ai_v6/dist/dist-BomuqvJJ.js
8625
+ //#region ../_vendored/ai_v6/dist/dist-BTWHzT8H.js
8608
8626
  var marker$1 = "vercel.ai.error";
8609
8627
  var symbol$1$1 = Symbol.for(marker$1);
8610
8628
  var _a$1$1;
@@ -9175,6 +9193,26 @@ var DownloadError = class extends (_b$2 = AISDKError, _a$2 = symbol$2, _b$2) {
9175
9193
  return AISDKError.hasMarker(error, marker$2);
9176
9194
  }
9177
9195
  };
9196
+ var initialGlobalFetch = globalThis.fetch;
9197
+ isNodeDefaultFetch(initialGlobalFetch);
9198
+ function isNodeDefaultFetch(fetch) {
9199
+ const source = Function.prototype.toString.call(fetch);
9200
+ return source.includes("internal/deps/undici") || source.includes("lazy loading of undici");
9201
+ }
9202
+ function getCurrentModulePath() {
9203
+ const originalPrepareStackTrace = Error.prepareStackTrace;
9204
+ try {
9205
+ Error.prepareStackTrace = (_error, callSites) => callSites;
9206
+ const error = /* @__PURE__ */ new Error("Capture current module path");
9207
+ Error.captureStackTrace(error, getCurrentModulePath);
9208
+ const [caller] = error.stack;
9209
+ const fileName = caller == null ? void 0 : caller.getFileName();
9210
+ if (fileName == null) throw new Error("Unable to determine the current module path");
9211
+ return fileName;
9212
+ } finally {
9213
+ Error.prepareStackTrace = originalPrepareStackTrace;
9214
+ }
9215
+ }
9178
9216
  var DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024;
9179
9217
  async function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE }) {
9180
9218
  const contentLength = response.headers.get("content-length");
@@ -9306,11 +9344,11 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
9306
9344
  normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" "));
9307
9345
  return Object.fromEntries(normalizedHeaders.entries());
9308
9346
  }
9309
- var VERSION$3 = "4.0.40";
9347
+ var VERSION$3 = "4.0.41";
9310
9348
  var getOriginalFetch = () => globalThis.fetch;
9311
- var getFromApi = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch() }) => {
9349
+ var getFromApi = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch() }) => {
9312
9350
  try {
9313
- const response = await fetch2(url, {
9351
+ const response = await fetch(url, {
9314
9352
  method: "GET",
9315
9353
  headers: withUserAgentSuffix(headers, `ai-sdk/provider-utils/${VERSION$3}`, getRuntimeEnvironmentUserAgent()),
9316
9354
  signal: abortSignal
@@ -10497,7 +10535,7 @@ function parseJsonEventStream({ stream, schema }) {
10497
10535
  } }));
10498
10536
  }
10499
10537
  var getOriginalFetch2 = () => globalThis.fetch;
10500
- var postJsonToApi = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }) => postToApi({
10538
+ var postJsonToApi = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => postToApi({
10501
10539
  url,
10502
10540
  headers: {
10503
10541
  "Content-Type": "application/json",
@@ -10510,11 +10548,11 @@ var postJsonToApi = async ({ url, headers, body, failedResponseHandler, successf
10510
10548
  failedResponseHandler,
10511
10549
  successfulResponseHandler,
10512
10550
  abortSignal,
10513
- fetch: fetch2
10551
+ fetch
10514
10552
  });
10515
- var postToApi = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch2() }) => {
10553
+ var postToApi = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch2() }) => {
10516
10554
  try {
10517
- const response = await fetch2(url, {
10555
+ const response = await fetch(url, {
10518
10556
  method: "POST",
10519
10557
  headers: withUserAgentSuffix(headers, `ai-sdk/provider-utils/${VERSION$3}`, getRuntimeEnvironmentUserAgent()),
10520
10558
  body: body.content,
@@ -10736,7 +10774,7 @@ function withoutTrailingSlash(url) {
10736
10774
  return url == null ? void 0 : url.replace(/\/$/, "");
10737
10775
  }
10738
10776
  //#endregion
10739
- //#region ../_vendored/ai_v6/dist/dist-iiYCn57Q.js
10777
+ //#region ../_vendored/ai_v6/dist/dist-3jq9sPhA.js
10740
10778
  function getContext() {
10741
10779
  return { headers: {} };
10742
10780
  }
@@ -12295,7 +12333,7 @@ async function getVercelRequestId() {
12295
12333
  var _a11;
12296
12334
  return (_a11 = getContext().headers) == null ? void 0 : _a11["x-vercel-id"];
12297
12335
  }
12298
- var VERSION$2 = "3.0.153";
12336
+ var VERSION$2 = "3.0.163";
12299
12337
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
12300
12338
  function createGatewayProvider(options = {}) {
12301
12339
  var _a11, _b11;
@@ -13454,7 +13492,7 @@ function getTotalTimeoutMs(timeout) {
13454
13492
  if (typeof timeout === "number") return timeout;
13455
13493
  return timeout.totalMs;
13456
13494
  }
13457
- var VERSION = "6.0.230";
13495
+ var VERSION = "6.0.241";
13458
13496
  var dataContentSchema = zod_v4.z.union([
13459
13497
  zod_v4.z.string(),
13460
13498
  zod_v4.z.instanceof(Uint8Array),
@@ -20460,6 +20498,68 @@ function isMessageAtOrBeforeCursor(msg, cursor) {
20460
20498
  return false;
20461
20499
  }
20462
20500
  /**
20501
+ * Return the toolCallId of a tool-invocation part in the given state, or undefined.
20502
+ */
20503
+ function getToolInvocationId(part, state) {
20504
+ if (part?.type !== "tool-invocation") return void 0;
20505
+ if (part.toolInvocation.state !== state) return void 0;
20506
+ return part.toolInvocation.toolCallId || void 0;
20507
+ }
20508
+ function collectPendingToolResultIds(allMessages, observedIds) {
20509
+ const pendingToolResultIds = /* @__PURE__ */ new Set();
20510
+ for (const msg of allMessages) {
20511
+ if (!msg?.id) continue;
20512
+ if (observedIds?.has(msg.id)) continue;
20513
+ const parts = msg.content?.parts;
20514
+ if (!parts || !Array.isArray(parts)) continue;
20515
+ for (const part of parts) {
20516
+ const id = getToolInvocationId(part, "result");
20517
+ if (id) pendingToolResultIds.add(id);
20518
+ }
20519
+ }
20520
+ return pendingToolResultIds;
20521
+ }
20522
+ function hasPendingToolResultPair(message, pendingToolResultIds) {
20523
+ if (pendingToolResultIds.size === 0) return false;
20524
+ const parts = message.content?.parts;
20525
+ if (!parts || !Array.isArray(parts)) return false;
20526
+ return parts.some((part) => {
20527
+ const id = getToolInvocationId(part, "call");
20528
+ return id !== void 0 && pendingToolResultIds.has(id);
20529
+ });
20530
+ }
20531
+ function collectPendingToolResultIdsAfterMarker(allMessages, markerMessageIndex, markerMessage) {
20532
+ const pendingToolResultIds = /* @__PURE__ */ new Set();
20533
+ const unobservedMarkerParts = getUnobservedParts(markerMessage);
20534
+ if (unobservedMarkerParts.length > 0) collectPendingToolResultIds([{
20535
+ ...markerMessage,
20536
+ content: {
20537
+ ...markerMessage.content,
20538
+ parts: unobservedMarkerParts
20539
+ }
20540
+ }], void 0).forEach((id) => pendingToolResultIds.add(id));
20541
+ collectPendingToolResultIds(allMessages.slice(markerMessageIndex + 1), void 0).forEach((id) => pendingToolResultIds.add(id));
20542
+ return pendingToolResultIds;
20543
+ }
20544
+ function getUnobservedPartsPreservingToolCallPairs(message) {
20545
+ const parts = message.content?.parts;
20546
+ if (!parts || !Array.isArray(parts)) return [];
20547
+ const endMarkerIndex = findLastCompletedObservationBoundary(message);
20548
+ if (endMarkerIndex === -1) return getUnobservedParts(message);
20549
+ const unobservedParts = getUnobservedParts(message);
20550
+ const unobservedResultIds = /* @__PURE__ */ new Set();
20551
+ for (const part of unobservedParts) {
20552
+ const id = getToolInvocationId(part, "result");
20553
+ if (id) unobservedResultIds.add(id);
20554
+ }
20555
+ if (unobservedResultIds.size === 0) return unobservedParts;
20556
+ const preservedCalls = parts.slice(0, endMarkerIndex).filter((part) => {
20557
+ const id = getToolInvocationId(part, "call");
20558
+ return id !== void 0 && unobservedResultIds.has(id);
20559
+ });
20560
+ return preservedCalls.length > 0 ? [...preservedCalls, ...unobservedParts] : unobservedParts;
20561
+ }
20562
+ /**
20463
20563
  * Safely extract buffered observation chunks from a record.
20464
20564
  * Handles both array and JSON-string formats, returning empty array if malformed.
20465
20565
  */
@@ -20475,6 +20575,7 @@ function filterObservedMessages(opts) {
20475
20575
  const allMessages = messageList.get.all.db();
20476
20576
  const useMarkerBoundaryPruning = opts.useMarkerBoundaryPruning ?? true;
20477
20577
  const preserveMessageIds = opts.preserveMessageIds ?? /* @__PURE__ */ new Set();
20578
+ const observedIds = new Set(Array.isArray(record?.observedMessageIds) ? record.observedMessageIds : []);
20478
20579
  let markerMessageIndex = -1;
20479
20580
  let markerMessage = null;
20480
20581
  for (let i = allMessages.length - 1; i >= 0; i--) {
@@ -20487,33 +20588,40 @@ function filterObservedMessages(opts) {
20487
20588
  }
20488
20589
  }
20489
20590
  if (useMarkerBoundaryPruning && markerMessage && markerMessageIndex !== -1) {
20591
+ const pendingToolResultIds = collectPendingToolResultIdsAfterMarker(allMessages, markerMessageIndex, markerMessage);
20490
20592
  const messagesToRemove = [];
20491
20593
  for (let i = 0; i < markerMessageIndex; i++) {
20492
20594
  const msg = allMessages[i];
20493
- if (msg?.id && msg.id !== "om-continuation" && !preserveMessageIds.has(msg.id)) messagesToRemove.push(msg.id);
20595
+ if (msg?.id && msg.id !== "om-continuation" && !preserveMessageIds.has(msg.id) && !hasPendingToolResultPair(msg, pendingToolResultIds)) messagesToRemove.push(msg.id);
20494
20596
  }
20495
20597
  if (messagesToRemove.length > 0) messageList.removeByIds(messagesToRemove);
20496
- const unobserved = getUnobservedParts(markerMessage);
20598
+ const unobserved = getUnobservedPartsPreservingToolCallPairs(markerMessage);
20497
20599
  if (unobserved.length === 0) {
20498
20600
  if (markerMessage.id) messageList.removeByIds([markerMessage.id]);
20499
20601
  } else if (unobserved.length < (markerMessage.content?.parts?.length ?? 0)) markerMessage.content.parts = unobserved;
20500
20602
  } else if (record) {
20501
- const observedIds = new Set(Array.isArray(record.observedMessageIds) ? record.observedMessageIds : []);
20603
+ const pendingToolResultIds = collectPendingToolResultIds(allMessages, observedIds);
20502
20604
  const derivedCursor = opts.fallbackCursor ?? getLastObservedMessageCursor(allMessages.filter((msg) => !!msg?.id && observedIds.has(msg.id) && !!msg.createdAt));
20503
20605
  const lastObservedAt = record.lastObservedAt;
20504
20606
  const messagesToRemove = [];
20505
20607
  for (const msg of allMessages) {
20506
20608
  if (!msg?.id || msg.id === "om-continuation" || preserveMessageIds.has(msg.id)) continue;
20609
+ const hasPendingPair = hasPendingToolResultPair(msg, pendingToolResultIds);
20507
20610
  if (observedIds.has(msg.id)) {
20611
+ if (hasPendingPair) continue;
20508
20612
  messagesToRemove.push(msg.id);
20509
20613
  continue;
20510
20614
  }
20511
20615
  if (derivedCursor && isMessageAtOrBeforeCursor(msg, derivedCursor)) {
20616
+ if (hasPendingPair) continue;
20512
20617
  messagesToRemove.push(msg.id);
20513
20618
  continue;
20514
20619
  }
20515
20620
  if (lastObservedAt && msg.createdAt) {
20516
- if (new Date(msg.createdAt) <= lastObservedAt) messagesToRemove.push(msg.id);
20621
+ if (new Date(msg.createdAt) <= lastObservedAt) {
20622
+ if (hasPendingPair) continue;
20623
+ messagesToRemove.push(msg.id);
20624
+ }
20517
20625
  }
20518
20626
  }
20519
20627
  if (messagesToRemove.length > 0) messageList.removeByIds(messagesToRemove);
@@ -23819,6 +23927,14 @@ var ObservationalMemory = class ObservationalMemory {
23819
23927
  */
23820
23928
  locks = /* @__PURE__ */ new Map();
23821
23929
  /**
23930
+ * Initial record lookup/creation promises keyed by the effective storage scope.
23931
+ * Concurrent callers share the full read-or-create operation so a stale read
23932
+ * cannot create another generation-zero record after the first insert finishes.
23933
+ * Entries are removed after both success and failure so later calls always
23934
+ * re-read storage and transient failures can be retried.
23935
+ */
23936
+ recordInitializations = /* @__PURE__ */ new Map();
23937
+ /**
23822
23938
  * Acquire a lock for the given key, execute the callback, then release.
23823
23939
  * If a lock is already held, waits for it to be released before acquiring.
23824
23940
  */
@@ -24179,10 +24295,14 @@ var ObservationalMemory = class ObservationalMemory {
24179
24295
  */
24180
24296
  async getOrCreateRecord(threadId, resourceId) {
24181
24297
  const ids = this.getStorageIds(threadId, resourceId);
24182
- let record = await this.storage.getObservationalMemory(ids.threadId, ids.resourceId);
24183
- if (!record) {
24298
+ const initializationKey = ids.threadId === null ? `resource:${ids.resourceId}` : `thread:${ids.threadId}`;
24299
+ const pendingInitialization = this.recordInitializations.get(initializationKey);
24300
+ if (pendingInitialization) return pendingInitialization;
24301
+ const initialization = Promise.resolve().then(async () => {
24302
+ const record = await this.storage.getObservationalMemory(ids.threadId, ids.resourceId);
24303
+ if (record) return record;
24184
24304
  const observedTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
24185
- record = await this.storage.initializeObservationalMemory({
24305
+ return this.storage.initializeObservationalMemory({
24186
24306
  threadId: ids.threadId,
24187
24307
  resourceId: ids.resourceId,
24188
24308
  scope: this.scope,
@@ -24193,8 +24313,13 @@ var ObservationalMemory = class ObservationalMemory {
24193
24313
  },
24194
24314
  observedTimezone
24195
24315
  });
24316
+ });
24317
+ this.recordInitializations.set(initializationKey, initialization);
24318
+ try {
24319
+ return await initialization;
24320
+ } finally {
24321
+ if (this.recordInitializations.get(initializationKey) === initialization) this.recordInitializations.delete(initializationKey);
24196
24322
  }
24197
- return record;
24198
24323
  }
24199
24324
  /**
24200
24325
  * Get current config snapshot for observation markers.
@@ -26562,6 +26687,11 @@ function filterSystemReminderMessages(messages, includeSystemReminders) {
26562
26687
  if (includeSystemReminders) return messages;
26563
26688
  return messages.filter((message) => !isSystemReminderMessage(message));
26564
26689
  }
26690
+ function isTransientSignalMessage(message) {
26691
+ if (message.role !== "signal" || !isRecord(message.content)) return false;
26692
+ const metadata = message.content.metadata;
26693
+ return isRecord(metadata) && isRecord(metadata.signal) && !Array.isArray(metadata.signal) && metadata.signal.transient === true;
26694
+ }
26565
26695
  function normalizeObservationalMemoryConfig(config) {
26566
26696
  if (config === true) return { model: "google/gemini-2.5-flash" };
26567
26697
  if (config === false || config === void 0) return void 0;
@@ -27095,7 +27225,7 @@ ${workingMemory}`;
27095
27225
  async saveMessages({ messages, memoryConfig, observabilityContext }) {
27096
27226
  const span = this.createMemorySpan("save", observabilityContext, void 0, { messageCount: messages.length });
27097
27227
  try {
27098
- const updatedMessages = messages.filter((m) => m.role !== "system").map((m) => {
27228
+ const updatedMessages = messages.filter((m) => m.role !== "system" && !isTransientSignalMessage(m)).map((m) => {
27099
27229
  return this.updateMessageToHideWorkingMemoryV2(m);
27100
27230
  }).filter((m) => Boolean(m));
27101
27231
  const config = this.getMergedThreadConfig(memoryConfig);
@@ -27387,7 +27517,7 @@ ${workingMemory}`;
27387
27517
  */
27388
27518
  async persistMessages(messages) {
27389
27519
  if (messages.length === 0) return;
27390
- const persistableMessages = messages.filter((m) => m.role !== "system");
27520
+ const persistableMessages = messages.filter((m) => m.role !== "system" && !isTransientSignalMessage(m));
27391
27521
  if (persistableMessages.length === 0) return;
27392
27522
  await (await this.getMemoryStore()).saveMessages({ messages: persistableMessages });
27393
27523
  }
@@ -28567,4 +28697,4 @@ Object.defineProperty(exports, "wrapInObservationGroup", {
28567
28697
  }
28568
28698
  });
28569
28699
 
28570
- //# sourceMappingURL=src-Bz9Fg416.cjs.map
28700
+ //# sourceMappingURL=src-CjTEWCUF.cjs.map