@mastra/memory 1.27.0 → 1.28.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +63 -0
- package/dist/docs/SKILL.md +5 -2
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/docs-guides-context-engineering.md +297 -0
- package/dist/docs/references/docs-storage.md +2 -0
- package/dist/docs/references/integrations-databases-elasticsearch.md +156 -0
- package/dist/docs/references/integrations-databases-libsql.md +16 -0
- package/dist/docs/references/integrations-databases-mongodb.md +1 -1
- package/dist/docs/references/integrations-databases-postgresql.md +26 -0
- package/dist/docs/references/integrations-databases-valkey.md +99 -0
- package/dist/docs/references/reference-vectors-mongodb.md +11 -11
- package/dist/docs/references/reference-vectors-pg.md +2 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +6 -3
- package/dist/index.d.ts.map +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/observation-turn/load-memory-context.d.ts +3 -1
- package/dist/processors/observational-memory/observation-turn/load-memory-context.d.ts.map +1 -1
- package/dist/processors/observational-memory/observation-turn/turn.d.ts +2 -1
- package/dist/processors/observational-memory/observation-turn/turn.d.ts.map +1 -1
- package/dist/processors/observational-memory/observational-memory.d.ts +6 -12
- package/dist/processors/observational-memory/observational-memory.d.ts.map +1 -1
- package/dist/processors/observational-memory/observer-agent.d.ts.map +1 -1
- package/dist/processors/observational-memory/processor.d.ts +2 -0
- package/dist/processors/observational-memory/processor.d.ts.map +1 -1
- package/dist/processors/observational-memory/reflector-runner.d.ts +15 -0
- package/dist/processors/observational-memory/reflector-runner.d.ts.map +1 -1
- package/dist/processors/observational-memory/tracing.d.ts.map +1 -1
- package/dist/processors/observational-memory/types.d.ts +23 -13
- package/dist/processors/observational-memory/types.d.ts.map +1 -1
- package/dist/{src-aTfbkxBl.js → src-BTHCV1ov.js} +314 -164
- package/dist/src-BTHCV1ov.js.map +1 -0
- package/dist/{src-CxkQ-ICG.cjs → src-D8byb8Ge.cjs} +314 -164
- package/dist/src-D8byb8Ge.cjs.map +1 -0
- package/package.json +7 -7
- package/dist/src-CxkQ-ICG.cjs.map +0 -1
- package/dist/src-aTfbkxBl.js.map +0 -1
|
@@ -3734,7 +3734,7 @@ function trimStartOfStream() {
|
|
|
3734
3734
|
};
|
|
3735
3735
|
}
|
|
3736
3736
|
//#endregion
|
|
3737
|
-
//#region ../_vendored/ai_v5/dist/dist-
|
|
3737
|
+
//#region ../_vendored/ai_v5/dist/dist-nVfjvSbw.js
|
|
3738
3738
|
var marker$1$4 = "vercel.ai.error";
|
|
3739
3739
|
var symbol$1$3 = Symbol.for(marker$1$4);
|
|
3740
3740
|
var _a$1$3;
|
|
@@ -4287,6 +4287,7 @@ async function cancelResponseBody$1(response) {
|
|
|
4287
4287
|
var initialGlobalFetch$1 = globalThis.fetch;
|
|
4288
4288
|
isNodeDefaultFetch$1(initialGlobalFetch$1);
|
|
4289
4289
|
function isNodeDefaultFetch$1(fetch) {
|
|
4290
|
+
if (typeof fetch !== "function") return false;
|
|
4290
4291
|
const source = Function.prototype.toString.call(fetch);
|
|
4291
4292
|
return source.includes("internal/deps/undici") || source.includes("lazy loading of undici");
|
|
4292
4293
|
}
|
|
@@ -8622,7 +8623,7 @@ var object$1 = ({ schema: inputSchema }) => {
|
|
|
8622
8623
|
};
|
|
8623
8624
|
};
|
|
8624
8625
|
//#endregion
|
|
8625
|
-
//#region ../_vendored/ai_v6/dist/dist-
|
|
8626
|
+
//#region ../_vendored/ai_v6/dist/dist-Gd4EIxPM.js
|
|
8626
8627
|
var marker$1 = "vercel.ai.error";
|
|
8627
8628
|
var symbol$1$1 = Symbol.for(marker$1);
|
|
8628
8629
|
var _a$1$1;
|
|
@@ -9196,6 +9197,7 @@ var DownloadError = class extends (_b$2 = AISDKError, _a$2 = symbol$2, _b$2) {
|
|
|
9196
9197
|
var initialGlobalFetch = globalThis.fetch;
|
|
9197
9198
|
isNodeDefaultFetch(initialGlobalFetch);
|
|
9198
9199
|
function isNodeDefaultFetch(fetch) {
|
|
9200
|
+
if (typeof fetch !== "function") return false;
|
|
9199
9201
|
const source = Function.prototype.toString.call(fetch);
|
|
9200
9202
|
return source.includes("internal/deps/undici") || source.includes("lazy loading of undici");
|
|
9201
9203
|
}
|
|
@@ -10774,7 +10776,7 @@ function withoutTrailingSlash(url) {
|
|
|
10774
10776
|
return url == null ? void 0 : url.replace(/\/$/, "");
|
|
10775
10777
|
}
|
|
10776
10778
|
//#endregion
|
|
10777
|
-
//#region ../_vendored/ai_v6/dist/dist-
|
|
10779
|
+
//#region ../_vendored/ai_v6/dist/dist-BoeKQsDe.js
|
|
10778
10780
|
function getContext() {
|
|
10779
10781
|
return { headers: {} };
|
|
10780
10782
|
}
|
|
@@ -18926,6 +18928,12 @@ function extractListItemsOnly(content) {
|
|
|
18926
18928
|
*/
|
|
18927
18929
|
const MAX_OBSERVATION_LINE_CHARS = 1e4;
|
|
18928
18930
|
/**
|
|
18931
|
+
* Minimum trimmed line length considered by the duplicate-line degenerate
|
|
18932
|
+
* check. Short lines (blank lines, separators, terse bullets) legitimately
|
|
18933
|
+
* repeat; long identical lines almost never do.
|
|
18934
|
+
*/
|
|
18935
|
+
const MIN_DUPLICATE_LINE_CHARS = 24;
|
|
18936
|
+
/**
|
|
18929
18937
|
* Truncate individual observation lines that exceed the maximum length.
|
|
18930
18938
|
*/
|
|
18931
18939
|
function sanitizeObservationLines(observations) {
|
|
@@ -18963,6 +18971,18 @@ function detectDegenerateRepetition(text) {
|
|
|
18963
18971
|
if (totalWindows > 5 && duplicateWindows / totalWindows > .4) return true;
|
|
18964
18972
|
const lines = text.split("\n");
|
|
18965
18973
|
for (const line of lines) if (line.length > 5e4) return true;
|
|
18974
|
+
const seenLines = /* @__PURE__ */ new Map();
|
|
18975
|
+
let duplicateLines = 0;
|
|
18976
|
+
let totalCountedLines = 0;
|
|
18977
|
+
for (const line of lines) {
|
|
18978
|
+
const trimmed = line.trim();
|
|
18979
|
+
if (trimmed.length < MIN_DUPLICATE_LINE_CHARS) continue;
|
|
18980
|
+
totalCountedLines++;
|
|
18981
|
+
const count = (seenLines.get(trimmed) ?? 0) + 1;
|
|
18982
|
+
seenLines.set(trimmed, count);
|
|
18983
|
+
if (count > 1) duplicateLines++;
|
|
18984
|
+
}
|
|
18985
|
+
if (totalCountedLines >= 20 && duplicateLines / totalCountedLines > .5) return true;
|
|
18966
18986
|
return false;
|
|
18967
18987
|
}
|
|
18968
18988
|
/**
|
|
@@ -18997,12 +19017,26 @@ function describeDegenerateOutput(text, snippetChars = 400) {
|
|
|
18997
19017
|
topWindow = window;
|
|
18998
19018
|
}
|
|
18999
19019
|
let longestLine = 0;
|
|
19000
|
-
|
|
19020
|
+
const seenLines = /* @__PURE__ */ new Map();
|
|
19021
|
+
let duplicateLines = 0;
|
|
19022
|
+
let totalCountedLines = 0;
|
|
19023
|
+
for (const line of text.split("\n")) {
|
|
19024
|
+
if (line.length > longestLine) longestLine = line.length;
|
|
19025
|
+
const trimmed = line.trim();
|
|
19026
|
+
if (trimmed.length < MIN_DUPLICATE_LINE_CHARS) continue;
|
|
19027
|
+
totalCountedLines++;
|
|
19028
|
+
const count = (seenLines.get(trimmed) ?? 0) + 1;
|
|
19029
|
+
seenLines.set(trimmed, count);
|
|
19030
|
+
if (count > 1) duplicateLines++;
|
|
19031
|
+
}
|
|
19001
19032
|
const duplicateRatio = totalWindows > 0 ? (duplicateWindows / totalWindows).toFixed(2) : "n/a";
|
|
19033
|
+
const duplicateLineRatio = totalCountedLines > 0 ? (duplicateLines / totalCountedLines).toFixed(2) : "n/a";
|
|
19002
19034
|
const parts = [
|
|
19003
19035
|
`length=${text.length}`,
|
|
19004
19036
|
`sampledWindows=${totalWindows}`,
|
|
19005
19037
|
`duplicateRatio=${duplicateRatio}`,
|
|
19038
|
+
`duplicateLineRatio=${duplicateLineRatio}`,
|
|
19039
|
+
`countedLines=${totalCountedLines}`,
|
|
19006
19040
|
`longestLine=${longestLine}`,
|
|
19007
19041
|
`topWindowCount=${topCount}`
|
|
19008
19042
|
];
|
|
@@ -19276,7 +19310,19 @@ async function withOmTracingSpan({ phase, model, inputTokens, requestContext, ob
|
|
|
19276
19310
|
});
|
|
19277
19311
|
const childObservabilityContext = (0, _mastra_core_observability.createObservabilityContext)({ currentSpan: span });
|
|
19278
19312
|
if (!span) return callback(childObservabilityContext);
|
|
19279
|
-
return span.executeInContext(() =>
|
|
19313
|
+
return span.executeInContext(async () => {
|
|
19314
|
+
try {
|
|
19315
|
+
const result = await callback(childObservabilityContext);
|
|
19316
|
+
span.end();
|
|
19317
|
+
return result;
|
|
19318
|
+
} catch (error) {
|
|
19319
|
+
span.error({
|
|
19320
|
+
error,
|
|
19321
|
+
endSpan: true
|
|
19322
|
+
});
|
|
19323
|
+
throw error;
|
|
19324
|
+
}
|
|
19325
|
+
});
|
|
19280
19326
|
}
|
|
19281
19327
|
//#endregion
|
|
19282
19328
|
//#region src/processors/observational-memory/observer-runner.ts
|
|
@@ -24413,10 +24459,11 @@ ObservationStrategy.create = ((om, opts) => {
|
|
|
24413
24459
|
});
|
|
24414
24460
|
//#endregion
|
|
24415
24461
|
//#region src/processors/observational-memory/observation-turn/load-memory-context.ts
|
|
24416
|
-
async function loadMemoryContextMessages({ memory, messageList, threadId, resourceId }) {
|
|
24462
|
+
async function loadMemoryContextMessages({ memory, messageList, threadId, resourceId, runState }) {
|
|
24417
24463
|
const ctx = await memory.getContext({
|
|
24418
24464
|
threadId,
|
|
24419
|
-
resourceId
|
|
24465
|
+
resourceId,
|
|
24466
|
+
runState
|
|
24420
24467
|
});
|
|
24421
24468
|
for (const msg of ctx.messages) if (msg.role !== "system") messageList.add(msg, "memory");
|
|
24422
24469
|
return ctx;
|
|
@@ -24874,10 +24921,11 @@ var ObservationTurn = class {
|
|
|
24874
24921
|
* If a MemoryContextProvider is passed, loads historical messages and adds
|
|
24875
24922
|
* them to the MessageList. Without a provider, only fetches/caches the record.
|
|
24876
24923
|
*/
|
|
24877
|
-
async start(memory) {
|
|
24924
|
+
async start(memory, runState) {
|
|
24878
24925
|
if (this._started) throw new Error("Turn already started");
|
|
24879
24926
|
this._started = true;
|
|
24880
24927
|
this._record = await this.om.getOrCreateRecord(this.threadId, this.resourceId);
|
|
24928
|
+
runState?.set(`observational-memory:record:${this.threadId}:${this.resourceId ?? ""}`, this._record);
|
|
24881
24929
|
this._generationCountAtStart = this._record.generationCount;
|
|
24882
24930
|
this.memory = memory;
|
|
24883
24931
|
if (memory) {
|
|
@@ -24885,7 +24933,8 @@ var ObservationTurn = class {
|
|
|
24885
24933
|
memory,
|
|
24886
24934
|
messageList: this.messageList,
|
|
24887
24935
|
threadId: this.threadId,
|
|
24888
|
-
resourceId: this.resourceId
|
|
24936
|
+
resourceId: this.resourceId,
|
|
24937
|
+
runState
|
|
24889
24938
|
});
|
|
24890
24939
|
this._context = {
|
|
24891
24940
|
messages: ctx.messages,
|
|
@@ -25365,6 +25414,21 @@ var ReflectorRunner = class {
|
|
|
25365
25414
|
memory;
|
|
25366
25415
|
onReflectionCommitted;
|
|
25367
25416
|
mastra;
|
|
25417
|
+
/**
|
|
25418
|
+
* Per-lock-key observation-token count of the last unproductive synchronous
|
|
25419
|
+
* reflection (failed, or committed while still over the reflection
|
|
25420
|
+
* threshold). `call()` already runs the full bounded compression ladder for
|
|
25421
|
+
* a given input, so re-running it against unchanged observations cannot
|
|
25422
|
+
* succeed — threshold-triggered sync reflection is skipped while the count
|
|
25423
|
+
* is unchanged and retried as soon as the input differs.
|
|
25424
|
+
* Keyed by lock key (thread/resource), which is stable across generations —
|
|
25425
|
+
* record ids change every time a generation is created.
|
|
25426
|
+
*
|
|
25427
|
+
* Lifecycle: an entry is deleted when a sync reflection finishes under
|
|
25428
|
+
* threshold and replaced on each unproductive attempt. Entries are one
|
|
25429
|
+
* number per active thread/resource key and live for the runner's lifetime.
|
|
25430
|
+
*/
|
|
25431
|
+
syncReflectionSuppression = /* @__PURE__ */ new Map();
|
|
25368
25432
|
constructor(opts) {
|
|
25369
25433
|
this.reflectionConfig = opts.reflectionConfig;
|
|
25370
25434
|
this.observationConfig = opts.observationConfig;
|
|
@@ -25447,8 +25511,8 @@ var ReflectorRunner = class {
|
|
|
25447
25511
|
};
|
|
25448
25512
|
let reflectedTokens = 0;
|
|
25449
25513
|
let attemptNumber = 0;
|
|
25450
|
-
/**
|
|
25451
|
-
let
|
|
25514
|
+
/** True when the latest attempt returned an empty block for non-empty input. */
|
|
25515
|
+
let emptyOutput = false;
|
|
25452
25516
|
while (currentLevel <= maxLevel) {
|
|
25453
25517
|
attemptNumber++;
|
|
25454
25518
|
const isRetry = attemptNumber > 1;
|
|
@@ -25512,21 +25576,20 @@ var ReflectorRunner = class {
|
|
|
25512
25576
|
}
|
|
25513
25577
|
finalProviderMetadata = result.providerMetadata ?? finalProviderMetadata;
|
|
25514
25578
|
parsed = parseReflectorOutput(result.text, observations, activeExtractors);
|
|
25579
|
+
emptyOutput = !parsed.degenerate && observations.trim().length > 0 && parsed.observations.trim().length === 0;
|
|
25515
25580
|
if (parsed.degenerate) {
|
|
25516
25581
|
omDebug(`[OM:callReflector] attempt #${attemptNumber}: degenerate repetition detected, treating as compression failure. ${describeDegenerateOutput(result.text, 2e3)}`);
|
|
25517
25582
|
reflectedTokens = originalTokens;
|
|
25583
|
+
} else if (emptyOutput) {
|
|
25584
|
+
omDebug(`[OM:callReflector] attempt #${attemptNumber}: empty observations block for non-empty input, treating as compression failure`);
|
|
25585
|
+
reflectedTokens = originalTokens;
|
|
25518
25586
|
} else reflectedTokens = this.tokenCounter.countObservations(parsed.observations);
|
|
25519
25587
|
omDebug(`[OM:callReflector] attempt #${attemptNumber} parsed: reflectedTokens=${reflectedTokens}, targetThreshold=${targetThreshold}, compressionValid=${validateCompression(reflectedTokens, targetThreshold)}, parsedObsLen=${parsed.observations?.length}, degenerate=${parsed.degenerate ?? false}`);
|
|
25520
|
-
if (!parsed.degenerate && (validateCompression(reflectedTokens, targetThreshold) || currentLevel >= maxLevel)) break;
|
|
25521
|
-
if (parsed.degenerate && currentLevel >= maxLevel) {
|
|
25522
|
-
omDebug(`[OM:callReflector] degenerate output persists at maxLevel=${maxLevel}, breaking`);
|
|
25523
|
-
break;
|
|
25524
|
-
}
|
|
25525
|
-
if (!parsed.degenerate && previousObservations !== void 0 && parsed.observations === previousObservations) {
|
|
25526
|
-
omDebug(`[OM:callReflector] attempt #${attemptNumber} returned output identical to the previous attempt; escalating cannot help, stopping the ladder`);
|
|
25588
|
+
if (!parsed.degenerate && !emptyOutput && (validateCompression(reflectedTokens, targetThreshold) || currentLevel >= maxLevel)) break;
|
|
25589
|
+
if ((parsed.degenerate || emptyOutput) && currentLevel >= maxLevel) {
|
|
25590
|
+
omDebug(`[OM:callReflector] ${parsed.degenerate ? "degenerate" : "empty"} output persists at maxLevel=${maxLevel}, breaking`);
|
|
25527
25591
|
break;
|
|
25528
25592
|
}
|
|
25529
|
-
previousObservations = parsed.observations;
|
|
25530
25593
|
if (streamContext?.writer) {
|
|
25531
25594
|
const failedMarker = createObservationFailedMarker({
|
|
25532
25595
|
cycleId: streamContext.cycleId,
|
|
@@ -25562,6 +25625,7 @@ var ReflectorRunner = class {
|
|
|
25562
25625
|
}
|
|
25563
25626
|
currentLevel = Math.min(currentLevel + 1, maxLevel);
|
|
25564
25627
|
}
|
|
25628
|
+
if (observations.trim().length > 0 && parsed.observations.trim().length === 0) throw new Error(`Reflector produced empty output after ${attemptNumber} attempt(s)${parsed.degenerate ? " (degenerate repetition)" : ""} — refusing to commit an empty reflection over ${originalTokens} observation tokens`);
|
|
25565
25629
|
const structuredExtraction = await extractStructuredValues({
|
|
25566
25630
|
agent,
|
|
25567
25631
|
source: "reflector",
|
|
@@ -25610,52 +25674,51 @@ var ReflectorRunner = class {
|
|
|
25610
25674
|
this.storage.setBufferingReflectionFlag(record.id, true).catch((err) => {
|
|
25611
25675
|
omError("[OM] Failed to set buffering reflection flag", err);
|
|
25612
25676
|
});
|
|
25613
|
-
|
|
25614
|
-
|
|
25677
|
+
const asyncOp = (async () => {
|
|
25678
|
+
let outcome;
|
|
25679
|
+
let reflectionError;
|
|
25615
25680
|
try {
|
|
25616
|
-
reflectionHooks?.
|
|
25617
|
-
|
|
25618
|
-
|
|
25619
|
-
|
|
25620
|
-
|
|
25621
|
-
|
|
25622
|
-
|
|
25623
|
-
|
|
25624
|
-
|
|
25625
|
-
|
|
25626
|
-
|
|
25627
|
-
|
|
25628
|
-
|
|
25629
|
-
|
|
25630
|
-
|
|
25631
|
-
|
|
25632
|
-
|
|
25633
|
-
|
|
25634
|
-
|
|
25635
|
-
|
|
25636
|
-
|
|
25637
|
-
}
|
|
25638
|
-
|
|
25639
|
-
|
|
25640
|
-
|
|
25641
|
-
|
|
25642
|
-
|
|
25643
|
-
|
|
25644
|
-
|
|
25645
|
-
|
|
25646
|
-
|
|
25681
|
+
await reflectionHooks?.onReflectionStart?.();
|
|
25682
|
+
outcome = await this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal);
|
|
25683
|
+
} catch (error) {
|
|
25684
|
+
reflectionError = error instanceof Error ? error : new Error(String(error));
|
|
25685
|
+
if (writer) try {
|
|
25686
|
+
const failedMarker = createBufferingFailedMarker({
|
|
25687
|
+
cycleId: `reflect-buf-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
|
|
25688
|
+
operationType: "reflection",
|
|
25689
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
25690
|
+
tokensAttempted: observationTokens,
|
|
25691
|
+
error: reflectionError.message,
|
|
25692
|
+
recordId: record.id,
|
|
25693
|
+
threadId: record.threadId ?? ""
|
|
25694
|
+
});
|
|
25695
|
+
writer.custom({
|
|
25696
|
+
...failedMarker,
|
|
25697
|
+
transient: true
|
|
25698
|
+
}).catch(() => {});
|
|
25699
|
+
await this.persistMarkerToStorage(failedMarker, record.threadId ?? "", record.resourceId ?? void 0);
|
|
25700
|
+
} catch (markerError) {
|
|
25701
|
+
omError("[OM] Failed to persist buffering-failed marker after async buffered reflection failure", markerError);
|
|
25702
|
+
}
|
|
25703
|
+
omError("[OM] Async buffered reflection failed", error);
|
|
25704
|
+
BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
|
|
25705
|
+
} finally {
|
|
25706
|
+
try {
|
|
25707
|
+
await reflectionHooks?.onReflectionEnd?.({
|
|
25708
|
+
usage: outcome?.usage,
|
|
25709
|
+
error: reflectionError,
|
|
25710
|
+
...outcome?.providerMetadata ? { providerMetadata: outcome.providerMetadata } : {}
|
|
25711
|
+
});
|
|
25712
|
+
} catch (hookError) {
|
|
25713
|
+
omError("[OM] onReflectionEnd hook failed after async buffered reflection", hookError);
|
|
25714
|
+
}
|
|
25715
|
+
BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
|
|
25716
|
+
unregisterOp(record.id, "bufferingReflection");
|
|
25717
|
+
this.storage.setBufferingReflectionFlag(record.id, false).catch((err) => {
|
|
25718
|
+
omError("[OM] Failed to clear buffering reflection flag", err);
|
|
25647
25719
|
});
|
|
25648
|
-
} catch (hookError) {
|
|
25649
|
-
omError("[OM] onReflectionEnd hook failed after async buffered reflection failure", hookError);
|
|
25650
25720
|
}
|
|
25651
|
-
|
|
25652
|
-
}).finally(() => {
|
|
25653
|
-
BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
|
|
25654
|
-
unregisterOp(record.id, "bufferingReflection");
|
|
25655
|
-
this.storage.setBufferingReflectionFlag(record.id, false).catch((err) => {
|
|
25656
|
-
omError("[OM] Failed to clear buffering reflection flag", err);
|
|
25657
|
-
});
|
|
25658
|
-
});
|
|
25721
|
+
})();
|
|
25659
25722
|
BufferingCoordinator.asyncBufferingOps.set(bufferKey, asyncOp);
|
|
25660
25723
|
}
|
|
25661
25724
|
/**
|
|
@@ -25916,6 +25979,13 @@ var ReflectorRunner = class {
|
|
|
25916
25979
|
return;
|
|
25917
25980
|
}
|
|
25918
25981
|
}
|
|
25982
|
+
if (activationTriggeredBy === "threshold") {
|
|
25983
|
+
const suppressedAtTokens = this.syncReflectionSuppression.get(lockKey);
|
|
25984
|
+
if (suppressedAtTokens !== void 0 && observationTokens === suppressedAtTokens) {
|
|
25985
|
+
omDebug(`[OM:reflect] skipping sync reflection — observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
|
|
25986
|
+
return;
|
|
25987
|
+
}
|
|
25988
|
+
}
|
|
25919
25989
|
await this.storage.setReflectingFlag(record.id, true);
|
|
25920
25990
|
registerOp(record.id, "reflecting");
|
|
25921
25991
|
const cycleId = crypto.randomUUID();
|
|
@@ -25956,8 +26026,15 @@ var ReflectorRunner = class {
|
|
|
25956
26026
|
let reflectionUsage;
|
|
25957
26027
|
let reflectionProviderMetadata;
|
|
25958
26028
|
let reflectionError;
|
|
25959
|
-
|
|
26029
|
+
let lifecycleError;
|
|
25960
26030
|
try {
|
|
26031
|
+
try {
|
|
26032
|
+
await reflectionHooks?.onReflectionStart?.();
|
|
26033
|
+
} catch (error) {
|
|
26034
|
+
lifecycleError = error;
|
|
26035
|
+
reflectionError = error instanceof Error ? error : new Error(String(error));
|
|
26036
|
+
throw error;
|
|
26037
|
+
}
|
|
25961
26038
|
const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
|
|
25962
26039
|
const reflectResult = await this.call(record.activeObservations, void 0, streamContext, reflectThreshold, abortSignal, void 0, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal);
|
|
25963
26040
|
reflectionUsage = reflectResult.usage;
|
|
@@ -25969,6 +26046,8 @@ var ReflectorRunner = class {
|
|
|
25969
26046
|
reflection: reflectResult.observations,
|
|
25970
26047
|
tokenCount: reflectionTokenCount
|
|
25971
26048
|
});
|
|
26049
|
+
if (reflectionTokenCount >= reflectThreshold) this.syncReflectionSuppression.set(lockKey, reflectionTokenCount);
|
|
26050
|
+
else this.syncReflectionSuppression.delete(lockKey);
|
|
25972
26051
|
await this.notifyReflectionCommitted({
|
|
25973
26052
|
parentThreadId: requestedThreadId ?? record.threadId ?? "",
|
|
25974
26053
|
resourceId: record.resourceId ?? "",
|
|
@@ -26027,18 +26106,28 @@ var ReflectorRunner = class {
|
|
|
26027
26106
|
await this.persistMarkerToStorage(failedMarker, threadId, record.resourceId ?? void 0);
|
|
26028
26107
|
}
|
|
26029
26108
|
reflectionError = error instanceof Error ? error : new Error(String(error));
|
|
26030
|
-
if (abortSignal?.aborted) throw error;
|
|
26109
|
+
if (lifecycleError !== void 0 || abortSignal?.aborted) throw error;
|
|
26110
|
+
this.syncReflectionSuppression.set(lockKey, observationTokens);
|
|
26031
26111
|
omError("[OM] Reflection failed", error);
|
|
26032
26112
|
} finally {
|
|
26033
|
-
await this.storage.setReflectingFlag(record.id, false);
|
|
26034
26113
|
try {
|
|
26035
|
-
|
|
26114
|
+
await this.storage.setReflectingFlag(record.id, false);
|
|
26115
|
+
} finally {
|
|
26116
|
+
unregisterOp(record.id, "reflecting");
|
|
26117
|
+
}
|
|
26118
|
+
let endHookError;
|
|
26119
|
+
try {
|
|
26120
|
+
await reflectionHooks?.onReflectionEnd?.({
|
|
26036
26121
|
usage: reflectionUsage,
|
|
26037
26122
|
error: reflectionError,
|
|
26038
26123
|
...reflectionProviderMetadata ? { providerMetadata: reflectionProviderMetadata } : {}
|
|
26039
26124
|
});
|
|
26040
|
-
}
|
|
26041
|
-
|
|
26125
|
+
} catch (error) {
|
|
26126
|
+
endHookError = error;
|
|
26127
|
+
}
|
|
26128
|
+
if (endHookError !== void 0) {
|
|
26129
|
+
if (lifecycleError === void 0 && !abortSignal?.aborted) throw endHookError;
|
|
26130
|
+
omDebug(`[OM:hooks] onReflectionEnd hook failed after cycle failure: ${endHookError instanceof Error ? endHookError.message : String(endHookError)}`);
|
|
26042
26131
|
}
|
|
26043
26132
|
}
|
|
26044
26133
|
}
|
|
@@ -26499,6 +26588,8 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
26499
26588
|
onIndexObservations;
|
|
26500
26589
|
/** Config-level lifecycle hooks fired for every observation/reflection cycle. */
|
|
26501
26590
|
hooks;
|
|
26591
|
+
/** Execution policy for config-level hooks on manual and turn-synchronous cycles. */
|
|
26592
|
+
hookExecution;
|
|
26502
26593
|
/** Observer agent runner — handles LLM calls for extracting observations. */
|
|
26503
26594
|
observer;
|
|
26504
26595
|
/** Reflector agent runner — handles LLM calls for compressing observations. */
|
|
@@ -26605,6 +26696,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
26605
26696
|
this.retrievalSearch = typeof config.retrieval === "object" && Boolean(config.retrieval.vector);
|
|
26606
26697
|
this.onIndexObservations = config.onIndexObservations;
|
|
26607
26698
|
this.hooks = config.hooks;
|
|
26699
|
+
this.hookExecution = config.hookExecution ?? "non-blocking";
|
|
26608
26700
|
this.mastra = config.mastra;
|
|
26609
26701
|
this.memory = config.memory;
|
|
26610
26702
|
this.curationCadence = config.curationCadence;
|
|
@@ -28397,57 +28489,54 @@ ${formattedMessages}
|
|
|
28397
28489
|
};
|
|
28398
28490
|
}
|
|
28399
28491
|
/**
|
|
28400
|
-
* Compose
|
|
28401
|
-
*
|
|
28402
|
-
*
|
|
28403
|
-
* never fail an observation/reflection cycle; per-call hooks keep their
|
|
28404
|
-
* existing payloads and propagation semantics. Returns undefined when
|
|
28405
|
-
* neither is configured, so call sites stay zero-cost.
|
|
28406
|
-
*
|
|
28407
|
-
* Used internally by every pipeline path (manual observe/reflect,
|
|
28408
|
-
* turn-engine sync observation, async buffering); public only so the
|
|
28409
|
-
* observation turn engine can thread config-level reflection hooks into
|
|
28410
|
-
* reflector calls.
|
|
28492
|
+
* Compose config-level hooks with optional per-call hooks and bind context to
|
|
28493
|
+
* config-level callbacks. The configured policy applies unless a background
|
|
28494
|
+
* path explicitly requests non-blocking invocation.
|
|
28411
28495
|
*
|
|
28412
28496
|
* @internal
|
|
28413
28497
|
*/
|
|
28414
|
-
composeHooks(callHooks, context) {
|
|
28498
|
+
composeHooks(callHooks, context, execution = "configured") {
|
|
28415
28499
|
const configHooks = this.hooks;
|
|
28416
28500
|
if (!configHooks) return callHooks;
|
|
28417
28501
|
if (!callHooks && !Object.keys(configHooks).length) return void 0;
|
|
28418
|
-
const
|
|
28502
|
+
const shouldAwaitConfig = execution === "configured" && this.hookExecution === "await";
|
|
28503
|
+
const invokeConfigHook = async (name, arg) => {
|
|
28419
28504
|
const hook = configHooks[name];
|
|
28420
28505
|
if (!hook) return;
|
|
28506
|
+
if (shouldAwaitConfig) {
|
|
28507
|
+
await hook(arg);
|
|
28508
|
+
return;
|
|
28509
|
+
}
|
|
28421
28510
|
const logHookFailure = (error) => omDebug(`[OM:hooks] config-level ${name} hook failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
28422
28511
|
try {
|
|
28423
|
-
const
|
|
28424
|
-
if (
|
|
28512
|
+
const result = hook(arg);
|
|
28513
|
+
if (result && typeof result.then === "function") result.then(void 0, logHookFailure);
|
|
28425
28514
|
} catch (error) {
|
|
28426
28515
|
logHookFailure(error);
|
|
28427
28516
|
}
|
|
28428
28517
|
};
|
|
28429
28518
|
return {
|
|
28430
|
-
onObservationStart: () => {
|
|
28431
|
-
|
|
28432
|
-
callHooks?.onObservationStart?.();
|
|
28519
|
+
onObservationStart: async () => {
|
|
28520
|
+
await invokeConfigHook("onObservationStart", context);
|
|
28521
|
+
await callHooks?.onObservationStart?.();
|
|
28433
28522
|
},
|
|
28434
|
-
onObservationEnd: (result) => {
|
|
28435
|
-
|
|
28523
|
+
onObservationEnd: async (result) => {
|
|
28524
|
+
await invokeConfigHook("onObservationEnd", {
|
|
28436
28525
|
...context,
|
|
28437
28526
|
...result
|
|
28438
28527
|
});
|
|
28439
|
-
callHooks?.onObservationEnd?.(result);
|
|
28528
|
+
await callHooks?.onObservationEnd?.(result);
|
|
28440
28529
|
},
|
|
28441
|
-
onReflectionStart: () => {
|
|
28442
|
-
|
|
28443
|
-
callHooks?.onReflectionStart?.();
|
|
28530
|
+
onReflectionStart: async () => {
|
|
28531
|
+
await invokeConfigHook("onReflectionStart", context);
|
|
28532
|
+
await callHooks?.onReflectionStart?.();
|
|
28444
28533
|
},
|
|
28445
|
-
onReflectionEnd: (result) => {
|
|
28446
|
-
|
|
28534
|
+
onReflectionEnd: async (result) => {
|
|
28535
|
+
await invokeConfigHook("onReflectionEnd", {
|
|
28447
28536
|
...context,
|
|
28448
28537
|
...result
|
|
28449
28538
|
});
|
|
28450
|
-
callHooks?.onReflectionEnd?.(result);
|
|
28539
|
+
await callHooks?.onReflectionEnd?.(result);
|
|
28451
28540
|
}
|
|
28452
28541
|
};
|
|
28453
28542
|
}
|
|
@@ -28460,22 +28549,29 @@ ${formattedMessages}
|
|
|
28460
28549
|
* end hook reports `error` for failed cycles even though nothing throws.
|
|
28461
28550
|
*/
|
|
28462
28551
|
async runBufferedObservationCycle(context, run) {
|
|
28463
|
-
const hooks = this.composeHooks(void 0, context);
|
|
28464
|
-
hooks?.onObservationStart?.();
|
|
28552
|
+
const hooks = this.composeHooks(void 0, context, "non-blocking");
|
|
28465
28553
|
let runResult;
|
|
28466
28554
|
let runError;
|
|
28555
|
+
let lifecycleError;
|
|
28467
28556
|
try {
|
|
28557
|
+
await hooks?.onObservationStart?.();
|
|
28468
28558
|
runResult = await run();
|
|
28469
28559
|
return runResult;
|
|
28470
28560
|
} catch (error) {
|
|
28561
|
+
lifecycleError = error;
|
|
28471
28562
|
runError = error instanceof Error ? error : new Error(String(error));
|
|
28472
28563
|
throw error;
|
|
28473
28564
|
} finally {
|
|
28474
|
-
|
|
28475
|
-
|
|
28476
|
-
|
|
28477
|
-
|
|
28478
|
-
|
|
28565
|
+
try {
|
|
28566
|
+
await hooks?.onObservationEnd?.({
|
|
28567
|
+
usage: runResult?.usage,
|
|
28568
|
+
error: runError ?? runResult?.error,
|
|
28569
|
+
...runResult?.providerMetadata ? { providerMetadata: runResult.providerMetadata } : {}
|
|
28570
|
+
});
|
|
28571
|
+
} catch (endHookError) {
|
|
28572
|
+
if (lifecycleError === void 0) throw endHookError;
|
|
28573
|
+
omDebug(`[OM:hooks] async-buffer onObservationEnd hook failed after cycle failure: ${endHookError instanceof Error ? endHookError.message : String(endHookError)}`);
|
|
28574
|
+
}
|
|
28479
28575
|
}
|
|
28480
28576
|
}
|
|
28481
28577
|
/**
|
|
@@ -28503,18 +28599,21 @@ ${formattedMessages}
|
|
|
28503
28599
|
let observed = false;
|
|
28504
28600
|
let observationUsage;
|
|
28505
28601
|
let observationProviderMetadata;
|
|
28602
|
+
let observationError;
|
|
28603
|
+
let lifecycleError;
|
|
28604
|
+
let observationStarted = false;
|
|
28506
28605
|
let generationBefore = -1;
|
|
28507
|
-
|
|
28508
|
-
|
|
28509
|
-
|
|
28510
|
-
|
|
28511
|
-
|
|
28512
|
-
|
|
28513
|
-
|
|
28514
|
-
|
|
28515
|
-
|
|
28516
|
-
|
|
28517
|
-
|
|
28606
|
+
try {
|
|
28607
|
+
await this.withLock(lockKey, async () => {
|
|
28608
|
+
const freshRecord = await this.getOrCreateRecord(threadId, resourceId);
|
|
28609
|
+
generationBefore = freshRecord.generationCount;
|
|
28610
|
+
const unobservedMessages = messages ? this.getUnobservedMessages(messages, freshRecord) : await this.loadMessagesFromStorage(threadId, resourceId, freshRecord.lastObservedAt ? new Date(freshRecord.lastObservedAt) : void 0);
|
|
28611
|
+
if (!this.meetsObservationThreshold({
|
|
28612
|
+
record: freshRecord,
|
|
28613
|
+
unobservedTokens: await this.tokenCounter.countMessagesAsync(unobservedMessages)
|
|
28614
|
+
})) return;
|
|
28615
|
+
observationStarted = true;
|
|
28616
|
+
await hooks?.onObservationStart?.();
|
|
28518
28617
|
const result = await ObservationStrategy.create(this, {
|
|
28519
28618
|
record: freshRecord,
|
|
28520
28619
|
threadId,
|
|
@@ -28532,17 +28631,22 @@ ${formattedMessages}
|
|
|
28532
28631
|
observed = result.observed;
|
|
28533
28632
|
observationUsage = result.usage;
|
|
28534
28633
|
observationProviderMetadata = result.providerMetadata;
|
|
28535
|
-
}
|
|
28536
|
-
|
|
28537
|
-
|
|
28538
|
-
|
|
28539
|
-
|
|
28540
|
-
|
|
28541
|
-
|
|
28542
|
-
|
|
28543
|
-
|
|
28544
|
-
|
|
28545
|
-
|
|
28634
|
+
});
|
|
28635
|
+
} catch (error) {
|
|
28636
|
+
lifecycleError = error;
|
|
28637
|
+
observationError = error instanceof Error ? error : new Error(String(error));
|
|
28638
|
+
}
|
|
28639
|
+
if (observationStarted) try {
|
|
28640
|
+
await hooks?.onObservationEnd?.({
|
|
28641
|
+
usage: observationUsage,
|
|
28642
|
+
error: observationError,
|
|
28643
|
+
...observationProviderMetadata ? { providerMetadata: observationProviderMetadata } : {}
|
|
28644
|
+
});
|
|
28645
|
+
} catch (endHookError) {
|
|
28646
|
+
if (lifecycleError === void 0) throw endHookError;
|
|
28647
|
+
omDebug(`[OM:hooks] onObservationEnd hook failed after cycle failure: ${endHookError instanceof Error ? endHookError.message : String(endHookError)}`);
|
|
28648
|
+
}
|
|
28649
|
+
if (lifecycleError !== void 0) throw lifecycleError;
|
|
28546
28650
|
const record = await this.getOrCreateRecord(threadId, resourceId);
|
|
28547
28651
|
const reflected = record.generationCount > generationBefore && generationBefore >= 0;
|
|
28548
28652
|
if (observed) this.maybeTriggerCadenceCuration(threadId, resourceId, record, requestContext).catch((error) => {
|
|
@@ -28616,11 +28720,18 @@ ${formattedMessages}
|
|
|
28616
28720
|
resourceId,
|
|
28617
28721
|
trigger: "manual"
|
|
28618
28722
|
});
|
|
28619
|
-
hooks?.onReflectionStart?.();
|
|
28620
28723
|
let reflectionUsage;
|
|
28621
28724
|
let reflectionProviderMetadata;
|
|
28622
28725
|
let reflectionError;
|
|
28726
|
+
let lifecycleError;
|
|
28623
28727
|
try {
|
|
28728
|
+
try {
|
|
28729
|
+
await hooks?.onReflectionStart?.();
|
|
28730
|
+
} catch (error) {
|
|
28731
|
+
lifecycleError = error;
|
|
28732
|
+
reflectionError = error instanceof Error ? error : new Error(String(error));
|
|
28733
|
+
throw error;
|
|
28734
|
+
}
|
|
28624
28735
|
const thread = await this.storage.getThreadById({ threadId });
|
|
28625
28736
|
const previousOmMetadata = (0, _mastra_core_memory.getThreadOMMetadata)(thread?.metadata);
|
|
28626
28737
|
const priorExtractedValues = getPriorExtractedValues(previousOmMetadata, this.reflectionConfig.extractors);
|
|
@@ -28658,6 +28769,7 @@ ${formattedMessages}
|
|
|
28658
28769
|
};
|
|
28659
28770
|
} catch (error) {
|
|
28660
28771
|
reflectionError = error instanceof Error ? error : new Error(String(error));
|
|
28772
|
+
if (lifecycleError !== void 0) throw error;
|
|
28661
28773
|
omError("[OM] reflect() failed", error);
|
|
28662
28774
|
return {
|
|
28663
28775
|
reflected: false,
|
|
@@ -28665,13 +28777,25 @@ ${formattedMessages}
|
|
|
28665
28777
|
usage: void 0
|
|
28666
28778
|
};
|
|
28667
28779
|
} finally {
|
|
28668
|
-
|
|
28669
|
-
|
|
28670
|
-
|
|
28671
|
-
|
|
28672
|
-
}
|
|
28673
|
-
|
|
28674
|
-
|
|
28780
|
+
try {
|
|
28781
|
+
await this.storage.setReflectingFlag(record.id, false);
|
|
28782
|
+
} finally {
|
|
28783
|
+
unregisterOp(record.id, "reflecting");
|
|
28784
|
+
}
|
|
28785
|
+
let endHookError;
|
|
28786
|
+
try {
|
|
28787
|
+
await hooks?.onReflectionEnd?.({
|
|
28788
|
+
usage: reflectionUsage,
|
|
28789
|
+
error: reflectionError,
|
|
28790
|
+
...reflectionProviderMetadata ? { providerMetadata: reflectionProviderMetadata } : {}
|
|
28791
|
+
});
|
|
28792
|
+
} catch (error) {
|
|
28793
|
+
endHookError = error;
|
|
28794
|
+
}
|
|
28795
|
+
if (endHookError !== void 0) {
|
|
28796
|
+
if (lifecycleError === void 0) throw endHookError;
|
|
28797
|
+
omDebug(`[OM:hooks] onReflectionEnd hook failed after cycle failure: ${endHookError instanceof Error ? endHookError.message : String(endHookError)}`);
|
|
28798
|
+
}
|
|
28675
28799
|
}
|
|
28676
28800
|
}
|
|
28677
28801
|
/**
|
|
@@ -28967,7 +29091,9 @@ var ObservationalMemoryProcessor = class {
|
|
|
28967
29091
|
return messageList;
|
|
28968
29092
|
}
|
|
28969
29093
|
const { threadId, resourceId } = context;
|
|
28970
|
-
const
|
|
29094
|
+
const memoryContext = (0, _mastra_core_memory.parseMemoryRequestContext)(requestContext);
|
|
29095
|
+
const runState = memoryContext?.runState?.();
|
|
29096
|
+
const readOnly = memoryContext?.memoryConfig?.readOnly;
|
|
28971
29097
|
const actorModelContext = model?.modelId ? {
|
|
28972
29098
|
provider: model.provider,
|
|
28973
29099
|
modelId: model.modelId,
|
|
@@ -28984,7 +29110,8 @@ var ObservationalMemoryProcessor = class {
|
|
|
28984
29110
|
memory: this.memory,
|
|
28985
29111
|
messageList,
|
|
28986
29112
|
threadId,
|
|
28987
|
-
resourceId
|
|
29113
|
+
resourceId,
|
|
29114
|
+
runState
|
|
28988
29115
|
});
|
|
28989
29116
|
const systemMessages = ctx.omRecord ? await this.engine.buildContextSystemMessages({
|
|
28990
29117
|
threadId,
|
|
@@ -29025,7 +29152,7 @@ var ObservationalMemoryProcessor = class {
|
|
|
29025
29152
|
this.turn.sendStateSignal = args.sendStateSignal;
|
|
29026
29153
|
this.turn.agent = args.agent;
|
|
29027
29154
|
this.turn.requestContext = requestContext;
|
|
29028
|
-
await this.turn.start(this.memory);
|
|
29155
|
+
await this.turn.start(this.memory, runState);
|
|
29029
29156
|
if (stepNumber === 0 && this.temporalMarkers) await insertTemporalGapMarkers({
|
|
29030
29157
|
messageList,
|
|
29031
29158
|
sendSignal: args.sendSignal
|
|
@@ -30195,14 +30322,18 @@ ${workingMemory}`;
|
|
|
30195
30322
|
if (!this.threadConfig.workingMemory?.enabled) return null;
|
|
30196
30323
|
return extractWorkingMemoryContent(text)?.trim() ?? null;
|
|
30197
30324
|
}
|
|
30198
|
-
async getWorkingMemory({ threadId, resourceId, memoryConfig }) {
|
|
30325
|
+
async getWorkingMemory({ threadId, resourceId, memoryConfig, runState }) {
|
|
30199
30326
|
const config = this.getMergedThreadConfig(memoryConfig || {});
|
|
30200
30327
|
if (!config.workingMemory?.enabled) return null;
|
|
30201
30328
|
const scope = config.workingMemory.scope || "resource";
|
|
30202
30329
|
let workingMemoryData = null;
|
|
30203
30330
|
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'.");
|
|
30204
|
-
if (scope === "resource" && resourceId)
|
|
30205
|
-
|
|
30331
|
+
if (scope === "resource" && resourceId) {
|
|
30332
|
+
const loadWorkingMemory = async () => {
|
|
30333
|
+
return (await (await this.getMemoryStore()).getResourceById({ resourceId }))?.workingMemory || null;
|
|
30334
|
+
};
|
|
30335
|
+
workingMemoryData = runState ? await runState.load(`working-memory:resource:${resourceId}`, loadWorkingMemory) : await loadWorkingMemory();
|
|
30336
|
+
} else workingMemoryData = (runState?.threadLoaded ? runState.thread : await this.getThreadById({ threadId }))?.metadata?.workingMemory;
|
|
30206
30337
|
if (!workingMemoryData) return null;
|
|
30207
30338
|
return workingMemoryData;
|
|
30208
30339
|
}
|
|
@@ -30234,16 +30365,18 @@ ${workingMemory}`;
|
|
|
30234
30365
|
content: (config.workingMemory.template || this.defaultWorkingMemoryTemplate).trim()
|
|
30235
30366
|
};
|
|
30236
30367
|
}
|
|
30237
|
-
async getSystemMessage({ threadId, resourceId, memoryConfig }) {
|
|
30368
|
+
async getSystemMessage({ threadId, resourceId, memoryConfig, runState }) {
|
|
30238
30369
|
const config = this.getMergedThreadConfig(memoryConfig);
|
|
30239
30370
|
this.assertWorkingMemoryStateSignalsCompatibility(config);
|
|
30240
30371
|
if (!config.workingMemory?.enabled) return null;
|
|
30241
30372
|
if (config.workingMemory?.useStateSignals) return null;
|
|
30242
|
-
const
|
|
30373
|
+
const loadTemplate = () => this.getWorkingMemoryTemplate({ memoryConfig });
|
|
30374
|
+
const workingMemoryTemplate = runState ? await runState.load("working-memory:template", loadTemplate) : await loadTemplate();
|
|
30243
30375
|
const workingMemoryData = await this.getWorkingMemory({
|
|
30244
30376
|
threadId,
|
|
30245
30377
|
resourceId,
|
|
30246
|
-
memoryConfig: config
|
|
30378
|
+
memoryConfig: config,
|
|
30379
|
+
runState
|
|
30247
30380
|
});
|
|
30248
30381
|
if (!workingMemoryTemplate) return null;
|
|
30249
30382
|
const workingMemoryConfig = config.workingMemory;
|
|
@@ -30276,7 +30409,7 @@ ${workingMemory}`;
|
|
|
30276
30409
|
* ```
|
|
30277
30410
|
*/
|
|
30278
30411
|
async getContext(opts) {
|
|
30279
|
-
const { threadId, resourceId, memoryConfig } = opts;
|
|
30412
|
+
const { threadId, resourceId, memoryConfig, runState } = opts;
|
|
30280
30413
|
const config = this.getMergedThreadConfig(memoryConfig);
|
|
30281
30414
|
const memoryStore = await this.getMemoryStore();
|
|
30282
30415
|
const systemParts = [];
|
|
@@ -30286,10 +30419,14 @@ ${workingMemory}`;
|
|
|
30286
30419
|
let otherThreadsContext;
|
|
30287
30420
|
const omEngine = await this.omEngine;
|
|
30288
30421
|
if (omEngine) {
|
|
30289
|
-
|
|
30422
|
+
const loadOmRecord = () => omEngine.getRecord(threadId, resourceId);
|
|
30423
|
+
omRecord = runState ? await runState.load(`observational-memory:record:${threadId}:${resourceId ?? ""}`, loadOmRecord) : await loadOmRecord();
|
|
30290
30424
|
if (omRecord?.activeObservations) {
|
|
30291
30425
|
hasObservations = true;
|
|
30292
|
-
if (omEngine.scope === "resource" && resourceId)
|
|
30426
|
+
if (omEngine.scope === "resource" && resourceId) {
|
|
30427
|
+
const loadOtherThreadsContext = () => omEngine.getOtherThreadsContext(resourceId, threadId);
|
|
30428
|
+
otherThreadsContext = runState ? await runState.load(`observational-memory:other-threads:${resourceId}:${threadId}:${omRecord.lastObservedAt ?? ""}`, loadOtherThreadsContext) : await loadOtherThreadsContext();
|
|
30429
|
+
}
|
|
30293
30430
|
const obsSystemMessage = await omEngine.buildContextSystemMessage({
|
|
30294
30431
|
threadId,
|
|
30295
30432
|
resourceId,
|
|
@@ -30317,30 +30454,41 @@ ${workingMemory}`;
|
|
|
30317
30454
|
const workingMemoryMessage = await this.getSystemMessage({
|
|
30318
30455
|
threadId,
|
|
30319
30456
|
resourceId,
|
|
30320
|
-
memoryConfig: config
|
|
30457
|
+
memoryConfig: config,
|
|
30458
|
+
runState
|
|
30321
30459
|
});
|
|
30322
30460
|
if (workingMemoryMessage) systemParts.push(workingMemoryMessage);
|
|
30323
30461
|
let messages;
|
|
30324
30462
|
if (omEngine && omRecord) {
|
|
30325
30463
|
const dateFilter = omRecord.lastObservedAt ? { dateRange: { start: new Date(new Date(omRecord.lastObservedAt).getTime() + 1) } } : void 0;
|
|
30326
|
-
|
|
30327
|
-
|
|
30328
|
-
|
|
30329
|
-
|
|
30330
|
-
|
|
30331
|
-
|
|
30332
|
-
|
|
30333
|
-
|
|
30334
|
-
|
|
30335
|
-
|
|
30336
|
-
|
|
30337
|
-
|
|
30338
|
-
|
|
30339
|
-
|
|
30340
|
-
|
|
30341
|
-
|
|
30342
|
-
|
|
30343
|
-
|
|
30464
|
+
const boundary = omRecord.lastObservedAt ? new Date(omRecord.lastObservedAt).toISOString() : "";
|
|
30465
|
+
if (omEngine.scope === "resource" && resourceId) {
|
|
30466
|
+
const loadMessages = async () => {
|
|
30467
|
+
return (await memoryStore.listMessagesByResourceId({
|
|
30468
|
+
resourceId,
|
|
30469
|
+
orderBy: {
|
|
30470
|
+
field: "createdAt",
|
|
30471
|
+
direction: "ASC"
|
|
30472
|
+
},
|
|
30473
|
+
perPage: false,
|
|
30474
|
+
filter: dateFilter
|
|
30475
|
+
})).messages;
|
|
30476
|
+
};
|
|
30477
|
+
messages = runState ? await runState.load(`observational-memory:messages:resource:${resourceId}:${boundary}`, loadMessages) : await loadMessages();
|
|
30478
|
+
} else {
|
|
30479
|
+
const loadMessages = async () => {
|
|
30480
|
+
return (await memoryStore.listMessages({
|
|
30481
|
+
threadId,
|
|
30482
|
+
orderBy: {
|
|
30483
|
+
field: "createdAt",
|
|
30484
|
+
direction: "ASC"
|
|
30485
|
+
},
|
|
30486
|
+
perPage: false,
|
|
30487
|
+
filter: dateFilter
|
|
30488
|
+
})).messages;
|
|
30489
|
+
};
|
|
30490
|
+
messages = runState ? await runState.load(`observational-memory:messages:thread:${threadId}:${boundary}`, loadMessages) : await loadMessages();
|
|
30491
|
+
}
|
|
30344
30492
|
} else {
|
|
30345
30493
|
const lastMessages = config.lastMessages;
|
|
30346
30494
|
if (lastMessages === false) messages = [];
|
|
@@ -30428,6 +30576,7 @@ ${workingMemory}`;
|
|
|
30428
30576
|
instruction: omConfig.observation.instruction,
|
|
30429
30577
|
threadTitle: omConfig.observation.threadTitle,
|
|
30430
30578
|
observeAttachments: omConfig.observation.observeAttachments,
|
|
30579
|
+
continuationHints: omConfig.observation.continuationHints,
|
|
30431
30580
|
extract: omConfig.observation.extract
|
|
30432
30581
|
} : void 0,
|
|
30433
30582
|
reflection: omConfig.reflection ? {
|
|
@@ -30438,6 +30587,7 @@ ${workingMemory}`;
|
|
|
30438
30587
|
bufferActivation: omConfig.reflection.bufferActivation,
|
|
30439
30588
|
blockAfter: omConfig.reflection.blockAfter,
|
|
30440
30589
|
instruction: omConfig.reflection.instruction,
|
|
30590
|
+
continuationHints: omConfig.reflection.continuationHints,
|
|
30441
30591
|
extract: omConfig.reflection.extract
|
|
30442
30592
|
} : void 0
|
|
30443
30593
|
});
|
|
@@ -31645,4 +31795,4 @@ Object.defineProperty(exports, "wrapInObservationGroup", {
|
|
|
31645
31795
|
}
|
|
31646
31796
|
});
|
|
31647
31797
|
|
|
31648
|
-
//# sourceMappingURL=src-
|
|
31798
|
+
//# sourceMappingURL=src-D8byb8Ge.cjs.map
|