@mastra/server 1.23.0-alpha.7 → 1.23.0-alpha.8

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 (112) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/_types/@internal_core/dist/index.d.ts +3 -1
  3. package/dist/{chunk-VMA5TY4H.cjs → chunk-2KF7EWOT.cjs} +314 -190
  4. package/dist/chunk-2KF7EWOT.cjs.map +1 -0
  5. package/dist/{chunk-VDHLJ6OD.cjs → chunk-3D2IBKF6.cjs} +4 -4
  6. package/dist/{chunk-VDHLJ6OD.cjs.map → chunk-3D2IBKF6.cjs.map} +1 -1
  7. package/dist/{chunk-B2OFZDJQ.cjs → chunk-4HHL4C6V.cjs} +13 -13
  8. package/dist/{chunk-B2OFZDJQ.cjs.map → chunk-4HHL4C6V.cjs.map} +1 -1
  9. package/dist/{chunk-QBXHK27Z.js → chunk-52JPWUPI.js} +3 -3
  10. package/dist/{chunk-QBXHK27Z.js.map → chunk-52JPWUPI.js.map} +1 -1
  11. package/dist/{chunk-VXBTV6LH.js → chunk-6MMZVEFC.js} +8 -3
  12. package/dist/chunk-6MMZVEFC.js.map +1 -0
  13. package/dist/{chunk-4EA2CJG4.js → chunk-A7BSSXDD.js} +3 -3
  14. package/dist/{chunk-4EA2CJG4.js.map → chunk-A7BSSXDD.js.map} +1 -1
  15. package/dist/{chunk-LRJ4LQBR.cjs → chunk-F4TKO2VD.cjs} +6 -6
  16. package/dist/{chunk-LRJ4LQBR.cjs.map → chunk-F4TKO2VD.cjs.map} +1 -1
  17. package/dist/{chunk-ZVSNY6VT.js → chunk-GMZFJZO4.js} +4 -3
  18. package/dist/chunk-GMZFJZO4.js.map +1 -0
  19. package/dist/{chunk-INKHQLVW.js → chunk-HKALCAKJ.js} +3 -3
  20. package/dist/{chunk-INKHQLVW.js.map → chunk-HKALCAKJ.js.map} +1 -1
  21. package/dist/{chunk-VOCNBP5Q.cjs → chunk-HUWHY7SC.cjs} +4 -3
  22. package/dist/chunk-HUWHY7SC.cjs.map +1 -0
  23. package/dist/{chunk-U6CWJTHH.cjs → chunk-I5FEAHJM.cjs} +29 -29
  24. package/dist/{chunk-U6CWJTHH.cjs.map → chunk-I5FEAHJM.cjs.map} +1 -1
  25. package/dist/{chunk-UVK6YXEL.cjs → chunk-IOGPYY6Z.cjs} +77 -75
  26. package/dist/chunk-IOGPYY6Z.cjs.map +1 -0
  27. package/dist/{chunk-5C535ZJO.cjs → chunk-KG5RK6PO.cjs} +4 -4
  28. package/dist/{chunk-5C535ZJO.cjs.map → chunk-KG5RK6PO.cjs.map} +1 -1
  29. package/dist/{chunk-AS6EW5BK.js → chunk-KYVNA2EN.js} +3 -3
  30. package/dist/{chunk-AS6EW5BK.js.map → chunk-KYVNA2EN.js.map} +1 -1
  31. package/dist/{chunk-FLGIOJA5.js → chunk-MO3ZKWYY.js} +80 -10
  32. package/dist/chunk-MO3ZKWYY.js.map +1 -0
  33. package/dist/{chunk-6Q6OH2XV.js → chunk-OOZYQF4U.js} +3 -2
  34. package/dist/chunk-OOZYQF4U.js.map +1 -0
  35. package/dist/{chunk-IFEMVRLI.cjs → chunk-OV2TAONK.cjs} +3 -2
  36. package/dist/chunk-OV2TAONK.cjs.map +1 -0
  37. package/dist/{chunk-DALTY2FC.js → chunk-P72YX3EY.js} +3 -3
  38. package/dist/{chunk-DALTY2FC.js.map → chunk-P72YX3EY.js.map} +1 -1
  39. package/dist/{chunk-SE5M6GC6.js → chunk-T4RZ3X4I.js} +4 -4
  40. package/dist/{chunk-SE5M6GC6.js.map → chunk-T4RZ3X4I.js.map} +1 -1
  41. package/dist/{chunk-XUIA3SIB.js → chunk-TBJHTT7B.js} +6 -4
  42. package/dist/chunk-TBJHTT7B.js.map +1 -0
  43. package/dist/{chunk-SZ2FSVP5.js → chunk-TX3IIDZN.js} +301 -177
  44. package/dist/chunk-TX3IIDZN.js.map +1 -0
  45. package/dist/{chunk-PNCR2M6Y.cjs → chunk-UHWF2UKO.cjs} +80 -10
  46. package/dist/chunk-UHWF2UKO.cjs.map +1 -0
  47. package/dist/{chunk-HHGZGERI.cjs → chunk-UI3SS2JO.cjs} +4 -4
  48. package/dist/{chunk-HHGZGERI.cjs.map → chunk-UI3SS2JO.cjs.map} +1 -1
  49. package/dist/{chunk-RNC7VEI6.cjs → chunk-WKBMLKBC.cjs} +8 -3
  50. package/dist/chunk-WKBMLKBC.cjs.map +1 -0
  51. package/dist/{chunk-SHWDJY3O.js → chunk-WZ6XPWVK.js} +3 -3
  52. package/dist/{chunk-SHWDJY3O.js.map → chunk-WZ6XPWVK.js.map} +1 -1
  53. package/dist/{chunk-SCEPRIRF.cjs → chunk-X2IFWP5E.cjs} +5 -5
  54. package/dist/{chunk-SCEPRIRF.cjs.map → chunk-X2IFWP5E.cjs.map} +1 -1
  55. package/dist/{chunk-DGS7O6Q7.js → chunk-XO5PXSFC.js} +3 -3
  56. package/dist/{chunk-DGS7O6Q7.js.map → chunk-XO5PXSFC.js.map} +1 -1
  57. package/dist/{chunk-LV4FV46S.cjs → chunk-ZWKZK4WO.cjs} +6 -6
  58. package/dist/{chunk-LV4FV46S.cjs.map → chunk-ZWKZK4WO.cjs.map} +1 -1
  59. package/dist/docs/SKILL.md +1 -1
  60. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  61. package/dist/{observational-memory-JQ34KLFS-CNLSTXO3.cjs → observational-memory-OVRHDQRG-OCHV6RZ7.cjs} +26 -26
  62. package/dist/{observational-memory-JQ34KLFS-CNLSTXO3.cjs.map → observational-memory-OVRHDQRG-OCHV6RZ7.cjs.map} +1 -1
  63. package/dist/{observational-memory-JQ34KLFS-KLWGOGP4.js → observational-memory-OVRHDQRG-RC3PRA65.js} +3 -3
  64. package/dist/{observational-memory-JQ34KLFS-KLWGOGP4.js.map → observational-memory-OVRHDQRG-RC3PRA65.js.map} +1 -1
  65. package/dist/server/handlers/a2a.cjs +9 -9
  66. package/dist/server/handlers/a2a.js +1 -1
  67. package/dist/server/handlers/agent-builder.cjs +16 -16
  68. package/dist/server/handlers/agent-builder.js +1 -1
  69. package/dist/server/handlers/agents.cjs +35 -35
  70. package/dist/server/handlers/agents.d.ts.map +1 -1
  71. package/dist/server/handlers/agents.js +1 -1
  72. package/dist/server/handlers/conversations.cjs +5 -5
  73. package/dist/server/handlers/conversations.js +1 -1
  74. package/dist/server/handlers/memory.cjs +27 -27
  75. package/dist/server/handlers/memory.d.ts +4 -0
  76. package/dist/server/handlers/memory.d.ts.map +1 -1
  77. package/dist/server/handlers/memory.js +1 -1
  78. package/dist/server/handlers/observability-new-endpoints.cjs +27 -27
  79. package/dist/server/handlers/observability-new-endpoints.js +1 -1
  80. package/dist/server/handlers/observability.cjs +33 -33
  81. package/dist/server/handlers/observability.js +2 -2
  82. package/dist/server/handlers/responses.cjs +4 -4
  83. package/dist/server/handlers/responses.js +1 -1
  84. package/dist/server/handlers/scores.cjs +7 -7
  85. package/dist/server/handlers/scores.js +1 -1
  86. package/dist/server/handlers/tools.cjs +6 -6
  87. package/dist/server/handlers/tools.js +1 -1
  88. package/dist/server/handlers/voice.cjs +8 -8
  89. package/dist/server/handlers/voice.js +1 -1
  90. package/dist/server/handlers.cjs +20 -20
  91. package/dist/server/handlers.js +10 -10
  92. package/dist/server/schemas/index.cjs +50 -50
  93. package/dist/server/schemas/index.js +2 -2
  94. package/dist/server/schemas/memory.d.ts +2 -0
  95. package/dist/server/schemas/memory.d.ts.map +1 -1
  96. package/dist/server/server-adapter/index.cjs +129 -129
  97. package/dist/server/server-adapter/index.js +11 -11
  98. package/dist/server/server-adapter/routes/memory.d.ts +4 -0
  99. package/dist/server/server-adapter/routes/memory.d.ts.map +1 -1
  100. package/package.json +5 -5
  101. package/dist/chunk-6Q6OH2XV.js.map +0 -1
  102. package/dist/chunk-FLGIOJA5.js.map +0 -1
  103. package/dist/chunk-IFEMVRLI.cjs.map +0 -1
  104. package/dist/chunk-PNCR2M6Y.cjs.map +0 -1
  105. package/dist/chunk-RNC7VEI6.cjs.map +0 -1
  106. package/dist/chunk-SZ2FSVP5.js.map +0 -1
  107. package/dist/chunk-UVK6YXEL.cjs.map +0 -1
  108. package/dist/chunk-VMA5TY4H.cjs.map +0 -1
  109. package/dist/chunk-VOCNBP5Q.cjs.map +0 -1
  110. package/dist/chunk-VXBTV6LH.js.map +0 -1
  111. package/dist/chunk-XUIA3SIB.js.map +0 -1
  112. package/dist/chunk-ZVSNY6VT.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { __commonJS as __commonJS$3, require_token_error as require_token_error$2, __toESM as __toESM$3 } from './chunk-JWVHBH4H.js';
