@mastra/memory 1.41.3-alpha.1 → 1.41.3-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 (93) hide show
  1. package/dist/docs/SKILL.md +1 -1
  2. package/dist/docs/assets/SOURCE_MAP.json +71 -71
  3. package/dist/docs/references/docs-memory-observational-memory.md +3 -3
  4. package/dist/docs/references/docs-memory-working-memory.md +33 -0
  5. package/dist/hooks.cjs +0 -2
  6. package/dist/hooks.js +0 -2
  7. package/dist/index.cjs +1 -1
  8. package/dist/index.d.ts +26 -3
  9. package/dist/index.js +1 -1
  10. package/dist/processors/index.cjs +1 -1
  11. package/dist/processors/index.js +1 -1
  12. package/dist/processors/observational-memory/buffered-reflection-values.d.ts +7 -0
  13. package/dist/processors/observational-memory/buffering-coordinator.d.ts +38 -0
  14. package/dist/processors/observational-memory/reflector-runner.d.ts +14 -0
  15. package/dist/processors/working-memory-instruction-compat.d.ts +54 -0
  16. package/dist/{src-CKA5LbDL.cjs → src-CDIIMmAU.cjs} +1342 -884
  17. package/dist/{src-BvZXenIm.js → src-CDv__4kY.js} +521 -63
  18. package/package.json +8 -7
  19. package/dist/hooks.cjs.map +0 -1
  20. package/dist/hooks.d.ts.map +0 -1
  21. package/dist/hooks.js.map +0 -1
  22. package/dist/index.d.ts.map +0 -1
  23. package/dist/persistence-projection.test-utils.d.ts.map +0 -1
  24. package/dist/processors/index.d.ts.map +0 -1
  25. package/dist/processors/observational-memory/activation-ttl.d.ts.map +0 -1
  26. package/dist/processors/observational-memory/anchor-ids.d.ts.map +0 -1
  27. package/dist/processors/observational-memory/auto-model.d.ts.map +0 -1
  28. package/dist/processors/observational-memory/buffering-coordinator.d.ts.map +0 -1
  29. package/dist/processors/observational-memory/built-in-extractors.d.ts.map +0 -1
  30. package/dist/processors/observational-memory/commit-queue.d.ts.map +0 -1
  31. package/dist/processors/observational-memory/constants.d.ts.map +0 -1
  32. package/dist/processors/observational-memory/date-utils.d.ts.map +0 -1
  33. package/dist/processors/observational-memory/debug.d.ts.map +0 -1
  34. package/dist/processors/observational-memory/error.d.ts.map +0 -1
  35. package/dist/processors/observational-memory/extracted-values.d.ts.map +0 -1
  36. package/dist/processors/observational-memory/extraction-runner.d.ts.map +0 -1
  37. package/dist/processors/observational-memory/extractor.d.ts.map +0 -1
  38. package/dist/processors/observational-memory/hooks.d.ts.map +0 -1
  39. package/dist/processors/observational-memory/index.d.ts.map +0 -1
  40. package/dist/processors/observational-memory/internal-request-context.d.ts.map +0 -1
  41. package/dist/processors/observational-memory/markers.d.ts.map +0 -1
  42. package/dist/processors/observational-memory/measure-image-buffer.d.ts.map +0 -1
  43. package/dist/processors/observational-memory/message-utils.d.ts.map +0 -1
  44. package/dist/processors/observational-memory/model-by-input-tokens.d.ts.map +0 -1
  45. package/dist/processors/observational-memory/model-context.d.ts.map +0 -1
  46. package/dist/processors/observational-memory/observation-groups.d.ts.map +0 -1
  47. package/dist/processors/observational-memory/observation-strategies/async-buffer.d.ts.map +0 -1
  48. package/dist/processors/observational-memory/observation-strategies/base.d.ts.map +0 -1
  49. package/dist/processors/observational-memory/observation-strategies/index.d.ts.map +0 -1
  50. package/dist/processors/observational-memory/observation-strategies/resource-scoped.d.ts.map +0 -1
  51. package/dist/processors/observational-memory/observation-strategies/sync.d.ts.map +0 -1
  52. package/dist/processors/observational-memory/observation-strategies/thread-title.d.ts.map +0 -1
  53. package/dist/processors/observational-memory/observation-strategies/types.d.ts.map +0 -1
  54. package/dist/processors/observational-memory/observation-turn/index.d.ts.map +0 -1
  55. package/dist/processors/observational-memory/observation-turn/load-memory-context.d.ts.map +0 -1
  56. package/dist/processors/observational-memory/observation-turn/safe-buffer-prefix.d.ts.map +0 -1
  57. package/dist/processors/observational-memory/observation-turn/step.d.ts.map +0 -1
  58. package/dist/processors/observational-memory/observation-turn/turn.d.ts.map +0 -1
  59. package/dist/processors/observational-memory/observation-turn/types.d.ts.map +0 -1
  60. package/dist/processors/observational-memory/observation-utils.d.ts.map +0 -1
  61. package/dist/processors/observational-memory/observational-memory.d.ts.map +0 -1
  62. package/dist/processors/observational-memory/observer-agent.d.ts.map +0 -1
  63. package/dist/processors/observational-memory/observer-runner.d.ts.map +0 -1
  64. package/dist/processors/observational-memory/operation-registry.d.ts.map +0 -1
  65. package/dist/processors/observational-memory/processor.d.ts.map +0 -1
  66. package/dist/processors/observational-memory/record-lineage.d.ts.map +0 -1
  67. package/dist/processors/observational-memory/reflector-agent.d.ts.map +0 -1
  68. package/dist/processors/observational-memory/reflector-runner.d.ts.map +0 -1
  69. package/dist/processors/observational-memory/repro-capture.d.ts.map +0 -1
  70. package/dist/processors/observational-memory/retry.d.ts.map +0 -1
  71. package/dist/processors/observational-memory/string-utils.d.ts.map +0 -1
  72. package/dist/processors/observational-memory/summarize.d.ts.map +0 -1
  73. package/dist/processors/observational-memory/temporal-markers.d.ts.map +0 -1
  74. package/dist/processors/observational-memory/temporary-memory.d.ts.map +0 -1
  75. package/dist/processors/observational-memory/thresholds.d.ts.map +0 -1
  76. package/dist/processors/observational-memory/token-counter.d.ts.map +0 -1
  77. package/dist/processors/observational-memory/tool-argument-helpers.d.ts.map +0 -1
  78. package/dist/processors/observational-memory/tool-result-helpers.d.ts.map +0 -1
  79. package/dist/processors/observational-memory/tracing.d.ts.map +0 -1
  80. package/dist/processors/observational-memory/transform-hooks.d.ts.map +0 -1
  81. package/dist/processors/observational-memory/types.d.ts.map +0 -1
  82. package/dist/processors/observational-memory/wait-with-abort.d.ts.map +0 -1
  83. package/dist/processors/observational-memory/working-memory-extractor.d.ts.map +0 -1
  84. package/dist/processors/working-memory-state/index.d.ts.map +0 -1
  85. package/dist/processors/working-memory-state/processor.d.ts.map +0 -1
  86. package/dist/removed-subconscious.d.ts.map +0 -1
  87. package/dist/src-BvZXenIm.js.map +0 -1
  88. package/dist/src-CKA5LbDL.cjs.map +0 -1
  89. package/dist/system-reminders.d.ts.map +0 -1
  90. package/dist/tools/om-observations.d.ts.map +0 -1
  91. package/dist/tools/om-search-context.d.ts.map +0 -1
  92. package/dist/tools/om-tools.d.ts.map +0 -1
  93. package/dist/tools/working-memory.d.ts.map +0 -1
@@ -30359,6 +30359,65 @@ var WorkingMemoryExtractor = class extends Extractor {
30359
30359
  }, false, true);
30360
30360
  }
30361
30361
  };
