@mastra/memory 0.0.0-studio-deploy-20260404182525 → 0.0.0-studio-cli-20260504022012

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.
Files changed (113) hide show
  1. package/CHANGELOG.md +461 -3
  2. package/dist/_types/@internal_ai-sdk-v4/dist/index.d.ts +51 -5
  3. package/dist/{chunk-4FMHSWZD.cjs → chunk-6ODYOMHN.cjs} +1279 -492
  4. package/dist/chunk-6ODYOMHN.cjs.map +1 -0
  5. package/dist/{chunk-C7PARRAD.js → chunk-Z5GWA7LB.js} +1280 -493
  6. package/dist/chunk-Z5GWA7LB.js.map +1 -0
  7. package/dist/{constants-HXOCZPB7.cjs → constants-PJXB7ZIS.cjs} +2 -2
  8. package/dist/{constants-HXOCZPB7.cjs.map → constants-PJXB7ZIS.cjs.map} +1 -1
  9. package/dist/{constants-BDOITAO3.js → constants-XEHPYRDJ.js} +2 -2
  10. package/dist/{constants-BDOITAO3.js.map → constants-XEHPYRDJ.js.map} +1 -1
  11. package/dist/docs/SKILL.md +3 -1
  12. package/dist/docs/assets/SOURCE_MAP.json +47 -59
  13. package/dist/docs/references/docs-agents-background-tasks.md +242 -0
  14. package/dist/docs/references/docs-agents-supervisor-agents.md +65 -0
  15. package/dist/docs/references/docs-memory-memory-processors.md +3 -3
  16. package/dist/docs/references/docs-memory-message-history.md +8 -2
  17. package/dist/docs/references/docs-memory-observational-memory.md +65 -8
  18. package/dist/docs/references/docs-memory-storage.md +1 -2
  19. package/dist/docs/references/docs-memory-working-memory.md +2 -2
  20. package/dist/docs/references/reference-memory-clone-utilities.md +4 -2
  21. package/dist/docs/references/reference-memory-cloneThread.md +4 -2
  22. package/dist/docs/references/reference-memory-observational-memory.md +4 -0
  23. package/dist/docs/references/reference-storage-redis.md +266 -0
  24. package/dist/docs/references/reference-vectors-mongodb.md +0 -2
  25. package/dist/index.cjs +1168 -553
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.ts +35 -4
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +1158 -535
  30. package/dist/index.js.map +1 -1
  31. package/dist/{observational-memory-5YDQLKHE.cjs → observational-memory-OVSEK47Z.cjs} +26 -26
  32. package/dist/{observational-memory-5YDQLKHE.cjs.map → observational-memory-OVSEK47Z.cjs.map} +1 -1
  33. package/dist/{observational-memory-B7AUSTEY.js → observational-memory-UMDC4VC2.js} +3 -3
  34. package/dist/{observational-memory-B7AUSTEY.js.map → observational-memory-UMDC4VC2.js.map} +1 -1
  35. package/dist/processors/index.cjs +24 -24
  36. package/dist/processors/index.js +1 -1
  37. package/dist/processors/observational-memory/date-utils.d.ts +6 -0
  38. package/dist/processors/observational-memory/date-utils.d.ts.map +1 -1
  39. package/dist/processors/observational-memory/index.d.ts +1 -1
  40. package/dist/processors/observational-memory/index.d.ts.map +1 -1
  41. package/dist/processors/observational-memory/markers.d.ts +5 -0
  42. package/dist/processors/observational-memory/markers.d.ts.map +1 -1
  43. package/dist/processors/observational-memory/message-utils.d.ts.map +1 -1
  44. package/dist/processors/observational-memory/model-context.d.ts +10 -0
  45. package/dist/processors/observational-memory/model-context.d.ts.map +1 -0
  46. package/dist/processors/observational-memory/observation-strategies/async-buffer.d.ts.map +1 -1
  47. package/dist/processors/observational-memory/observation-strategies/base.d.ts +3 -3
  48. package/dist/processors/observational-memory/observation-strategies/base.d.ts.map +1 -1
  49. package/dist/processors/observational-memory/observation-strategies/types.d.ts +9 -0
  50. package/dist/processors/observational-memory/observation-strategies/types.d.ts.map +1 -1
  51. package/dist/processors/observational-memory/observation-turn/step.d.ts.map +1 -1
  52. package/dist/processors/observational-memory/observation-turn/turn.d.ts +6 -2
  53. package/dist/processors/observational-memory/observation-turn/turn.d.ts.map +1 -1
  54. package/dist/processors/observational-memory/observation-turn/types.d.ts +1 -0
  55. package/dist/processors/observational-memory/observation-turn/types.d.ts.map +1 -1
  56. package/dist/processors/observational-memory/observational-memory.d.ts +54 -3
  57. package/dist/processors/observational-memory/observational-memory.d.ts.map +1 -1
  58. package/dist/processors/observational-memory/observer-agent.d.ts.map +1 -1
  59. package/dist/processors/observational-memory/processor.d.ts +5 -1
  60. package/dist/processors/observational-memory/processor.d.ts.map +1 -1
  61. package/dist/processors/observational-memory/reflector-runner.d.ts +14 -2
  62. package/dist/processors/observational-memory/reflector-runner.d.ts.map +1 -1
  63. package/dist/processors/observational-memory/repro-capture.d.ts +8 -0
  64. package/dist/processors/observational-memory/repro-capture.d.ts.map +1 -1
  65. package/dist/processors/observational-memory/string-utils.d.ts +13 -0
  66. package/dist/processors/observational-memory/string-utils.d.ts.map +1 -0
  67. package/dist/processors/observational-memory/temporal-markers.d.ts +4 -0
  68. package/dist/processors/observational-memory/temporal-markers.d.ts.map +1 -0
  69. package/dist/processors/observational-memory/tool-result-helpers.d.ts.map +1 -1
  70. package/dist/processors/observational-memory/types.d.ts +56 -2
  71. package/dist/processors/observational-memory/types.d.ts.map +1 -1
  72. package/dist/tools/om-tools.d.ts +14 -2
  73. package/dist/tools/om-tools.d.ts.map +1 -1
  74. package/dist/tools/working-memory.d.ts.map +1 -1
  75. package/package.json +15 -15
  76. package/dist/chunk-3PUO6DLX.js +0 -439
  77. package/dist/chunk-3PUO6DLX.js.map +0 -1
  78. package/dist/chunk-4FMHSWZD.cjs.map +0 -1
  79. package/dist/chunk-C7PARRAD.js.map +0 -1
  80. package/dist/chunk-CK4U3AYR.cjs +0 -84
  81. package/dist/chunk-CK4U3AYR.cjs.map +0 -1
  82. package/dist/chunk-DAJJSFVA.cjs +0 -441
  83. package/dist/chunk-DAJJSFVA.cjs.map +0 -1
  84. package/dist/chunk-DGUM43GV.js +0 -10
  85. package/dist/chunk-DGUM43GV.js.map +0 -1
  86. package/dist/chunk-EQ4M72KU.js +0 -439
  87. package/dist/chunk-EQ4M72KU.js.map +0 -1
  88. package/dist/chunk-IDRQZVB4.cjs +0 -84
  89. package/dist/chunk-IDRQZVB4.cjs.map +0 -1
  90. package/dist/chunk-JEQ2X3Z6.cjs +0 -12
  91. package/dist/chunk-JEQ2X3Z6.cjs.map +0 -1
  92. package/dist/chunk-RC6RZVYE.js +0 -79
  93. package/dist/chunk-RC6RZVYE.js.map +0 -1
  94. package/dist/chunk-SVPZMV27.js +0 -79
  95. package/dist/chunk-SVPZMV27.js.map +0 -1
  96. package/dist/chunk-ZD3BKU5O.cjs +0 -441
  97. package/dist/chunk-ZD3BKU5O.cjs.map +0 -1
  98. package/dist/token-APYSY3BW-2DN6RAUY.js +0 -61
  99. package/dist/token-APYSY3BW-2DN6RAUY.js.map +0 -1
  100. package/dist/token-APYSY3BW-POD4OUWN.cjs +0 -63
  101. package/dist/token-APYSY3BW-POD4OUWN.cjs.map +0 -1
  102. package/dist/token-APYSY3BW-YTVQELJT.js +0 -61
  103. package/dist/token-APYSY3BW-YTVQELJT.js.map +0 -1
  104. package/dist/token-APYSY3BW-ZQ7TMBY7.cjs +0 -63
  105. package/dist/token-APYSY3BW-ZQ7TMBY7.cjs.map +0 -1
  106. package/dist/token-util-RMHT2CPJ-6TGPE335.cjs +0 -10
  107. package/dist/token-util-RMHT2CPJ-6TGPE335.cjs.map +0 -1
  108. package/dist/token-util-RMHT2CPJ-77HHGIQN.cjs +0 -10
  109. package/dist/token-util-RMHT2CPJ-77HHGIQN.cjs.map +0 -1
  110. package/dist/token-util-RMHT2CPJ-RJEA3FAN.js +0 -8
  111. package/dist/token-util-RMHT2CPJ-RJEA3FAN.js.map +0 -1
  112. package/dist/token-util-RMHT2CPJ-WJZ2SYAR.js +0 -8
  113. package/dist/token-util-RMHT2CPJ-WJZ2SYAR.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,14 +1,13 @@
1
1
  'use strict';
2
2
 
3
- var chunkCK4U3AYR_cjs = require('./chunk-CK4U3AYR.cjs');
4
- var chunkIDRQZVB4_cjs = require('./chunk-IDRQZVB4.cjs');
5
- var chunk4FMHSWZD_cjs = require('./chunk-4FMHSWZD.cjs');
3
+ var chunk6ODYOMHN_cjs = require('./chunk-6ODYOMHN.cjs');
6
4
  var v3 = require('zod/v3');
7
5
  var zod = require('zod');
8
6
  var z4 = require('zod/v4');
9
7
  var agent = require('@mastra/core/agent');
10
8
  var features = require('@mastra/core/features');
11
9
  var memory = require('@mastra/core/memory');
10
+ var observability = require('@mastra/core/observability');
12
11
  var utils = require('@mastra/core/utils');
13
12
  var schema = require('@mastra/schema-compat/schema');
14
13
  var asyncMutex = require('async-mutex');
@@ -48,7 +47,7 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
48
47
  var __getOwnPropNames = Object.getOwnPropertyNames;
49
48
  var __getProtoOf = Object.getPrototypeOf;
50
49
  var __hasOwnProp = Object.prototype.hasOwnProperty;
51
- var __commonJS3 = (cb, mod) => function __require2() {
50
+ var __commonJS = (cb, mod) => function __require2() {
52
51
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
53
52
  };
54
53
  var __copyProps = (to, from, except, desc) => {
@@ -59,7 +58,7 @@ var __copyProps = (to, from, except, desc) => {
59
58
  }
60
59
  return to;
61
60
  };
62
- var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
61
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
63
62
  // If the importer is in node compatibility mode or this is not an ESM
64
63
  // file that has been converted to a CommonJS file using a Babel-
65
64
  // compatible transform (i.e. "__esModule" has not been set), then set
@@ -67,7 +66,7 @@ var __toESM3 = (mod, isNodeMode, target) => (target = mod != null ? __create(__g
67
66
  __defProp(target, "default", { value: mod, enumerable: true }),
68
67
  mod
69
68
  ));
70
- var require_secure_json_parse = __commonJS3({
69
+ var require_secure_json_parse = __commonJS({
71
70
  "../../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports$1, module) {
72
71
  var hasBuffer = typeof Buffer !== "undefined";
73
72
  var suspectProtoRx3 = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
@@ -338,7 +337,7 @@ var customAlphabet = (alphabet, defaultSize = 21) => {
338
337
  return id;
339
338
  };
340
339
  };
341
- var import_secure_json_parse = __toESM3(require_secure_json_parse());
340
+ var import_secure_json_parse = __toESM(require_secure_json_parse());
342
341
  function convertAsyncIteratorToReadableStream(iterator) {
343
342
  return new ReadableStream({
344
343
  /**
@@ -4585,7 +4584,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
4585
4584
  );
4586
4585
  return Object.fromEntries(normalizedHeaders.entries());
4587
4586
  }
4588
- var VERSION2 = "3.0.22";
4587
+ var VERSION2 = "3.0.23";
4589
4588
  var getOriginalFetch = () => globalThis.fetch;
4590
4589
  var getFromApi = async ({
4591
4590
  url,
@@ -6247,138 +6246,17 @@ function asSchema2(schema) {
6247
6246
  function withoutTrailingSlash(url) {
6248
6247
  return url == null ? void 0 : url.replace(/\/$/, "");
6249
6248
  }
6250
- var require_get_context = chunkCK4U3AYR_cjs.__commonJS({
6251
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-context.js"(exports$1, module) {
6252
- var __defProp22 = Object.defineProperty;
6253
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
6254
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
6255
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
6256
- var __export22 = (target, all) => {
6257
- for (var name163 in all)
6258
- __defProp22(target, name163, { get: all[name163], enumerable: true });
6259
- };
6260
- var __copyProps2 = (to, from, except, desc) => {
6261
- if (from && typeof from === "object" || typeof from === "function") {
6262
- for (let key of __getOwnPropNames2(from))
6263
- if (!__hasOwnProp2.call(to, key) && key !== except)
6264
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
6265
- }
6266
- return to;
6267
- };
6268
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
6269
- var get_context_exports = {};
6270
- __export22(get_context_exports, {
6271
- SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,
6272
- getContext: () => getContext3
6273
- });
6274
- module.exports = __toCommonJS(get_context_exports);
6275
- var SYMBOL_FOR_REQ_CONTEXT = /* @__PURE__ */ Symbol.for("@vercel/request-context");
6276
- function getContext3() {
6277
- const fromSymbol = globalThis;
6278
- return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
6279
- }
6280
- }
6281
- });
6282
- var require_get_vercel_oidc_token = chunkCK4U3AYR_cjs.__commonJS({
6283
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports$1, module) {
6284
- var __defProp22 = Object.defineProperty;
6285
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
6286
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
6287
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
6288
- var __export22 = (target, all) => {
6289
- for (var name163 in all)
6290
- __defProp22(target, name163, { get: all[name163], enumerable: true });
6291
- };
6292
- var __copyProps2 = (to, from, except, desc) => {
6293
- if (from && typeof from === "object" || typeof from === "function") {
6294
- for (let key of __getOwnPropNames2(from))
6295
- if (!__hasOwnProp2.call(to, key) && key !== except)
6296
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
6297
- }
6298
- return to;
6299
- };
6300
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
6301
- var get_vercel_oidc_token_exports = {};
6302
- __export22(get_vercel_oidc_token_exports, {
6303
- getVercelOidcToken: () => getVercelOidcToken3,
6304
- getVercelOidcTokenSync: () => getVercelOidcTokenSync2
6305
- });
6306
- module.exports = __toCommonJS(get_vercel_oidc_token_exports);
6307
- var import_get_context = require_get_context();
6308
- var import_token_error = chunkCK4U3AYR_cjs.require_token_error();
6309
- async function getVercelOidcToken3() {
6310
- let token = "";
6311
- let err;
6312
- try {
6313
- token = getVercelOidcTokenSync2();
6314
- } catch (error) {
6315
- err = error;
6316
- }
6317
- try {
6318
- const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
6319
- await import('./token-util-RMHT2CPJ-77HHGIQN.cjs'),
6320
- await import('./token-APYSY3BW-POD4OUWN.cjs')
6321
- ]);
6322
- if (!token || isExpired(getTokenPayload(token))) {
6323
- await refreshToken();
6324
- token = getVercelOidcTokenSync2();
6325
- }
6326
- } catch (error) {
6327
- let message = err instanceof Error ? err.message : "";
6328
- if (error instanceof Error) {
6329
- message = `${message}
6330
- ${error.message}`;
6331
- }
6332
- if (message) {
6333
- throw new import_token_error.VercelOidcTokenError(message);
6334
- }
6335
- throw error;
6336
- }
6337
- return token;
6338
- }
6339
- function getVercelOidcTokenSync2() {
6340
- const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
6341
- if (!token) {
6342
- throw new Error(
6343
- `The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`
6344
- );
6345
- }
6346
- return token;
6347
- }
6348
- }
6349
- });
6350
- var require_dist = chunkCK4U3AYR_cjs.__commonJS({
6351
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/index.js"(exports$1, module) {
6352
- var __defProp22 = Object.defineProperty;
6353
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
6354
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
6355
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
6356
- var __export22 = (target, all) => {
6357
- for (var name163 in all)
6358
- __defProp22(target, name163, { get: all[name163], enumerable: true });
6359
- };
6360
- var __copyProps2 = (to, from, except, desc) => {
6361
- if (from && typeof from === "object" || typeof from === "function") {
6362
- for (let key of __getOwnPropNames2(from))
6363
- if (!__hasOwnProp2.call(to, key) && key !== except)
6364
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
6365
- }
6366
- return to;
6367
- };
6368
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
6369
- var src_exports = {};
6370
- __export22(src_exports, {
6371
- getContext: () => import_get_context.getContext,
6372
- getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
6373
- getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync
6374
- });
6375
- module.exports = __toCommonJS(src_exports);
6376
- var import_get_vercel_oidc_token = require_get_vercel_oidc_token();
6377
- var import_get_context = require_get_context();
6249
+ function getContext() {
6250
+ return {
6251
+ headers: {}
6252
+ };
6253
+ }
6254
+ async function getVercelOidcToken() {
6255
+ if (process.env.VERCEL_OIDC_TOKEN) {
6256
+ return process.env.VERCEL_OIDC_TOKEN ?? "";
6378
6257
  }
6379
- });
6380
- var import_oidc = chunkCK4U3AYR_cjs.__toESM(require_dist(), 1);
6381
- var import_oidc2 = chunkCK4U3AYR_cjs.__toESM(require_dist(), 1);
6258
+ throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.");
6259
+ }
6382
6260
  var marker18 = "vercel.ai.gateway.error";
6383
6261
  var symbol18 = Symbol.for(marker18);
6384
6262
  var _a18;
@@ -6753,6 +6631,7 @@ async function parseAuthMethod(headers) {
6753
6631
  var gatewayAuthMethodSchema = lazyValidator(
6754
6632
  () => zodSchema2(z4.z.union([z4.z.literal("api-key"), z4.z.literal("oidc")]))
6755
6633
  );
6634
+ var KNOWN_MODEL_TYPES = ["embedding", "image", "language"];
6756
6635
  var GatewayFetchMetadata = class {
6757
6636
  constructor(config) {
6758
6637
  this.config = config;
@@ -6823,8 +6702,12 @@ var gatewayAvailableModelsResponseSchema = lazyValidator(
6823
6702
  provider: z4.z.string(),
6824
6703
  modelId: z4.z.string()
6825
6704
  }),
6826
- modelType: z4.z.enum(["language", "embedding", "image"]).nullish()
6705
+ modelType: z4.z.string().nullish()
6827
6706
  })
6707
+ ).transform(
6708
+ (models) => models.filter(
6709
+ (m) => m.modelType == null || KNOWN_MODEL_TYPES.includes(m.modelType)
6710
+ )
6828
6711
  )