2
2
  import { __commonJS as __commonJS$1, require_token_error, __toESM } from './chunk-BZZVTO7B.js';
3
3
  import { __commonJS as __commonJS$2, require_token_error as require_token_error$1, __toESM as __toESM$1 } from './chunk-PWAXLHKP.js';
4
- import { e, truncateStringByTokens, estimateTokenCount, resolveToolResultValue, formatToolResultForObserver } from './chunk-FLGIOJA5.js';
4
+ import { e, truncateStringByTokens, estimateTokenCount, resolveToolResultValue, formatToolResultForObserver } from './chunk-MO3ZKWYY.js';
5
5
  import { openai } from './chunk-PALNMAC6.js';
6
6
  import { LIST_WORKFLOWS_ROUTE, GET_WORKFLOW_BY_ID_ROUTE, LIST_WORKFLOW_RUNS_ROUTE, GET_WORKFLOW_RUN_BY_ID_ROUTE, CREATE_WORKFLOW_RUN_ROUTE, STREAM_WORKFLOW_ROUTE, START_ASYNC_WORKFLOW_ROUTE, START_WORKFLOW_RUN_ROUTE, OBSERVE_STREAM_WORKFLOW_ROUTE, RESUME_ASYNC_WORKFLOW_ROUTE, RESUME_WORKFLOW_ROUTE, RESUME_STREAM_WORKFLOW_ROUTE, CANCEL_WORKFLOW_RUN_ROUTE, STREAM_LEGACY_WORKFLOW_ROUTE, OBSERVE_STREAM_LEGACY_WORKFLOW_ROUTE } from './chunk-TTIBLMTX.js';
