@mastra/server 1.84.0-alpha.1 → 1.84.0-alpha.3

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 (42) hide show
  1. package/dist/{agent-builder-CiOghrTT.js → agent-builder-D9rubwk0.js} +2 -2
  2. package/dist/{agent-builder-CiOghrTT.js.map → agent-builder-D9rubwk0.js.map} +1 -1
  3. package/dist/{agent-builder-DLFPC1xm.cjs → agent-builder-DHqHFO5d.cjs} +2 -2
  4. package/dist/{agent-builder-DLFPC1xm.cjs.map → agent-builder-DHqHFO5d.cjs.map} +1 -1
  5. package/dist/{api-schema-manifest-ClDNVUxK.cjs → api-schema-manifest-AltoM-cn.cjs} +2 -2
  6. package/dist/{api-schema-manifest-ClDNVUxK.cjs.map → api-schema-manifest-AltoM-cn.cjs.map} +1 -1
  7. package/dist/{api-schema-manifest-BKeWpPyw.js → api-schema-manifest-D1A2zfm3.js} +2 -2
  8. package/dist/{api-schema-manifest-BKeWpPyw.js.map → api-schema-manifest-D1A2zfm3.js.map} +1 -1
  9. package/dist/{catalogue-B5aCtg9L.cjs → catalogue-BW2a1gu4.cjs} +3 -3
  10. package/dist/{catalogue-B5aCtg9L.cjs.map → catalogue-BW2a1gu4.cjs.map} +1 -1
  11. package/dist/{catalogue-GycxwkWT.js → catalogue-DPLsw3zE.js} +3 -3
  12. package/dist/{catalogue-GycxwkWT.js.map → catalogue-DPLsw3zE.js.map} +1 -1
  13. package/dist/{dist-D50lVcGc.js → dist-CMgUx8hS.js} +118 -25
  14. package/dist/{dist-D50lVcGc.js.map → dist-CMgUx8hS.js.map} +1 -1
  15. package/dist/{dist-CgezUz3C.cjs → dist-D2zyg15_.cjs} +118 -25
  16. package/dist/{dist-CgezUz3C.cjs.map → dist-D2zyg15_.cjs.map} +1 -1
  17. package/dist/dist-HNpJc8bT.js +1 -0
  18. package/dist/{dist-DNQOx6xv.cjs → dist-ToffHjwd.cjs} +1 -1
  19. package/dist/docs/SKILL.md +1 -1
  20. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  21. package/dist/{probe-image-size-DVVxU5Q8.cjs → probe-image-size--ACsCqf-.cjs} +2 -2
  22. package/dist/{probe-image-size-DVVxU5Q8.cjs.map → probe-image-size--ACsCqf-.cjs.map} +1 -1
  23. package/dist/{probe-image-size-BFwgURuP.js → probe-image-size-CxVMV0gk.js} +2 -2
  24. package/dist/{probe-image-size-BFwgURuP.js.map → probe-image-size-CxVMV0gk.js.map} +1 -1
  25. package/dist/{routes-CuiId75P.js → routes-CH5SQLu2.js} +3 -3
  26. package/dist/{routes-CuiId75P.js.map → routes-CH5SQLu2.js.map} +1 -1
  27. package/dist/{routes-B8RVC_It.cjs → routes-bWCQflz5.cjs} +3 -3
  28. package/dist/{routes-B8RVC_It.cjs.map → routes-bWCQflz5.cjs.map} +1 -1
  29. package/dist/server/handlers/agent-builder.cjs +1 -1
  30. package/dist/server/handlers/agent-builder.js +1 -1
  31. package/dist/server/handlers/system.cjs +1 -1
  32. package/dist/server/handlers/system.js +1 -1
  33. package/dist/server/handlers.cjs +1 -1
  34. package/dist/server/handlers.js +1 -1
  35. package/dist/server/server-adapter/index.cjs +2 -2
  36. package/dist/server/server-adapter/index.js +2 -2
  37. package/dist/{server-adapter-DlhCV-sv.js → server-adapter-B3kR1OJs.js} +2 -2
  38. package/dist/{server-adapter-DlhCV-sv.js.map → server-adapter-B3kR1OJs.js.map} +1 -1
  39. package/dist/{server-adapter-B27F74-Q.cjs → server-adapter-SLljXCyr.cjs} +2 -2
  40. package/dist/{server-adapter-B27F74-Q.cjs.map → server-adapter-SLljXCyr.cjs.map} +1 -1
  41. package/package.json +5 -5
  42. package/dist/dist-mbbahDg1.js +0 -1