30362
+ // src/processors/working-memory-instruction-compat.ts
30363
+ /**
30364
+ * Stand-in for core's `WorkingMemory` input processor on `@mastra/core` versions whose processor renders its own
30365
+ * built-in instruction text and has no instruction provider (every core before `getWorkingMemoryInstruction`
30366
+ * was added to `MastraMemory`, including 1.86.0-alpha.1 through 1.86.0-alpha.5). `Memory.getInputProcessors()`
30367
+ * swaps it in for the auto-created processor on those cores, so `Memory` subclass instruction overrides reach
30368
+ * the model there too (#29752).
30369
+ *
30370
+ * Loading and caching match core's `WorkingMemory.processInput` exactly; only the instruction comes from the
30371
+ * memory instance. Keep it in sync with packages/core/src/processors/memory/working-memory.ts.
30372
+ */
30373
+ var WorkingMemoryInstructionCompat = class {
30374
+ options;
30375
+ id = "working-memory";
30376
+ name = "WorkingMemory";
30377
+ constructor(options) {
30378
+ this.options = options;
30379
+ }
30380
+ async processInput(args) {
30381
+ const { messageList, requestContext } = args;
30382
+ const memoryContext = parseMemoryRequestContext(requestContext);
30383
+ const threadId = memoryContext?.thread?.id;
30384
+ const resourceId = memoryContext?.resourceId;
30385
+ if (!memoryContext || !threadId && !resourceId) return messageList;
30386
+ const scope = this.options.scope || "resource";
30387
+ const memoryRunState = memoryContext.runState?.();
30388
+ let workingMemoryData = null;
30389
+ if (scope === "thread" && threadId) {
30390
+ const stored = (memoryRunState?.thread ?? await this.options.storage.getThreadById({ threadId }))?.metadata?.workingMemory;
30391
+ workingMemoryData = typeof stored === "string" && stored ? stored : null;
30392
+ } else if (scope === "resource" && resourceId) {
30393
+ const loadWorkingMemory = async () => {
30394
+ const resource = await this.options.storage.getResourceById({ resourceId });
30395
+ return typeof resource?.workingMemory === "string" && resource.workingMemory ? resource.workingMemory : null;
30396
+ };
30397
+ workingMemoryData = memoryRunState ? await memoryRunState.load(`working-memory:resource:${resourceId}`, loadWorkingMemory) : await loadWorkingMemory();
30398
+ }
30399
+ const loadTemplate = () => this.options.getWorkingMemoryTemplate({ memoryConfig: memoryContext.memoryConfig });
30400
+ const template = (memoryRunState ? await memoryRunState.load("working-memory:template", loadTemplate) : await loadTemplate()) || this.options.template || {
30401
+ format: "markdown",
30402
+ content: this.options.defaultTemplate
30403
+ };
30404
+ const workingMemoryConfig = memoryContext.memoryConfig?.workingMemory;
30405
+ const isConfiguredReadOnly = Boolean(this.options.readOnly || memoryContext.memoryConfig?.readOnly);
30406
+ const isAppManaged = this.options.agentManaged === false || typeof workingMemoryConfig === "object" && workingMemoryConfig.agentManaged === false;
30407
+ const instruction = this.options.renderInstruction(isConfiguredReadOnly || isAppManaged ? {
30408
+ kind: "read-only",
30409
+ template,
30410
+ data: workingMemoryData,
30411
+ autoUpdated: !isConfiguredReadOnly
30412
+ } : {
30413
+ kind: this.options.useVNext ? "vnext" : "tool",
30414
+ template,
30415
+ data: workingMemoryData
30416
+ });
30417
+ if (instruction) messageList.addSystem(instruction, "memory");
30418
+ return messageList;
30419
+ }
30420
+ };
30362
30421
  // src/removed-subconscious.ts
30363
30422
  /**
30364
30423
  * Subconscious was removed. These stubs keep code written against older `@mastra/memory`
@@ -30492,13 +30551,57 @@ function getUnobservedPartsPreservingToolCallPairs(message) {
30492
30551
  if (id) unobservedResultIds.add(id);
30493
30552
  }
30494
30553
  if (unobservedResultIds.size === 0) return unobservedParts;
30495
- const preservedCalls = parts.slice(0, endMarkerIndex).filter((part) => {
30554
+ const preserved = [];
30555
+ let pendingReasoning = [];
30556
+ let toolSinceReasoning = false;
30557
+ let keptAnything = false;
30558
+ for (let i = 0; i < endMarkerIndex; i++) {
30559
+ const part = parts[i];
30496
30560
  const id = getToolInvocationId(part, "call");
30497
- return id !== void 0 && unobservedResultIds.has(id);
30498
- });
30499
- return preservedCalls.length > 0 ? [...preservedCalls, ...unobservedParts] : unobservedParts;
30561
+ if (id !== void 0 && unobservedResultIds.has(id)) {
30562
+ for (const index of pendingReasoning) preserved.push(parts[index]);
30563
+ pendingReasoning = [];
30564
+ toolSinceReasoning = true;
30565
+ preserved.push(part);
30566
+ keptAnything = true;
30567
+ continue;
30568
+ }
30569
+ if (part?.type === "reasoning" && hasReplayableReasoningMetadata(part)) {
30570
+ if (toolSinceReasoning) pendingReasoning = [];
30571
+ toolSinceReasoning = false;
30572
+ pendingReasoning.push(i);
30573
+ continue;
30574
+ }
30575
+ if (part?.type === "tool-invocation") {
30576
+ toolSinceReasoning = true;
30577
+ continue;
30578
+ }
30579
+ if (part?.type === "step-start") {
30580
+ if (toolSinceReasoning) pendingReasoning = [];
30581
+ continue;
30582
+ }
30583
+ if (part?.type === "text") continue;
30584
+ pendingReasoning = [];
30585
+ }
30586
+ return keptAnything ? [...preserved, ...unobservedParts] : unobservedParts;
30500
30587
  }
30501
30588
  /**
30589
+ * Reasoning part metadata a provider can replay (a signature, redacted payload, item id).
30590
+ * Mirrors `hasReplayableReasoningMetadata` in `@mastra/core`'s message-list utils.
30591
+ */
30592
+ function hasReplayableReasoningMetadata(part) {
30593
+ const metadata = part.providerMetadata;
30594
+ if (!metadata || typeof metadata !== "object") return false;
30595
+ return Object.values(metadata).some((value) => !!value && typeof value === "object" && REPLAYABLE_REASONING_KEYS.some((key) => key in value));
30596
+ }
30597
+ const REPLAYABLE_REASONING_KEYS = [
30598
+ "signature",
30599
+ "redactedData",
30600
+ "itemId",
30601
+ "reasoningEncryptedContent",
30602
+ "thoughtSignature"
30603
+ ];
30604
+ /**
30502
30605
  * Get the messages Observational Memory is allowed to work with.
30503
30606
  *
30504
30607
  * Messages supplied through the `context` option and the synthetic `om-continuation`
@@ -32923,6 +33026,79 @@ var BufferingCoordinator = class BufferingCoordinator {
32923
33026
  * Key format: "refl:{lockKey}"
32924
33027
  */
32925
33028
  static reflectionBufferCycleIds = /* @__PURE__ */ new Map();