7
7
  import { actionIdPathParams, actionRunPathParams, streamAgentBuilderBodySchema, startAsyncAgentBuilderBodySchema, resumeAgentBuilderBodySchema, streamLegacyAgentBuilderBodySchema } from './chunk-S7PYDU5I.js';
@@ -20,7 +20,8 @@ import { z } from 'zod';
20
20
  import * as z4 from 'zod/v4';
21
21
  import { z as z$1 } from 'zod/v4';
22
22
  import { coreFeatures } from '@mastra/core/features';
23
- import { MastraMemory, removeWorkingMemoryTags, extractWorkingMemoryContent } from '@mastra/core/memory';
23
+ import { MastraMemory, filterSystemReminderMessages, removeWorkingMemoryTags, extractWorkingMemoryContent } from '@mastra/core/memory';
24
+ import { EntityType, SpanType } from '@mastra/core/observability';
24
25
  import { generateEmptyFromSchema } from '@mastra/core/utils';
25
26
  import { createTool } from '@mastra/core/tools';
26
27
  import { toStandardSchema, isStandardSchemaWithJSON as isStandardSchemaWithJSON$1 } from '@mastra/core/schema';
@@ -17292,94 +17293,149 @@ var Memory = class extends MastraMemory {
17292
17293
  );
17293
17294
  }
17294
17295
  }