@@ -8654,7 +8654,7 @@ function splitLines(text) {
8654
8654
  else result.push(result.pop().slice(0, -1));
8655
8655
  return result;
8656
8656
  }
8657
- // ../memory/dist/src-CshY_uyn.js
8657
+ // ../memory/dist/src-Xhctgeae.js
8658
8658
  var __defProp$3 = Object.defineProperty;
8659
8659
  var __exportAll = (all, no_symbols) => {
8660
8660
  let target = {};
@@ -36583,6 +36583,19 @@ function buildEstimateKey(kind, text) {
36583
36583
  function resolveEstimatorId() {
36584
36584
  return "tokenx";
36585
36585
  }
36586
+ const ATTACHMENT_CONTENT_PART_TYPES = /* @__PURE__ */ new Set([
36587
+ "image",
36588
+ "image-data",
36589
+ "media",
36590
+ "audio",
36591
+ "file-data"
36592
+ ]);
36593
+ /** Mirrors the parts countMultimodalToolResultContent counts as attachments. */
36594
+ function isAttachmentContentPart(item) {
36595
+ if (!item || typeof item !== "object") return false;
36596
+ const contentPart = item;
36597
+ return ATTACHMENT_CONTENT_PART_TYPES.has(contentPart.type) && typeof contentPart.data === "string";
36598
+ }
36586
36599
  function isTokenEstimateEntry(value) {
36587
36600
  if (!value || typeof value !== "object") return false;
36588
36601
  const entry = value;
@@ -36772,7 +36785,7 @@ async function resolveImageDimensionsAsync(part) {
36772
36785
  const url = resolveHttpAssetUrl(getObjectValue(part, "image") ?? getObjectValue(part, "data"));
36773
36786
  if (!url) return existing;
36774
36787
  try {
36775
- const probeImageSize = (await Promise.resolve().then(() => /* @__PURE__ */ require_rolldown_runtime.__toESM(require("./probe-image-size-DVVxU5Q8.cjs").default, 1))).default;
36788
+ const probeImageSize = (await Promise.resolve().then(() => /* @__PURE__ */ require_rolldown_runtime.__toESM(require("./probe-image-size--ACsCqf-.cjs").default, 1))).default;
36776
36789
  const probed = await probeImageSize(url, {
36777
36790
  open_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
36778
36791
  response_timeout: REMOTE_IMAGE_PROBE_TIMEOUT_MS,
@@ -37375,12 +37388,12 @@ var TokenCounter = class TokenCounter {
37375
37388
  }
37376
37389
  countMultimodalToolResultContent(part, toolResult) {
37377
37390
  if (!toolResult || typeof toolResult !== "object") return;
37391
+ const output = toolResult;
37392
+ const content = output.type === "content" && Array.isArray(output.value) ? output.value : output.content;
37393
+ if (!Array.isArray(content) || !content.some(isAttachmentContentPart)) return;
37378
37394
  const resultKey = buildEstimateKey("tool-result-multimodal-content-source", JSON.stringify(toolResult));
37379
37395
  const cached = this.multimodalToolResultCounts.get(part);
37380
37396
  if (cached?.resultKey === resultKey) return cached.tokens;
37381
- const output = toolResult;
37382
- const content = output.type === "content" && Array.isArray(output.value) ? output.value : output.content;
37383
- if (!Array.isArray(content)) return;
37384
37397
  let hasAttachment = false;
37385
37398
  let tokens = 0;
37386
37399
  const cacheParts = [];
@@ -48142,12 +48155,25 @@ function getOmObservabilityContext(args) {
48142
48155
  metrics: args.metrics
48143
48156
  };
48144
48157
  }
48145
- /** Key used to store gateway detection result in per-processor state. */
48146
- const GATEWAY_STATE_KEY = "__isGatewayModel";
48158
+ /** Key used to store whether the gateway manages memory for the current step in per-processor state. */
48159
+ const GATEWAY_STATE_KEY = "__isGatewayMemoryManaged";
48147
48160
  /** Step number OM last recovered from a context-overflow error, so each step retries at most once. */
48148
48161
  const CONTEXT_OVERFLOW_STEP_KEY = "__omContextOverflowStep";
48149
- /** Check if the model is routed through a Mastra gateway (duck-type check to avoid cross-package instanceof issues). */
48150
- function isMastraGatewayModel(model) {
48162
+ /**
48163
+ * Whether the Mastra gateway serves Observational Memory for this step's model.
48164
+ *
48165
+ * Gateway models only get memory from the gateway when the credential is a Gateway project
48166
+ * key. Organization keys (`msk-gateway-…`, `mskv2_…`) are served by a gateway without the
48167
+ * memory API, so memory has to stay local. Newer `@mastra/core` exposes that decision on the
48168
+ * router model; when it is absent (older core, or a plain model) fall back to the historical
48169
+ * `mastra/` prefix check so gateway-side memory is never double-processed.
48170
+ *
48171
+ * A model that fails the check is not treated as local. Core answers `false` only for a model
48172
+ * that isn't on the gateway, and throws when the credential can't be resolved — including when it
48173
+ * is missing; letting that through keeps the two sides in agreement.
48174
+ */
48175
+ async function isGatewayMemoryManaged(model) {
48176
+ if (typeof model === "object" && model !== null && typeof model.isGatewayMemoryManaged === "function") return Boolean(await model.isGatewayMemoryManaged());
48151
48177
  return typeof model === "object" && model !== null && "gatewayId" in model && model.gatewayId === "mastra";
48152
48178
  }
48153
48179
  function injectObservationContextMessages({ messageList, systemMessages, continuationMessage, hasObservations, threadId, resourceId }) {
@@ -48213,6 +48239,34 @@ var ObservationalMemoryProcessor = class {
48213
48239
  this.memory = memory;
48214
48240
  this.temporalMarkers = options?.temporalMarkers ?? false;
48215
48241
  }
48242
+ /**
48243
+ * End any locally started turn without leaving it dangling.
48244
+ *
48245
+ * A gateway-managed step short-circuits both processor phases, so a turn started on an
48246
+ * earlier step of the same run — a delegation run whose model changed, or a run whose key
48247
+ * changed — would otherwise never be ended and its messages never persisted. `end()` with
48248
+ * no arguments flushes what the turn already tracked; finalization passes the accepted
48249
+ * terminal list for the same reason the regular output path does.
48250
+ *
48251
+ * A rejected write is not swallowed. `end()` marks the turn ended before it persists, so a
48252
+ * failed write leaves the turn unusable and its messages would be lost silently while the run
48253
+ * reported success. The drain persists those messages directly and rethrows, so a storage
48254
+ * failure surfaces instead of dropping the turn.
48255
+ */
48256
+ async endActiveTurn(state, messageList) {
48257
+ const activeTurn = asLiveTurn(state.__omTurn) ?? this.turn;
48258
+ this.turn = void 0;
48259
+ state.__omTurn = void 0;
48260
+ if (!activeTurn || activeTurn.ended) return;
48261
+ const terminalList = messageList ?? activeTurn.messageList;
48262
+ const unsavedMessages = [...terminalList.get.input.db(), ...terminalList.get.response.db()];
48263
+ try {
48264
+ await activeTurn.end(terminalList);
48265
+ } catch (error) {
48266
+ if (unsavedMessages.length > 0) await this.engine.persistMessages(unsavedMessages, activeTurn.threadId, activeTurn.resourceId).catch(() => {});
48267
+ throw error;
48268
+ }
48269
+ }
48216
48270
  async processInputStep(args) {
48217
48271
  const { messageList, requestContext, stepNumber, state: _state, writer, model, abortSignal, abort, messageId, rotateResponseMessageId } = args;
48218
48272
  const state = _state ?? {};
@@ -48222,9 +48276,11 @@ var ObservationalMemoryProcessor = class {
48222
48276
  omDebug(`[OM:processInputStep:NO-CONTEXT] getThreadContext returned null — returning early`);
48223
48277
  return messageList;
48224
48278
  }
48225
- if (isMastraGatewayModel(model)) {
48226
- state[GATEWAY_STATE_KEY] = true;
48227
- omDebug(`[OM:processInputStep:GATEWAY] gateway handles OM — skipping local processing`);
48279
+ const gatewayMemoryManaged = await isGatewayMemoryManaged(model);
48280
+ state[GATEWAY_STATE_KEY] = gatewayMemoryManaged;
48281
+ if (gatewayMemoryManaged) {
48282
+ await this.endActiveTurn(state);
48283
+ omDebug(`[OM:processInputStep:GATEWAY] gateway manages memory — skipping local processing`);
48228
48284
  return messageList;
48229
48285
  }
48230
48286
  const { threadId, resourceId } = context;
@@ -48414,7 +48470,10 @@ var ObservationalMemoryProcessor = class {
48414
48470
  const state = _state ?? {};
48415
48471
  const context = this.engine.getThreadContext(requestContext, messageList);
48416
48472
  if (!context) return messageList;
48417
- if (state[GATEWAY_STATE_KEY]) return messageList;
48473
+ if (state[GATEWAY_STATE_KEY]) {
48474
+ await this.endActiveTurn(state, messageList.cloneForPersistence());
48475
+ return messageList;
48476
+ }
48418
48477
  state.__omObservabilityContext = getOmObservabilityContext(args);
48419
48478
  return this.engine.getTokenCounter().runWithModelContext(state.__omActorModelContext, async () => {
48420
48479
  if ((0, _mastra_core_memory.parseMemoryRequestContext)(requestContext)?.memoryConfig?.readOnly) return messageList;
@@ -48887,7 +48946,7 @@ var Memory = class Memory extends _mastra_core_memory.MastraMemory {
48887
48946
  }
48888
48947
  }
48889
48948
  const threshold = (typeof config.semanticRecall === "object" ? config.semanticRecall : void 0)?.threshold;
48890
- const filteredVectorResults = threshold !== void 0 ? vectorResults.filter((r) => r.score >= threshold) : vectorResults;
48949
+ const filteredVectorResults = vectorResults.filter((r) => (threshold === void 0 || r.score >= threshold) && (resourceScope ? r.metadata?.resource_id === resourceId : r.metadata?.thread_id === threadId));
48891
48950
  const memoryStore = await this.getMemoryStore();
48892
48951
  const include = filteredVectorResults.map((r) => ({
48893
48952
  id: r.metadata?.message_id,
@@ -48951,6 +49010,7 @@ var Memory = class Memory extends _mastra_core_memory.MastraMemory {
48951
49010
  rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;
48952
49011
  ({total, page: resultPage, perPage: resultPerPage, hasMore} = paginatedResult);
48953
49012
  }
49013
+ if (include.length) rawMessages = rawMessages.filter((message) => message.threadId === threadId || resourceScope && message.resourceId === resourceId);
48954
49014
  const messages = filterSystemReminderMessages(new _mastra_core_agent.MessageList({
48955
49015
  threadId,
48956
49016
  resourceId
@@ -49301,42 +49361,74 @@ ${workingMemory}`;
49301
49361
  this.embeddingCache.set(key, result);
49302
49362
  return result;
49303
49363
  }
49364
+ chunkEmbeddingCache = new I({ max: DEFAULT_EMBEDDING_CACHE_MAX_SIZE });
49365
+ chunkEmbeddingCacheOwner = {};
49366
+ /**
49367
+ * Embeds one message's chunks, reusing vectors already produced for the same chunks. Usage is
49368
+ * returned only for a call that reached the embedder.
49369
+ */
49370
+ async embedMessageChunks(chunks) {
49371
+ const producer = {
49372
+ embedder: this.embedder,
49373
+ embedderOptions: this.embedderOptions
49374
+ };
49375
+ const key = (await this.hasher).h64(JSON.stringify(chunks));
49376
+ if (producer.embedder !== this.embedder || producer.embedderOptions !== this.embedderOptions) return this.embedValues(chunks, producer);
49377
+ const owner = this.chunkEmbeddingCacheOwner;
49378
+ if (owner.embedder !== producer.embedder || owner.embedderOptions !== producer.embedderOptions) {
49379
+ this.chunkEmbeddingCache.clear();
49380
+ this.chunkEmbeddingCacheOwner = producer;
49381
+ }
49382
+ const cached = this.chunkEmbeddingCache.get(key);
49383
+ if (cached) return { embeddings: await cached };
49384
+ const result = this.embedValues(chunks, producer);
49385
+ const embeddings = result.then(({ embeddings }) => {
49386
+ if (embeddings.length !== chunks.length) evict();
49387
+ return embeddings;
49388
+ });
49389
+ const evict = () => {
49390
+ if (this.chunkEmbeddingCache.get(key) === embeddings) this.chunkEmbeddingCache.delete(key);
49391
+ };
49392
+ embeddings.catch(evict);
49393
+ this.chunkEmbeddingCache.set(key, embeddings);
49394
+ return result;
49395
+ }
49304
49396
  /** Sends texts to the embedder through the AI SDK version that matches its spec. */
49305
- async embedValues(values) {
49306
- if (typeof this.embedder === `undefined`) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
49307
- const isFastEmbed = this.embedder.provider === `fastembed`;
49397
+ async embedValues(values, { embedder, embedderOptions } = this) {
49398
+ if (typeof embedder === `undefined`) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
49399
+ const isFastEmbed = embedder.provider === `fastembed`;
49308
49400
  if (isFastEmbed && this.firstEmbed instanceof Promise) await this.firstEmbed;
49309
49401
  const options = {
49310
49402
  values,
49311
49403
  maxRetries: 3
49312
49404
  };
49313
- const model = this.embedder;
49405
+ const model = embedder;
49314
49406
  let promise;
49315
49407
  switch (model.specificationVersion) {
49316
49408
  case "v4":
49317
49409
  promise = embedMany({
49318
49410
  ...options,
49319
- ...this.embedderOptions,
49411
+ ...embedderOptions,
49320
49412
  model
49321
49413
  });
49322
49414
  break;
49323
49415
  case "v3":
49324
49416
  promise = embedMany$1({
49325
49417
  ...options,
49326
- ...this.embedderOptions,
49418
+ ...embedderOptions,
49327
49419
  model
49328
49420
  });
49329
49421
  break;
49330
49422
  case "v2":
49331
49423
  promise = embedMany$2({
49332
49424
  ...options,
49333
- ...this.embedderOptions,
49425
+ ...embedderOptions,
49334
49426
  model
49335
49427
  });
49336
49428
  break;
49337
49429
  default: promise = embedMany$3({
49338
49430
  ...options,
49339
- ...this.embedderOptions,
49431
+ ...embedderOptions,
49340
49432
  model
49341
49433
  });
49342
49434
  }
@@ -49378,7 +49470,7 @@ ${workingMemory}`;
49378
49470
  if (!this.embedder && !this.isSelfEmbedding) throw new Error(`Tried to embed message content but this Memory instance doesn't have an attached embedder.`);
49379
49471
  return (0, _mastra_core_memory.buildMessageEmbeddingRows)({
49380
49472
  items,
49381
- embed: this.isSelfEmbedding ? void 0 : (chunks) => this.embedValues(chunks),
49473
+ embed: this.isSelfEmbedding ? void 0 : (chunks) => this.embedMessageChunks(chunks),
49382
49474
  maxChunkChars: (0, _mastra_core_memory.resolveMaxChunkChars)({
49383
49475
  maxChunkChars: this.configuredMaxChunkChars,
49384
49476
  embedder: this.embedder
@@ -49964,6 +50056,7 @@ Notes:
49964
50056
  });
49965
50057
  for (const r of results) {
49966
50058
  if (!r.metadata?.thread_id) continue;
50059
+ if (r.metadata.resource_id !== resourceId || filter?.threadId && r.metadata.thread_id !== filter.threadId) continue;
49967
50060
  const groupId = typeof r.metadata.group_id === "string" ? r.metadata.group_id : void 0;
49968
50061
  if (!groupId) continue;
49969
50062
  queryResults.push({
@@ -52013,7 +52106,7 @@ const createModelInstance = async (provider, modelId, version = "v2") => {
52013
52106
  try {
52014
52107
  const providerFn = version === `v1` ? { v1: {
52015
52108
  openai: async () => {
52016
- const { openai } = await Promise.resolve().then(() => require("./dist-DNQOx6xv.cjs"));
52109
+ const { openai } = await Promise.resolve().then(() => require("./dist-ToffHjwd.cjs"));
52017
52110
  return openai(modelId);
52018
52111
  },
52019
52112
  anthropic: async () => {
@@ -59843,4 +59936,4 @@ Object.defineProperty(exports, "require_webp", {
59843
59936
  }
59844
59937
  });
59845
59938
 
59846
- //# sourceMappingURL=dist-CgezUz3C.cjs.map
59939
+ //# sourceMappingURL=dist-D2zyg15_.cjs.map