33029
+ /**
33030
+ * The buffered-reflection op that set the reflection boundary and cycle, and the generation
33031
+ * it buffers for. Key format: "refl:{lockKey}"
33032
+ */
33033
+ static reflectionBufferOwners = /* @__PURE__ */ new Map();
33034
+ /** Set the reflection boundary for a new buffered-reflection op on generation `recordId`. */
33035
+ static startReflectionBuffer(bufferKey, tokens, recordId) {
33036
+ const owner = {
33037
+ recordId,
33038
+ retired: false
33039
+ };
33040
+ BufferingCoordinator.lastBufferedBoundary.set(bufferKey, tokens);
33041
+ BufferingCoordinator.reflectionBufferOwners.set(bufferKey, owner);
33042
+ return owner;
33043
+ }
33044
+ /** Drop this process's reflection boundary, cycle, and owner. */
33045
+ static clearReflectionBuffer(bufferKey) {
33046
+ BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
33047
+ BufferingCoordinator.reflectionBufferCycleIds.delete(bufferKey);
33048
+ BufferingCoordinator.reflectionBufferOwners.delete(bufferKey);
33049
+ }
33050
+ /**
33051
+ * Another writer retired generation `recordId`, so a buffer this process prepared for it can
33052
+ * never activate. Its boundary and cycle are dropped now, or, while the op that set them is
33053
+ * still running (it may be awaiting its `onReflectionEnd` hook), when that op finishes. State
33054
+ * owned by a newer generation is kept.
33055
+ */
33056
+ static retireReflectionBuffer(bufferKey, recordId) {
33057
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
33058
+ if (owner && owner.recordId !== recordId) return;
33059
+ if (owner && BufferingCoordinator.asyncBufferingOps.has(bufferKey)) {
33060
+ owner.retired = true;
33061
+ return;
33062
+ }
33063
+ BufferingCoordinator.clearReflectionBuffer(bufferKey);
33064
+ }
33065
+ /**
33066
+ * Reconcile this process's reflection buffer state against an observed head record.
33067
+ * Whenever `head.id` differs from `owner.recordId`, confirm against a fresh storage read started
33068
+ * after `owner` existed (never trusting `generationCount`, which resets to 0 after `clear()`):
33069
+ * only retire/clear when storage's live head is no longer `owner.recordId`.
33070
+ */
33071
+ static async reconcileReflectionBufferHead(bufferKey, headId, readLiveHead) {
33072
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
33073
+ if (!owner || owner.recordId === headId) return;
33074
+ const ownerRecordId = owner.recordId;
33075
+ const live = await readLiveHead();
33076
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner || owner.recordId !== ownerRecordId) return;
33077
+ if (live?.id === ownerRecordId) return;
33078
+ if (BufferingCoordinator.asyncBufferingOps.has(bufferKey)) {
33079
+ owner.retired = true;
33080
+ return;
33081
+ }
33082
+ BufferingCoordinator.clearReflectionBuffer(bufferKey);
33083
+ }
33084
+ /**
33085
+ * Take the buffered-reflection cycle id for generation `recordId` and release its
33086
+ * coordinator state after its buffer activates. State owned by another generation
33087
+ * is left untouched.
33088
+ */
33089
+ static consumeReflectionBuffer(bufferKey, recordId) {
33090
+ const owner = BufferingCoordinator.reflectionBufferOwners.get(bufferKey);
33091
+ if (owner && owner.recordId !== recordId) return void 0;
33092
+ const cycleId = BufferingCoordinator.reflectionBufferCycleIds.get(bufferKey);
33093
+ if (owner && BufferingCoordinator.asyncBufferingOps.has(bufferKey)) owner.retired = true;
33094
+ else BufferingCoordinator.clearReflectionBuffer(bufferKey);
33095
+ return cycleId;
33096
+ }
33097
+ /** Called when the op that started as `owner` finishes; completes a deferred retirement. */
33098
+ static finishReflectionBuffer(bufferKey, owner) {
33099
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) return;
33100
+ if (owner.retired) BufferingCoordinator.clearReflectionBuffer(bufferKey);
33101
+ }
32926
33102
  constructor(opts) {
32927
33103
  this.observationConfig = opts.observationConfig;
32928
33104
  this.reflectionConfig = opts.reflectionConfig;
@@ -32978,6 +33154,7 @@ var BufferingCoordinator = class BufferingCoordinator {
32978
33154
  BufferingCoordinator.asyncBufferingOps.delete(obsBufKey);
32979
33155
  BufferingCoordinator.asyncBufferingOps.delete(reflBufKey);
32980
33156
  BufferingCoordinator.reflectionBufferCycleIds.delete(reflBufKey);
33157
+ BufferingCoordinator.reflectionBufferOwners.delete(reflBufKey);
32981
33158
  }
32982
33159
  }
32983
33160
  /**
@@ -35845,6 +36022,80 @@ var ObservationTurn = class {
35845
36022
  };
35846
36023
  }
35847
36024
  };
36025
+ // src/processors/observational-memory/buffered-reflection-values.ts
36026
+ const pendingValuesBaseSchema = z.object({
36027
+ recordId: z.string(),
36028
+ reflectedObservationLineCount: z.number(),
36029
+ values: z.record(z.string(), z.unknown())
36030
+ });
36031
+ const pendingValuesSchema = z.union([pendingValuesBaseSchema.extend({
36032
+ reflectionDigest: z.string().regex(/^[a-f0-9]{64}$/),
36033
+ reflection: z.never().optional()
36034
+ }), pendingValuesBaseSchema.extend({
36035
+ reflection: z.string(),
36036
+ reflectionDigest: z.never().optional()
36037
+ })]);
36038
+ const metadataSchema = z.record(z.string(), z.unknown());
36039
+ function reflectionDigest(reflection) {
36040
+ return createHash("sha256").update(reflection).digest("hex");
36041
+ }
36042
+ function getMastraMetadata(metadata) {
36043
+ const parsed = metadataSchema.safeParse(metadata?.mastra);
36044
+ return parsed.success ? parsed.data : {};
36045
+ }
36046
+ /** Keep prepared values outside active OM metadata, durable across Memory instances. */
36047
+ async function stageBufferedReflectionValues(storage, record, values) {
36048
+ if (!record.threadId || !record.bufferedReflection) return;
36049
+ const digest = reflectionDigest(record.bufferedReflection);
36050
+ await storage.updateThreadMetadata({
36051
+ id: record.threadId,
36052
+ update: (thread) => ({
36053
+ ...thread.metadata,
36054
+ mastra: {
36055
+ ...getMastraMetadata(thread.metadata),
36056
+ omBufferedReflection: {
36057
+ recordId: record.id,
36058
+ reflectionDigest: digest,
36059
+ reflectedObservationLineCount: record.reflectedObservationLineCount ?? 0,
36060
+ values: values ?? {}
36061
+ }
36062
+ }
36063
+ })
36064
+ });
36065
+ }
36066
+ /** Called under the OM commit lock, only after this exact buffer was activated. */
36067
+ async function publishBufferedReflectionValues(storage, extractors, record) {
36068
+ if (!record.threadId || !record.bufferedReflection) return;
36069
+ const digest = reflectionDigest(record.bufferedReflection);
36070
+ await storage.updateThreadMetadata({
36071
+ id: record.threadId,
36072
+ update: (thread) => {
36073
+ const mastra = getMastraMetadata(thread.metadata);
36074
+ const parsed = pendingValuesSchema.safeParse(mastra.omBufferedReflection);
36075
+ if (!parsed.success) return;
36076
+ const pending = parsed.data;
36077
+ if (pending.recordId !== record.id || (pending.reflectionDigest !== void 0 ? pending.reflectionDigest !== digest : pending.reflection !== record.bufferedReflection) || pending.reflectedObservationLineCount !== (record.reflectedObservationLineCount ?? 0)) return;
36078
+ const update = buildThreadMetadataFromExtractedValues(extractors, pending.values);
36079
+ const previous = getThreadOMMetadata(thread.metadata);
36080
+ const metadata = setThreadOMMetadata(thread.metadata, {
36081
+ currentTask: update.currentTask ?? previous?.currentTask,
36082
+ suggestedResponse: update.suggestedResponse ?? previous?.suggestedResponse,
36083
+ threadTitle: update.threadTitle ?? previous?.threadTitle,
36084
+ extracted: {
36085
+ ...previous?.extracted,
36086
+ ...update.extracted
36087
+ }
36088
+ });
36089
+ return {
36090
+ ...metadata,
36091
+ mastra: {
36092
+ ...getMastraMetadata(metadata),
36093
+ omBufferedReflection: null
36094
+ }
36095
+ };
36096
+ }
36097
+ });
36098
+ }
35848
36099
  // src/processors/observational-memory/reflector-agent.ts