6829
6712
  })
6830
6713
  )
@@ -6840,6 +6723,187 @@ var gatewayCreditsResponseSchema = lazyValidator(
6840
6723
  }))
6841
6724
  )
6842
6725
  );
6726
+ var GatewaySpendReport = class {
6727
+ constructor(config) {
6728
+ this.config = config;
6729
+ }
6730
+ async getSpendReport(params) {
6731
+ try {
6732
+ const baseUrl = new URL(this.config.baseURL);
6733
+ const searchParams = new URLSearchParams();
6734
+ searchParams.set("start_date", params.startDate);
6735
+ searchParams.set("end_date", params.endDate);
6736
+ if (params.groupBy) {
6737
+ searchParams.set("group_by", params.groupBy);
6738
+ }
6739
+ if (params.datePart) {
6740
+ searchParams.set("date_part", params.datePart);
6741
+ }
6742
+ if (params.userId) {
6743
+ searchParams.set("user_id", params.userId);
6744
+ }
6745
+ if (params.model) {
6746
+ searchParams.set("model", params.model);
6747
+ }
6748
+ if (params.provider) {
6749
+ searchParams.set("provider", params.provider);
6750
+ }
6751
+ if (params.credentialType) {
6752
+ searchParams.set("credential_type", params.credentialType);
6753
+ }
6754
+ if (params.tags && params.tags.length > 0) {
6755
+ searchParams.set("tags", params.tags.join(","));
6756
+ }
6757
+ const { value } = await getFromApi({
6758
+ url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
6759
+ headers: await resolve(this.config.headers()),
6760
+ successfulResponseHandler: createJsonResponseHandler(
6761
+ gatewaySpendReportResponseSchema
6762
+ ),
6763
+ failedResponseHandler: createJsonErrorResponseHandler({
6764
+ errorSchema: z4.z.any(),
6765
+ errorToMessage: (data) => data
6766
+ }),
6767
+ fetch: this.config.fetch
6768
+ });
6769
+ return value;
6770
+ } catch (error) {
6771
+ throw await asGatewayError(error);
6772
+ }
6773
+ }
6774
+ };
6775
+ var gatewaySpendReportResponseSchema = lazySchema(
6776
+ () => zodSchema2(
6777
+ z4.z.object({
6778
+ results: z4.z.array(
6779
+ z4.z.object({
6780
+ day: z4.z.string().optional(),
6781
+ hour: z4.z.string().optional(),
6782
+ user: z4.z.string().optional(),
6783
+ model: z4.z.string().optional(),
6784
+ tag: z4.z.string().optional(),
6785
+ provider: z4.z.string().optional(),
6786
+ credential_type: z4.z.enum(["byok", "system"]).optional(),
6787
+ total_cost: z4.z.number(),
6788
+ market_cost: z4.z.number().optional(),
6789
+ input_tokens: z4.z.number().optional(),
6790
+ output_tokens: z4.z.number().optional(),
6791
+ cached_input_tokens: z4.z.number().optional(),
6792
+ cache_creation_input_tokens: z4.z.number().optional(),
6793
+ reasoning_tokens: z4.z.number().optional(),
6794
+ request_count: z4.z.number().optional()
6795
+ }).transform(
6796
+ ({
6797
+ credential_type,
6798
+ total_cost,
6799
+ market_cost,
6800
+ input_tokens,
6801
+ output_tokens,
6802
+ cached_input_tokens,
6803
+ cache_creation_input_tokens,
6804
+ reasoning_tokens,
6805
+ request_count,
6806
+ ...rest
6807
+ }) => ({
6808
+ ...rest,
6809
+ ...credential_type !== void 0 ? { credentialType: credential_type } : {},
6810
+ totalCost: total_cost,
6811
+ ...market_cost !== void 0 ? { marketCost: market_cost } : {},
6812
+ ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},
6813
+ ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},
6814
+ ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},
6815
+ ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
6816
+ ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},
6817
+ ...request_count !== void 0 ? { requestCount: request_count } : {}
6818
+ })
6819
+ )
6820
+ )
6821
+ })
6822
+ )
6823
+ );
6824
+ var GatewayGenerationInfoFetcher = class {
6825
+ constructor(config) {
6826
+ this.config = config;
6827
+ }
6828
+ async getGenerationInfo(params) {
6829
+ try {
6830
+ const baseUrl = new URL(this.config.baseURL);
6831
+ const { value } = await getFromApi({
6832
+ url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
6833
+ headers: await resolve(this.config.headers()),
6834
+ successfulResponseHandler: createJsonResponseHandler(
6835
+ gatewayGenerationInfoResponseSchema
6836
+ ),
6837
+ failedResponseHandler: createJsonErrorResponseHandler({
6838
+ errorSchema: z4.z.any(),
6839
+ errorToMessage: (data) => data
6840
+ }),
6841
+ fetch: this.config.fetch
6842
+ });
6843
+ return value;
6844
+ } catch (error) {
6845
+ throw await asGatewayError(error);
6846
+ }
6847
+ }
6848
+ };
6849
+ var gatewayGenerationInfoResponseSchema = lazySchema(
6850
+ () => zodSchema2(
6851
+ z4.z.object({
6852
+ data: z4.z.object({
6853
+ id: z4.z.string(),
6854
+ total_cost: z4.z.number(),
6855
+ upstream_inference_cost: z4.z.number(),
6856
+ usage: z4.z.number(),
6857
+ created_at: z4.z.string(),
6858
+ model: z4.z.string(),
6859
+ is_byok: z4.z.boolean(),
6860
+ provider_name: z4.z.string(),
6861
+ streamed: z4.z.boolean(),
6862
+ finish_reason: z4.z.string(),
6863
+ latency: z4.z.number(),
6864
+ generation_time: z4.z.number(),
6865
+ native_tokens_prompt: z4.z.number(),
6866
+ native_tokens_completion: z4.z.number(),
6867
+ native_tokens_reasoning: z4.z.number(),
6868
+ native_tokens_cached: z4.z.number(),
6869
+ native_tokens_cache_creation: z4.z.number(),
6870
+ billable_web_search_calls: z4.z.number()
6871
+ }).transform(
6872
+ ({
6873
+ total_cost,
6874
+ upstream_inference_cost,
6875
+ created_at,
6876
+ is_byok,
6877
+ provider_name,
6878
+ finish_reason,
6879
+ generation_time,
6880
+ native_tokens_prompt,
6881
+ native_tokens_completion,
6882
+ native_tokens_reasoning,
6883
+ native_tokens_cached,
6884
+ native_tokens_cache_creation,
6885
+ billable_web_search_calls,
6886
+ ...rest
6887
+ }) => ({
6888
+ ...rest,
6889
+ totalCost: total_cost,
6890
+ upstreamInferenceCost: upstream_inference_cost,
6891
+ createdAt: created_at,
6892
+ isByok: is_byok,
6893
+ providerName: provider_name,
6894
+ finishReason: finish_reason,
6895
+ generationTime: generation_time,
6896
+ promptTokens: native_tokens_prompt,
6897
+ completionTokens: native_tokens_completion,
6898
+ reasoningTokens: native_tokens_reasoning,
6899
+ cachedTokens: native_tokens_cached,
6900
+ cacheCreationTokens: native_tokens_cache_creation,
6901
+ billableWebSearchCalls: billable_web_search_calls
6902
+ })
6903
+ )
6904
+ }).transform(({ data }) => data)
6905
+ )
6906
+ );
6843
6907
  var GatewayLanguageModel = class {
6844
6908
  constructor(modelId, config) {
6845
6909
  this.modelId = modelId;
@@ -7340,9 +7404,9 @@ var gatewayTools = {
7340
7404
  };
7341
7405
  async function getVercelRequestId() {
7342
7406
  var _a932;
7343
- return (_a932 = (0, import_oidc.getContext)().headers) == null ? void 0 : _a932["x-vercel-id"];
7407
+ return (_a932 = getContext().headers) == null ? void 0 : _a932["x-vercel-id"];
7344
7408
  }
7345
- var VERSION3 = "2.0.59";
7409
+ var VERSION3 = "2.0.82";
7346
7410
  var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
7347
7411
  function createGatewayProvider(options = {}) {
7348
7412
  var _a932, _b93;
@@ -7440,6 +7504,30 @@ function createGatewayProvider(options = {}) {
7440
7504
  );
7441
7505
  });
7442
7506
  };