17296
+ createMemorySpan(operationType, observabilityContext, input, attributes) {
17297
+ const currentSpan = observabilityContext?.tracingContext?.currentSpan;
17298
+ if (!currentSpan) return void 0;
17299
+ return currentSpan.createChildSpan({
17300
+ type: SpanType.MEMORY_OPERATION,
17301
+ name: `memory: ${operationType}`,
17302
+ entityType: EntityType.MEMORY,
17303
+ entityName: "Memory",
17304
+ input,
17305
+ attributes: { operationType, ...attributes }
17306
+ });
17307
+ }
17295
17308
  async recall(args) {
17296
- const { threadId, resourceId, perPage: perPageArg, page, orderBy, threadConfig, vectorSearchString, filter: filter32 } = args;
17297
- const config = this.getMergedThreadConfig(threadConfig || {});
17298
- if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId, config);
17299
- const perPage = perPageArg !== void 0 ? perPageArg : config.lastMessages;
17300
- const historyDisabledByConfig = config.lastMessages === false && perPageArg === void 0;
17301
- const shouldGetNewestAndReverse = !orderBy && perPage !== false;
17302
- const effectiveOrderBy = shouldGetNewestAndReverse ? { field: "createdAt", direction: "DESC" } : orderBy;
17303
- const vectorResults = [];
17304
- this.logger.debug("Memory recall", {
17309
+ const {
17305
17310
  threadId,
17306
- perPage,
17311
+ resourceId,
17312
+ perPage: perPageArg,
17307
17313
  page,
17308
- orderBy: effectiveOrderBy,
17309
- hasWorkingMemorySchema: Boolean(config.workingMemory?.schema),
17310
- workingMemoryEnabled: config.workingMemory?.enabled,
17311
- semanticRecallEnabled: Boolean(config.semanticRecall),
17312
- historyDisabledByConfig
17313
- });
17314
- const defaultRange = DEFAULT_MESSAGE_RANGE;
17315
- const defaultTopK = DEFAULT_TOP_K;
17316
- const vectorConfig = typeof config?.semanticRecall === `boolean` ? {
17317
- topK: defaultTopK,
17318
- messageRange: defaultRange
17319
- } : {
17320
- topK: config?.semanticRecall?.topK ?? defaultTopK,
17321
- messageRange: config?.semanticRecall?.messageRange ?? defaultRange
17322
- };
17323
- const resourceScope = typeof config?.semanticRecall === "object" && config?.semanticRecall?.scope !== `thread` || config.semanticRecall === true;
17324
- if (resourceScope && !resourceId && config?.semanticRecall && vectorSearchString) {
17325
- throw new Error(
17326
- `Memory error: Resource-scoped semantic recall is enabled but no resourceId was provided. Either provide a resourceId or explicitly set semanticRecall.scope to 'thread'.`
17327
- );
17328
- }
17329
- let usage;
17330
- if (historyDisabledByConfig && (!config.semanticRecall || !vectorSearchString || !this.vector)) {
17331
- return { messages: [], usage: void 0, total: 0, page: page ?? 0, perPage: 0, hasMore: false };
17332
- }
17333
- if (config?.semanticRecall && vectorSearchString && this.vector) {
17334
- const result = await this.embedMessageContent(vectorSearchString);
17335
- usage = result.usage;
17336
- const { embeddings, dimension } = result;
17337
- const { indexName } = await this.createEmbeddingIndex(dimension, config);
17338
- await Promise.all(
17339
- embeddings.map(async (embedding) => {
17340
- if (typeof this.vector === `undefined`) {
17341
- throw new Error(
17342
- `Tried to query vector index ${indexName} but this Memory instance doesn't have an attached vector db.`
17314
+ orderBy,
17315
+ threadConfig,
17316
+ vectorSearchString,
17317
+ includeSystemReminders,
17318
+ filter: filter32
17319
+ } = args;
17320
+ const config = this.getMergedThreadConfig(threadConfig || {});
17321
+ const semanticRecallEnabled = Boolean(config.semanticRecall);
17322
+ const span = this.createMemorySpan(
17323
+ "recall",
17324
+ args.observabilityContext,
17325
+ { threadId, resourceId, vectorSearchString },
17326
+ {
17327
+ semanticRecallEnabled,
17328
+ lastMessages: config.lastMessages
17329
+ }
17330
+ );
17331
+ try {
17332
+ if (resourceId) await this.validateThreadIsOwnedByResource(threadId, resourceId, config);
17333
+ const perPage = perPageArg !== void 0 ? perPageArg : config.lastMessages;
17334
+ const historyDisabledByConfig = config.lastMessages === false && perPageArg === void 0;
17335
+ const shouldGetNewestAndReverse = !orderBy && perPage !== false;
17336
+ const effectiveOrderBy = shouldGetNewestAndReverse ? { field: "createdAt", direction: "DESC" } : orderBy;
17337
+ const vectorResults = [];
17338
+ this.logger.debug("Memory recall", {
17339
+ threadId,
17340
+ perPage,
17341
+ page,
17342
+ orderBy: effectiveOrderBy,
17343
+ hasWorkingMemorySchema: Boolean(config.workingMemory?.schema),
17344
+ workingMemoryEnabled: config.workingMemory?.enabled,
17345
+ semanticRecallEnabled,
17346
+ historyDisabledByConfig
17347
+ });
17348
+ const defaultRange = DEFAULT_MESSAGE_RANGE;
17349
+ const defaultTopK = DEFAULT_TOP_K;
17350
+ const vectorConfig = typeof config?.semanticRecall === `boolean` ? {
17351
+ topK: defaultTopK,
17352
+ messageRange: defaultRange
17353
+ } : {
17354
+ topK: config?.semanticRecall?.topK ?? defaultTopK,
17355
+ messageRange: config?.semanticRecall?.messageRange ?? defaultRange
17356
+ };
17357
+ const resourceScope = typeof config?.semanticRecall === "object" && config?.semanticRecall?.scope !== `thread` || config.semanticRecall === true;
17358
+ if (resourceScope && !resourceId && config?.semanticRecall && vectorSearchString) {
17359
+ throw new Error(
17360
+ `Memory error: Resource-scoped semantic recall is enabled but no resourceId was provided. Either provide a resourceId or explicitly set semanticRecall.scope to 'thread'.`
17361
+ );
17362
+ }
17363
+ let usage;
17364
+ if (historyDisabledByConfig && (!config.semanticRecall || !vectorSearchString || !this.vector)) {
17365
+ const result = {
17366
+ messages: [],
17367
+ usage: void 0,
17368
+ total: 0,
17369
+ page: page ?? 0,
17370
+ perPage: 0,
17371
+ hasMore: false
17372
+ };
17373
+ span?.end({ output: { success: true }, attributes: { messageCount: 0 } });
17374
+ return result;
17375
+ }
17376
+ if (config?.semanticRecall && vectorSearchString && this.vector) {
17377
+ const result = await this.embedMessageContent(vectorSearchString);
17378
+ usage = result.usage;
17379
+ const { embeddings, dimension } = result;
17380
+ const { indexName } = await this.createEmbeddingIndex(dimension, config);
17381
+ await Promise.all(
17382
+ embeddings.map(async (embedding) => {
17383
+ if (typeof this.vector === `undefined`) {
17384
+ throw new Error(
17385
+ `Tried to query vector index ${indexName} but this Memory instance doesn't have an attached vector db.`
17386
+ );
17387
+ }
17388
+ vectorResults.push(
17389
+ ...await this.vector.query({
17390
+ indexName,
17391
+ queryVector: embedding,
17392
+ topK: vectorConfig.topK,
17393
+ filter: resourceScope ? {
17394
+ resource_id: resourceId
17395
+ } : {
17396
+ thread_id: threadId
17397
+ }
17398
+ })
17343
17399
  );
17344
- }
17345
- vectorResults.push(
17346
- ...await this.vector.query({
17347
- indexName,
17348
- queryVector: embedding,
17349
- topK: vectorConfig.topK,
17350
- filter: resourceScope ? {
17351
- resource_id: resourceId
17352
- } : {
17353
- thread_id: threadId
17354
- }
17355
- })
17356
- );
17357
- })
17358
- );
17400
+ })
17401
+ );
17402
+ }
17403
+ const memoryStore = await this.getMemoryStore();
17404
+ const effectivePerPage = historyDisabledByConfig ? 0 : perPage;
17405
+ const paginatedResult = await memoryStore.listMessages({
17406
+ threadId,
17407
+ resourceId,
17408
+ perPage: effectivePerPage,
17409
+ page,
17410
+ orderBy: effectiveOrderBy,
17411
+ filter: filter32,
17412
+ ...vectorResults?.length ? {
17413
+ include: vectorResults.map((r) => ({
17414
+ id: r.metadata?.message_id,
17415
+ threadId: r.metadata?.thread_id,
17416
+ withNextMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.after,
17417
+ withPreviousMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.before
17418
+ }))
17419
+ } : {}
17420
+ });
17421
+ const rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;
17422
+ const list = new MessageList({ threadId, resourceId }).add(rawMessages, "memory");
17423
+ const messages = filterSystemReminderMessages(list.get.all.db(), includeSystemReminders);
17424
+ const { total, page: resultPage, perPage: resultPerPage, hasMore } = paginatedResult;
17425
+ const recallResult = { messages, usage, total, page: resultPage, perPage: resultPerPage, hasMore };
17426
+ span?.end({
17427
+ output: { success: true },
17428
+ attributes: {
17429
+ messageCount: messages.length,
17430
+ embeddingTokens: usage?.tokens,
17431
+ vectorResultCount: vectorResults.length
17432
+ }
17433
+ });
17434
+ return recallResult;
17435
+ } catch (error) {
17436
+ span?.error({ error, endSpan: true });
17437
+ throw error;
17359
17438
  }
17360
- const memoryStore = await this.getMemoryStore();
17361
- const effectivePerPage = historyDisabledByConfig ? 0 : perPage;
17362
- const paginatedResult = await memoryStore.listMessages({
17363
- threadId,
17364
- resourceId,
17365
- perPage: effectivePerPage,
17366
- page,
17367
- orderBy: effectiveOrderBy,
17368
- filter: filter32,
17369
- ...vectorResults?.length ? {
17370
- include: vectorResults.map((r) => ({
17371
- id: r.metadata?.message_id,
17372
- threadId: r.metadata?.thread_id,
17373
- withNextMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.after,
17374
- withPreviousMessages: typeof vectorConfig.messageRange === "number" ? vectorConfig.messageRange : vectorConfig.messageRange.before
17375
- }))
17376
- } : {}
17377
- });
17378
- const rawMessages = shouldGetNewestAndReverse ? paginatedResult.messages.reverse() : paginatedResult.messages;
17379
- const list = new MessageList({ threadId, resourceId }).add(rawMessages, "memory");
17380
- const messages = list.get.all.db();
17381
- const { total, page: resultPage, perPage: resultPerPage, hasMore } = paginatedResult;
17382
- return { messages, usage, total, page: resultPage, perPage: resultPerPage, hasMore };
17383
17439
  }
17384
17440
  async getThreadById({ threadId }) {
17385
17441
  const memoryStore = await this.getMemoryStore();
@@ -17489,45 +17545,60 @@ var Memory = class extends MastraMemory {
17489
17545
  threadId,
17490
17546
  resourceId,
17491
17547
  workingMemory,
17492
- memoryConfig
17548
+ memoryConfig,
17549
+ observabilityContext
17493
17550
  }) {
17494
17551
  const config = this.getMergedThreadConfig(memoryConfig || {});
17495
17552
  if (!config.workingMemory?.enabled) {
17496
17553
  throw new Error("Working memory is not enabled for this memory instance");
17497
17554
  }
17498
- const scope = config.workingMemory.scope || "resource";
17499
- if (scope === "resource" && !resourceId) {
17500
- throw new Error(
17501
- `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`
17502
- );
17503
- }
17504
- const mutexKey = scope === "resource" ? `resource-${resourceId}` : `thread-${threadId}`;
17505
- const mutex = this.updateWorkingMemoryMutexes.has(mutexKey) ? this.updateWorkingMemoryMutexes.get(mutexKey) : new Mutex();
17506
- this.updateWorkingMemoryMutexes.set(mutexKey, mutex);
17507
- const release = await mutex.acquire();
17555
+ const span = this.createMemorySpan(
17556
+ "update",
17557
+ observabilityContext,
17558
+ { threadId, resourceId },
17559
+ {
17560
+ workingMemoryEnabled: true
17561
+ }
17562
+ );
17508
17563
  try {
17509
- const memoryStore = await this.getMemoryStore();
17510
- if (scope === "resource" && resourceId) {
17511
- await memoryStore.updateResource({
17512
- resourceId,
17513
- workingMemory
17514
- });
17515
- } else {
17516
- const thread = await this.getThreadById({ threadId });
17517
- if (!thread) {
17518
- throw new Error(`Thread ${threadId} not found`);
17519
- }
17520
- await memoryStore.updateThread({
17521
- id: threadId,
17522
- title: thread.title || "",
17523
- metadata: {
17524
- ...thread.metadata,
17564
+ const scope = config.workingMemory.scope || "resource";
17565
+ if (scope === "resource" && !resourceId) {
17566
+ throw new Error(
17567
+ `Memory error: Resource-scoped working memory is enabled but no resourceId was provided. Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.`
17568
+ );
17569
+ }
17570
+ const mutexKey = scope === "resource" ? `resource-${resourceId}` : `thread-${threadId}`;
17571
+ const mutex = this.updateWorkingMemoryMutexes.has(mutexKey) ? this.updateWorkingMemoryMutexes.get(mutexKey) : new Mutex();
17572
+ this.updateWorkingMemoryMutexes.set(mutexKey, mutex);
17573
+ const release = await mutex.acquire();
17574
+ try {
17575
+ const memoryStore = await this.getMemoryStore();
17576
+ if (scope === "resource" && resourceId) {
17577
+ await memoryStore.updateResource({
17578
+ resourceId,
17525
17579
  workingMemory
17580
+ });
17581
+ } else {
17582
+ const thread = await this.getThreadById({ threadId });
17583
+ if (!thread) {
17584
+ throw new Error(`Thread ${threadId} not found`);
17526
17585
  }
17527
- });
17586
+ await memoryStore.updateThread({
17587
+ id: threadId,
17588
+ title: thread.title || "",
17589
+ metadata: {
17590
+ ...thread.metadata,
17591
+ workingMemory
17592
+ }
17593
+ });
17594
+ }
17595
+ } finally {
17596
+ release();
17528
17597
  }
17529
- } finally {
17530
- release();
17598
+ span?.end({ output: { success: true } });
17599
+ } catch (error) {
17600
+ span?.error({ error, endSpan: true });
17601
+ throw error;
17531
17602
  }
17532
17603
  }
17533
17604
  updateWorkingMemoryMutexes = /* @__PURE__ */ new Map();
@@ -17705,67 +17776,85 @@ ${workingMemory}`;
17705
17776
  }
17706
17777
  async saveMessages({
17707
17778
  messages,
17708
- memoryConfig
17779
+ memoryConfig,
17780
+ observabilityContext
17709
17781
  }) {
17710
- const updatedMessages = messages.map((m) => {
17711
- return this.updateMessageToHideWorkingMemoryV2(m);
17712
- }).filter((m) => Boolean(m));
17713
- const config = this.getMergedThreadConfig(memoryConfig);
17714
- const dbMessages = new MessageList({
17715
- generateMessageId: () => this.generateId()
17716
- }).add(updatedMessages, "memory").get.all.db();
17717
- const memoryStore = await this.getMemoryStore();
17718
- const result = await memoryStore.saveMessages({
17719
- messages: dbMessages
17782
+ const span = this.createMemorySpan("save", observabilityContext, void 0, {
17783
+ messageCount: messages.length
17720
17784
  });
17721
- let totalTokens = 0;
17722
- if (this.vector && config.semanticRecall) {
17723
- const embeddingData = [];
17724
- let dimension;
17725
- await Promise.all(
17726
- updatedMessages.map(async (message) => {
17727
- let textForEmbedding = null;
17728
- if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") {
17729
- textForEmbedding = message.content.content;
17730
- } else if (message.content.parts && message.content.parts.length > 0) {
17731
- const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
17732
- if (joined) textForEmbedding = joined;
17785
+ try {
17786
+ const updatedMessages = messages.map((m) => {
17787
+ return this.updateMessageToHideWorkingMemoryV2(m);
17788
+ }).filter((m) => Boolean(m));
17789
+ const config = this.getMergedThreadConfig(memoryConfig);
17790
+ const dbMessages = new MessageList({
17791
+ generateMessageId: () => this.generateId()
17792
+ }).add(updatedMessages, "memory").get.all.db();
17793
+ const memoryStore = await this.getMemoryStore();
17794
+ const result = await memoryStore.saveMessages({
17795
+ messages: dbMessages
17796
+ });
17797
+ let totalTokens = 0;
17798
+ if (this.vector && config.semanticRecall) {
17799
+ const embeddingData = [];
17800
+ let dimension;
17801
+ await Promise.all(
17802
+ updatedMessages.map(async (message) => {
17803
+ let textForEmbedding = null;
17804
+ if (message.content.content && typeof message.content.content === "string" && message.content.content.trim() !== "") {
17805
+ textForEmbedding = message.content.content;
17806
+ } else if (message.content.parts && message.content.parts.length > 0) {
17807
+ const joined = message.content.parts.filter((part) => part.type === "text").map((part) => part.text).join(" ").trim();
17808
+ if (joined) textForEmbedding = joined;
17809
+ }
17810
+ if (!textForEmbedding) return;
17811
+ const result2 = await this.embedMessageContent(textForEmbedding);
17812
+ dimension = result2.dimension;
17813
+ if (result2.usage?.tokens) {
17814
+ totalTokens += result2.usage.tokens;
17815
+ }
17816
+ embeddingData.push({
17817
+ embeddings: result2.embeddings,
17818
+ metadata: result2.chunks.map(() => ({
17819
+ message_id: message.id,
17820
+ thread_id: message.threadId,
17821
+ resource_id: message.resourceId
17822
+ }))
17823
+ });
17824
+ })
17825
+ );
17826
+ if (embeddingData.length > 0 && dimension !== void 0) {
17827
+ if (typeof this.vector === `undefined`) {
17828
+ throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);
17733
17829
  }
17734
- if (!textForEmbedding) return;
17735
- const result2 = await this.embedMessageContent(textForEmbedding);
17736
- dimension = result2.dimension;
17737
- if (result2.usage?.tokens) {
17738
- totalTokens += result2.usage.tokens;
17830
+ const { indexName } = await this.createEmbeddingIndex(dimension, config);
17831
+ const allVectors = [];
17832
+ const allMetadata = [];
17833
+ for (const data of embeddingData) {
17834
+ allVectors.push(...data.embeddings);
17835
+ allMetadata.push(...data.metadata);
17739
17836
  }
17740
- embeddingData.push({
17741
- embeddings: result2.embeddings,
17742
- metadata: result2.chunks.map(() => ({
17743
- message_id: message.id,
17744
- thread_id: message.threadId,
17745
- resource_id: message.resourceId
17746
- }))
17837
+ await this.vector.upsert({
17838
+ indexName,
17839
+ vectors: allVectors,
17840
+ metadata: allMetadata
17747
17841
  });
17748
- })
17749
- );
17750
- if (embeddingData.length > 0 && dimension !== void 0) {
17751
- if (typeof this.vector === `undefined`) {
17752
- throw new Error(`Tried to upsert embeddings but this Memory instance doesn't have an attached vector db.`);
17753
17842
  }
17754
- const { indexName } = await this.createEmbeddingIndex(dimension, config);
17755
- const allVectors = [];
17756
- const allMetadata = [];
17757
- for (const data of embeddingData) {
17758
- allVectors.push(...data.embeddings);
17759
- allMetadata.push(...data.metadata);
17760
- }
17761
- await this.vector.upsert({
17762
- indexName,
17763
- vectors: allVectors,
17764
- metadata: allMetadata
17765
- });
17766
17843
  }
17844
+ const saveResult = { ...result, usage: totalTokens > 0 ? { tokens: totalTokens } : void 0 };
17845
+ span?.end({
17846
+ output: { success: true },
17847
+ attributes: {
17848
+ messageCount: dbMessages.length,
17849
+ embeddingTokens: saveResult.usage?.tokens,
17850
+ semanticRecallEnabled: Boolean(config.semanticRecall)
17851
+ }
17852
+ });
17853
+ return saveResult;
17854
+ } catch (error) {
17855
+ span?.error({ error, endSpan: true });
17856
+ throw error;
17767
17857
  }