35849
36100
  /**
35850
36101
  * Build the Reflector's system prompt.
@@ -36204,6 +36455,15 @@ function isReflectionApplied(returned, newRecordId, reflectedRecordId) {
36204
36455
  return returned.supersededBy === void 0 && returned.id !== reflectedRecordId;
36205
36456
  }
36206
36457
  /**
36458
+ * The active observations a buffered-reflection swap writes: the buffered reflection replaces the
36459
+ * first `reflectedLineCount` lines, and the trimmed remainder follows after a blank line. Mirrors
36460
+ * `swapBufferedReflectionToActive` in the storage adapters.
36461
+ */
36462
+ function bufferedActivationText({ bufferedReflection, observations, reflectedLineCount }) {
36463
+ const unreflected = observations.split("\n").slice(reflectedLineCount).join("\n").trim();
36464
+ return unreflected ? `${bufferedReflection}\n\n${unreflected}` : bufferedReflection;
36465
+ }
36466
+ /**
36207
36467
  * Runs the Reflector agent for compressing observations.
36208
36468
  * Handles synchronous reflection, async buffered reflection, and activation.
36209
36469
  */
@@ -36512,18 +36772,18 @@ var ReflectorRunner = class {
36512
36772
  startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
36513
36773
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
36514
36774
  if (this.buffering.isAsyncBufferingInProgress(bufferKey)) return;
36515
- BufferingCoordinator.lastBufferedBoundary.set(bufferKey, observationTokens);
36775
+ const owner = BufferingCoordinator.startReflectionBuffer(bufferKey, observationTokens, record.id);
36516
36776
  registerOp(record.id, "bufferingReflection");
36517
36777
  const flagSet = this.storage.setBufferingReflectionFlag(record.id, true).catch((err) => {
36518
36778
  omError("[OM] Failed to set buffering reflection flag", err);
36519
36779
  });
36520
- const asyncOp = (async () => {
36780
+ const run = async () => {
36521
36781
  await flagSet;
36522
36782
  let outcome;
36523
36783
  let reflectionError;
36524
36784
  try {
36525
36785
  await reflectionHooks?.onReflectionStart?.();
36526
- outcome = await this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
36786
+ outcome = await this.doAsyncBufferedReflection(record, bufferKey, owner, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
36527
36787
  } catch (error) {
36528
36788
  reflectionError = error instanceof Error ? error : new Error(String(error));
36529
36789
  if (writer) try {
@@ -36546,7 +36806,7 @@ var ReflectorRunner = class {
36546
36806
  omError("[OM] Failed to persist buffering-failed marker after async buffered reflection failure", markerError);
36547
36807
  }
36548
36808
  omError("[OM] Async buffered reflection failed", error);
36549
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
36809
+ owner.retired = true;
36550
36810
  } finally {
36551
36811
  try {
36552
36812
  await reflectionHooks?.onReflectionEnd?.({
@@ -36557,13 +36817,15 @@ var ReflectorRunner = class {
36557
36817
  } catch (hookError) {
36558
36818
  omError("[OM] onReflectionEnd hook failed after async buffered reflection", hookError);
36559
36819
  }
36560
- BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
36820
+ BufferingCoordinator.finishReflectionBuffer(bufferKey, owner);
36821
+ if (BufferingCoordinator.asyncBufferingOps.get(bufferKey) === asyncOp) BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
36561
36822
  unregisterOp(record.id, "bufferingReflection");
36562
36823
  await this.storage.setBufferingReflectionFlag(record.id, false).catch((err) => {
36563
36824
  omError("[OM] Failed to clear buffering reflection flag", err);
36564
36825
  });
36565
36826
  }
36566
- })();
36827
+ };
36828
+ const asyncOp = run();
36567
36829
  BufferingCoordinator.asyncBufferingOps.set(bufferKey, asyncOp);
36568
36830
  this.trackBackgroundWork?.(asyncOp, lockKey);
36569
36831
  }
@@ -36571,13 +36833,27 @@ var ReflectorRunner = class {
36571
36833
  * Perform async buffered reflection — reflects observations and stores to bufferedReflection.
36572
36834
  * Does NOT create a new generation or update activeObservations.
36573
36835
  */
36574
- async doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
36575
- const currentRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId) ?? record;
36836
+ async doAsyncBufferedReflection(record, bufferKey, owner, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
36837
+ const freshRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
36838
+ if (BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) {
36839
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: ${bufferKey} was cleared while the op waited; stopping`);
36840
+ return;
36841
+ }
36842
+ const currentRecord = freshRecord ?? record;
36843
+ if (freshRecord?.bufferedReflection) {
36844
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: live head ${freshRecord.id} already has a buffered reflection; skipping duplicate run`);
36845
+ owner.retired = true;
36846
+ return;
36847
+ }
36576
36848
  const observationTokens = currentRecord.observationTokenCount ?? 0;
36577
36849
  const reflectThreshold = getMaxThreshold(this.getEffectiveReflectionTokens(currentRecord));
36578
36850
  const bufferActivation = this.reflectionConfig.bufferActivation ?? .5;
36579
36851
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
36580
36852
  const cycleId = `reflect-buf-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
36853
+ if (owner.recordId !== currentRecord.id) {
36854
+ owner.recordId = currentRecord.id;
36855
+ owner.retired = false;
36856
+ }
36581
36857
  BufferingCoordinator.reflectionBufferCycleIds.set(bufferKey, cycleId);
36582
36858
  const allLines = (currentRecord.activeObservations ?? "").split("\n");
36583
36859
  const totalLines = allLines.length;
@@ -36614,10 +36890,18 @@ var ReflectorRunner = class {
36614
36890
  const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
36615
36891
  const reflectResult = await this.call(activeObservations, void 0, void 0, compressionTarget, void 0, true, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal, currentModel);
36616
36892
  reflectResult.observations = await applyTextTransform(this.hooks, "afterReflection", reflectResult.observations, hookContext);
36893
+ if (!reflectResult.observations.trim()) {
36894
+ omDebug(`[OM:reflect] doAsyncBufferedReflection: reflection for ${currentRecord.id} is empty after afterReflection; discarding it`);
36895
+ owner.retired = true;
36896
+ return {
36897
+ usage: reflectResult.usage,
36898
+ providerMetadata: reflectResult.providerMetadata
36899
+ };
36900
+ }
36617
36901
  const reflectionTokenCount = this.tokenCounter.countObservations(reflectResult.observations);
36618
36902
  omDebug(`[OM:reflect] doAsyncBufferedReflection: reflector returned ${reflectionTokenCount} tokens (${reflectResult.observations?.length} chars), saving to recordId=${currentRecord.id}`);
36619
36903
  if (!await runOMCommit(this.buffering.getLockKey(currentRecord.threadId, currentRecord.resourceId), async () => {
36620
- if ((await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId))?.id !== currentRecord.id) return false;
36904
+ if ((await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId))?.id !== currentRecord.id || BufferingCoordinator.reflectionBufferOwners.get(bufferKey) !== owner) return false;
36621
36905
  await this.storage.updateBufferedReflection({
36622
36906
  id: currentRecord.id,
36623
36907
  reflection: reflectResult.observations,
@@ -36625,17 +36909,18 @@ var ReflectorRunner = class {
36625
36909
  inputTokenCount: sliceTokenEstimate,
36626
36910
  reflectedObservationLineCount
36627
36911
  });
36912
+ const buffered = await this.storage.getObservationalMemory(currentRecord.threadId, currentRecord.resourceId);
36913
+ if (buffered?.id === currentRecord.id && buffered.bufferedReflection === reflectResult.observations) await stageBufferedReflectionValues(this.storage, buffered, reflectResult.extractedValues);
36628
36914
  return true;
36629
36915
  })) {
36630
36916
  omDebug(`[OM:reflect] doAsyncBufferedReflection: record ${currentRecord.id} is no longer the head; discarding the buffered reflection`);
36631
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
36917
+ owner.retired = true;
36632
36918
  return {
36633
36919
  usage: reflectResult.usage,
36634
36920
  providerMetadata: reflectResult.providerMetadata
36635
36921
  };
36636
36922
  }
36637
36923
  omDebug(`[OM:reflect] doAsyncBufferedReflection: bufferedReflection saved with lineCount=${reflectedObservationLineCount}`);
36638
- await persistThreadExtractedValues(this.storage, this.reflectionConfig.extractors, currentRecord.threadId ?? void 0, reflectResult.extractedValues);
36639
36924
  if (writer) {
36640
36925
  const endMarker = createBufferingEndMarker({
36641
36926
  cycleId,
@@ -36661,6 +36946,57 @@ var ReflectorRunner = class {
36661
36946
  };
36662
36947
  }
36663
36948
  /**
36949
+ * Decide what a buffered-reflection swap did. Built-in adapters only swap the buffer and line
36950
+ * count in the snapshot, return the stored record (no new generation) when another writer
36951
+ * extended them after the head check, and mark a generation they created after that check with
36952
+ * `bufferedReflectionVerified`. Adapters without that check build the new generation from
36953
+ * whatever is stored. Either way the swap must also produce what the snapshot's buffer and line
36954
+ * count give from the text the swap retired (retired records are never written again, so that
36955
+ * text is exactly what the swap read).
36956
+ *
36957
+ * Staged values are published only with the adapter's proof. Without it an extension that
36958
+ * repeats the unreflected tail produces the same text as the snapshot's buffer, so the values
36959
+ * fail closed: the activation still applies, but the staged values stay unpublished.
36960
+ */
36961
+ async classifyBufferedReflectionSwap({ result, newRecordId, snapshot, bufferedReflection, reflectedLineCount }) {
36962
+ if (result.id === snapshot.id) return {
36963
+ kind: "not-applied",
36964
+ headId: result.id
36965
+ };
36966
+ const createdByThisSwap = result.id === newRecordId;
36967
+ if (!createdByThisSwap && result.supersededBy !== void 0) return {
36968
+ kind: "not-applied",
36969
+ headId: result.id
36970
+ };
36971
+ const swapActiveObservations = result.activeObservations;
36972
+ const bufferedReflectionVerified = result.bufferedReflectionVerified === true;
36973
+ let matchesSnapshotBuffer = false;
36974
+ try {
36975
+ const retired = (await this.storage.getObservationalMemoryHistory(snapshot.threadId, snapshot.resourceId, 5, { recordId: snapshot.id })).find((candidate) => candidate.id === snapshot.id);
36976
+ matchesSnapshotBuffer = retired !== void 0 && swapActiveObservations === bufferedActivationText({
36977
+ bufferedReflection,
36978
+ observations: retired.activeObservations,
36979
+ reflectedLineCount
36980
+ });
36981
+ } catch (error) {
36982
+ omError("[OM] Failed to read the generation retired by buffered reflection activation", error);
36983
+ }
36984
+ const snapshotBufferActivated = matchesSnapshotBuffer && bufferedReflectionVerified;
36985
+ if (createdByThisSwap) return {
36986
+ kind: "applied",
36987
+ record: result,
36988
+ snapshotBufferActivated
36989
+ };
36990
+ return matchesSnapshotBuffer ? {
36991
+ kind: "applied",
36992
+ record: result,
36993
+ snapshotBufferActivated
36994
+ } : {
36995
+ kind: "not-applied",
36996
+ headId: result.id
36997
+ };
36998
+ }
36999
+ /**
36664
37000
  * Try to activate buffered reflection when threshold is reached.
36665
37001
  * Returns a discriminated result so the caller can distinguish between
36666
37002
  * "activated", "no buffer present", and "suppressed by overshoot guard"
@@ -36680,18 +37016,26 @@ var ReflectorRunner = class {
36680
37016
  }
36681
37017
  }
36682
37018
  }
36683
- const freshRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
37019
+ const storedRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
37020
+ const freshRecord = storedRecord ? { ...storedRecord } : void 0;
36684
37021
  omDebug(`[OM:reflect] tryActivateBufferedReflection: recordId=${record.id}, hasBufferedReflection=${!!freshRecord?.bufferedReflection}, bufferedReflectionLen=${freshRecord?.bufferedReflection?.length ?? 0}`);
36685
37022
  omDebug(`[OM:reflect] tryActivateBufferedReflection: freshRecord.id=${freshRecord?.id}, freshBufferedReflection=${freshRecord?.bufferedReflection ? "present (" + freshRecord.bufferedReflection.length + " chars)" : "empty"}, freshObsTokens=${freshRecord?.observationTokenCount}`);
37023
+ if (freshRecord) await BufferingCoordinator.reconcileReflectionBufferHead(bufferKey, freshRecord.id, () => this.storage.getObservationalMemory(record.threadId, record.resourceId));
36686
37024
  if (!freshRecord?.bufferedReflection) {
36687
37025
  omDebug(`[OM:reflect] tryActivateBufferedReflection: no buffered reflection after re-fetch`);
36688
37026
  return { status: "no-buffer" };
36689
37027
  }
36690
37028
  const beforeTokens = freshRecord.observationTokenCount ?? 0;
36691
37029
  const reflectedLineCount = freshRecord.reflectedObservationLineCount ?? 0;
36692
- const unreflectedLines = (freshRecord.activeObservations ?? "").split("\n").slice(reflectedLineCount);
37030
+ const currentObservations = freshRecord.activeObservations ?? "";
37031
+ const unreflectedLines = currentObservations.split("\n").slice(reflectedLineCount);
36693
37032
  const unreflectedContent = unreflectedLines.join("\n").trim();
36694
- const combinedObservations = unreflectedContent ? `${freshRecord.bufferedReflection}\n\n${unreflectedContent}` : freshRecord.bufferedReflection;
37033
+ const bufferedReflection = freshRecord.bufferedReflection;
37034
+ const combinedObservations = bufferedActivationText({
37035
+ bufferedReflection,
37036
+ observations: currentObservations,
37037
+ reflectedLineCount
37038
+ });
36695
37039
  const combinedTokenCount = this.tokenCounter.countObservations(combinedObservations);
36696
37040
  if (activationMetadata?.triggeredBy === "ttl" || activationMetadata?.triggeredBy === "provider_change") {
36697
37041
  const unreflectedTailTokens = unreflectedContent ? this.tokenCounter.countObservations(unreflectedContent) : 0;
@@ -36717,28 +37061,48 @@ var ReflectorRunner = class {
36717
37061
  }
36718
37062
  omDebug(`[OM:reflect] tryActivateBufferedReflection: activating, beforeTokens=${beforeTokens}, combinedTokenCount=${combinedTokenCount}, reflectedLineCount=${reflectedLineCount}, unreflectedLines=${unreflectedLines.length}`);
36719
37063
  const newRecordId = crypto.randomUUID();
36720
- const swapped = await runOMCommit(lockKey, () => {
37064
+ const commit = await runOMCommit(lockKey, async () => {
36721
37065
  abortSignal?.throwIfAborted();
36722
- return this.storage.swapBufferedReflectionToActive({
37066
+ const head = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
37067
+ if (head && (head.id !== freshRecord.id || head.bufferedReflection !== freshRecord.bufferedReflection || head.reflectedObservationLineCount !== freshRecord.reflectedObservationLineCount)) return {
37068
+ kind: "not-applied",
37069
+ headId: head.id
37070
+ };
37071
+ const result = await this.storage.swapBufferedReflectionToActive({
36723
37072
  currentRecord: freshRecord,
36724
37073
  tokenCount: combinedTokenCount,
36725
37074
  newRecordId
36726
37075
  });
37076
+ const outcome = await this.classifyBufferedReflectionSwap({
37077
+ result,
37078
+ newRecordId,
37079
+ snapshot: freshRecord,
37080
+ bufferedReflection,
37081
+ reflectedLineCount
37082
+ });
37083
+ if (outcome.kind === "applied" && outcome.snapshotBufferActivated) try {
37084
+ await publishBufferedReflectionValues(this.storage, this.reflectionConfig.extractors, freshRecord);
37085
+ } catch (error) {
37086
+ omError("[OM] Failed to publish buffered reflection values after activation", error);
37087
+ }
37088
+ return outcome;
36727
37089
  }, {
36728
37090
  priority: "reflection",
36729
37091
  abortSignal
36730
37092
  });
36731
- if (!isReflectionApplied(swapped, newRecordId, freshRecord.id)) {
36732
- omDebug(`[OM:reflect] tryActivateBufferedReflection: buffered reflection on ${freshRecord.id} not applied (head is ${swapped.id})`);
37093
+ if (commit.kind === "not-applied") {
37094
+ omDebug(`[OM:reflect] tryActivateBufferedReflection: buffered reflection on ${freshRecord.id} not applied (head is ${commit.headId})`);
37095
+ if (commit.headId !== freshRecord.id) BufferingCoordinator.retireReflectionBuffer(bufferKey, freshRecord.id);
36733
37096
  return { status: "not-applied" };
36734
37097
  }
36735
- BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
37098
+ if (!commit.snapshotBufferActivated) omDebug(`[OM:reflect] tryActivateBufferedReflection: ${commit.record.id} does not hold exactly the snapshot's buffered reflection (extended by another writer, or unverifiable); staged values stay unpublished`);
37099
+ const originalCycleId = BufferingCoordinator.consumeReflectionBuffer(bufferKey, freshRecord.id);
36736
37100
  const afterRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
36737
37101
  const afterTokens = afterRecord?.observationTokenCount ?? 0;
36738
37102
  omDebug(`[OM:reflect] tryActivateBufferedReflection: activation complete! beforeTokens=${beforeTokens}, afterTokens=${afterTokens}, newRecordId=${afterRecord?.id}, newGenCount=${afterRecord?.generationCount}`);
36739
37103
  if (writer) {
36740
37104
  const activationMarker = createActivationMarker({
36741
- cycleId: BufferingCoordinator.reflectionBufferCycleIds.get(bufferKey) ?? `reflect-act-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
37105
+ cycleId: originalCycleId ?? `reflect-act-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
36742
37106
  operationType: "reflection",
36743
37107
  chunksActivated: 1,
36744
37108
  tokensActivated: beforeTokens,
@@ -36764,7 +37128,6 @@ var ReflectorRunner = class {
36764
37128
  }).catch(() => {});
36765
37129
  await this.persistMarkerToMessage(activationMarker, messageList, freshRecord.threadId ?? "", freshRecord.resourceId ?? void 0, abortSignal);
36766
37130
  }
36767
- BufferingCoordinator.reflectionBufferCycleIds.delete(bufferKey);
36768
37131
  return { status: "activated" };
36769
37132
  }
36770
37133
  /**
@@ -36781,7 +37144,7 @@ var ReflectorRunner = class {
36781
37144
  const priorExtractedValues = await getThreadExtractedValues(this.storage, this.reflectionConfig.extractors, requestedThreadId ?? record.threadId);
36782
37145
  abortSignal?.throwIfAborted();
36783
37146
  if (this.buffering.isAsyncReflectionEnabled() && observationTokens < reflectThreshold) {
36784
- if ((() => {
37147
+ if (await (async () => {
36785
37148
  if (!this.buffering.isAsyncReflectionEnabled()) return false;
36786
37149
  if (record.isBufferingReflection) {
36787
37150
  if (isOpActiveInProcess(record.id, "bufferingReflection")) return false;
@@ -36789,6 +37152,7 @@ var ReflectorRunner = class {
36789
37152
  this.storage.setBufferingReflectionFlag(record.id, false).catch(() => {});
36790
37153
  }
36791
37154
  const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
37155
+ await BufferingCoordinator.reconcileReflectionBufferHead(bufferKey, record.id, () => this.storage.getObservationalMemory(record.threadId, record.resourceId));
36792
37156
  if (this.buffering.isAsyncBufferingInProgress(bufferKey)) return false;
36793
37157
  if (BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) return false;
36794
37158
  if (record.bufferedReflection) return false;
@@ -36834,6 +37198,11 @@ var ReflectorRunner = class {
36834
37198
  omDebug(`[OM:reflect] skipping async reflection — observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
36835
37199
  return;
36836
37200
  }
37201
+ const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
37202
+ if (this.buffering.isAsyncBufferingInProgress(bufferKey) || BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) {
37203
+ omDebug(`[OM:reflect] skipping async reflection — reflection buffer already active or present for ${bufferKey}`);
37204
+ return;
37205
+ }
36837
37206
  omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) — starting background reflection`);
36838
37207
  this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
36839
37208
  return;
@@ -40755,6 +41124,26 @@ function isTransientSignalMessage(message) {
40755
41124
  const metadata = message.content.metadata;
40756
41125
  return isRecord(metadata) && isRecord(metadata.signal) && !Array.isArray(metadata.signal) && metadata.signal.transient === true;
40757
41126
  }
41127
+ const DEFAULT_WORKING_MEMORY_TEMPLATE = `
41128
+ # User Information
41129
+ - **First Name**:
41130
+ - **Last Name**:
41131
+ - **Location**:
41132
+ - **Occupation**:
41133
+ - **Interests**:
41134
+ - **Goals**:
41135
+ - **Events**:
41136
+ - **Facts**:
41137
+ - **Projects**:
41138
+ `;
41139
+ /**
41140
+ * True when the installed `@mastra/core` builds its WorkingMemory processor with the memory instance as the
41141
+ * instruction provider. Cores from before `MastraMemory.getWorkingMemoryInstruction` existed (up to and
41142
+ * including 1.86.0-alpha.5) don't, and render their own built-in text. Checked per call, not at import.
41143
+ */
41144
+ function coreRendersWorkingMemoryInstructionThroughMemory() {
41145
+ return "getWorkingMemoryInstruction" in MastraMemory.prototype;
41146
+ }
40758
41147
  function normalizeObservationalMemoryConfig(config) {
40759
41148
  if (config === true) return { model: "auto" };
40760
41149
  if (config === false || config === void 0) return void 0;
@@ -41686,10 +42075,14 @@ ${workingMemory}`;
41686
42075
  if (scope === "resource" && !resourceId) throw new Error("Memory error: Resource-scoped working memory is enabled but no resourceId was provided. Either provide a resourceId or explicitly set workingMemory.scope to 'thread'.");
41687
42076
  if (scope === "resource" && resourceId) {
41688
42077
  const loadWorkingMemory = async () => {
41689
- return (await (await this.getMemoryStore()).getResourceById({ resourceId }))?.workingMemory || null;
42078
+ const resource = await (await this.getMemoryStore()).getResourceById({ resourceId });
42079
+ return typeof resource?.workingMemory === "string" && resource.workingMemory ? resource.workingMemory : null;
41690
42080
  };
41691
42081
  workingMemoryData = runState ? await runState.load(`working-memory:resource:${resourceId}`, loadWorkingMemory) : await loadWorkingMemory();
41692
- } else workingMemoryData = (runState?.threadLoaded ? runState.thread : await this.getThreadById({ threadId }))?.metadata?.workingMemory;
42082
+ } else {
42083
+ const stored = (runState?.threadLoaded ? runState.thread : await this.getThreadById({ threadId }))?.metadata?.workingMemory;
42084
+ workingMemoryData = typeof stored === "string" && stored ? stored : null;
42085
+ }
41693
42086
  if (!workingMemoryData) return null;
41694
42087
  return workingMemoryData;
41695
42088
  }
@@ -41736,18 +42129,17 @@ ${workingMemory}`;
41736
42129
  });
41737
42130
  if (!workingMemoryTemplate) return null;
41738
42131
  const workingMemoryConfig = config.workingMemory;
41739
- if (config?.readOnly || workingMemoryConfig.agentManaged === false) return this.getReadOnlyWorkingMemoryInstruction({
42132
+ const args = config?.readOnly || workingMemoryConfig.agentManaged === false ? {
42133
+ kind: "read-only",
41740
42134
  template: workingMemoryTemplate,
41741
42135
  data: workingMemoryData,
41742
42136
  autoUpdated: !config?.readOnly
41743
- });
41744
- return this.isVNextWorkingMemoryConfig(memoryConfig) ? this.__experimental_getWorkingMemoryToolInstructionVNext({
41745
- template: workingMemoryTemplate,
41746
- data: workingMemoryData
41747
- }) : this.getWorkingMemoryToolInstruction({
42137
+ } : {
42138
+ kind: "version" in workingMemoryConfig && workingMemoryConfig.version === "vnext" ? "vnext" : "tool",
41748
42139
  template: workingMemoryTemplate,
41749
42140
  data: workingMemoryData
41750
- });
42141
+ };
42142
+ return (this.getWorkingMemoryInstruction(args) ?? this.renderBuiltInWorkingMemoryInstruction(args)) || null;
41751
42143
  }
41752
42144
  /** Fetch current stored copies of messages in a resumed turn, bypassing run-state history caches. */
41753
42145
  async getPersistedMessages(threadId, ids) {
@@ -41994,19 +42386,8 @@ ${workingMemory}`;
41994
42386
  } : void 0
41995
42387
  });
41996
42388
  }
41997
- defaultWorkingMemoryTemplate = `
41998
- # User Information
41999
- - **First Name**:
42000
- - **Last Name**:
42001
- - **Location**:
42002
- - **Occupation**:
42003
- - **Interests**:
42004
- - **Goals**:
42005
- - **Events**:
42006
- - **Facts**:
42007
- - **Projects**:
42008
- `;
42009
- getWorkingMemoryToolInstruction({ template, data }) {
42389
+ defaultWorkingMemoryTemplate = DEFAULT_WORKING_MEMORY_TEMPLATE;
42390
+ builtInWorkingMemoryToolInstruction({ template, data }) {
42010
42391
  const emptyWorkingMemoryTemplateObject = template.format === "json" ? generateEmptyFromSchema(template.content) : null;
42011
42392
  const hasEmptyWorkingMemoryTemplateObject = emptyWorkingMemoryTemplateObject && Object.keys(emptyWorkingMemoryTemplateObject).length > 0;
42012
42393
  return `WORKING_MEMORY_SYSTEM_INSTRUCTION:
@@ -42042,7 +42423,8 @@ Notes:
42042
42423
  - IMPORTANT: You MUST call updateWorkingMemory in every response to a prompt where you received relevant information.
42043
42424
  - IMPORTANT: Preserve the ${template.format === "json" ? "JSON" : "Markdown"} formatting structure above while updating the content.`;
42044
42425
  }
42045
- __experimental_getWorkingMemoryToolInstructionVNext({ template, data }) {
42426
+ builtInWorkingMemoryToolInstructionVNext({ template, data }) {
42427
+ const templateContent = typeof template.content === "string" ? template.content : JSON.stringify(template.content);
42046
42428
  return `WORKING_MEMORY_SYSTEM_INSTRUCTION:
42047
42429
  Store and update any conversation-relevant information by calling the updateWorkingMemory tool.
42048
42430
 
@@ -42055,7 +42437,7 @@ Guidelines:
42055
42437
  6. Information not being relevant to the current conversation is not a valid reason to replace or remove working memory information. Your working memory spans across multiple conversations and may be needed again later, even if it's not currently relevant.
42056
42438
 
42057
42439
  <working_memory_template>
42058
- ${template.content}
42440
+ ${templateContent}
42059
42441
  </working_memory_template>
42060
42442
 
42061
42443
  <working_memory_data>
@@ -42064,7 +42446,7 @@ ${data || "No working memory data available."}
42064
42446
 
42065
42447
  Notes:
42066
42448
  - Update memory whenever referenced information changes
42067
- ${template.content !== this.defaultWorkingMemoryTemplate ? `- Only store information if it's in the working memory template, do not store other information unless the user asks you to remember it, as that non-template information may be irrelevant` : `- If you're unsure whether to store something, store it (eg if the user tells you information about themselves, call updateWorkingMemory immediately to update it)
42449
+ ${templateContent !== DEFAULT_WORKING_MEMORY_TEMPLATE ? `- Only store information if it's in the working memory template, do not store other information unless the user asks you to remember it, as that non-template information may be irrelevant` : `- If you're unsure whether to store something, store it (eg if the user tells you information about themselves, call updateWorkingMemory immediately to update it)
42068
42450
  `}
42069
42451
  - This system is here so that you can maintain the conversation when your context window is very short. Update your working memory because you may need it to maintain the conversation without the full conversation history
42070
42452
  - REMEMBER: the way you update your working memory is by calling the updateWorkingMemory tool with the ${template.format === "json" ? "JSON" : "Markdown"} content. The system will store it for you. The user will not see it.
@@ -42072,12 +42454,7 @@ ${template.content !== this.defaultWorkingMemoryTemplate ? `- Only store informa
42072
42454
  - IMPORTANT: Preserve the ${template.format === "json" ? "JSON" : "Markdown"} formatting structure above while updating the content.
42073
42455
  `;
42074
42456
  }
42075
- /**
42076
- * Generate read-only working memory instructions.
42077
- * This provides the working memory context without any tool update instructions.
42078
- * Used when memory is in readOnly mode, or with `autoUpdated` when the app updates it (agentManaged: false).
42079
- */
42080
- getReadOnlyWorkingMemoryInstruction({ data, autoUpdated = false }) {
42457
+ builtInReadOnlyWorkingMemoryInstruction({ data, autoUpdated = false }) {
42081
42458
  return `WORKING_MEMORY_SYSTEM_INSTRUCTION (${autoUpdated ? "AUTO-UPDATED" : "READ-ONLY"}):
42082
42459
  The following is your working memory - persistent information about the user and conversation collected over previous interactions. This data is provided for context to help you maintain continuity.
42083
42460
 
@@ -42094,6 +42471,46 @@ Notes:
42094
42471
  - This system is here so that you can maintain the conversation when your context window is very short
42095
42472
  - The user will not see the working memory data directly`;
42096
42473
  }
42474
+ /** Instruction for agents that update working memory with the updateWorkingMemory tool. Override to customize it. */
42475
+ getWorkingMemoryToolInstruction(args) {
42476
+ return this.builtInWorkingMemoryToolInstruction(args);
42477
+ }
42478
+ /** Instruction for `version: 'vnext'` template working memory. Override to customize it. */
42479
+ __experimental_getWorkingMemoryToolInstructionVNext(args) {
42480
+ return this.builtInWorkingMemoryToolInstructionVNext(args);
42481
+ }
42482
+ /**
42483
+ * Generate read-only working memory instructions.
42484
+ * This provides the working memory context without any tool update instructions.
42485
+ * Used when memory is in readOnly mode, or with `autoUpdated` when the app updates it (agentManaged: false).
42486
+ * Override to customize it.
42487
+ */
42488
+ getReadOnlyWorkingMemoryInstruction(args) {
42489
+ return this.builtInReadOnlyWorkingMemoryInstruction(args);
42490
+ }
42491
+ /**
42492
+ * Renders the working memory instruction an agent receives, using the instruction methods above,
42493
+ * so a subclass that overrides them changes what the model sees. Return `undefined` to use the
42494
+ * built-in instruction, or an empty string to send none.
42495
+ */
42496
+ getWorkingMemoryInstruction(args) {
42497
+ switch (args.kind) {
42498
+ case "read-only": return this.getReadOnlyWorkingMemoryInstruction(args);
42499
+ case "vnext": return this.__experimental_getWorkingMemoryToolInstructionVNext(args);
42500
+ case "tool": return this.getWorkingMemoryToolInstruction(args);
42501
+ }
42502
+ }
42503
+ /**
42504
+ * The built-in text, ignoring subclass overrides of the instruction methods. Used when
42505
+ * getWorkingMemoryInstruction returns `undefined`, matching the agent processor's own fallback.
42506
+ */
42507
+ renderBuiltInWorkingMemoryInstruction(args) {
42508
+ switch (args.kind) {
42509
+ case "read-only": return this.builtInReadOnlyWorkingMemoryInstruction(args);
42510
+ case "vnext": return this.builtInWorkingMemoryToolInstructionVNext(args);
42511
+ case "tool": return this.builtInWorkingMemoryToolInstruction(args);
42512
+ }
42513
+ }
42097
42514
  isVNextWorkingMemoryConfig(config) {
42098
42515
  if (!config?.workingMemory) return false;
42099
42516
  const isMDWorkingMemory = !(`schema` in config.workingMemory) && (typeof config.workingMemory.template === `string` || config.workingMemory.template) && config.workingMemory;
@@ -42793,8 +43210,11 @@ Notes:
42793
43210
  };
42794
43211
  }
42795
43212
  const moved = /* @__PURE__ */ new Set();
42796
- for (;;) {
42797
- const pending = (await vector.query({
43213
+ const deadline = Date.now() + 12e4;
43214
+ let retryDelayMs = 1e3;
43215
+ let complete = false;
43216
+ migration: while (Date.now() < deadline) {
43217
+ const stale = await vector.query({
42798
43218
  indexName,
42799
43219
  ...readParams,
42800
43220
  topK: 20,
@@ -42802,9 +43222,21 @@ Notes:
42802
43222
  thread_id: threadId,
42803
43223
  resource_id: { $ne: resourceId }
42804
43224
  }
42805
- })).filter((result) => !moved.has(result.id));
42806
- if (pending.length === 0) break;
43225
+ });
43226
+ if (stale.length === 0) {
43227
+ complete = true;
43228
+ break;
43229
+ }
43230
+ const pending = stale.filter((result) => !moved.has(result.id));
43231
+ if (pending.length === 0) {
43232
+ const delayMs = Math.min(retryDelayMs, Math.max(0, deadline - Date.now()));
43233
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
43234
+ retryDelayMs = Math.min(retryDelayMs * 2, 3e4);
43235
+ continue;
43236
+ }
43237
+ retryDelayMs = 1e3;
42807
43238
  for (const result of pending) {
43239
+ if (Date.now() >= deadline) break migration;
42808
43240
  moved.add(result.id);
42809
43241
  if (!result.metadata) {
42810
43242
  this.logger.warn("Skipping observation vector without metadata during thread transfer", {
@@ -42826,6 +43258,7 @@ Notes:
42826
43258
  });
42827
43259
  }
42828
43260
  }
43261
+ if (!complete) throw new Error(`Observation vector migration in index "${indexName}" did not complete within 120 seconds (${moved.size} vector IDs processed). The store may still be returning stale results; retry the transfer.`);
42829
43262
  }
42830
43263
  }
42831
43264
  /**
@@ -43026,6 +43459,10 @@ Notes:
43026
43459
  */
43027
43460
  async getInputProcessors(configuredProcessors = [], context) {
43028
43461
  const processors = await super.getInputProcessors(configuredProcessors, context);
43462
+ if (!coreRendersWorkingMemoryInstructionThroughMemory()) {
43463
+ const index = processors.findIndex((p) => p.id === "working-memory" && !configuredProcessors.includes(p));
43464
+ if (index !== -1) processors[index] = await this.createWorkingMemoryInstructionCompatProcessor(context);
43465
+ }
43029
43466
  const om = await this.createOMProcessor(configuredProcessors, context);
43030
43467
  if (om) processors.push(om);
43031
43468
  const wm = await this.createWorkingMemoryStateProcessor(configuredProcessors, context);
@@ -43074,6 +43511,29 @@ Notes:
43074
43511
  return new ObservationalMemoryProcessor(engine, this, { temporalMarkers: effectiveConfig.temporalMarkers });
43075
43512
  }
43076
43513
  /**
43514
+ * Builds the WorkingMemory input processor for cores without an instruction provider, from the same
43515
+ * config core's `MastraMemory.getInputProcessors()` uses for the processor it replaces.
43516
+ */
43517
+ async createWorkingMemoryInstructionCompatProcessor(context) {
43518
+ const runtimeMemory = context?.get("MastraMemory");
43519
+ const effectiveConfig = runtimeMemory?.memoryConfig ? this.getMergedThreadConfig(runtimeMemory.memoryConfig) : this.threadConfig;
43520
+ const workingMemory = typeof effectiveConfig.workingMemory === "object" ? effectiveConfig.workingMemory : void 0;
43521
+ return new WorkingMemoryInstructionCompat({
43522
+ storage: await this.getMemoryStore(),
43523
+ template: workingMemory?.template ? {
43524
+ format: "markdown",
43525
+ content: workingMemory.template
43526
+ } : void 0,
43527
+ scope: workingMemory?.scope,
43528
+ useVNext: workingMemory !== void 0 && "version" in workingMemory && workingMemory.version === "vnext",
43529
+ readOnly: effectiveConfig.readOnly,
43530
+ agentManaged: workingMemory?.agentManaged,
43531
+ defaultTemplate: DEFAULT_WORKING_MEMORY_TEMPLATE,
43532
+ getWorkingMemoryTemplate: (args) => this.getWorkingMemoryTemplate(args),
43533
+ renderInstruction: (args) => this.getWorkingMemoryInstruction(args) ?? this.renderBuiltInWorkingMemoryInstruction(args)
43534
+ });
43535
+ }
43536
+ /**
43077
43537
  * Creates a WorkingMemoryStateProcessor when working memory is enabled and the
43078
43538
  * `useStateSignals` opt-in is set. Returns null otherwise or if the processor
43079
43539
  * is already present in the user's configured processors.
@@ -43090,5 +43550,3 @@ Notes:
43090
43550
  }
43091
43551
  };
43092
43552
  export { WorkingMemoryExtractor as A, hasCurrentTaskSection as B, reconcileObservationGroupsFromReflection as C, KnowledgeSemanticIndexCoordinator as D, wrapInObservationGroup as E, OBSERVER_SYSTEM_PROMPT as F, stripEphemeralAnchorIds as G, parseObserverOutput as H, buildObserverPrompt as I, OBSERVATION_CONTEXT_INSTRUCTIONS as J, Extractor as K, buildObserverSystemPrompt as L, SUMMARIZE_THREAD_DEFAULTS as M, summarizeConversation as N, StaleKnowledgeSemanticIndexError as O, TokenCounter as P, getObservationContextPrompt as Q, extractCurrentTask as R, parseObservationGroups as S, stripObservationGroups as T, injectAnchorIds as U, optimizeObservationsForContext as V, parseAnchorId as W, OBSERVATION_CONTEXT_PROMPT_THREAD as X, OBSERVATION_CONTEXT_PROMPT as Y, OBSERVATION_CONTINUATION_HINT as Z, WORKING_MEMORY_STATE_PROCESSOR_ID as _, asUserTurn as a, combineObservationGroupRanges as b, extractWorkingMemoryTags as c, getObservationsAsOf as d, ObservationalMemoryProcessor as f, WORKING_MEMORY_STATE_ID as g, resolveAutoModelId as h, WorkingMemory as i, deepMergeWorkingMemory as j, Subconscious as k, removeWorkingMemoryTags as l, AUTO_MODEL_BY_PROVIDER as m, MessageHistory$1 as n, escapeTurnMarkup as o, ObservationalMemory as p, OBSERVATIONAL_MEMORY_DEFAULTS as q, SemanticRecall as r, extractWorkingMemoryContent as s, Memory as t, sealTurnMarkup as u, WorkingMemoryStateProcessor as v, renderObservationGroupsForReflection as w, deriveObservationGroupProvenance as x, ModelByInputTokens as y, formatMessagesForObserver as z };
43093
-
43094
- //# sourceMappingURL=src-BvZXenIm.js.map