7507
+ const getSpendReport = async (params) => {
7508
+ return new GatewaySpendReport({
7509
+ baseURL,
7510
+ headers: getHeaders,
7511
+ fetch: options.fetch
7512
+ }).getSpendReport(params).catch(async (error) => {
7513
+ throw await asGatewayError(
7514
+ error,
7515
+ await parseAuthMethod(await getHeaders())
7516
+ );
7517
+ });
7518
+ };
7519
+ const getGenerationInfo = async (params) => {
7520
+ return new GatewayGenerationInfoFetcher({
7521
+ baseURL,
7522
+ headers: getHeaders,
7523
+ fetch: options.fetch
7524
+ }).getGenerationInfo(params).catch(async (error) => {
7525
+ throw await asGatewayError(
7526
+ error,
7527
+ await parseAuthMethod(await getHeaders())
7528
+ );
7529
+ });
7530
+ };
7443
7531
  const provider = function(modelId) {
7444
7532
  if (new.target) {
7445
7533
  throw new Error(
@@ -7450,6 +7538,8 @@ function createGatewayProvider(options = {}) {
7450
7538
  };
7451
7539
  provider.getAvailableModels = getAvailableModels;
7452
7540
  provider.getCredits = getCredits;
7541
+ provider.getSpendReport = getSpendReport;
7542
+ provider.getGenerationInfo = getGenerationInfo;
7453
7543
  provider.imageModel = (modelId) => {
7454
7544
  return new GatewayImageModel(modelId, {
7455
7545
  provider: "gateway",
@@ -7485,7 +7575,7 @@ async function getGatewayAuthToken(options) {
7485
7575
  };
7486
7576
  }
7487
7577
  try {
7488
- const oidcToken = await (0, import_oidc2.getVercelOidcToken)();
7578
+ const oidcToken = await getVercelOidcToken();
7489
7579
  return {
7490
7580
  token: oidcToken,
7491
7581
  authMethod: "oidc"
@@ -8303,7 +8393,7 @@ function getGlobalProvider() {
8303
8393
  var _a163;
8304
8394
  return (_a163 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a163 : gateway;
8305
8395
  }
8306
- var VERSION32 = "5.0.155";
8396
+ var VERSION32 = "5.0.179";
8307
8397
  var dataContentSchema2 = z4.z.union([
8308
8398
  z4.z.string(),
8309
8399
  z4.z.instanceof(Uint8Array),
@@ -9914,7 +10004,7 @@ function withUserAgentSuffix2(headers, ...userAgentSuffixParts) {
9914
10004
  );
9915
10005
  return Object.fromEntries(normalizedHeaders.entries());
9916
10006
  }
9917
- var VERSION4 = "4.0.19";
10007
+ var VERSION4 = "4.0.23";
9918
10008
  var getOriginalFetch3 = () => globalThis.fetch;
9919
10009
  var getFromApi2 = async ({
9920
10010
  url,
@@ -11574,138 +11664,17 @@ var createJsonResponseHandler2 = (responseSchema) => async ({ response, url, req
11574
11664
  function withoutTrailingSlash2(url) {
11575
11665
  return url == null ? void 0 : url.replace(/\/$/, "");
11576
11666
  }
11577
- var require_get_context2 = chunkIDRQZVB4_cjs.__commonJS({
11578
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-context.js"(exports$1, module) {
11579
- var __defProp22 = Object.defineProperty;
11580
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
11581
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
11582
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
11583
- var __export22 = (target, all) => {
11584
- for (var name21 in all)
11585
- __defProp22(target, name21, { get: all[name21], enumerable: true });
11586
- };
11587
- var __copyProps2 = (to, from, except, desc) => {
11588
- if (from && typeof from === "object" || typeof from === "function") {
11589
- for (let key of __getOwnPropNames2(from))
11590
- if (!__hasOwnProp2.call(to, key) && key !== except)
11591
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
11592
- }
11593
- return to;
11594
- };
11595
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
11596
- var get_context_exports = {};
11597
- __export22(get_context_exports, {
11598
- SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,
11599
- getContext: () => getContext3
11600
- });
11601
- module.exports = __toCommonJS(get_context_exports);
11602
- var SYMBOL_FOR_REQ_CONTEXT = /* @__PURE__ */ Symbol.for("@vercel/request-context");
11603
- function getContext3() {
11604
- const fromSymbol = globalThis;
11605
- return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};
11606
- }
11607
- }
11608
- });
11609
- var require_get_vercel_oidc_token2 = chunkIDRQZVB4_cjs.__commonJS({
11610
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/get-vercel-oidc-token.js"(exports$1, module) {
11611
- var __defProp22 = Object.defineProperty;
11612
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
11613
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
11614
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
11615
- var __export22 = (target, all) => {
11616
- for (var name21 in all)
11617
- __defProp22(target, name21, { get: all[name21], enumerable: true });
11618
- };
11619
- var __copyProps2 = (to, from, except, desc) => {
11620
- if (from && typeof from === "object" || typeof from === "function") {
11621
- for (let key of __getOwnPropNames2(from))
11622
- if (!__hasOwnProp2.call(to, key) && key !== except)
11623
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
11624
- }
11625
- return to;
11626
- };
11627
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
11628
- var get_vercel_oidc_token_exports = {};
11629
- __export22(get_vercel_oidc_token_exports, {
11630
- getVercelOidcToken: () => getVercelOidcToken3,
11631
- getVercelOidcTokenSync: () => getVercelOidcTokenSync2
11632
- });
11633
- module.exports = __toCommonJS(get_vercel_oidc_token_exports);
11634
- var import_get_context = require_get_context2();
11635
- var import_token_error = chunkIDRQZVB4_cjs.require_token_error();
11636
- async function getVercelOidcToken3() {
11637
- let token = "";
11638
- let err;
11639
- try {
11640
- token = getVercelOidcTokenSync2();
11641
- } catch (error) {
11642
- err = error;
11643
- }
11644
- try {
11645
- const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
11646
- await import('./token-util-RMHT2CPJ-6TGPE335.cjs'),
11647
- await import('./token-APYSY3BW-ZQ7TMBY7.cjs')
11648
- ]);
11649
- if (!token || isExpired(getTokenPayload(token))) {
11650
- await refreshToken();
11651
- token = getVercelOidcTokenSync2();
11652
- }
11653
- } catch (error) {
11654
- let message = err instanceof Error ? err.message : "";
11655
- if (error instanceof Error) {
11656
- message = `${message}
11657
- ${error.message}`;
11658
- }
11659
- if (message) {
11660
- throw new import_token_error.VercelOidcTokenError(message);
11661
- }
11662
- throw error;
11663
- }
11664
- return token;
11665
- }
11666
- function getVercelOidcTokenSync2() {
11667
- const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
11668
- if (!token) {
11669
- throw new Error(
11670
- `The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?`
11671
- );
11672
- }
11673
- return token;
11674
- }
11675
- }
11676
- });
11677
- var require_dist2 = chunkIDRQZVB4_cjs.__commonJS({
11678
- "../../../node_modules/.pnpm/@vercel+oidc@3.1.0/node_modules/@vercel/oidc/dist/index.js"(exports$1, module) {
11679
- var __defProp22 = Object.defineProperty;
11680
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
11681
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
11682
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
11683
- var __export22 = (target, all) => {
11684
- for (var name21 in all)
11685
- __defProp22(target, name21, { get: all[name21], enumerable: true });
11686
- };
11687
- var __copyProps2 = (to, from, except, desc) => {
11688
- if (from && typeof from === "object" || typeof from === "function") {
11689
- for (let key of __getOwnPropNames2(from))
11690
- if (!__hasOwnProp2.call(to, key) && key !== except)
11691
- __defProp22(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
11692
- }
11693
- return to;
11694
- };
11695
- var __toCommonJS = (mod) => __copyProps2(__defProp22({}, "__esModule", { value: true }), mod);
11696
- var src_exports = {};
11697
- __export22(src_exports, {
11698
- getContext: () => import_get_context.getContext,
11699
- getVercelOidcToken: () => import_get_vercel_oidc_token.getVercelOidcToken,
11700
- getVercelOidcTokenSync: () => import_get_vercel_oidc_token.getVercelOidcTokenSync
11701
- });
11702
- module.exports = __toCommonJS(src_exports);
11703
- var import_get_vercel_oidc_token = require_get_vercel_oidc_token2();
11704
- var import_get_context = require_get_context2();
11667
+ function getContext2() {
11668
+ return {
11669
+ headers: {}
11670
+ };
11671
+ }
11672
+ async function getVercelOidcToken2() {
11673
+ if (process.env.VERCEL_OIDC_TOKEN) {
11674
+ return process.env.VERCEL_OIDC_TOKEN ?? "";
11705
11675
  }
11706
- });
11707
- var import_oidc3 = chunkIDRQZVB4_cjs.__toESM(require_dist2(), 1);
11708
- var import_oidc22 = chunkIDRQZVB4_cjs.__toESM(require_dist2(), 1);
11676
+ throw new Error("@vercel/oidc is not available in the vendored @internal AI packages. Provide an API key instead.");
11677
+ }
11709
11678
  var marker20 = "vercel.ai.gateway.error";
11710
11679
  var symbol20 = Symbol.for(marker20);
11711
11680
  var _a20;
@@ -12120,6 +12089,13 @@ async function parseAuthMethod2(headers) {
12120
12089
  var gatewayAuthMethodSchema2 = lazySchema2(
12121
12090
  () => zodSchema3(z4.z.union([z4.z.literal("api-key"), z4.z.literal("oidc")]))
12122
12091
  );
12092
+ var KNOWN_MODEL_TYPES2 = [
12093
+ "embedding",
12094
+ "image",
12095
+ "language",
12096
+ "reranking",
12097
+ "video"
12098
+ ];
12123
12099
  var GatewayFetchMetadata2 = class {
12124
12100
  constructor(config) {
12125
12101
  this.config = config;
@@ -12190,8 +12166,12 @@ var gatewayAvailableModelsResponseSchema2 = lazySchema2(
12190
12166
  provider: z4.z.string(),
12191
12167
  modelId: z4.z.string()
12192
12168
  }),
12193
- modelType: z4.z.enum(["embedding", "image", "language", "video"]).nullish()
12169
+ modelType: z4.z.string().nullish()
12194
12170
  })
12171
+ ).transform(
12172
+ (models) => models.filter(
12173
+ (m) => m.modelType == null || KNOWN_MODEL_TYPES2.includes(m.modelType)
12174
+ )
12195
12175
  )
12196
12176
  })
12197
12177
  )
@@ -12207,6 +12187,187 @@ var gatewayCreditsResponseSchema2 = lazySchema2(
12207
12187
  }))
12208
12188
  )
12209
12189
  );
12190
+ var GatewaySpendReport2 = class {
12191
+ constructor(config) {
12192
+ this.config = config;
12193
+ }
12194
+ async getSpendReport(params) {
12195
+ try {
12196
+ const baseUrl = new URL(this.config.baseURL);
12197
+ const searchParams = new URLSearchParams();
12198
+ searchParams.set("start_date", params.startDate);
12199
+ searchParams.set("end_date", params.endDate);
12200
+ if (params.groupBy) {
12201
+ searchParams.set("group_by", params.groupBy);
12202
+ }
12203
+ if (params.datePart) {
12204
+ searchParams.set("date_part", params.datePart);
12205
+ }
12206
+ if (params.userId) {
12207
+ searchParams.set("user_id", params.userId);
12208
+ }
12209
+ if (params.model) {
12210
+ searchParams.set("model", params.model);
12211
+ }
12212
+ if (params.provider) {
12213
+ searchParams.set("provider", params.provider);
12214
+ }
12215
+ if (params.credentialType) {
12216
+ searchParams.set("credential_type", params.credentialType);
12217
+ }
12218
+ if (params.tags && params.tags.length > 0) {
12219
+ searchParams.set("tags", params.tags.join(","));
12220
+ }
12221
+ const { value } = await getFromApi2({
12222
+ url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
12223
+ headers: await resolve2(this.config.headers()),
12224
+ successfulResponseHandler: createJsonResponseHandler2(
12225
+ gatewaySpendReportResponseSchema2
12226
+ ),
12227
+ failedResponseHandler: createJsonErrorResponseHandler2({
12228
+ errorSchema: z4.z.any(),
12229
+ errorToMessage: (data) => data
12230
+ }),
12231
+ fetch: this.config.fetch
12232
+ });
12233
+ return value;
12234
+ } catch (error) {
12235
+ throw await asGatewayError2(error);
12236
+ }
12237
+ }
12238
+ };
12239
+ var gatewaySpendReportResponseSchema2 = lazySchema2(
12240
+ () => zodSchema3(
12241
+ z4.z.object({
12242
+ results: z4.z.array(
12243
+ z4.z.object({
12244
+ day: z4.z.string().optional(),
12245
+ hour: z4.z.string().optional(),
12246
+ user: z4.z.string().optional(),
12247
+ model: z4.z.string().optional(),
12248
+ tag: z4.z.string().optional(),
12249
+ provider: z4.z.string().optional(),
12250
+ credential_type: z4.z.enum(["byok", "system"]).optional(),
12251
+ total_cost: z4.z.number(),
12252
+ market_cost: z4.z.number().optional(),
12253
+ input_tokens: z4.z.number().optional(),
12254
+ output_tokens: z4.z.number().optional(),
12255
+ cached_input_tokens: z4.z.number().optional(),
12256
+ cache_creation_input_tokens: z4.z.number().optional(),
12257
+ reasoning_tokens: z4.z.number().optional(),
12258
+ request_count: z4.z.number().optional()
12259
+ }).transform(
12260
+ ({
12261
+ credential_type,
12262
+ total_cost,
12263
+ market_cost,
12264
+ input_tokens,
12265
+ output_tokens,
12266
+ cached_input_tokens,
12267
+ cache_creation_input_tokens,
12268
+ reasoning_tokens,
12269
+ request_count,
12270
+ ...rest
12271
+ }) => ({
12272
+ ...rest,
12273
+ ...credential_type !== void 0 ? { credentialType: credential_type } : {},
12274
+ totalCost: total_cost,
12275
+ ...market_cost !== void 0 ? { marketCost: market_cost } : {},
12276
+ ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},
12277
+ ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},
12278
+ ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},
12279
+ ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
12280
+ ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},
12281
+ ...request_count !== void 0 ? { requestCount: request_count } : {}
12282
+ })
12283
+ )
12284
+ )
12285
+ })
12286
+ )
12287
+ );
12288
+ var GatewayGenerationInfoFetcher2 = class {
12289
+ constructor(config) {
12290
+ this.config = config;
12291
+ }
12292
+ async getGenerationInfo(params) {
12293
+ try {
12294
+ const baseUrl = new URL(this.config.baseURL);
12295
+ const { value } = await getFromApi2({
12296
+ url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
12297
+ headers: await resolve2(this.config.headers()),
12298
+ successfulResponseHandler: createJsonResponseHandler2(
12299
+ gatewayGenerationInfoResponseSchema2
12300
+ ),
12301
+ failedResponseHandler: createJsonErrorResponseHandler2({
12302
+ errorSchema: z4.z.any(),
12303
+ errorToMessage: (data) => data
12304
+ }),
12305
+ fetch: this.config.fetch
12306
+ });
12307
+ return value;
12308
+ } catch (error) {
12309
+ throw await asGatewayError2(error);
12310
+ }
12311
+ }
12312
+ };
12313
+ var gatewayGenerationInfoResponseSchema2 = lazySchema2(
12314
+ () => zodSchema3(
12315
+ z4.z.object({
12316
+ data: z4.z.object({
12317
+ id: z4.z.string(),
12318
+ total_cost: z4.z.number(),
12319
+ upstream_inference_cost: z4.z.number(),
12320
+ usage: z4.z.number(),
12321
+ created_at: z4.z.string(),
12322
+ model: z4.z.string(),
12323
+ is_byok: z4.z.boolean(),
12324
+ provider_name: z4.z.string(),
12325
+ streamed: z4.z.boolean(),
12326
+ finish_reason: z4.z.string(),
12327
+ latency: z4.z.number(),
12328
+ generation_time: z4.z.number(),
12329
+ native_tokens_prompt: z4.z.number(),
12330
+ native_tokens_completion: z4.z.number(),
12331
+ native_tokens_reasoning: z4.z.number(),
12332
+ native_tokens_cached: z4.z.number(),
12333
+ native_tokens_cache_creation: z4.z.number(),
12334
+ billable_web_search_calls: z4.z.number()
12335
+ }).transform(
12336
+ ({
12337
+ total_cost,
12338
+ upstream_inference_cost,
12339
+ created_at,
12340
+ is_byok,
12341
+ provider_name,
12342
+ finish_reason,
12343
+ generation_time,
12344
+ native_tokens_prompt,
12345
+ native_tokens_completion,
12346
+ native_tokens_reasoning,
12347
+ native_tokens_cached,
12348
+ native_tokens_cache_creation,
12349
+ billable_web_search_calls,
12350
+ ...rest
12351
+ }) => ({
12352
+ ...rest,
12353
+ totalCost: total_cost,
12354
+ upstreamInferenceCost: upstream_inference_cost,
12355
+ createdAt: created_at,
12356
+ isByok: is_byok,
12357
+ providerName: provider_name,
12358
+ finishReason: finish_reason,
12359
+ generationTime: generation_time,
12360
+ promptTokens: native_tokens_prompt,
12361
+ completionTokens: native_tokens_completion,
12362
+ reasoningTokens: native_tokens_reasoning,
12363
+ cachedTokens: native_tokens_cached,
12364
+ cacheCreationTokens: native_tokens_cache_creation,
12365
+ billableWebSearchCalls: billable_web_search_calls
12366
+ })
12367
+ )
12368
+ }).transform(({ data }) => data)
12369
+ )
12370
+ );
12210
12371
  var GatewayLanguageModel2 = class {
12211
12372
  constructor(modelId, config) {
12212
12373
  this.modelId = modelId;
@@ -12754,37 +12915,117 @@ var gatewayVideoEventSchema = z4.z.discriminatedUnion("type", [
12754
12915
  param: z4.z.unknown().nullable()
12755
12916
  })
12756
12917
  ]);