17768
- return { ...result, usage: totalTokens > 0 ? { tokens: totalTokens } : void 0 };
17769
17858
  }
17770
17859
  updateMessageToHideWorkingMemoryV2(message) {
17771
17860
  const newMessage = { ...message };
@@ -18037,7 +18126,7 @@ ${workingMemory}`;
18037
18126
  "Observational memory requires @mastra/core support for request-response-id-rotation. Please bump @mastra/core to a newer version."
18038
18127
  );
18039
18128
  }
18040
- const { ObservationalMemory: OMClass } = await import('./observational-memory-JQ34KLFS-KLWGOGP4.js');
18129
+ const { ObservationalMemory: OMClass } = await import('./observational-memory-OVRHDQRG-RC3PRA65.js');
18041
18130
  const onIndexObservations = this.hasRetrievalSearch(omConfig.retrieval) ? async (observation) => {
18042
18131
  await this.indexObservation(observation);
18043
18132
  } : void 0;
@@ -18300,6 +18389,32 @@ Notes:
18300
18389
  }))
18301
18390
  });
18302
18391
  }
18392
+ /**
18393
+ * Update per-record observational memory config overrides for a thread.
18394
+ * The provided config is deep-merged, so you only need to specify fields you want to change.
18395
+ *
18396
+ * @example
18397
+ * ```ts
18398
+ * await memory.updateObservationalMemoryConfig({
18399
+ * threadId: 'thread-1',
18400
+ * config: {
18401
+ * observation: { messageTokens: 2000 },
18402
+ * reflection: { observationTokens: 8000 },
18403
+ * },
18404
+ * });
18405
+ * ```
18406
+ */
18407
+ async updateObservationalMemoryConfig({
18408
+ threadId,
18409
+ resourceId,
18410
+ config
18411
+ }) {
18412
+ const omEngine = await this.omEngine;
18413
+ if (!omEngine) {
18414
+ throw new Error("Observational memory is not enabled");
18415
+ }
18416
+ await omEngine.updateRecordConfig(threadId, resourceId, config);
18417
+ }
18303
18418
  /**
18304
18419
  * Index a list of messages directly (without querying storage).
18305
18420
  * Used by observe-time indexing to vectorize newly-observed messages.
@@ -18473,7 +18588,7 @@ Notes:
18473
18588
  * - Message objects with 'id' properties
18474
18589
  * @returns Promise that resolves when all messages are deleted
18475
18590
  */
18476
- async deleteMessages(input) {
18591
+ async deleteMessages(input, observabilityContext) {
18477
18592
  let messageIds;
18478
18593
  if (!Array.isArray(input)) {
18479
18594
  throw new Error("Invalid input: must be an array of message IDs or message objects");
@@ -18494,10 +18609,19 @@ Notes:
18494
18609
  if (invalidIds.length > 0) {
18495
18610
  throw new Error("All message IDs must be non-empty strings");
18496
18611
  }
18497
- const memoryStore = await this.getMemoryStore();
18498
- await memoryStore.deleteMessages(messageIds);
18499
- if (this.vector) {
18500
- void this.deleteMessageVectors(messageIds);
18612
+ const span = this.createMemorySpan("delete", observabilityContext, void 0, {
18613
+ messageCount: messageIds.length
18614
+ });
18615
+ try {
18616
+ const memoryStore = await this.getMemoryStore();
18617
+ await memoryStore.deleteMessages(messageIds);
18618
+ if (this.vector) {
18619
+ void this.deleteMessageVectors(messageIds);
18620
+ }
18621
+ span?.end({ output: { success: true }, attributes: { messageCount: messageIds.length } });
18622
+ } catch (error) {
18623
+ span?.error({ error, endSpan: true });
18624
+ throw error;
18501
18625
  }
18502
18626
  }
18503
18627
  /**
@@ -18925,7 +19049,7 @@ Notes:
18925
19049
  if (!effectiveConfig) return null;
18926
19050
  const engine = await this.omEngine;
18927
19051
  if (!engine) return null;
18928
- const { ObservationalMemoryProcessor } = await import('./observational-memory-JQ34KLFS-KLWGOGP4.js');
19052
+ const { ObservationalMemoryProcessor } = await import('./observational-memory-OVRHDQRG-RC3PRA65.js');
18929
19053
  return new ObservationalMemoryProcessor(engine, this);
18930
19054
  }
18931
19055
  };
@@ -30130,5 +30254,5 @@ var OBSERVE_STREAM_LEGACY_AGENT_BUILDER_ACTION_ROUTE = createRoute({
30130
30254
  });
30131
30255
 
30132
30256
  export { CANCEL_AGENT_BUILDER_ACTION_RUN_ROUTE, CREATE_AGENT_BUILDER_ACTION_RUN_ROUTE, GET_AGENT_BUILDER_ACTION_BY_ID_ROUTE, GET_AGENT_BUILDER_ACTION_RUN_BY_ID_ROUTE, LIST_AGENT_BUILDER_ACTIONS_ROUTE, LIST_AGENT_BUILDER_ACTION_RUNS_ROUTE, OBSERVE_STREAM_AGENT_BUILDER_ACTION_ROUTE, OBSERVE_STREAM_LEGACY_AGENT_BUILDER_ACTION_ROUTE, RESUME_AGENT_BUILDER_ACTION_ROUTE, RESUME_ASYNC_AGENT_BUILDER_ACTION_ROUTE, RESUME_STREAM_AGENT_BUILDER_ACTION_ROUTE, START_AGENT_BUILDER_ACTION_RUN_ROUTE, START_ASYNC_AGENT_BUILDER_ACTION_ROUTE, STREAM_AGENT_BUILDER_ACTION_ROUTE, STREAM_LEGACY_AGENT_BUILDER_ACTION_ROUTE, agent_builder_exports };
30133
- //# sourceMappingURL=chunk-SZ2FSVP5.js.map
30134
- //# sourceMappingURL=chunk-SZ2FSVP5.js.map
30257
+ //# sourceMappingURL=chunk-TX3IIDZN.js.map
30258
+ //# sourceMappingURL=chunk-TX3IIDZN.js.map