@mastra/memory 1.41.3-alpha.2 → 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.
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +55 -55
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/processors/index.cjs +1 -1
- package/dist/processors/index.js +1 -1
- package/dist/processors/observational-memory/buffered-reflection-values.d.ts +7 -0
- package/dist/processors/observational-memory/buffering-coordinator.d.ts +38 -0
- package/dist/processors/observational-memory/reflector-runner.d.ts +14 -0
- package/dist/{src-BC-wnTHt.cjs → src-CDIIMmAU.cjs} +1109 -843
- package/dist/{src-CRmfe-8x.js → src-CDv__4kY.js} +288 -22
- package/package.json +5 -5
|
@@ -33026,6 +33026,79 @@ var BufferingCoordinator = class BufferingCoordinator {
|
|
|
33026
33026
|
* Key format: "refl:{lockKey}"
|
|
33027
33027
|
*/
|
|
33028
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
|
+
}
|
|
33029
33102
|
constructor(opts) {
|
|
33030
33103
|
this.observationConfig = opts.observationConfig;
|
|
33031
33104
|
this.reflectionConfig = opts.reflectionConfig;
|
|
@@ -33081,6 +33154,7 @@ var BufferingCoordinator = class BufferingCoordinator {
|
|
|
33081
33154
|
BufferingCoordinator.asyncBufferingOps.delete(obsBufKey);
|
|
33082
33155
|
BufferingCoordinator.asyncBufferingOps.delete(reflBufKey);
|
|
33083
33156
|
BufferingCoordinator.reflectionBufferCycleIds.delete(reflBufKey);
|
|
33157
|
+
BufferingCoordinator.reflectionBufferOwners.delete(reflBufKey);
|
|
33084
33158
|
}
|
|
33085
33159
|
}
|
|
33086
33160
|
/**
|
|
@@ -35948,6 +36022,80 @@ var ObservationTurn = class {
|
|
|
35948
36022
|
};
|
|
35949
36023
|
}
|
|
35950
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
|
+
}
|
|
35951
36099
|
// src/processors/observational-memory/reflector-agent.ts
|
|
35952
36100
|
/**
|
|
35953
36101
|
* Build the Reflector's system prompt.
|
|
@@ -36307,6 +36455,15 @@ function isReflectionApplied(returned, newRecordId, reflectedRecordId) {
|
|
|
36307
36455
|
return returned.supersededBy === void 0 && returned.id !== reflectedRecordId;
|
|
36308
36456
|
}
|
|
36309
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
|
+
/**
|
|
36310
36467
|
* Runs the Reflector agent for compressing observations.
|
|
36311
36468
|
* Handles synchronous reflection, async buffered reflection, and activation.
|
|
36312
36469
|
*/
|
|
@@ -36615,18 +36772,18 @@ var ReflectorRunner = class {
|
|
|
36615
36772
|
startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
|
|
36616
36773
|
const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
|
|
36617
36774
|
if (this.buffering.isAsyncBufferingInProgress(bufferKey)) return;
|
|
36618
|
-
BufferingCoordinator.
|
|
36775
|
+
const owner = BufferingCoordinator.startReflectionBuffer(bufferKey, observationTokens, record.id);
|
|
36619
36776
|
registerOp(record.id, "bufferingReflection");
|
|
36620
36777
|
const flagSet = this.storage.setBufferingReflectionFlag(record.id, true).catch((err) => {
|
|
36621
36778
|
omError("[OM] Failed to set buffering reflection flag", err);
|
|
36622
36779
|
});
|
|
36623
|
-
const
|
|
36780
|
+
const run = async () => {
|
|
36624
36781
|
await flagSet;
|
|
36625
36782
|
let outcome;
|
|
36626
36783
|
let reflectionError;
|
|
36627
36784
|
try {
|
|
36628
36785
|
await reflectionHooks?.onReflectionStart?.();
|
|
36629
|
-
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);
|
|
36630
36787
|
} catch (error) {
|
|
36631
36788
|
reflectionError = error instanceof Error ? error : new Error(String(error));
|
|
36632
36789
|
if (writer) try {
|
|
@@ -36649,7 +36806,7 @@ var ReflectorRunner = class {
|
|
|
36649
36806
|
omError("[OM] Failed to persist buffering-failed marker after async buffered reflection failure", markerError);
|
|
36650
36807
|
}
|
|
36651
36808
|
omError("[OM] Async buffered reflection failed", error);
|
|
36652
|
-
|
|
36809
|
+
owner.retired = true;
|
|
36653
36810
|
} finally {
|
|
36654
36811
|
try {
|
|
36655
36812
|
await reflectionHooks?.onReflectionEnd?.({
|
|
@@ -36660,13 +36817,15 @@ var ReflectorRunner = class {
|
|
|
36660
36817
|
} catch (hookError) {
|
|
36661
36818
|
omError("[OM] onReflectionEnd hook failed after async buffered reflection", hookError);
|
|
36662
36819
|
}
|
|
36663
|
-
BufferingCoordinator.
|
|
36820
|
+
BufferingCoordinator.finishReflectionBuffer(bufferKey, owner);
|
|
36821
|
+
if (BufferingCoordinator.asyncBufferingOps.get(bufferKey) === asyncOp) BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
|
|
36664
36822
|
unregisterOp(record.id, "bufferingReflection");
|
|
36665
36823
|
await this.storage.setBufferingReflectionFlag(record.id, false).catch((err) => {
|
|
36666
36824
|
omError("[OM] Failed to clear buffering reflection flag", err);
|
|
36667
36825
|
});
|
|
36668
36826
|
}
|
|
36669
|
-
}
|
|
36827
|
+
};
|
|
36828
|
+
const asyncOp = run();
|
|
36670
36829
|
BufferingCoordinator.asyncBufferingOps.set(bufferKey, asyncOp);
|
|
36671
36830
|
this.trackBackgroundWork?.(asyncOp, lockKey);
|
|
36672
36831
|
}
|
|
@@ -36674,13 +36833,27 @@ var ReflectorRunner = class {
|
|
|
36674
36833
|
* Perform async buffered reflection — reflects observations and stores to bufferedReflection.
|
|
36675
36834
|
* Does NOT create a new generation or update activeObservations.
|
|
36676
36835
|
*/
|
|
36677
|
-
async doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel) {
|
|
36678
|
-
const
|
|
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
|
+
}
|
|
36679
36848
|
const observationTokens = currentRecord.observationTokenCount ?? 0;
|
|
36680
36849
|
const reflectThreshold = getMaxThreshold(this.getEffectiveReflectionTokens(currentRecord));
|
|
36681
36850
|
const bufferActivation = this.reflectionConfig.bufferActivation ?? .5;
|
|
36682
36851
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
36683
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
|
+
}
|
|
36684
36857
|
BufferingCoordinator.reflectionBufferCycleIds.set(bufferKey, cycleId);
|
|
36685
36858
|
const allLines = (currentRecord.activeObservations ?? "").split("\n");
|
|
36686
36859
|
const totalLines = allLines.length;
|
|
@@ -36717,10 +36890,18 @@ var ReflectorRunner = class {
|
|
|
36717
36890
|
const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
|
|
36718
36891
|
const reflectResult = await this.call(activeObservations, void 0, void 0, compressionTarget, void 0, true, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal, currentModel);
|
|
36719
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
|
+
}
|
|
36720
36901
|
const reflectionTokenCount = this.tokenCounter.countObservations(reflectResult.observations);
|
|
36721
36902
|
omDebug(`[OM:reflect] doAsyncBufferedReflection: reflector returned ${reflectionTokenCount} tokens (${reflectResult.observations?.length} chars), saving to recordId=${currentRecord.id}`);
|
|
36722
36903
|
if (!await runOMCommit(this.buffering.getLockKey(currentRecord.threadId, currentRecord.resourceId), async () => {
|
|
36723
|
-
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;
|
|
36724
36905
|
await this.storage.updateBufferedReflection({
|
|
36725
36906
|
id: currentRecord.id,
|
|
36726
36907
|
reflection: reflectResult.observations,
|
|
@@ -36728,17 +36909,18 @@ var ReflectorRunner = class {
|
|
|
36728
36909
|
inputTokenCount: sliceTokenEstimate,
|
|
36729
36910
|
reflectedObservationLineCount
|
|
36730
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);
|
|
36731
36914
|
return true;
|
|
36732
36915
|
})) {
|
|
36733
36916
|
omDebug(`[OM:reflect] doAsyncBufferedReflection: record ${currentRecord.id} is no longer the head; discarding the buffered reflection`);
|
|
36734
|
-
|
|
36917
|
+
owner.retired = true;
|
|
36735
36918
|
return {
|
|
36736
36919
|
usage: reflectResult.usage,
|
|
36737
36920
|
providerMetadata: reflectResult.providerMetadata
|
|
36738
36921
|
};
|
|
36739
36922
|
}
|
|
36740
36923
|
omDebug(`[OM:reflect] doAsyncBufferedReflection: bufferedReflection saved with lineCount=${reflectedObservationLineCount}`);
|
|
36741
|
-
await persistThreadExtractedValues(this.storage, this.reflectionConfig.extractors, currentRecord.threadId ?? void 0, reflectResult.extractedValues);
|
|
36742
36924
|
if (writer) {
|
|
36743
36925
|
const endMarker = createBufferingEndMarker({
|
|
36744
36926
|
cycleId,
|
|
@@ -36764,6 +36946,57 @@ var ReflectorRunner = class {
|
|
|
36764
36946
|
};
|
|
36765
36947
|
}
|
|
36766
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
|
+
/**
|
|
36767
37000
|
* Try to activate buffered reflection when threshold is reached.
|
|
36768
37001
|
* Returns a discriminated result so the caller can distinguish between
|
|
36769
37002
|
* "activated", "no buffer present", and "suppressed by overshoot guard"
|
|
@@ -36783,18 +37016,26 @@ var ReflectorRunner = class {
|
|
|
36783
37016
|
}
|
|
36784
37017
|
}
|
|
36785
37018
|
}
|
|
36786
|
-
const
|
|
37019
|
+
const storedRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
|
|
37020
|
+
const freshRecord = storedRecord ? { ...storedRecord } : void 0;
|
|
36787
37021
|
omDebug(`[OM:reflect] tryActivateBufferedReflection: recordId=${record.id}, hasBufferedReflection=${!!freshRecord?.bufferedReflection}, bufferedReflectionLen=${freshRecord?.bufferedReflection?.length ?? 0}`);
|
|
36788
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));
|
|
36789
37024
|
if (!freshRecord?.bufferedReflection) {
|
|
36790
37025
|
omDebug(`[OM:reflect] tryActivateBufferedReflection: no buffered reflection after re-fetch`);
|
|
36791
37026
|
return { status: "no-buffer" };
|
|
36792
37027
|
}
|
|
36793
37028
|
const beforeTokens = freshRecord.observationTokenCount ?? 0;
|
|
36794
37029
|
const reflectedLineCount = freshRecord.reflectedObservationLineCount ?? 0;
|
|
36795
|
-
const
|
|
37030
|
+
const currentObservations = freshRecord.activeObservations ?? "";
|
|
37031
|
+
const unreflectedLines = currentObservations.split("\n").slice(reflectedLineCount);
|
|
36796
37032
|
const unreflectedContent = unreflectedLines.join("\n").trim();
|
|
36797
|
-
const
|
|
37033
|
+
const bufferedReflection = freshRecord.bufferedReflection;
|
|
37034
|
+
const combinedObservations = bufferedActivationText({
|
|
37035
|
+
bufferedReflection,
|
|
37036
|
+
observations: currentObservations,
|
|
37037
|
+
reflectedLineCount
|
|
37038
|
+
});
|
|
36798
37039
|
const combinedTokenCount = this.tokenCounter.countObservations(combinedObservations);
|
|
36799
37040
|
if (activationMetadata?.triggeredBy === "ttl" || activationMetadata?.triggeredBy === "provider_change") {
|
|
36800
37041
|
const unreflectedTailTokens = unreflectedContent ? this.tokenCounter.countObservations(unreflectedContent) : 0;
|
|
@@ -36820,28 +37061,48 @@ var ReflectorRunner = class {
|
|
|
36820
37061
|
}
|
|
36821
37062
|
omDebug(`[OM:reflect] tryActivateBufferedReflection: activating, beforeTokens=${beforeTokens}, combinedTokenCount=${combinedTokenCount}, reflectedLineCount=${reflectedLineCount}, unreflectedLines=${unreflectedLines.length}`);
|
|
36822
37063
|
const newRecordId = crypto.randomUUID();
|
|
36823
|
-
const
|
|
37064
|
+
const commit = await runOMCommit(lockKey, async () => {
|
|
36824
37065
|
abortSignal?.throwIfAborted();
|
|
36825
|
-
|
|
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({
|
|
36826
37072
|
currentRecord: freshRecord,
|
|
36827
37073
|
tokenCount: combinedTokenCount,
|
|
36828
37074
|
newRecordId
|
|
36829
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;
|
|
36830
37089
|
}, {
|
|
36831
37090
|
priority: "reflection",
|
|
36832
37091
|
abortSignal
|
|
36833
37092
|
});
|
|
36834
|
-
if (
|
|
36835
|
-
omDebug(`[OM:reflect] tryActivateBufferedReflection: buffered reflection on ${freshRecord.id} not applied (head is ${
|
|
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);
|
|
36836
37096
|
return { status: "not-applied" };
|
|
36837
37097
|
}
|
|
36838
|
-
|
|
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);
|
|
36839
37100
|
const afterRecord = await this.storage.getObservationalMemory(record.threadId, record.resourceId);
|
|
36840
37101
|
const afterTokens = afterRecord?.observationTokenCount ?? 0;
|
|
36841
37102
|
omDebug(`[OM:reflect] tryActivateBufferedReflection: activation complete! beforeTokens=${beforeTokens}, afterTokens=${afterTokens}, newRecordId=${afterRecord?.id}, newGenCount=${afterRecord?.generationCount}`);
|
|
36842
37103
|
if (writer) {
|
|
36843
37104
|
const activationMarker = createActivationMarker({
|
|
36844
|
-
cycleId:
|
|
37105
|
+
cycleId: originalCycleId ?? `reflect-act-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
|
|
36845
37106
|
operationType: "reflection",
|
|
36846
37107
|
chunksActivated: 1,
|
|
36847
37108
|
tokensActivated: beforeTokens,
|
|
@@ -36867,7 +37128,6 @@ var ReflectorRunner = class {
|
|
|
36867
37128
|
}).catch(() => {});
|
|
36868
37129
|
await this.persistMarkerToMessage(activationMarker, messageList, freshRecord.threadId ?? "", freshRecord.resourceId ?? void 0, abortSignal);
|
|
36869
37130
|
}
|
|
36870
|
-
BufferingCoordinator.reflectionBufferCycleIds.delete(bufferKey);
|
|
36871
37131
|
return { status: "activated" };
|
|
36872
37132
|
}
|
|
36873
37133
|
/**
|
|
@@ -36884,7 +37144,7 @@ var ReflectorRunner = class {
|
|
|
36884
37144
|
const priorExtractedValues = await getThreadExtractedValues(this.storage, this.reflectionConfig.extractors, requestedThreadId ?? record.threadId);
|
|
36885
37145
|
abortSignal?.throwIfAborted();
|
|
36886
37146
|
if (this.buffering.isAsyncReflectionEnabled() && observationTokens < reflectThreshold) {
|
|
36887
|
-
if ((() => {
|
|
37147
|
+
if (await (async () => {
|
|
36888
37148
|
if (!this.buffering.isAsyncReflectionEnabled()) return false;
|
|
36889
37149
|
if (record.isBufferingReflection) {
|
|
36890
37150
|
if (isOpActiveInProcess(record.id, "bufferingReflection")) return false;
|
|
@@ -36892,6 +37152,7 @@ var ReflectorRunner = class {
|
|
|
36892
37152
|
this.storage.setBufferingReflectionFlag(record.id, false).catch(() => {});
|
|
36893
37153
|
}
|
|
36894
37154
|
const bufferKey = this.buffering.getReflectionBufferKey(lockKey);
|
|
37155
|
+
await BufferingCoordinator.reconcileReflectionBufferHead(bufferKey, record.id, () => this.storage.getObservationalMemory(record.threadId, record.resourceId));
|
|
36895
37156
|
if (this.buffering.isAsyncBufferingInProgress(bufferKey)) return false;
|
|
36896
37157
|
if (BufferingCoordinator.lastBufferedBoundary.has(bufferKey)) return false;
|
|
36897
37158
|
if (record.bufferedReflection) return false;
|
|
@@ -36937,6 +37198,11 @@ var ReflectorRunner = class {
|
|
|
36937
37198
|
omDebug(`[OM:reflect] skipping async reflection — observationTokens (${observationTokens}) below activation point (${activationPoint}), triggered by ${activationTriggeredBy}`);
|
|
36938
37199
|
return;
|
|
36939
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
|
+
}
|
|
36940
37206
|
omDebug(`[OM:reflect] async activation failed, no blockAfter or below it (obsTokens=${observationTokens}, blockAfter=${this.reflectionConfig.blockAfter}) — starting background reflection`);
|
|
36941
37207
|
this.startAsyncBufferedReflection(record, observationTokens, lockKey, writer, requestContext, observabilityContext, reflectionHooks, priorExtractedValues, mainAgent, sendSignal, trigger, currentModel);
|
|
36942
37208
|
return;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/memory",
|
|
3
|
-
"version": "1.41.3-alpha.
|
|
3
|
+
"version": "1.41.3-alpha.3",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -68,12 +68,12 @@
|
|
|
68
68
|
"typescript": "^6.0.3",
|
|
69
69
|
"vitest": "5.1.0",
|
|
70
70
|
"@internal/ai-sdk-v4": "0.0.98",
|
|
71
|
-
"@internal/ai-sdk-v5": "0.0.98",
|
|
72
|
-
"@internal/ai-v7": "0.0.98",
|
|
73
|
-
"@internal/ai-v6": "0.0.98",
|
|
74
71
|
"@internal/lint": "0.0.151",
|
|
75
72
|
"@internal/types-builder": "0.0.126",
|
|
76
|
-
"@mastra/core": "1.86.0-alpha.
|
|
73
|
+
"@mastra/core": "1.86.0-alpha.7",
|
|
74
|
+
"@internal/ai-sdk-v5": "0.0.98",
|
|
75
|
+
"@internal/ai-v6": "0.0.98",
|
|
76
|
+
"@internal/ai-v7": "0.0.98"
|
|
77
77
|
},
|
|
78
78
|
"peerDependencies": {
|
|
79
79
|
"@mastra/core": ">=1.85.1-0 <2.0.0-0"
|