12757
- var parallelSearchInputSchema2 = lazySchema2(
12758
- () => zodSchema3(
12759
- zod.z.object({
12760
- objective: zod.z.string().describe(
12761
- "Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."
12762
- ),
12763
- search_queries: zod.z.array(zod.z.string()).optional().describe(
12764
- "Optional search queries to supplement the objective. Maximum 200 characters per query."
12765
- ),
12766
- mode: zod.z.enum(["one-shot", "agentic"]).optional().describe(
12767
- 'Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'
12768
- ),
12769
- max_results: zod.z.number().optional().describe(
12770
- "Maximum number of results to return (1-20). Defaults to 10 if not specified."
12771
- ),
12772
- source_policy: zod.z.object({
12773
- include_domains: zod.z.array(zod.z.string()).optional().describe("List of domains to include in search results."),
12774
- exclude_domains: zod.z.array(zod.z.string()).optional().describe("List of domains to exclude from search results."),
12775
- after_date: zod.z.string().optional().describe(
12776
- "Only include results published after this date (ISO 8601 format)."
12777
- )
12778
- }).optional().describe(
12779
- "Source policy for controlling which domains to include/exclude and freshness."
12780
- ),
12781
- excerpts: zod.z.object({
12782
- max_chars_per_result: zod.z.number().optional().describe("Maximum characters per result."),
12783
- max_chars_total: zod.z.number().optional().describe("Maximum total characters across all results.")
12784
- }).optional().describe("Excerpt configuration for controlling result length."),
12785
- fetch_policy: zod.z.object({
12786
- max_age_seconds: zod.z.number().optional().describe(
12787
- "Maximum age in seconds for cached content. Set to 0 to always fetch fresh content."
12918
+ var GatewayRerankingModel = class {
12919
+ constructor(modelId, config) {
12920
+ this.modelId = modelId;
12921
+ this.config = config;
12922
+ this.specificationVersion = "v3";
12923
+ }
12924
+ get provider() {
12925
+ return this.config.provider;
12926
+ }
12927
+ async doRerank({
12928
+ documents,
12929
+ query,
12930
+ topN,
12931
+ headers,
12932
+ abortSignal,
12933
+ providerOptions
12934
+ }) {
12935
+ const resolvedHeaders = await resolve2(this.config.headers());
12936
+ try {
12937
+ const {
12938
+ responseHeaders,
12939
+ value: responseBody,
12940
+ rawValue
12941
+ } = await postJsonToApi2({
12942
+ url: this.getUrl(),
12943
+ headers: combineHeaders2(
12944
+ resolvedHeaders,
12945
+ headers != null ? headers : {},
12946
+ this.getModelConfigHeaders(),
12947
+ await resolve2(this.config.o11yHeaders)
12948
+ ),
12949
+ body: {
12950
+ documents,
12951
+ query,
12952
+ ...topN != null ? { topN } : {},
12953
+ ...providerOptions ? { providerOptions } : {}
12954
+ },
12955
+ successfulResponseHandler: createJsonResponseHandler2(
12956
+ gatewayRerankingResponseSchema
12957
+ ),
12958
+ failedResponseHandler: createJsonErrorResponseHandler2({
12959
+ errorSchema: z4.z.any(),
12960
+ errorToMessage: (data) => data
12961
+ }),
12962
+ ...abortSignal && { abortSignal },
12963
+ fetch: this.config.fetch
12964
+ });
12965
+ return {
12966
+ ranking: responseBody.ranking,
12967
+ providerMetadata: responseBody.providerMetadata,
12968
+ response: { headers: responseHeaders, body: rawValue },
12969
+ warnings: []
12970
+ };
12971
+ } catch (error) {
12972
+ throw await asGatewayError2(error, await parseAuthMethod2(resolvedHeaders));
12973
+ }
12974
+ }
12975
+ getUrl() {
12976
+ return `${this.config.baseURL}/reranking-model`;
12977
+ }
12978
+ getModelConfigHeaders() {
12979
+ return {
12980
+ "ai-reranking-model-specification-version": "3",
12981
+ "ai-model-id": this.modelId
12982
+ };
12983
+ }
12984
+ };
12985
+ var gatewayRerankingResponseSchema = lazySchema2(
12986
+ () => zodSchema3(
12987
+ z4.z.object({
12988
+ ranking: z4.z.array(
12989
+ z4.z.object({
12990
+ index: z4.z.number(),
12991
+ relevanceScore: z4.z.number()
12992
+ })
12993
+ ),
12994
+ providerMetadata: z4.z.record(z4.z.string(), z4.z.record(z4.z.string(), z4.z.unknown())).optional()
12995
+ })
12996
+ )
12997
+ );
12998
+ var parallelSearchInputSchema2 = lazySchema2(
12999
+ () => zodSchema3(
13000
+ zod.z.object({
13001
+ objective: zod.z.string().describe(
13002
+ "Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."
13003
+ ),
13004
+ search_queries: zod.z.array(zod.z.string()).optional().describe(
13005
+ "Optional search queries to supplement the objective. Maximum 200 characters per query."
13006
+ ),
13007
+ mode: zod.z.enum(["one-shot", "agentic"]).optional().describe(
13008
+ 'Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'
13009
+ ),
13010
+ max_results: zod.z.number().optional().describe(
13011
+ "Maximum number of results to return (1-20). Defaults to 10 if not specified."
13012
+ ),
13013
+ source_policy: zod.z.object({
13014
+ include_domains: zod.z.array(zod.z.string()).optional().describe("List of domains to include in search results."),
13015
+ exclude_domains: zod.z.array(zod.z.string()).optional().describe("List of domains to exclude from search results."),
13016
+ after_date: zod.z.string().optional().describe(
13017
+ "Only include results published after this date (ISO 8601 format)."
13018
+ )
13019
+ }).optional().describe(
13020
+ "Source policy for controlling which domains to include/exclude and freshness."
13021
+ ),
13022
+ excerpts: zod.z.object({
13023
+ max_chars_per_result: zod.z.number().optional().describe("Maximum characters per result."),
13024
+ max_chars_total: zod.z.number().optional().describe("Maximum total characters across all results.")
13025
+ }).optional().describe("Excerpt configuration for controlling result length."),
13026
+ fetch_policy: zod.z.object({
13027
+ max_age_seconds: zod.z.number().optional().describe(
13028
+ "Maximum age in seconds for cached content. Set to 0 to always fetch fresh content."
12788
13029
  )
12789
13030
  }).optional().describe("Fetch policy for controlling content freshness.")
12790
13031
  })
@@ -12928,9 +13169,9 @@ var gatewayTools2 = {
12928
13169
  };
12929
13170
  async function getVercelRequestId2() {
12930
13171
  var _a932;
12931
- return (_a932 = (0, import_oidc3.getContext)().headers) == null ? void 0 : _a932["x-vercel-id"];
13172
+ return (_a932 = getContext2().headers) == null ? void 0 : _a932["x-vercel-id"];
12932
13173
  }
12933
- var VERSION5 = "3.0.66";
13174
+ var VERSION5 = "3.0.104";
12934
13175
  var AI_GATEWAY_PROTOCOL_VERSION2 = "0.0.1";
12935
13176
  function createGatewayProvider2(options = {}) {
12936
13177
  var _a932, _b93;
@@ -13030,6 +13271,30 @@ function createGatewayProvider2(options = {}) {
13030
13271
  );
13031
13272
  });
13032
13273
  };
13274
+ const getSpendReport = async (params) => {
13275
+ return new GatewaySpendReport2({
13276
+ baseURL,
13277
+ headers: getHeaders,
13278
+ fetch: options.fetch
13279
+ }).getSpendReport(params).catch(async (error) => {
13280
+ throw await asGatewayError2(
13281
+ error,
13282
+ await parseAuthMethod2(await getHeaders())
13283
+ );
13284
+ });
13285
+ };
13286
+ const getGenerationInfo = async (params) => {
13287
+ return new GatewayGenerationInfoFetcher2({
13288
+ baseURL,
13289
+ headers: getHeaders,
13290
+ fetch: options.fetch
13291
+ }).getGenerationInfo(params).catch(async (error) => {
13292
+ throw await asGatewayError2(
13293
+ error,
13294
+ await parseAuthMethod2(await getHeaders())
13295
+ );
13296
+ });
13297
+ };
13033
13298
  const provider = function(modelId) {
13034
13299
  if (new.target) {
13035
13300
  throw new Error(
@@ -13041,6 +13306,8 @@ function createGatewayProvider2(options = {}) {
13041
13306
  provider.specificationVersion = "v3";
13042
13307
  provider.getAvailableModels = getAvailableModels;
13043
13308
  provider.getCredits = getCredits;
13309
+ provider.getSpendReport = getSpendReport;
13310
+ provider.getGenerationInfo = getGenerationInfo;
13044
13311
  provider.imageModel = (modelId) => {
13045
13312
  return new GatewayImageModel2(modelId, {
13046
13313
  provider: "gateway",
@@ -13071,6 +13338,17 @@ function createGatewayProvider2(options = {}) {
13071
13338
  o11yHeaders: createO11yHeaders()
13072
13339
  });
13073
13340
  };
13341
+ const createRerankingModel = (modelId) => {
13342
+ return new GatewayRerankingModel(modelId, {
13343
+ provider: "gateway",
13344
+ baseURL,
13345
+ headers: getHeaders,
13346
+ fetch: options.fetch,
13347
+ o11yHeaders: createO11yHeaders()
13348
+ });
13349
+ };
13350
+ provider.rerankingModel = createRerankingModel;
13351
+ provider.reranking = createRerankingModel;
13074
13352
  provider.chat = provider.languageModel;
13075
13353
  provider.embedding = provider.embeddingModel;
13076
13354
  provider.image = provider.imageModel;
@@ -13090,7 +13368,7 @@ async function getGatewayAuthToken2(options) {
13090
13368
  authMethod: "api-key"
13091
13369
  };
13092
13370
  }
13093
- const oidcToken = await (0, import_oidc22.getVercelOidcToken)();
13371
+ const oidcToken = await getVercelOidcToken2();
13094
13372
  return {
13095
13373
  token: oidcToken,
13096
13374
  authMethod: "oidc"
@@ -14003,7 +14281,7 @@ function getTotalTimeoutMs(timeout) {
14003
14281
  }
14004
14282
  return timeout.totalMs;
14005
14283
  }
14006
- var VERSION33 = "6.0.116";
14284
+ var VERSION33 = "6.0.168";
14007
14285
  var dataContentSchema3 = z4.z.union([
14008
14286
  z4.z.string(),
14009
14287
  z4.z.instanceof(Uint8Array),
@@ -15447,10 +15725,16 @@ var DefaultEmbedManyResult3 = class {
15447
15725
  };
15448
15726
  createIdGenerator3({ prefix: "aiobj", size: 24 });
15449
15727
  createIdGenerator3({ prefix: "aiobj", size: 24 });
15728
+ function getMessageParts(msg) {
15729
+ if (typeof msg.content === "string") return [];
15730
+ if (Array.isArray(msg.content)) return msg.content;
15731
+ const parts = msg.content?.parts;
15732
+ return Array.isArray(parts) ? parts : [];
15733
+ }
15450
15734
  function hasVisibleParts(msg) {
15451
15735
  if (typeof msg.content === "string") return msg.content.length > 0;
15452
- const parts = msg.content?.parts;
15453
- if (!parts || !Array.isArray(parts)) return false;
15736
+ const parts = getMessageParts(msg);
15737
+ if (parts.length === 0) return Boolean(msg.content?.content);
15454
15738
  return parts.some((p) => !p.type?.startsWith("data-"));
15455
15739
  }
15456
15740
  function parseRangeFormat(cursor) {
@@ -15702,7 +15986,7 @@ function formatTimestamp(date) {
15702
15986
  }
15703
15987
  function truncateByTokens(text4, maxTokens, hint) {
15704
15988
  if (tokenx.estimateTokenCount(text4) <= maxTokens) return { text: text4, wasTruncated: false };
15705
- const truncated = chunk4FMHSWZD_cjs.truncateStringByTokens(text4, maxTokens);
15989
+ const truncated = chunk6ODYOMHN_cjs.truncateStringByTokens(text4, maxTokens);
15706
15990
  const suffix = hint ? ` [${hint} for more]` : "";
15707
15991
  return { text: truncated + suffix, wasTruncated: true };
15708
15992
  }
@@ -15711,13 +15995,13 @@ function lowDetailPartLimit(type) {
15711
15995
  if (type === "tool-result" || type === "tool-call") return AUTO_EXPAND_TOOL_TOKENS;
15712
15996
  return LOW_DETAIL_PART_TOKENS;
15713
15997
  }
15714
- function makePart(msg, partIndex, type, fullText, detail) {
15998
+ function makePart(msg, partIndex, type, fullText, detail, toolName) {
15715
15999
  if (detail === "high") {
15716
- return { messageId: msg.id, partIndex, role: msg.role, type, text: fullText, fullText };
16000
+ return { messageId: msg.id, partIndex, role: msg.role, type, text: fullText, fullText, toolName };
15717
16001
  }
15718
16002
  const hint = `recall cursor="${msg.id}" partIndex=${partIndex} detail="high"`;
15719
16003
  const { text: text4 } = truncateByTokens(fullText, lowDetailPartLimit(type), hint);
15720
- return { messageId: msg.id, partIndex, role: msg.role, type, text: text4, fullText };
16004
+ return { messageId: msg.id, partIndex, role: msg.role, type, text: text4, fullText, toolName };
15721
16005
  }
15722
16006
  function formatMessageParts(msg, detail) {
15723
16007
  const parts = [];
@@ -15725,32 +16009,73 @@ function formatMessageParts(msg, detail) {
15725
16009
  parts.push(makePart(msg, 0, "text", msg.content, detail));
15726
16010
  return parts;
15727
16011
  }
15728
- if (msg.content?.parts && Array.isArray(msg.content.parts)) {
15729
- for (let i = 0; i < msg.content.parts.length; i++) {
15730
- const part = msg.content.parts[i];
16012
+ const messageParts = getMessageParts(msg);
16013
+ if (messageParts.length > 0) {
16014
+ for (let i = 0; i < messageParts.length; i++) {
16015
+ const part = messageParts[i];
15731
16016
  const partType = part.type;
15732
16017
  if (partType === "text") {
15733
16018
  const text4 = part.text;
15734
- parts.push(makePart(msg, i, "text", text4, detail));
16019
+ if (text4) {
16020
+ parts.push(makePart(msg, i, "text", text4, detail));
16021
+ }
15735
16022
  } else if (partType === "tool-invocation") {
15736
16023
  const inv = part.toolInvocation;
15737
- if (inv.state === "result") {
15738
- const { value: resultValue } = chunk4FMHSWZD_cjs.resolveToolResultValue(
15739
- part,
15740
- inv.result
15741
- );
15742
- const resultStr = chunk4FMHSWZD_cjs.formatToolResultForObserver(resultValue, { maxTokens: HIGH_DETAIL_TOOL_RESULT_TOKENS });
15743
- const fullText = `[Tool Result: ${inv.toolName}]
15744
- ${resultStr}`;
15745
- parts.push(makePart(msg, i, "tool-result", fullText, detail));
15746
- } else {
15747
- const argsStr = detail === "low" ? "" : `
16024
+ if (inv?.toolName) {
16025
+ const hasArgs = inv.args != null;
16026
+ if (inv.state !== "partial-call" && hasArgs) {
16027
+ const argsStr = detail === "low" ? "" : `
15748
16028
  ${JSON.stringify(inv.args, null, 2)}`;
15749
- const fullText = `[Tool Call: ${inv.toolName}]${argsStr}`;
15750
- parts.push({ messageId: msg.id, partIndex: i, role: msg.role, type: "tool-call", text: fullText, fullText });
16029
+ const fullText = `[Tool Call: ${inv.toolName}]${argsStr}`;
16030
+ parts.push({
16031
+ messageId: msg.id,
16032
+ partIndex: i,
16033
+ role: msg.role,
16034
+ type: "tool-call",
16035
+ text: fullText,
16036
+ fullText,
16037
+ toolName: inv.toolName
16038
+ });
16039
+ }
16040
+ if (inv.state === "result") {
16041
+ const { value: resultValue } = chunk6ODYOMHN_cjs.resolveToolResultValue(
16042
+ part,
16043
+ inv.result
16044
+ );
16045
+ const resultStr = chunk6ODYOMHN_cjs.formatToolResultForObserver(resultValue, { maxTokens: HIGH_DETAIL_TOOL_RESULT_TOKENS });
16046
+ const fullText = `[Tool Result: ${inv.toolName}]
16047
+ ${resultStr}`;
16048
+ parts.push(makePart(msg, i, "tool-result", fullText, detail, inv.toolName));
16049
+ }
16050
+ }
16051
+ } else if (partType === "tool-call") {
16052
+ const toolName = part.toolName;
16053
+ if (toolName) {
16054
+ const rawArgs = part.input ?? part.args;
16055
+ const argsStr = detail === "low" || rawArgs == null ? "" : `
16056
+ ${typeof rawArgs === "string" ? rawArgs : JSON.stringify(rawArgs, null, 2)}`;
16057
+ const fullText = `[Tool Call: ${toolName}]${argsStr}`;
16058
+ parts.push({
16059
+ messageId: msg.id,
16060
+ partIndex: i,
16061
+ role: msg.role,
16062
+ type: "tool-call",
16063
+ text: fullText,
16064
+ fullText,
16065
+ toolName
16066
+ });
16067
+ }
16068
+ } else if (partType === "tool-result") {
16069
+ const toolName = part.toolName;
16070
+ if (toolName) {
16071
+ const rawResult = part.output ?? part.result;
16072
+ const resultStr = chunk6ODYOMHN_cjs.formatToolResultForObserver(rawResult, { maxTokens: HIGH_DETAIL_TOOL_RESULT_TOKENS });
16073
+ const fullText = `[Tool Result: ${toolName}]
16074
+ ${resultStr}`;
16075
+ parts.push(makePart(msg, i, "tool-result", fullText, detail, toolName));
15751
16076
  }
15752
16077
  } else if (partType === "reasoning") {
15753
- const reasoning = part.reasoning;
16078
+ const reasoning = part.reasoning ?? part.text;
15754
16079
  if (reasoning) {
15755
16080
  parts.push(makePart(msg, i, "reasoning", reasoning, detail));
15756
16081
  }
@@ -15823,7 +16148,7 @@ function renderFormattedParts(parts, timestamps, options) {
15823
16148
  const text4 = buildRenderedText(parts, timestamps);
15824
16149
  let totalTokens = tokenx.estimateTokenCount(text4);
15825
16150
  if (totalTokens > options.maxTokens) {
15826
- const truncated = chunk4FMHSWZD_cjs.truncateStringByTokens(text4, options.maxTokens);
16151
+ const truncated = chunk6ODYOMHN_cjs.truncateStringByTokens(text4, options.maxTokens);
15827
16152
  return { text: truncated, truncated: true, tokenOffset: totalTokens - options.maxTokens };
15828
16153
  }
15829
16154
  const truncatedIndices = parts.map((p, i) => ({ part: p, index: i })).filter(({ part }) => part.text !== part.fullText).sort((a, b) => expandPriority(a.part) - expandPriority(b.part));
@@ -15856,7 +16181,7 @@ function renderFormattedParts(parts, timestamps, options) {
15856
16181
  if (expandedTokens <= options.maxTokens) {
15857
16182
  return { text: expanded, truncated: false, tokenOffset: 0 };
15858
16183
  }
15859
- const hardTruncated = chunk4FMHSWZD_cjs.truncateStringByTokens(expanded, options.maxTokens);
16184
+ const hardTruncated = chunk6ODYOMHN_cjs.truncateStringByTokens(expanded, options.maxTokens);
15860
16185
  return { text: hardTruncated, truncated: true, tokenOffset: expandedTokens - options.maxTokens };
15861
16186
  }
15862
16187
  async function recallPart({
@@ -15888,7 +16213,7 @@ async function recallPart({
15888
16213
  `Message ${cursor} has no visible content (it may be an internal system message). Try a neighboring message ID instead.`
15889
16214
  );
15890
16215
  }
15891
- const target = allParts.find((p) => p.partIndex === partIndex);
16216
+ const target = [...allParts].reverse().find((p) => p.partIndex === partIndex);
15892
16217
  if (!target) {
15893
16218
  const availableIndices = allParts.map((p) => p.partIndex).join(", ");
15894
16219
  const highestVisiblePartIndex = Math.max(...allParts.map((p) => p.partIndex));
@@ -15907,7 +16232,7 @@ async function recallPart({
15907
16232
 
15908
16233
  `;
15909
16234
  const fallbackText = `${fallbackNote}${firstNextPart.text}`;
15910
- const truncatedText2 = chunk4FMHSWZD_cjs.truncateStringByTokens(fallbackText, maxTokens);
16235
+ const truncatedText2 = chunk6ODYOMHN_cjs.truncateStringByTokens(fallbackText, maxTokens);
15911
16236
  const wasTruncated2 = truncatedText2 !== fallbackText;
15912
16237
  return {
15913
16238
  text: truncatedText2,
@@ -15922,7 +16247,7 @@ async function recallPart({
15922
16247
  }
15923
16248
  throw new Error(`Part index ${partIndex} not found in message ${cursor}. Available indices: ${availableIndices}`);
15924
16249
  }
15925
- const truncatedText = chunk4FMHSWZD_cjs.truncateStringByTokens(target.text, maxTokens);
16250
+ const truncatedText = chunk6ODYOMHN_cjs.truncateStringByTokens(target.text, maxTokens);
15926
16251
  const wasTruncated = truncatedText !== target.text;
15927
16252
  return {
15928
16253
  text: truncatedText,
@@ -15941,6 +16266,8 @@ async function recallMessages({
15941
16266
  page = 1,
15942
16267
  limit = 20,
15943
16268
  detail = "low",
16269
+ partType,
16270
+ toolName,
15944
16271
  threadScope,
15945
16272
  maxTokens = DEFAULT_MAX_RESULT_TOKENS
15946
16273
  }) {
@@ -16030,12 +16357,18 @@ async function recallMessages({
16030
16357
  }
16031
16358
  const hasNextPage = isForward ? hasMore : pageIndex > 0;
16032
16359
  const hasPrevPage = isForward ? pageIndex > 0 : hasMore;
16033
- const allParts = [];
16360
+ let allParts = [];
16034
16361
  const timestamps = /* @__PURE__ */ new Map();
16035
16362
  for (const msg of messages) {
16036
16363
  timestamps.set(msg.id, msg.createdAt);
16037
16364
  allParts.push(...formatMessageParts(msg, detail));
16038
16365
  }
16366
+ if (toolName) {
16367
+ allParts = allParts.filter((p) => (p.type === "tool-call" || p.type === "tool-result") && p.toolName === toolName);
16368
+ }
16369
+ if (partType) {
16370
+ allParts = allParts.filter((p) => p.type === partType);
16371
+ }
16039
16372
  if (detail === "high" && allParts.length > 0) {
16040
16373
  const firstPart = allParts[0];
16041
16374
  const sameMsgParts = allParts.filter((p) => p.messageId === firstPart.messageId);
@@ -16072,8 +16405,9 @@ High detail returns 1 part at a time. To continue: ${hints.join(", or ")}.`;
16072
16405
  };
16073
16406
  }
16074
16407
  const rendered = renderFormattedParts(allParts, timestamps, { maxTokens });
16408
+ const emptyMessage = allParts.length === 0 ? partType || toolName ? "(no message parts matched the current filters)" : "(no visible message parts found for this page)" : "(no messages found)";
16075
16409
  return {
16076
- messages: rendered.text,
16410
+ messages: rendered.text || emptyMessage,
16077
16411
  count: messages.length,
16078
16412
  cursor,
16079
16413
  page: normalizedPage,
@@ -16092,6 +16426,9 @@ async function recallThreadFromStart({
16092
16426
  page = 1,
16093
16427
  limit = 20,
16094
16428
  detail = "low",
16429
+ partType,
16430
+ toolName,
16431
+ anchor = "start",
16095
16432
  maxTokens = DEFAULT_MAX_RESULT_TOKENS
16096
16433
  }) {
16097
16434
  if (!memory) {
@@ -16117,29 +16454,37 @@ async function recallThreadFromStart({
16117
16454
  resourceId,
16118
16455
  page: 0,
16119
16456
  perPage: fetchCount,
16120
- orderBy: { field: "createdAt", direction: "ASC" }
16457
+ orderBy: { field: "createdAt", direction: anchor === "end" ? "DESC" : "ASC" }
16121
16458
  });
16122
- const visibleMessages = result.messages.filter(hasVisibleParts);
16123
- const total = visibleMessages.length;
16459
+ const visibleMessages = anchor === "end" ? result.messages.slice(0, fetchCount).filter(hasVisibleParts).reverse() : result.messages.slice(0, fetchCount).filter(hasVisibleParts);
16124
16460
  const skip = pageIndex * normalizedLimit;
16125
- const hasMore = total > skip + normalizedLimit;
16126
16461
  const messages = visibleMessages.slice(skip, skip + normalizedLimit);
16127
- const allParts = [];
16462
+ const hasExtraMessage = visibleMessages.length > skip + messages.length;
16463
+ const hasNextPage = messages.length > 0 ? anchor === "end" ? pageIndex > 0 : hasExtraMessage : false;
16464
+ const hasPrevPage = messages.length > 0 ? anchor === "end" ? hasExtraMessage : pageIndex > 0 : pageIndex > 0;
16465
+ let allParts = [];
16128
16466
  const timestamps = /* @__PURE__ */ new Map();
16129
16467
  for (const msg of messages) {
16130
16468
  timestamps.set(msg.id, msg.createdAt);
16131
16469
  allParts.push(...formatMessageParts(msg, detail));
16132
16470
  }
16471
+ if (toolName) {
16472
+ allParts = allParts.filter((p) => (p.type === "tool-call" || p.type === "tool-result") && p.toolName === toolName);
16473
+ }
16474
+ if (partType) {
16475
+ allParts = allParts.filter((p) => p.type === partType);
16476
+ }
16133
16477
  const rendered = renderFormattedParts(allParts, timestamps, { maxTokens });
16478
+ const emptyMessage = messages.length === 0 ? pageIndex > 0 ? `(no messages found on page ${normalizedPage} for this thread)` : "(no messages in this thread)" : partType || toolName ? "(no message parts matched the current filters)" : "(no messages found)";
16134
16479
  return {
16135
- messages: rendered.text || "(no messages in this thread)",
16480
+ messages: rendered.text || emptyMessage,
16136
16481
  count: messages.length,
16137
16482
  cursor: messages[0]?.id || "",
16138
16483
  page: normalizedPage,
16139
16484
  limit: normalizedLimit,
16140
16485
  detail,
16141
- hasNextPage: hasMore,
16142
- hasPrevPage: pageIndex > 0,
16486
+ hasNextPage,
16487
+ hasPrevPage,
16143
16488
  truncated: rendered.truncated,
16144
16489
  tokenOffset: rendered.tokenOffset
16145
16490
  };
@@ -16147,7 +16492,7 @@ async function recallThreadFromStart({
16147
16492
  var recallTool = (_memoryConfig, options) => {
16148
16493
  const retrievalScope = options?.retrievalScope ?? "thread";
16149
16494
  const isResourceScope = retrievalScope === "resource";
16150
- const description = isResourceScope ? 'Browse conversation history. Use mode="threads" to list all threads for the current user. Use mode="messages" (default) to browse messages in the current thread or pass threadId to browse another thread in the active resource. If you pass only a cursor, it must belong to the current thread. Use mode="search" to find messages by content across all threads.' : `Browse conversation history in the current thread. Use mode="messages" (default) to page through messages near a cursor. Use mode="search" to find messages by content in this thread. Use mode="threads" to get the current thread's ID and title.`;
16495
+ const description = isResourceScope ? 'Browse conversation history. Use mode="threads" to list all threads for the current user. Use mode="messages" (default) to browse messages in the current thread or pass threadId to browse another thread in the active resource. When mode="messages" has no cursor or threadId, it defaults to the current thread and says so at the top of the result. If you pass only a cursor, it must belong to the current thread. Use mode="search" to find messages by content across all threads.' : `Browse conversation history in the current thread. Use mode="messages" (default) to page through messages near a cursor. Use mode="search" to find messages by content in this thread. Use mode="threads" to get the current thread's ID and title.`;
16151
16496
  return tools.createTool({
16152
16497
  id: "recall",
16153
16498
  description,
@@ -16156,7 +16501,9 @@ var recallTool = (_memoryConfig, options) => {
16156
16501
  mode: zod.z.enum(["messages", "threads", "search"]).optional().describe(
16157
16502
  'What to retrieve. "messages" (default) pages through message history. "threads" lists all threads for the current user. "search" finds messages by semantic similarity across all threads.'
16158
16503
  ),
16159
- threadId: zod.z.string().min(1).optional().describe('Browse a different thread. Use mode="threads" first to discover thread IDs.'),
16504
+ threadId: zod.z.string().min(1).optional().describe(
16505
+ 'Browse a different thread, or use "current" for the active thread. Use mode="threads" first to discover thread IDs.'
16506
+ ),
16160
16507
  before: zod.z.string().optional().describe(
16161
16508
  'For mode="threads": only show threads created before this date. ISO 8601 or natural date string (e.g. "2026-03-15", "2026-03-10T00:00:00Z").'
16162
16509
  ),
@@ -16170,7 +16517,10 @@ var recallTool = (_memoryConfig, options) => {
16170
16517
  },
16171
16518
  query: zod.z.string().min(1).optional().describe('Search query for mode="search". Finds messages semantically similar to this text.'),
16172
16519
  cursor: zod.z.string().min(1).optional().describe(
16173
- 'A message ID to use as the pagination cursor. For mode="messages", provide either cursor or threadId. If only cursor is provided, it must belong to the current thread. Extract it from the start or end of an observation group range.'
16520
+ 'A message ID to use as the pagination cursor. For mode="messages", omit both cursor and threadId to browse the current thread. If only cursor is provided, it must belong to the current thread. Extract it from the start or end of an observation group range.'
16521
+ ),
16522
+ anchor: zod.z.enum(["start", "end"]).optional().describe(
16523
+ 'For mode="messages" without a cursor, page from the start (oldest-first) or end (newest-first) of the thread. Defaults to "start".'
16174
16524
  ),
16175
16525
  page: zod.z.number().int().min(-50).max(50).optional().describe(
16176
16526
  "Pagination offset. For messages: positive pages move forward from cursor, negative move backward. For threads: page number (0-indexed). 0 is treated as 1 for messages."
@@ -16179,6 +16529,10 @@ var recallTool = (_memoryConfig, options) => {
16179
16529
  detail: zod.z.enum(["low", "high"]).optional().describe(
16180
16530
  'Detail level for messages. "low" (default) returns truncated text and tool names. "high" returns full content with tool args/results.'
16181
16531
  ),
16532
+ partType: zod.z.enum(["text", "tool-call", "tool-result", "reasoning", "image", "file"]).optional().describe('Filter results to only include parts of this type. Only applies to mode="messages".'),
16533
+ toolName: zod.z.string().min(1).optional().describe(
16534
+ 'Filter results to only include tool-call and tool-result parts matching this tool name. Only applies to mode="messages".'
16535
+ ),
16182
16536
  partIndex: zod.z.number().int().min(0).optional().describe(
16183
16537
  "Fetch a single part from the cursor message by its positional index. When provided, returns only that part at high detail. Indices are shown as [p0], [p1], etc. in recall results."
16184
16538
  )
@@ -16188,9 +16542,12 @@ var recallTool = (_memoryConfig, options) => {
16188
16542
  query,
16189
16543
  cursor,
16190
16544
  threadId: explicitThreadId,
16545
+ anchor,
16191
16546
  page,
16192
16547
  limit,
16193
16548
  detail,
16549
+ partType,
16550
+ toolName,
16194
16551
  partIndex,
16195
16552
  before,
16196
16553
  after
@@ -16198,9 +16555,13 @@ var recallTool = (_memoryConfig, options) => {
16198
16555
  const memory = context2?.memory;
16199
16556
  const currentThreadId = context2?.agent?.threadId;
16200
16557
  const resourceId = context2?.agent?.resourceId;
16558
+ const resolvedExplicitThreadId = explicitThreadId === "current" ? currentThreadId : explicitThreadId;
16201
16559
  if (!memory) {
16202
16560
  throw new Error("Memory instance is required for recall");
16203
16561
  }
16562
+ if (explicitThreadId === "current" && !currentThreadId) {
16563
+ throw new Error("Could not resolve current thread.");
16564
+ }
16204
16565
  if (mode === "search") {
16205
16566
  if (!query) {
16206
16567
  throw new Error('query is required for mode="search"');
@@ -16216,11 +16577,12 @@ var recallTool = (_memoryConfig, options) => {
16216
16577
  topK: limit ?? 10,
16217
16578
  before,
16218
16579
  after,
16219
- threadScope: !isResourceScope ? currentThreadId || void 0 : void 0
16580
+ threadScope: !isResourceScope ? currentThreadId || void 0 : resolvedExplicitThreadId || void 0
16220
16581
  });
16221
16582
  }
16222
16583
  if (mode === "threads") {
16223
- if (!isResourceScope) {
16584
+ const requestedCurrentThread = explicitThreadId === "current";
16585
+ if (!isResourceScope || requestedCurrentThread) {
16224
16586
  if (!currentThreadId || !memory.getThreadById) {
16225
16587
  return { error: "Could not resolve current thread." };
16226
16588
  }
@@ -16228,6 +16590,9 @@ var recallTool = (_memoryConfig, options) => {
16228
16590
  if (!thread) {
16229
16591
  return { error: "Could not resolve current thread." };
16230
16592
  }
16593
+ if (isResourceScope && resourceId && thread.resourceId !== resourceId) {
16594
+ throw new Error("Thread does not belong to the active resource");
16595
+ }
16231
16596
  return {
16232
16597
  threads: `- **${thread.title || "(untitled)"}** \u2190 current
16233
16598
  id: ${thread.id}
@@ -16250,7 +16615,13 @@ var recallTool = (_memoryConfig, options) => {
16250
16615
  after
16251
16616
  });
16252
16617
  }
16253
- const hasExplicitThreadId = typeof explicitThreadId === "string" && explicitThreadId.length > 0;
16618
+ const usedDefaultThreadId = isResourceScope && !explicitThreadId && !cursor && Boolean(currentThreadId);
16619
+ const defaultThreadNote = usedDefaultThreadId ? `threadId wasn't passed so used default ${currentThreadId}.
16620
+
16621
+ ` : "";
16622
+ const effectiveThreadId = explicitThreadId || (usedDefaultThreadId ? "current" : void 0);
16623
+ const resolvedThreadId = effectiveThreadId === "current" ? currentThreadId : effectiveThreadId;
16624
+ const hasExplicitThreadId = typeof resolvedThreadId === "string" && resolvedThreadId.length > 0;
16254
16625
  const hasCursor = typeof cursor === "string" && cursor.length > 0;
16255
16626
  if (!hasExplicitThreadId && !hasCursor) {
16256
16627
  throw new Error('Either cursor or threadId is required for mode="messages"');
@@ -16267,7 +16638,7 @@ var recallTool = (_memoryConfig, options) => {
16267
16638
  if (!memory.getThreadById) {
16268
16639
  throw new Error("Memory instance cannot verify thread access for recall");
16269
16640
  }
16270
- const thread = await memory.getThreadById({ threadId: explicitThreadId });
16641
+ const thread = await memory.getThreadById({ threadId: resolvedThreadId });
16271
16642
  if (!thread || thread.resourceId !== resourceId) {
16272
16643
  throw new Error("Thread does not belong to the active resource");
16273
16644
  }
@@ -16302,14 +16673,21 @@ var recallTool = (_memoryConfig, options) => {
16302
16673
  throw new Error("Thread ID is required for recall");
16303
16674
  }
16304
16675
  if (!cursor) {
16305
- return recallThreadFromStart({
16676
+ const result = await recallThreadFromStart({
16306
16677
  memory,
16307
16678
  threadId: targetThreadId,
16308
16679
  resourceId: isResourceScope ? resourceId : void 0,
16309
16680
  page: page ?? 1,
16310
16681
  limit: limit ?? 20,
16311
- detail: detail ?? "low"
16682
+ detail: detail ?? "low",
16683
+ partType,
16684
+ toolName,
16685
+ anchor: anchor ?? "start"
16312
16686
  });
16687
+ if (defaultThreadNote) {
16688
+ return { ...result, messages: `${defaultThreadNote}${result.messages}` };
16689
+ }
16690
+ return result;
16313
16691
  }
16314
16692
  if (partIndex !== void 0 && partIndex !== null) {
16315
16693
  return recallPart({
@@ -16329,6 +16707,8 @@ var recallTool = (_memoryConfig, options) => {
16329
16707
  page,
16330
16708
  limit,
16331
16709
  detail: detail ?? "low",
16710
+ partType,
16711
+ toolName,
16332
16712
  threadScope
16333
16713
  });
16334
16714
  }
@@ -16360,6 +16740,25 @@ function deepMergeWorkingMemory(existing, update) {
16360
16740
  }
16361
16741
  return result;
16362
16742
  }
16743
+ function stripNullsFromOptional(value, schema) {
16744
+ if (Array.isArray(value)) {
16745
+ const itemSchema = schema.items ?? {};
16746
+ return value.map((item) => stripNullsFromOptional(item, itemSchema));
16747
+ }
16748
+ if (typeof value === "object" && value !== null) {
16749
+ const properties = schema.properties ?? {};
16750
+ const required = schema.required ?? [];
16751
+ const result = {};
16752
+ for (const [key, propertyValue] of Object.entries(value)) {
16753
+ if (propertyValue === null && !required.includes(key)) {
16754
+ continue;
16755
+ }
16756
+ result[key] = stripNullsFromOptional(propertyValue, properties[key] ?? {});
16757
+ }
16758
+ return result;
16759
+ }
16760
+ return value;
16761
+ }
16363
16762
  var updateWorkingMemoryTool = (memoryConfig) => {
16364
16763
  const schema$2 = memoryConfig?.workingMemory?.schema;
16365
16764
  let inputSchema = zod.z.object({
@@ -16369,7 +16768,7 @@ var updateWorkingMemoryTool = (memoryConfig) => {
16369
16768
  const standardSchema2 = schema$1.isStandardSchemaWithJSON(schema$2) ? schema$2 : schema$1.toStandardSchema(schema$2);
16370
16769
  const jsonSchema4 = schema.standardSchemaToJSONSchema(standardSchema2, { io: "input" });
16371
16770
  delete jsonSchema4.$schema;
16372
- inputSchema = schema$1.toStandardSchema({
16771
+ const wrappedSchema = schema$1.toStandardSchema({
16373
16772
  $schema: "http://json-schema.org/draft-07/schema#",
16374
16773
  type: "object",
16375
16774
  description: "The JSON formatted working memory content to store.",
@@ -16378,6 +16777,41 @@ var updateWorkingMemoryTool = (memoryConfig) => {
16378
16777
  },
16379
16778
  required: ["memory"]
16380
16779
  });
16780
+ inputSchema = {
16781
+ "~standard": {
16782
+ version: 1,
16783
+ vendor: "mastra",
16784
+ validate: (value) => {
16785
+ const wrappedResult = wrappedSchema["~standard"].validate(value);
16786
+ if (wrappedResult instanceof Promise) {
16787
+ return wrappedResult.then((result) => {
16788
+ if (!("issues" in result) || !result.issues) {
16789
+ return result;
16790
+ }
16791
+ if (!value || typeof value !== "object" || Array.isArray(value) || "memory" in value) {
16792
+ return result;
16793
+ }
16794
+ return wrappedSchema["~standard"].validate({
16795
+ memory: stripNullsFromOptional(value, jsonSchema4)
16796
+ });
16797
+ });
16798
+ }
16799
+ if (!("issues" in wrappedResult) || !wrappedResult.issues) {
16800
+ return wrappedResult;
16801
+ }
16802
+ if (!value || typeof value !== "object" || Array.isArray(value) || "memory" in value) {
16803
+ return wrappedResult;
16804
+ }
16805
+ return wrappedSchema["~standard"].validate({
16806
+ memory: stripNullsFromOptional(value, jsonSchema4)
16807
+ });
16808
+ },
16809
+ jsonSchema: {
16810
+ input: (props) => wrappedSchema["~standard"].jsonSchema.input(props),
16811
+ output: (props) => wrappedSchema["~standard"].jsonSchema.output(props)
16812
+ }
16813
+ }
16814
+ };
16381
16815
  }
16382
16816
  const usesMergeSemantics = Boolean(schema$2);
16383
16817
  const description = schema$2 ? `Update the working memory with new information. Data is merged with existing memory - only include fields you want to add or update. To preserve existing data, omit the field entirely. Arrays are replaced entirely when provided, so pass the complete array or omit it to keep the existing values.` : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`;
@@ -16549,6 +16983,69 @@ var __experimental_updateWorkingMemoryToolVNext = (config) => {
16549
16983
  }
16550
16984
  });
16551
16985
  };
16986
+ var WORKING_MEMORY_START_TAG = "<working_memory>";
16987
+ var WORKING_MEMORY_END_TAG = "</working_memory>";
16988
+ var LEGACY_SYSTEM_REMINDER_METADATA_KEY = "dynamicAgentsMdReminder";
16989
+ function isRecord(value) {
16990
+ return typeof value === "object" && value !== null;
16991
+ }
16992
+ function extractWorkingMemoryTags(text4) {
16993
+ const results = [];
16994
+ let pos = 0;
16995
+ while (pos < text4.length) {
16996
+ const start = text4.indexOf(WORKING_MEMORY_START_TAG, pos);
16997
+ if (start === -1) break;
16998
+ const end = text4.indexOf(WORKING_MEMORY_END_TAG, start + WORKING_MEMORY_START_TAG.length);
16999
+ if (end === -1) break;
17000
+ results.push(text4.substring(start, end + WORKING_MEMORY_END_TAG.length));
17001
+ pos = end + WORKING_MEMORY_END_TAG.length;
17002
+ }
17003
+ return results.length > 0 ? results : null;
17004
+ }
17005
+ function removeWorkingMemoryTags(text4) {
17006
+ let result = "";
17007
+ let pos = 0;
17008
+ while (pos < text4.length) {
17009
+ const start = text4.indexOf(WORKING_MEMORY_START_TAG, pos);
17010
+ if (start === -1) {
17011
+ result += text4.substring(pos);
17012
+ break;
17013
+ }
17014
+ result += text4.substring(pos, start);
17015
+ const end = text4.indexOf(WORKING_MEMORY_END_TAG, start + WORKING_MEMORY_START_TAG.length);
17016
+ if (end === -1) {
17017
+ result += text4.substring(start);
17018
+ break;
17019
+ }
17020
+ pos = end + WORKING_MEMORY_END_TAG.length;
17021
+ }
17022
+ return result;
17023
+ }
17024
+ function extractWorkingMemoryContent(text4) {
17025
+ const start = text4.indexOf(WORKING_MEMORY_START_TAG);
17026
+ if (start === -1) return null;
17027
+ const contentStart = start + WORKING_MEMORY_START_TAG.length;
17028
+ const end = text4.indexOf(WORKING_MEMORY_END_TAG, contentStart);
17029
+ if (end === -1) return null;
17030
+ return text4.substring(contentStart, end);
17031
+ }
17032
+ function isSystemReminderMessage(message) {
17033
+ if (message.role !== "user" || !isRecord(message.content)) {
17034
+ return false;
17035
+ }
17036
+ const metadata = message.content.metadata;
17037
+ if (isRecord(metadata) && (isRecord(metadata.systemReminder) || LEGACY_SYSTEM_REMINDER_METADATA_KEY in metadata)) {
17038
+ return true;
17039
+ }
17040
+ const firstTextPart = message.content.parts.find((part) => part.type === "text");
17041
+ return typeof firstTextPart?.text === "string" && firstTextPart.text.startsWith("<system-reminder");
17042
+ }
17043
+ function filterSystemReminderMessages(messages, includeSystemReminders) {
17044
+ if (includeSystemReminders) {
17045
+ return messages;
17046
+ }
17047
+ return messages.filter((message) => !isSystemReminderMessage(message));
17048
+ }
16552
17049
  function normalizeObservationalMemoryConfig(config) {
16553
17050
  if (config === true) return { model: "google/gemini-2.5-flash" };
16554
17051
  if (config === false || config === void 0) return void 0;
@@ -16621,94 +17118,149 @@ var Memory = class extends memory.MastraMemory {
16621
17118
  );
16622
17119
  }
16623
17120
  }
17121
+ createMemorySpan(operationType, observabilityContext, input, attributes) {
17122
+ const currentSpan = observabilityContext?.tracingContext?.currentSpan;
17123
+ if (!currentSpan) return void 0;
17124
+ return currentSpan.createChildSpan({
17125
+ type: observability.SpanType.MEMORY_OPERATION,
17126
+ name: `memory: ${operationType}`,
17127
+ entityType: observability.EntityType.MEMORY,
17128
+ entityName: "Memory",
17129
+ input,
17130
+ attributes: { operationType, ...attributes }
17131
+ });
17132
+ }
16624
17133
  async recall(args) {
16625
- const { threadId, resourceId, perPage: perPageArg, page, orderBy, threadConfig, vectorSearchString, filter: filter3 } = args;
16626
- const config = this.getMergedThreadConfig(threadConfig || {});
16627
- if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId, config);
16628
- const perPage = perPageArg !== void 0 ? perPageArg : config.lastMessages;
16629
- const historyDisabledByConfig = config.lastMessages === false && perPageArg === void 0;
16630
- const shouldGetNewestAndReverse = !orderBy && perPage !== false;
16631
- const effectiveOrderBy = shouldGetNewestAndReverse ? { field: "createdAt", direction: "DESC" } : orderBy;
16632
- const vectorResults = [];
16633
- this.logger.debug("Memory recall", {
17134
+ const {
16634
17135
  threadId,
16635
- perPage,
17136
+ resourceId,
17137
+ perPage: perPageArg,
16636
17138
  page,
16637
- orderBy: effectiveOrderBy,
16638
- hasWorkingMemorySchema: Boolean(config.workingMemory?.schema),
16639
- workingMemoryEnabled: config.workingMemory?.enabled,
16640
- semanticRecallEnabled: Boolean(config.semanticRecall),
16641
- historyDisabledByConfig
16642
- });
16643
- const defaultRange = DEFAULT_MESSAGE_RANGE;
16644
- const defaultTopK = DEFAULT_TOP_K;
16645
- const vectorConfig = typeof config?.semanticRecall === `boolean` ? {
16646
- topK: defaultTopK,
16647
- messageRange: defaultRange
16648
- } : {
16649
- topK: config?.semanticRecall?.topK ?? defaultTopK,
16650
- messageRange: config?.semanticRecall?.messageRange ?? defaultRange
16651
- };
16652
- const resourceScope = typeof config?.semanticRecall === "object" && config?.semanticRecall?.scope !== `thread` || config.semanticRecall === true;
16653
- if (resourceScope && !resourceId && config?.semanticRecall && vectorSearchString) {
16654
- throw new Error(
16655
- `Memory error: Resource-scoped semantic recall is enabled but no resourceId was provided. Either provide a resourceId or explicitly set semanticRecall.scope to 'thread'.`
16656
- );
16657
- }
16658
- let usage;
16659
- if (historyDisabledByConfig && (!config.semanticRecall || !vectorSearchString || !this.vector)) {
16660
- return { messages: [], usage: void 0, total: 0, page: page ?? 0, perPage: 0, hasMore: false };
16661
- }
16662
- if (config?.semanticRecall && vectorSearchString && this.vector) {
16663
- const result = await this.embedMessageContent(vectorSearchString);
16664
- usage = result.usage;
16665
- const { embeddings, dimension } = result;
16666
- const { indexName } = await this.createEmbeddingIndex(dimension, config);
16667
- await Promise.all(
16668
- embeddings.map(async (embedding) => {
16669
- if (typeof this.vector === `undefined`) {
16670
- throw new Error(
16671
- `Tried to query vector index ${indexName} but this Memory instance doesn't have an attached vector db.`
17139
+ orderBy,
17140
+ threadConfig,
17141
+ vectorSearchString,
17142
+ includeSystemReminders,
17143
+ filter: filter3
17144
+ } = args;
17145
+ const config = this.getMergedThreadConfig(threadConfig || {});
17146
+ const semanticRecallEnabled = Boolean(config.semanticRecall);
17147
+ const span = this.createMemorySpan(
17148
+ "recall",
17149
+ args.observabilityContext,
17150
+ { threadId, resourceId, vectorSearchString },
17151
+ {
17152
+ semanticRecallEnabled,
17153
+ lastMessages: config.lastMessages
17154
+ }
17155
+ );
17156
+ try {
17157
+ if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId, config);
17158
+ const perPage = perPageArg !== void 0 ? perPageArg : config.lastMessages;
17159
+ const historyDisabledByConfig = config.lastMessages === false && perPageArg === void 0;
17160
+ const shouldGetNewestAndReverse = !orderBy && perPage !== false;
17161
+ const effectiveOrderBy = shouldGetNewestAndReverse ? { field: "createdAt", direction: "DESC" } : orderBy;
17162
+ const vectorResults = [];
17163
+ this.logger.debug("Memory recall", {
17164
+ threadId,
17165
+ perPage,
17166
+ page,
17167
+ orderBy: effectiveOrderBy,
17168
+ hasWorkingMemorySchema: Boolean(config.workingMemory?.schema),
17169
+ workingMemoryEnabled: config.workingMemory?.enabled,
17170
+ semanticRecallEnabled,
17171
+ historyDisabledByConfig
17172
+ });
17173
+ const defaultRange = DEFAULT_MESSAGE_RANGE;
17174
+ const defaultTopK = DEFAULT_TOP_K;
17175
+ const vectorConfig = typeof config?.semanticRecall === `boolean` ? {
17176
+ topK: defaultTopK,
17177
+ messageRange: defaultRange
17178
+ } : {
17179
+ topK: config?.semanticRecall?.topK ?? defaultTopK,
17180
+ messageRange: config?.semanticRecall?.messageRange ?? defaultRange
17181
+ };
17182
+ const resourceScope = typeof config?.semanticRecall === "object" && config?.semanticRecall?.scope !== `thread` || config.semanticRecall === true;
17183
+ if (resourceScope && !resourceId && config?.semanticRecall && vectorSearchString) {
17184
+ throw new Error(
17185
+ `Memory error: Resource-scoped semantic recall is enabled but no resourceId was provided. Either provide a resourceId or explicitly set semanticRecall.scope to 'thread'.`
17186
+ );
17187
+ }
17188
+ let usage;
17189
+ if (historyDisabledByConfig && (!config.semanticRecall || !vectorSearchString || !this.vector)) {
17190
+ const result = {
17191
+ messages: [],
17192
+ usage: void 0,
17193
+ total: 0,
17194
+ page: page ?? 0,
17195
+ perPage: 0,
17196
+ hasMore: false
17197
+ };
17198
+ span?.end({ output: { success: true }, attributes: { messageCount: 0 } });
17199
+ return result;
17200
+ }
17201
+ if (config?.semanticRecall && vectorSearchString && this.vector) {
17202
+ const result = await this.embedMessageContent(vectorSearchString);
17203
+ usage = result.usage;
17204
+ const { embeddings, dimension } = result;
17205
+ const { indexName } = await this.createEmbeddingIndex(dimension, config);
17206
+ await Promise.all(
17207
+ embeddings.map(async (embedding) => {
17208
+ if (typeof this.vector === `undefined`) {
17209
+ throw new Error(
17210
+ `Tried to query vector index ${indexName} but this Memory instance doesn't have an attached vector db.`
17211
+ );
17212
+ }
17213
+ vectorResults.push(
17214
+ ...await this.vector.query({
17215
+ indexName,
17216
+ queryVector: embedding,
17217
+ topK: vectorConfig.topK,
17218
+ filter: resourceScope ? {
17219
+ resource_id: resourceId
17220
+ } : {
17221
+ thread_id: threadId
17222
+ }
17223
+ })
16672
17224
  );
16673
- }
16674
- vectorResults.push(
16675
- ...await this.vector.query({
16676
- indexName,
16677
- queryVector: embedding,
16678
- topK: vectorConfig.topK,
16679
- filter: resourceScope ? {
16680
- resource_id: resourceId
16681
- } : {
16682
- thread_id: threadId
16683
- }
16684
- })
16685
- );
16686
- })
16687
- );
17225
+ })
17226
+ );
17227
+ }
17228
+ const memoryStore = await this.getMemoryStore();
17229
+ const effectivePerPage = historyDisabledByConfig ? 0 : perPage;
17230
+ const paginatedResult = await memoryStore.listMessages({
17231
+ threadId,
17232
+ resourceId,
17233
+ perPage: effectivePerPage,
17234
+ page,
17235
+ orderBy: effectiveOrderBy,
17236
+ filter: filter3,
17237
+ ...vectorResults?.length ? {
17238
+ include: vectorResults.map((r) => ({
17239
+ id: r.metadata?.message_id,
17240
+ threadId: r.metadata?.thread_id,
17241
+ withNextMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.after,
17242
+ withPreviousMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.before
17243
+ }))
17244
+ } : {}
17245
+ });
17246
+ const rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;
17247
+ const list = new agent.MessageList({ threadId, resourceId }).add(rawMessages, "memory");
17248
+ const messages = filterSystemReminderMessages(list.get.all.db(), includeSystemReminders);
17249
+ const { total, page: resultPage, perPage: resultPerPage, hasMore } = paginatedResult;
17250
+ const recallResult = { messages, usage, total, page: resultPage, perPage: resultPerPage, hasMore };
17251
+ span?.end({
17252
+ output: { success: true },
17253
+ attributes: {
17254
+ messageCount: messages.length,
17255
+ embeddingTokens: usage?.tokens,
17256
+ vectorResultCount: vectorResults.length
17257
+ }
17258
+ });
17259
+ return recallResult;
17260
+ } catch (error) {
17261
+ span?.error({ error, endSpan: true });
17262
+ throw error;
16688
17263
  }
16689
- const memoryStore = await this.getMemoryStore();
16690
- const effectivePerPage = historyDisabledByConfig ? 0 : perPage;
16691
- const paginatedResult = await memoryStore.listMessages({
16692
- threadId,
16693
- resourceId,
16694
- perPage: effectivePerPage,
16695
- page,
16696
- orderBy: effectiveOrderBy,
16697
- filter: filter3,
16698
- ...vectorResults?.length ? {
16699
- include: vectorResults.map((r) => ({
16700
- id: r.metadata?.message_id,
16701
- threadId: r.metadata?.thread_id,
16702
- withNextMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.after,
16703
- withPreviousMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.before
16704
- }))
16705
- } : {}
16706
- });
16707
- const rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;
16708
- const list = new agent.MessageList({ threadId, resourceId }).add(rawMessages, "memory");
16709
- const messages = list.get.all.db();
16710
- const { total, page: resultPage, perPage: resultPerPage, hasMore } = paginatedResult;
16711
- return { messages, usage, total, page: resultPage, perPage: resultPerPage, hasMore };
16712
17264
  }
16713
17265
  async getThreadById({ threadId }) {
16714
17266
  const memoryStore = await this.getMemoryStore();
@@ -16818,45 +17370,60 @@ var Memory = class extends memory.MastraMemory {
16818
17370
  threadId,
16819
17371
  resourceId,
16820
17372
  workingMemory,
16821
- memoryConfig
17373
+ memoryConfig,
17374
+ observabilityContext
16822
17375
  }) {
16823
17376
  const config = this.getMergedThreadConfig(memoryConfig || {});
16824
17377
  if (!config.workingMemory?.enabled) {
16825
17378
  throw new Error("Working memory is not enabled for this memory instance");
16826
17379
  }
16827
- const scope = config.workingMemory.scope || "resource";
16828
- if (scope === "resource" && !resourceId) {
16829
- throw new Error(
16830
- `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`
16831
- );
16832
- }
16833
- const mutexKey = scope === "resource" ? `resource-${resourceId}` : `thread-${threadId}`;
16834
- const mutex = this.updateWorkingMemoryMutexes.has(mutexKey) ? this.updateWorkingMemoryMutexes.get(mutexKey) : new asyncMutex.Mutex();
16835
- this.updateWorkingMemoryMutexes.set(mutexKey, mutex);
16836
- const release = await mutex.acquire();
17380
+ const span = this.createMemorySpan(
17381
+ "update",
17382
+ observabilityContext,
17383
+ { threadId, resourceId },
17384
+ {
17385
+ workingMemoryEnabled: true
17386
+ }
17387
+ );
16837
17388
  try {
16838
- const memoryStore = await this.getMemoryStore();
16839
- if (scope === "resource" && resourceId) {
16840
- await memoryStore.updateResource({
16841
- resourceId,
16842
- workingMemory
16843
- });
16844
- } else {
16845
- const thread = await this.getThreadById({ threadId });
16846
- if (!thread) {
16847
- throw new Error(`Thread ${threadId} not found`);
16848
- }
16849
- await memoryStore.updateThread({
16850
- id: threadId,
16851
- title: thread.title || "",
16852
- metadata: {
16853
- ...thread.metadata,
17389
+ const scope = config.workingMemory.scope || "resource";
17390
+ if (scope === "resource" && !resourceId) {
17391
+ throw new Error(
17392
+ `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`
17393
+ );
17394
+ }
17395
+ const mutexKey = scope === "resource" ? `resource-${resourceId}` : `thread-${threadId}`;
17396
+ const mutex = this.updateWorkingMemoryMutexes.has(mutexKey) ? this.updateWorkingMemoryMutexes.get(mutexKey) : new asyncMutex.Mutex();
17397
+ this.updateWorkingMemoryMutexes.set(mutexKey, mutex);
17398
+ const release = await mutex.acquire();
17399
+ try {
17400
+ const memoryStore = await this.getMemoryStore();
17401
+ if (scope === "resource" && resourceId) {
17402
+ await memoryStore.updateResource({
17403
+ resourceId,
16854
17404
  workingMemory
17405
+ });
17406
+ } else {
17407
+ const thread = await this.getThreadById({ threadId });
17408
+ if (!thread) {
17409
+ throw new Error(`Thread ${threadId} not found`);
16855
17410
  }
16856
- });
17411
+ await memoryStore.updateThread({
17412
+ id: threadId,
17413
+ title: thread.title || "",
17414
+ metadata: {
17415
+ ...thread.metadata,
17416
+ workingMemory
17417
+ }
17418
+ });
17419
+ }
17420
+ } finally {
17421
+ release();
16857
17422
  }
16858
- } finally {
16859
- release();
17423
+ span?.end({ output: { success: true } });
17424
+ } catch (error) {
17425
+ span?.error({ error, endSpan: true });
17426
+ throw error;
16860
17427
  }
16861
17428
  }
16862
17429
  updateWorkingMemoryMutexes = /* @__PURE__ */ new Map();
@@ -17034,67 +17601,85 @@ ${workingMemory}`;
17034
17601
  }
17035
17602
  async saveMessages({
17036
17603
  messages,
17037
- memoryConfig
17604
+ memoryConfig,
17605
+ observabilityContext
17038
17606
  }) {
17039
- const updatedMessages = messages.map((m) => {
17040
- return this.updateMessageToHideWorkingMemoryV2(m);
17041
- }).filter((m) => Boolean(m));
17042
- const config = this.getMergedThreadConfig(memoryConfig);
17043
- const dbMessages = new agent.MessageList({
17044
- generateMessageId: () => this.generateId()
17045
- }).add(updatedMessages, "memory").get.all.db();
17046
- const memoryStore = await this.getMemoryStore();
17047
- const result = await memoryStore.saveMessages({
17048
- messages: dbMessages
17607
+ const span = this.createMemorySpan("save", observabilityContext, void 0, {
17608
+ messageCount: messages.length
17049
17609
  });
17050
- let totalTokens = 0;
17051
- if (this.vector && config.semanticRecall) {
17052
- const embeddingData = [];
17053
- let dimension;
17054
- await Promise.all(
17055
- updatedMessages.map(async (message) => {
17056
- let textForEmbedding = null;
17057
- if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") {
17058
- textForEmbedding = message.content.content;
17059
- } else if (message.content.parts && message.content.parts.length > 0) {
17060
- const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
17061
- if (joined) textForEmbedding = joined;
17610
+ try {
17611
+ const updatedMessages = messages.map((m) => {
17612
+ return this.updateMessageToHideWorkingMemoryV2(m);
17613
+ }).filter((m) => Boolean(m));
17614
+ const config = this.getMergedThreadConfig(memoryConfig);
17615
+ const dbMessages = new agent.MessageList({
17616
+ generateMessageId: () => this.generateId()
17617
+ }).add(updatedMessages, "memory").get.all.db();
17618
+ const memoryStore = await this.getMemoryStore();
17619
+ const result = await memoryStore.saveMessages({
17620
+ messages: dbMessages
17621
+ });
17622
+ let totalTokens = 0;
17623
+ if (this.vector && config.semanticRecall) {
17624
+ const embeddingData = [];
17625
+ let dimension;
17626
+ await Promise.all(
17627
+ updatedMessages.map(async (message) => {
17628
+ let textForEmbedding = null;
17629
+ if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") {
17630
+ textForEmbedding = message.content.content;
17631
+ } else if (message.content.parts && message.content.parts.length > 0) {
17632
+ const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
17633
+ if (joined) textForEmbedding = joined;
17634
+ }
17635
+ if (!textForEmbedding) return;
17636
+ const result2 = await this.embedMessageContent(textForEmbedding);
17637
+ dimension = result2.dimension;
17638
+ if (result2.usage?.tokens) {
17639
+ totalTokens += result2.usage.tokens;
17640
+ }
17641
+ embeddingData.push({
17642
+ embeddings: result2.embeddings,
17643
+ metadata: result2.chunks.map(() => ({
17644
+ message_id: message.id,
17645
+ thread_id: message.threadId,
17646
+ resource_id: message.resourceId
17647
+ }))
17648
+ });
17649
+ })
17650
+ );
17651
+ if (embeddingData.length > 0 && dimension !== void 0) {
17652
+ if (typeof this.vector === `undefined`) {
17653
+ throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);
17062
17654
  }
17063
- if (!textForEmbedding) return;
17064
- const result2 = await this.embedMessageContent(textForEmbedding);
17065
- dimension = result2.dimension;
17066
- if (result2.usage?.tokens) {
17067
- totalTokens += result2.usage.tokens;
17655
+ const { indexName } = await this.createEmbeddingIndex(dimension, config);
17656
+ const allVectors = [];
17657
+ const allMetadata = [];
17658
+ for (const data of embeddingData) {
17659
+ allVectors.push(...data.embeddings);
17660
+ allMetadata.push(...data.metadata);
17068
17661
  }
17069
- embeddingData.push({
17070
- embeddings: result2.embeddings,
17071
- metadata: result2.chunks.map(() => ({
17072
- message_id: message.id,
17073
- thread_id: message.threadId,
17074
- resource_id: message.resourceId
17075
- }))
17662
+ await this.vector.upsert({
17663
+ indexName,
17664
+ vectors: allVectors,
17665
+ metadata: allMetadata
17076
17666
  });
17077
- })
17078
- );
17079
- if (embeddingData.length > 0 && dimension !== void 0) {
17080
- if (typeof this.vector === `undefined`) {
17081
- throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);
17082
17667
  }
17083
- const { indexName } = await this.createEmbeddingIndex(dimension, config);
17084
- const allVectors = [];
17085
- const allMetadata = [];
17086
- for (const data of embeddingData) {
17087
- allVectors.push(...data.embeddings);
17088
- allMetadata.push(...data.metadata);
17089
- }
17090
- await this.vector.upsert({
17091
- indexName,
17092
- vectors: allVectors,
17093
- metadata: allMetadata
17094
- });
17095
17668
  }
17669
+ const saveResult = { ...result, usage: totalTokens > 0 ? { tokens: totalTokens } : void 0 };
17670
+ span?.end({
17671
+ output: { success: true },
17672
+ attributes: {
17673
+ messageCount: dbMessages.length,
17674
+ embeddingTokens: saveResult.usage?.tokens,
17675
+ semanticRecallEnabled: Boolean(config.semanticRecall)
17676
+ }
17677
+ });
17678
+ return saveResult;
17679
+ } catch (error) {
17680
+ span?.error({ error, endSpan: true });
17681
+ throw error;
17096
17682
  }
17097
- return { ...result, usage: totalTokens > 0 ? { tokens: totalTokens } : void 0 };
17098
17683
  }
17099
17684
  updateMessageToHideWorkingMemoryV2(message) {
17100
17685
  const newMessage = { ...message };
@@ -17102,7 +17687,7 @@ ${workingMemory}`;
17102
17687
  newMessage.content = { ...message.content };
17103
17688
  }
17104
17689
  if (typeof newMessage.content?.content === "string" && newMessage.content.content.length > 0) {
17105
- newMessage.content.content = memory.removeWorkingMemoryTags(newMessage.content.content).trim();
17690
+ newMessage.content.content = removeWorkingMemoryTags(newMessage.content.content).trim();
17106
17691
  }
17107
17692
  if (Array.isArray(newMessage.content?.parts)) {
17108
17693
  newMessage.content.parts = newMessage.content.parts.filter((part) => {
@@ -17115,7 +17700,7 @@ ${workingMemory}`;
17115
17700
  const text4 = typeof part.text === "string" ? part.text : "";
17116
17701
  return {
17117
17702
  ...part,
17118
- text: memory.removeWorkingMemoryTags(text4).trim()
17703
+ text: removeWorkingMemoryTags(text4).trim()
17119
17704
  };
17120
17705
  }
17121
17706
  return part;
@@ -17131,7 +17716,7 @@ ${workingMemory}`;
17131
17716
  }
17132
17717
  parseWorkingMemory(text4) {
17133
17718
  if (!this.threadConfig.workingMemory?.enabled) return null;
17134
- const content = memory.extractWorkingMemoryContent(text4);
17719
+ const content = extractWorkingMemoryContent(text4);
17135
17720
  return content?.trim() ?? null;
17136
17721
  }
17137
17722
  async getWorkingMemory({
@@ -17266,7 +17851,7 @@ ${workingMemory}`;
17266
17851
  if (obsSystemMessage) {
17267
17852
  systemParts.push(obsSystemMessage);
17268
17853
  }
17269
- const { OBSERVATION_CONTINUATION_HINT } = await import('./constants-HXOCZPB7.cjs');
17854
+ const { OBSERVATION_CONTINUATION_HINT } = await import('./constants-PJXB7ZIS.cjs');
17270
17855
  continuationMessage = {
17271
17856
  id: "om-continuation",
17272
17857
  role: "user",
@@ -17366,7 +17951,7 @@ ${workingMemory}`;
17366
17951
  "Observational memory requires @mastra/core support for request-response-id-rotation. Please bump @mastra/core to a newer version."
17367
17952
  );
17368
17953
  }
17369
- const { ObservationalMemory: OMClass } = await import('./observational-memory-5YDQLKHE.cjs');
17954
+ const { ObservationalMemory: OMClass } = await import('./observational-memory-OVSEK47Z.cjs');
17370
17955
  const onIndexObservations = this.hasRetrievalSearch(omConfig.retrieval) ? async (observation) => {
17371
17956
  await this.indexObservation(observation);
17372
17957
  } : void 0;
@@ -17374,6 +17959,8 @@ ${workingMemory}`;
17374
17959
  storage: memoryStore,
17375
17960
  scope: omConfig.scope,
17376
17961
  retrieval: omConfig.retrieval,
17962
+ activateAfterIdle: omConfig.activateAfterIdle,
17963
+ activateOnProviderChange: omConfig.activateOnProviderChange,
17377
17964
  shareTokenBudget: omConfig.shareTokenBudget,
17378
17965
  model: omConfig.model,
17379
17966
  onIndexObservations,
@@ -17629,6 +18216,32 @@ Notes:
17629
18216
  }))
17630
18217
  });
17631
18218
  }
18219
+ /**
18220
+ * Update per-record observational memory config overrides for a thread.
18221
+ * The provided config is deep-merged, so you only need to specify fields you want to change.
18222
+ *
18223
+ * @example
18224
+ * ```ts
18225
+ * await memory.updateObservationalMemoryConfig({
18226
+ * threadId: 'thread-1',
18227
+ * config: {
18228
+ * observation: { messageTokens: 2000 },
18229
+ * reflection: { observationTokens: 8000 },
18230
+ * },
18231
+ * });
18232
+ * ```
18233
+ */
18234
+ async updateObservationalMemoryConfig({
18235
+ threadId,
18236
+ resourceId,
18237
+ config
18238
+ }) {
18239
+ const omEngine = await this.omEngine;
18240
+ if (!omEngine) {
18241
+ throw new Error("Observational memory is not enabled");
18242
+ }
18243
+ await omEngine.updateRecordConfig(threadId, resourceId, config);
18244
+ }
17632
18245
  /**
17633
18246
  * Index a list of messages directly (without querying storage).
17634
18247
  * Used by observe-time indexing to vectorize newly-observed messages.
@@ -17802,7 +18415,7 @@ Notes:
17802
18415
  * - Message objects with 'id' properties
17803
18416
  * @returns Promise that resolves when all messages are deleted
17804
18417
  */
17805
- async deleteMessages(input) {
18418
+ async deleteMessages(input, observabilityContext) {
17806
18419
  let messageIds;
17807
18420
  if (!Array.isArray(input)) {
17808
18421
  throw new Error("Invalid input: must be an array of message IDs or message objects");
@@ -17823,10 +18436,19 @@ Notes:
17823
18436
  if (invalidIds.length > 0) {
17824
18437
  throw new Error("All message IDs must be non-empty strings");
17825
18438
  }
17826
- const memoryStore = await this.getMemoryStore();
17827
- await memoryStore.deleteMessages(messageIds);
17828
- if (this.vector) {
17829
- void this.deleteMessageVectors(messageIds);
18439
+ const span = this.createMemorySpan("delete", observabilityContext, void 0, {
18440
+ messageCount: messageIds.length
18441
+ });
18442
+ try {
18443
+ const memoryStore = await this.getMemoryStore();
18444
+ await memoryStore.deleteMessages(messageIds);
18445
+ if (this.vector) {
18446
+ void this.deleteMessageVectors(messageIds);
18447
+ }
18448
+ span?.end({ output: { success: true }, attributes: { messageCount: messageIds.length } });
18449
+ } catch (error) {
18450
+ span?.error({ error, endSpan: true });
18451
+ throw error;
17830
18452
  }
17831
18453
  }
17832
18454
  /**
@@ -18254,30 +18876,20 @@ Notes:
18254
18876
  if (!effectiveConfig) return null;
18255
18877
  const engine = await this.omEngine;
18256
18878
  if (!engine) return null;
18257
- const { ObservationalMemoryProcessor } = await import('./observational-memory-5YDQLKHE.cjs');
18258
- return new ObservationalMemoryProcessor(engine, this);
18879
+ const { ObservationalMemoryProcessor } = await import('./observational-memory-OVSEK47Z.cjs');
18880
+ return new ObservationalMemoryProcessor(engine, this, {
18881
+ temporalMarkers: effectiveConfig.temporalMarkers
18882
+ });
18259
18883
  }
18260
18884
  };
18261
18885
 
18262
18886
  Object.defineProperty(exports, "ModelByInputTokens", {
18263
18887
  enumerable: true,
18264
- get: function () { return chunk4FMHSWZD_cjs.ModelByInputTokens; }
18888
+ get: function () { return chunk6ODYOMHN_cjs.ModelByInputTokens; }
18265
18889
  });
18266
18890
  Object.defineProperty(exports, "getObservationsAsOf", {
18267
18891
  enumerable: true,
18268
- get: function () { return chunk4FMHSWZD_cjs.getObservationsAsOf; }
18269
- });
18270
- Object.defineProperty(exports, "extractWorkingMemoryContent", {
18271
- enumerable: true,
18272
- get: function () { return memory.extractWorkingMemoryContent; }
18273
- });
18274
- Object.defineProperty(exports, "extractWorkingMemoryTags", {
18275
- enumerable: true,
18276
- get: function () { return memory.extractWorkingMemoryTags; }
18277
- });
18278
- Object.defineProperty(exports, "removeWorkingMemoryTags", {
18279
- enumerable: true,
18280
- get: function () { return memory.removeWorkingMemoryTags; }
18892
+ get: function () { return chunk6ODYOMHN_cjs.getObservationsAsOf; }
18281
18893
  });
18282
18894
  Object.defineProperty(exports, "MessageHistory", {
18283
18895
  enumerable: true,
@@ -18293,5 +18905,8 @@ Object.defineProperty(exports, "WorkingMemory", {
18293
18905
  });
18294
18906
  exports.Memory = Memory;
18295
18907
  exports.deepMergeWorkingMemory = deepMergeWorkingMemory;
18908
+ exports.extractWorkingMemoryContent = extractWorkingMemoryContent;
18909
+ exports.extractWorkingMemoryTags = extractWorkingMemoryTags;
18910
+ exports.removeWorkingMemoryTags = removeWorkingMemoryTags;
18296
18911
  //# sourceMappingURL=index.cjs.map
18297
18912
  //# sourceMappingURL=index.cjs.map