@mastra/server 1.62.0-alpha.2 → 1.62.0-alpha.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/dist/{datasets-DmN9V4rU.js → datasets-CInAtVdf.js} +3 -1
- package/dist/datasets-CInAtVdf.js.map +1 -0
- package/dist/{datasets-CNtKg_3d.cjs → datasets-DYhcB-od.cjs} +3 -1
- package/dist/datasets-DYhcB-od.cjs.map +1 -0
- package/dist/{dist-DERatX43.cjs → dist-Czh_Btxb.cjs} +313 -162
- package/dist/dist-Czh_Btxb.cjs.map +1 -0
- package/dist/{dist-Cw-T1gX6.js → dist-DkFSqWZ7.js} +313 -162
- package/dist/dist-DkFSqWZ7.js.map +1 -0
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/docs/references/docs-server-middleware.md +4 -0
- package/dist/server/handlers/agent-builder.cjs +1 -1
- package/dist/server/handlers/agent-builder.js +1 -1
- package/dist/server/handlers/datasets.cjs +1 -1
- package/dist/server/handlers/datasets.d.ts +10 -0
- package/dist/server/handlers/datasets.d.ts.map +1 -1
- package/dist/server/handlers/datasets.js +1 -1
- package/dist/server/handlers/mcp-client-versions.cjs +1 -1
- package/dist/server/handlers/mcp-client-versions.js +1 -1
- package/dist/server/handlers/prompt-block-versions.cjs +1 -1
- package/dist/server/handlers/prompt-block-versions.js +1 -1
- package/dist/server/handlers/scorer-versions.cjs +1 -1
- package/dist/server/handlers/scorer-versions.js +1 -1
- package/dist/server/handlers/stored-mcp-clients.cjs +1 -1
- package/dist/server/handlers/stored-mcp-clients.js +1 -1
- package/dist/server/handlers/stored-prompt-blocks.cjs +1 -1
- package/dist/server/handlers/stored-prompt-blocks.js +1 -1
- package/dist/server/handlers/stored-scorers.cjs +1 -1
- package/dist/server/handlers/stored-scorers.js +1 -1
- package/dist/server/handlers/stored-skill-favorites.cjs +1 -1
- package/dist/server/handlers/stored-skill-favorites.js +1 -1
- package/dist/server/handlers/stored-skills.cjs +1 -1
- package/dist/server/handlers/stored-skills.js +1 -1
- package/dist/server/schemas/datasets.d.ts +4 -0
- package/dist/server/schemas/datasets.d.ts.map +1 -1
- package/dist/server/schemas/index.cjs +2 -2
- package/dist/server/schemas/index.js +2 -2
- package/dist/server/server-adapter/index.cjs +21 -2
- package/dist/server/server-adapter/index.cjs.map +1 -1
- package/dist/server/server-adapter/index.d.ts +13 -0
- package/dist/server/server-adapter/index.d.ts.map +1 -1
- package/dist/server/server-adapter/index.js +21 -2
- package/dist/server/server-adapter/index.js.map +1 -1
- package/dist/server/server-adapter/routes/datasets.d.ts +10 -0
- package/dist/server/server-adapter/routes/datasets.d.ts.map +1 -1
- package/package.json +6 -6
- package/dist/datasets-CNtKg_3d.cjs.map +0 -1
- package/dist/datasets-DmN9V4rU.js.map +0 -1
- package/dist/dist-Cw-T1gX6.js.map +0 -1
- package/dist/dist-DERatX43.cjs.map +0 -1
|
@@ -4693,7 +4693,7 @@ function splitLines(text) {
|
|
|
4693
4693
|
return result;
|
|
4694
4694
|
}
|
|
4695
4695
|
//#endregion
|
|
4696
|
-
//#region ../memory/dist/src-
|
|
4696
|
+
//#region ../memory/dist/src-BTHCV1ov.js
|
|
4697
4697
|
var __defProp$3 = Object.defineProperty;
|
|
4698
4698
|
var __exportAll = (all, no_symbols) => {
|
|
4699
4699
|
let target = {};
|
|
@@ -8927,6 +8927,7 @@ async function cancelResponseBody$1(response) {
|
|
|
8927
8927
|
var initialGlobalFetch$1 = globalThis.fetch;
|
|
8928
8928
|
isNodeDefaultFetch$1(initialGlobalFetch$1);
|
|
8929
8929
|
function isNodeDefaultFetch$1(fetch) {
|
|
8930
|
+
if (typeof fetch !== "function") return false;
|
|
8930
8931
|
const source = Function.prototype.toString.call(fetch);
|
|
8931
8932
|
return source.includes("internal/deps/undici") || source.includes("lazy loading of undici");
|
|
8932
8933
|
}
|
|
@@ -13818,6 +13819,7 @@ var DownloadError$2 = class extends (_b$2$1 = AISDKError$3, _a$2$1 = symbol$2$1,
|
|
|
13818
13819
|
var initialGlobalFetch$2 = globalThis.fetch;
|
|
13819
13820
|
isNodeDefaultFetch$2(initialGlobalFetch$2);
|
|
13820
13821
|
function isNodeDefaultFetch$2(fetch) {
|
|
13822
|
+
if (typeof fetch !== "function") return false;
|
|
13821
13823
|
const source = Function.prototype.toString.call(fetch);
|
|
13822
13824
|
return source.includes("internal/deps/undici") || source.includes("lazy loading of undici");
|
|
13823
13825
|
}
|
|
@@ -23480,6 +23482,12 @@ function extractListItemsOnly(content) {
|
|
|
23480
23482
|
*/
|
|
23481
23483
|
const MAX_OBSERVATION_LINE_CHARS = 1e4;
|
|
23482
23484
|
/**
|
|
23485
|
+
* Minimum trimmed line length considered by the duplicate-line degenerate
|
|
23486
|
+
* check. Short lines (blank lines, separators, terse bullets) legitimately
|
|
23487
|
+
* repeat; long identical lines almost never do.
|
|
23488
|
+
*/
|
|
23489
|
+
const MIN_DUPLICATE_LINE_CHARS = 24;
|
|
23490
|
+
/**
|
|
23483
23491
|
* Truncate individual observation lines that exceed the maximum length.
|
|
23484
23492
|
*/
|
|
23485
23493
|
function sanitizeObservationLines(observations) {
|
|
@@ -23517,6 +23525,18 @@ function detectDegenerateRepetition(text) {
|
|
|
23517
23525
|
if (totalWindows > 5 && duplicateWindows / totalWindows > .4) return true;
|
|
23518
23526
|
const lines = text.split("\n");
|
|
23519
23527
|
for (const line of lines) if (line.length > 5e4) return true;
|
|
23528
|
+
const seenLines = /* @__PURE__ */ new Map();
|
|
23529
|
+
let duplicateLines = 0;
|
|
23530
|
+
let totalCountedLines = 0;
|
|
23531
|
+
for (const line of lines) {
|
|
23532
|
+
const trimmed = line.trim();
|
|
23533
|
+
if (trimmed.length < MIN_DUPLICATE_LINE_CHARS) continue;
|
|
23534
|
+
totalCountedLines++;
|
|
23535
|
+
const count = (seenLines.get(trimmed) ?? 0) + 1;
|
|
23536
|
+
seenLines.set(trimmed, count);
|
|
23537
|
+
if (count > 1) duplicateLines++;
|
|
23538
|
+
}
|
|
23539
|
+
if (totalCountedLines >= 20 && duplicateLines / totalCountedLines > .5) return true;
|
|
23520
23540
|
return false;
|
|
23521
23541
|
}
|
|
23522
23542
|
/**
|
|
@@ -23551,12 +23571,26 @@ function describeDegenerateOutput(text, snippetChars = 400) {
|
|
|
23551
23571
|
topWindow = window;
|
|
23552
23572
|
}
|
|
23553
23573
|
let longestLine = 0;
|
|
23554
|
-
|
|
23574
|
+
const seenLines = /* @__PURE__ */ new Map();
|
|
23575
|
+
let duplicateLines = 0;
|
|
23576
|
+
let totalCountedLines = 0;
|
|
23577
|
+
for (const line of text.split("\n")) {
|
|
23578
|
+
if (line.length > longestLine) longestLine = line.length;
|
|
23579
|
+
const trimmed = line.trim();
|
|
23580
|
+
if (trimmed.length < MIN_DUPLICATE_LINE_CHARS) continue;
|
|
23581
|
+
totalCountedLines++;
|
|
23582
|
+
const count = (seenLines.get(trimmed) ?? 0) + 1;
|
|
23583
|
+
seenLines.set(trimmed, count);
|
|
23584
|
+
if (count > 1) duplicateLines++;
|
|
23585
|
+
}
|
|
23555
23586
|
const duplicateRatio = totalWindows > 0 ? (duplicateWindows / totalWindows).toFixed(2) : "n/a";
|
|
23587
|
+
const duplicateLineRatio = totalCountedLines > 0 ? (duplicateLines / totalCountedLines).toFixed(2) : "n/a";
|
|
23556
23588
|
const parts = [
|
|
23557
23589
|
`length=${text.length}`,
|
|
23558
23590
|
`sampledWindows=${totalWindows}`,
|
|
23559
23591
|
`duplicateRatio=${duplicateRatio}`,
|
|
23592
|
+
`duplicateLineRatio=${duplicateLineRatio}`,
|
|
23593
|
+
`countedLines=${totalCountedLines}`,
|
|
23560
23594
|
`longestLine=${longestLine}`,
|
|
23561
23595
|
`topWindowCount=${topCount}`
|
|
23562
23596
|
];
|
|
@@ -23824,7 +23858,19 @@ async function withOmTracingSpan({ phase, model, inputTokens, requestContext, ob
|
|
|
23824
23858
|
});
|
|
23825
23859
|
const childObservabilityContext = (0, _mastra_core_observability.createObservabilityContext)({ currentSpan: span });
|
|
23826
23860
|
if (!span) return callback(childObservabilityContext);
|
|
23827
|
-
return span.executeInContext(() =>
|
|
23861
|
+
return span.executeInContext(async () => {
|
|
23862
|
+
try {
|
|
23863
|
+
const result = await callback(childObservabilityContext);
|
|
23864
|
+
span.end();
|
|
23865
|
+
return result;
|
|
23866
|
+
} catch (error) {
|
|
23867
|
+
span.error({
|
|
23868
|
+
error,
|
|
23869
|
+
endSpan: true
|
|
23870
|
+
});
|
|
23871
|
+
throw error;
|
|
23872
|
+
}
|
|
23873
|
+
});
|
|
23828
23874
|
}
|
|
23829
23875
|
function filterObserverExtractors(extractors, skipContinuationHints) {
|
|
23830
23876
|
const configuredExtractors = extractors ?? [];
|
|
@@ -28917,10 +28963,11 @@ ObservationStrategy.create = ((om, opts) => {
|
|
|
28917
28963
|
if (deps.scope === "resource" && opts.resourceId) return new ResourceScopedObservationStrategy(deps, opts);
|
|
28918
28964
|
return new SyncObservationStrategy(deps, opts);
|
|
28919
28965
|
});
|
|
28920
|
-
async function loadMemoryContextMessages({ memory, messageList, threadId, resourceId }) {
|
|
28966
|
+
async function loadMemoryContextMessages({ memory, messageList, threadId, resourceId, runState }) {
|
|
28921
28967
|
const ctx = await memory.getContext({
|
|
28922
28968
|
threadId,
|
|
28923
|
-
resourceId
|
|
28969
|
+
resourceId,
|
|
28970
|
+
runState
|
|
28924
28971
|
});
|
|
28925
28972
|
for (const msg of ctx.messages) if (msg.role !== "system") messageList.add(msg, "memory");
|
|
28926
28973
|
return ctx;
|
|
@@ -29374,10 +29421,11 @@ var ObservationTurn = class {
|
|
|
29374
29421
|
* If a MemoryContextProvider is passed, loads historical messages and adds
|
|
29375
29422
|
* them to the MessageList. Without a provider, only fetches/caches the record.
|
|
29376
29423
|
*/
|
|
29377
|
-
async start(memory) {
|
|
29424
|
+
async start(memory, runState) {
|
|
29378
29425
|
if (this._started) throw new Error("Turn already started");
|
|
29379
29426
|
this._started = true;
|
|
29380
29427
|
this._record = await this.om.getOrCreateRecord(this.threadId, this.resourceId);
|
|
29428
|
+
runState?.set(`observational-memory:record:${this.threadId}:${this.resourceId ?? ""}`, this._record);
|
|
29381
29429
|
this._generationCountAtStart = this._record.generationCount;
|
|
29382
29430
|
this.memory = memory;
|
|
29383
29431
|
if (memory) {
|
|
@@ -29385,7 +29433,8 @@ var ObservationTurn = class {
|
|
|
29385
29433
|
memory,
|
|
29386
29434
|
messageList: this.messageList,
|
|
29387
29435
|
threadId: this.threadId,
|
|
29388
|
-
resourceId: this.resourceId
|
|
29436
|
+
resourceId: this.resourceId,
|
|
29437
|
+
runState
|
|
29389
29438
|
});
|
|
29390
29439
|
this._context = {
|
|
29391
29440
|
messages: ctx.messages,
|
|
@@ -29861,6 +29910,21 @@ var ReflectorRunner = class {
|
|
|
29861
29910
|
memory;
|
|
29862
29911
|
onReflectionCommitted;
|
|
29863
29912
|
mastra;
|
|
29913
|
+
/**
|
|
29914
|
+
* Per-lock-key observation-token count of the last unproductive synchronous
|
|
29915
|
+
* reflection (failed, or committed while still over the reflection
|
|
29916
|
+
* threshold). `call()` already runs the full bounded compression ladder for
|
|
29917
|
+
* a given input, so re-running it against unchanged observations cannot
|
|
29918
|
+
* succeed — threshold-triggered sync reflection is skipped while the count
|
|
29919
|
+
* is unchanged and retried as soon as the input differs.
|
|
29920
|
+
* Keyed by lock key (thread/resource), which is stable across generations —
|
|
29921
|
+
* record ids change every time a generation is created.
|
|
29922
|
+
*
|
|
29923
|
+
* Lifecycle: an entry is deleted when a sync reflection finishes under
|
|
29924
|
+
* threshold and replaced on each unproductive attempt. Entries are one
|
|
29925
|
+
* number per active thread/resource key and live for the runner's lifetime.
|
|
29926
|
+
*/
|
|
29927
|
+
syncReflectionSuppression = /* @__PURE__ */ new Map();
|
|
29864
29928
|
constructor(opts) {
|
|
29865
29929
|
this.reflectionConfig = opts.reflectionConfig;
|
|
29866
29930
|
this.observationConfig = opts.observationConfig;
|
|
@@ -29943,8 +30007,8 @@ var ReflectorRunner = class {
|
|
|
29943
30007
|
};
|
|
29944
30008
|
let reflectedTokens = 0;
|
|
29945
30009
|
let attemptNumber = 0;
|
|
29946
|
-
/**
|
|
29947
|
-
let
|
|
30010
|
+
/** True when the latest attempt returned an empty block for non-empty input. */
|
|
30011
|
+
let emptyOutput = false;
|
|
29948
30012
|
while (currentLevel <= maxLevel) {
|
|
29949
30013
|
attemptNumber++;
|
|
29950
30014
|
const isRetry = attemptNumber > 1;
|
|
@@ -30008,21 +30072,20 @@ var ReflectorRunner = class {
|
|
|
30008
30072
|
}
|
|
30009
30073
|
finalProviderMetadata = result.providerMetadata ?? finalProviderMetadata;
|
|
30010
30074
|
parsed = parseReflectorOutput(result.text, observations, activeExtractors);
|
|
30075
|
+
emptyOutput = !parsed.degenerate && observations.trim().length > 0 && parsed.observations.trim().length === 0;
|
|
30011
30076
|
if (parsed.degenerate) {
|
|
30012
30077
|
omDebug(`[OM:callReflector] attempt #${attemptNumber}: degenerate repetition detected, treating as compression failure. ${describeDegenerateOutput(result.text, 2e3)}`);
|
|
30013
30078
|
reflectedTokens = originalTokens;
|
|
30079
|
+
} else if (emptyOutput) {
|
|
30080
|
+
omDebug(`[OM:callReflector] attempt #${attemptNumber}: empty observations block for non-empty input, treating as compression failure`);
|
|
30081
|
+
reflectedTokens = originalTokens;
|
|
30014
30082
|
} else reflectedTokens = this.tokenCounter.countObservations(parsed.observations);
|
|
30015
30083
|
omDebug(`[OM:callReflector] attempt #${attemptNumber} parsed: reflectedTokens=${reflectedTokens}, targetThreshold=${targetThreshold}, compressionValid=${validateCompression(reflectedTokens, targetThreshold)}, parsedObsLen=${parsed.observations?.length}, degenerate=${parsed.degenerate ?? false}`);
|
|
30016
|
-
if (!parsed.degenerate && (validateCompression(reflectedTokens, targetThreshold) || currentLevel >= maxLevel)) break;
|
|
30017
|
-
if (parsed.degenerate && currentLevel >= maxLevel) {
|
|
30018
|
-
omDebug(`[OM:callReflector] degenerate output persists at maxLevel=${maxLevel}, breaking`);
|
|
30019
|
-
break;
|
|
30020
|
-
}
|
|
30021
|
-
if (!parsed.degenerate && previousObservations !== void 0 && parsed.observations === previousObservations) {
|
|
30022
|
-
omDebug(`[OM:callReflector] attempt #${attemptNumber} returned output identical to the previous attempt; escalating cannot help, stopping the ladder`);
|
|
30084
|
+
if (!parsed.degenerate && !emptyOutput && (validateCompression(reflectedTokens, targetThreshold) || currentLevel >= maxLevel)) break;
|
|
30085
|
+
if ((parsed.degenerate || emptyOutput) && currentLevel >= maxLevel) {
|
|
30086
|
+
omDebug(`[OM:callReflector] ${parsed.degenerate ? "degenerate" : "empty"} output persists at maxLevel=${maxLevel}, breaking`);
|
|
30023
30087
|
break;
|
|
30024
30088
|
}
|
|
30025
|
-
previousObservations = parsed.observations;
|
|
30026
30089
|
if (streamContext?.writer) {
|
|
30027
30090
|
const failedMarker = createObservationFailedMarker({
|
|
30028
30091
|
cycleId: streamContext.cycleId,
|
|
@@ -30058,6 +30121,7 @@ var ReflectorRunner = class {
|
|
|
30058
30121
|
}
|
|
30059
30122
|
currentLevel = Math.min(currentLevel + 1, maxLevel);
|
|
30060
30123
|
}
|
|
30124
|
+
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`);
|
|
30061
30125
|
const structuredExtraction = await extractStructuredValues({
|
|
30062
30126
|
agent,
|
|
30063
30127
|
source: "reflector",
|
|
@@ -30106,52 +30170,51 @@ var ReflectorRunner = class {
|
|
|
30106
30170
|
this.storage.setBufferingReflectionFlag(record.id, true).catch((err) => {
|
|
30107
30171
|
omError("[OM] Failed to set buffering reflection flag", err);
|
|
30108
30172
|
});
|
|
30109
|
-
|
|
30110
|
-
|
|
30111
|
-
|
|
30112
|
-
reflectionHooks?.onReflectionEnd?.({
|
|
30113
|
-
usage: outcome?.usage,
|
|
30114
|
-
...outcome?.providerMetadata ? { providerMetadata: outcome.providerMetadata } : {}
|
|
30115
|
-
});
|
|
30116
|
-
} catch (hookError) {
|
|
30117
|
-
omError("[OM] onReflectionEnd hook failed after async buffered reflection", hookError);
|
|
30118
|
-
}
|
|
30119
|
-
}, async (error) => {
|
|
30120
|
-
if (writer) try {
|
|
30121
|
-
const failedMarker = createBufferingFailedMarker({
|
|
30122
|
-
cycleId: `reflect-buf-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
|
|
30123
|
-
operationType: "reflection",
|
|
30124
|
-
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
30125
|
-
tokensAttempted: observationTokens,
|
|
30126
|
-
error: error instanceof Error ? error.message : String(error),
|
|
30127
|
-
recordId: record.id,
|
|
30128
|
-
threadId: record.threadId ?? ""
|
|
30129
|
-
});
|
|
30130
|
-
writer.custom({
|
|
30131
|
-
...failedMarker,
|
|
30132
|
-
transient: true
|
|
30133
|
-
}).catch(() => {});
|
|
30134
|
-
await this.persistMarkerToStorage(failedMarker, record.threadId ?? "", record.resourceId ?? void 0);
|
|
30135
|
-
} catch (markerError) {
|
|
30136
|
-
omError("[OM] Failed to persist buffering-failed marker after async buffered reflection failure", markerError);
|
|
30137
|
-
}
|
|
30138
|
-
omError("[OM] Async buffered reflection failed", error);
|
|
30173
|
+
const asyncOp = (async () => {
|
|
30174
|
+
let outcome;
|
|
30175
|
+
let reflectionError;
|
|
30139
30176
|
try {
|
|
30140
|
-
reflectionHooks?.
|
|
30141
|
-
|
|
30142
|
-
|
|
30177
|
+
await reflectionHooks?.onReflectionStart?.();
|
|
30178
|
+
outcome = await this.doAsyncBufferedReflection(record, bufferKey, writer, requestContext, observabilityContext, priorExtractedValues, mainAgent, sendSignal);
|
|
30179
|
+
} catch (error) {
|
|
30180
|
+
reflectionError = error instanceof Error ? error : new Error(String(error));
|
|
30181
|
+
if (writer) try {
|
|
30182
|
+
const failedMarker = createBufferingFailedMarker({
|
|
30183
|
+
cycleId: `reflect-buf-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
|
|
30184
|
+
operationType: "reflection",
|
|
30185
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
30186
|
+
tokensAttempted: observationTokens,
|
|
30187
|
+
error: reflectionError.message,
|
|
30188
|
+
recordId: record.id,
|
|
30189
|
+
threadId: record.threadId ?? ""
|
|
30190
|
+
});
|
|
30191
|
+
writer.custom({
|
|
30192
|
+
...failedMarker,
|
|
30193
|
+
transient: true
|
|
30194
|
+
}).catch(() => {});
|
|
30195
|
+
await this.persistMarkerToStorage(failedMarker, record.threadId ?? "", record.resourceId ?? void 0);
|
|
30196
|
+
} catch (markerError) {
|
|
30197
|
+
omError("[OM] Failed to persist buffering-failed marker after async buffered reflection failure", markerError);
|
|
30198
|
+
}
|
|
30199
|
+
omError("[OM] Async buffered reflection failed", error);
|
|
30200
|
+
BufferingCoordinator.lastBufferedBoundary.delete(bufferKey);
|
|
30201
|
+
} finally {
|
|
30202
|
+
try {
|
|
30203
|
+
await reflectionHooks?.onReflectionEnd?.({
|
|
30204
|
+
usage: outcome?.usage,
|
|
30205
|
+
error: reflectionError,
|
|
30206
|
+
...outcome?.providerMetadata ? { providerMetadata: outcome.providerMetadata } : {}
|
|
30207
|
+
});
|
|
30208
|
+
} catch (hookError) {
|
|
30209
|
+
omError("[OM] onReflectionEnd hook failed after async buffered reflection", hookError);
|
|
30210
|
+
}
|
|
30211
|
+
BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
|
|
30212
|
+
unregisterOp(record.id, "bufferingReflection");
|
|
30213
|
+
this.storage.setBufferingReflectionFlag(record.id, false).catch((err) => {
|
|
30214
|
+
omError("[OM] Failed to clear buffering reflection flag", err);
|
|
30143
30215
|
});
|
|
30144
|
-
} catch (hookError) {
|
|
30145
|
-
omError("[OM] onReflectionEnd hook failed after async buffered reflection failure", hookError);
|
|
30146
30216
|
}
|
|
30147
|
-
|
|
30148
|
-
}).finally(() => {
|
|
30149
|
-
BufferingCoordinator.asyncBufferingOps.delete(bufferKey);
|
|
30150
|
-
unregisterOp(record.id, "bufferingReflection");
|
|
30151
|
-
this.storage.setBufferingReflectionFlag(record.id, false).catch((err) => {
|
|
30152
|
-
omError("[OM] Failed to clear buffering reflection flag", err);
|
|
30153
|
-
});
|
|
30154
|
-
});
|
|
30217
|
+
})();
|
|
30155
30218
|
BufferingCoordinator.asyncBufferingOps.set(bufferKey, asyncOp);
|
|
30156
30219
|
}
|
|
30157
30220
|
/**
|
|
@@ -30412,6 +30475,13 @@ var ReflectorRunner = class {
|
|
|
30412
30475
|
return;
|
|
30413
30476
|
}
|
|
30414
30477
|
}
|
|
30478
|
+
if (activationTriggeredBy === "threshold") {
|
|
30479
|
+
const suppressedAtTokens = this.syncReflectionSuppression.get(lockKey);
|
|
30480
|
+
if (suppressedAtTokens !== void 0 && observationTokens === suppressedAtTokens) {
|
|
30481
|
+
omDebug(`[OM:reflect] skipping sync reflection — observations unchanged at ${observationTokens} tokens since the last unproductive attempt; retrying once they change`);
|
|
30482
|
+
return;
|
|
30483
|
+
}
|
|
30484
|
+
}
|
|
30415
30485
|
await this.storage.setReflectingFlag(record.id, true);
|
|
30416
30486
|
registerOp(record.id, "reflecting");
|
|
30417
30487
|
const cycleId = crypto.randomUUID();
|
|
@@ -30452,8 +30522,15 @@ var ReflectorRunner = class {
|
|
|
30452
30522
|
let reflectionUsage;
|
|
30453
30523
|
let reflectionProviderMetadata;
|
|
30454
30524
|
let reflectionError;
|
|
30455
|
-
|
|
30525
|
+
let lifecycleError;
|
|
30456
30526
|
try {
|
|
30527
|
+
try {
|
|
30528
|
+
await reflectionHooks?.onReflectionStart?.();
|
|
30529
|
+
} catch (error) {
|
|
30530
|
+
lifecycleError = error;
|
|
30531
|
+
reflectionError = error instanceof Error ? error : new Error(String(error));
|
|
30532
|
+
throw error;
|
|
30533
|
+
}
|
|
30457
30534
|
const compressionStartLevel = await this.getCompressionStartLevel(requestContext);
|
|
30458
30535
|
const reflectResult = await this.call(record.activeObservations, void 0, streamContext, reflectThreshold, abortSignal, void 0, compressionStartLevel, requestContext, priorExtractedValues, observabilityContext, void 0, mainAgent, sendSignal);
|
|
30459
30536
|
reflectionUsage = reflectResult.usage;
|
|
@@ -30465,6 +30542,8 @@ var ReflectorRunner = class {
|
|
|
30465
30542
|
reflection: reflectResult.observations,
|
|
30466
30543
|
tokenCount: reflectionTokenCount
|
|
30467
30544
|
});
|
|
30545
|
+
if (reflectionTokenCount >= reflectThreshold) this.syncReflectionSuppression.set(lockKey, reflectionTokenCount);
|
|
30546
|
+
else this.syncReflectionSuppression.delete(lockKey);
|
|
30468
30547
|
await this.notifyReflectionCommitted({
|
|
30469
30548
|
parentThreadId: requestedThreadId ?? record.threadId ?? "",
|
|
30470
30549
|
resourceId: record.resourceId ?? "",
|
|
@@ -30523,18 +30602,28 @@ var ReflectorRunner = class {
|
|
|
30523
30602
|
await this.persistMarkerToStorage(failedMarker, threadId, record.resourceId ?? void 0);
|
|
30524
30603
|
}
|
|
30525
30604
|
reflectionError = error instanceof Error ? error : new Error(String(error));
|
|
30526
|
-
if (abortSignal?.aborted) throw error;
|
|
30605
|
+
if (lifecycleError !== void 0 || abortSignal?.aborted) throw error;
|
|
30606
|
+
this.syncReflectionSuppression.set(lockKey, observationTokens);
|
|
30527
30607
|
omError("[OM] Reflection failed", error);
|
|
30528
30608
|
} finally {
|
|
30529
|
-
await this.storage.setReflectingFlag(record.id, false);
|
|
30530
30609
|
try {
|
|
30531
|
-
|
|
30610
|
+
await this.storage.setReflectingFlag(record.id, false);
|
|
30611
|
+
} finally {
|
|
30612
|
+
unregisterOp(record.id, "reflecting");
|
|
30613
|
+
}
|
|
30614
|
+
let endHookError;
|
|
30615
|
+
try {
|
|
30616
|
+
await reflectionHooks?.onReflectionEnd?.({
|
|
30532
30617
|
usage: reflectionUsage,
|
|
30533
30618
|
error: reflectionError,
|
|
30534
30619
|
...reflectionProviderMetadata ? { providerMetadata: reflectionProviderMetadata } : {}
|
|
30535
30620
|
});
|
|
30536
|
-
}
|
|
30537
|
-
|
|
30621
|
+
} catch (error) {
|
|
30622
|
+
endHookError = error;
|
|
30623
|
+
}
|
|
30624
|
+
if (endHookError !== void 0) {
|
|
30625
|
+
if (lifecycleError === void 0 && !abortSignal?.aborted) throw endHookError;
|
|
30626
|
+
omDebug(`[OM:hooks] onReflectionEnd hook failed after cycle failure: ${endHookError instanceof Error ? endHookError.message : String(endHookError)}`);
|
|
30538
30627
|
}
|
|
30539
30628
|
}
|
|
30540
30629
|
}
|
|
@@ -30991,6 +31080,8 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
30991
31080
|
onIndexObservations;
|
|
30992
31081
|
/** Config-level lifecycle hooks fired for every observation/reflection cycle. */
|
|
30993
31082
|
hooks;
|
|
31083
|
+
/** Execution policy for config-level hooks on manual and turn-synchronous cycles. */
|
|
31084
|
+
hookExecution;
|
|
30994
31085
|
/** Observer agent runner — handles LLM calls for extracting observations. */
|
|
30995
31086
|
observer;
|
|
30996
31087
|
/** Reflector agent runner — handles LLM calls for compressing observations. */
|
|
@@ -31097,6 +31188,7 @@ var ObservationalMemory = class ObservationalMemory {
|
|
|
31097
31188
|
this.retrievalSearch = typeof config.retrieval === "object" && Boolean(config.retrieval.vector);
|
|
31098
31189
|
this.onIndexObservations = config.onIndexObservations;
|
|
31099
31190
|
this.hooks = config.hooks;
|
|
31191
|
+
this.hookExecution = config.hookExecution ?? "non-blocking";
|
|
31100
31192
|
this.mastra = config.mastra;
|
|
31101
31193
|
this.memory = config.memory;
|
|
31102
31194
|
this.curationCadence = config.curationCadence;
|
|
@@ -32889,57 +32981,54 @@ ${formattedMessages}
|
|
|
32889
32981
|
};
|
|
32890
32982
|
}
|
|
32891
32983
|
/**
|
|
32892
|
-
* Compose
|
|
32893
|
-
*
|
|
32894
|
-
*
|
|
32895
|
-
* never fail an observation/reflection cycle; per-call hooks keep their
|
|
32896
|
-
* existing payloads and propagation semantics. Returns undefined when
|
|
32897
|
-
* neither is configured, so call sites stay zero-cost.
|
|
32898
|
-
*
|
|
32899
|
-
* Used internally by every pipeline path (manual observe/reflect,
|
|
32900
|
-
* turn-engine sync observation, async buffering); public only so the
|
|
32901
|
-
* observation turn engine can thread config-level reflection hooks into
|
|
32902
|
-
* reflector calls.
|
|
32984
|
+
* Compose config-level hooks with optional per-call hooks and bind context to
|
|
32985
|
+
* config-level callbacks. The configured policy applies unless a background
|
|
32986
|
+
* path explicitly requests non-blocking invocation.
|
|
32903
32987
|
*
|
|
32904
32988
|
* @internal
|
|
32905
32989
|
*/
|
|
32906
|
-
composeHooks(callHooks, context) {
|
|
32990
|
+
composeHooks(callHooks, context, execution = "configured") {
|
|
32907
32991
|
const configHooks = this.hooks;
|
|
32908
32992
|
if (!configHooks) return callHooks;
|
|
32909
32993
|
if (!callHooks && !Object.keys(configHooks).length) return void 0;
|
|
32910
|
-
const
|
|
32994
|
+
const shouldAwaitConfig = execution === "configured" && this.hookExecution === "await";
|
|
32995
|
+
const invokeConfigHook = async (name, arg) => {
|
|
32911
32996
|
const hook = configHooks[name];
|
|
32912
32997
|
if (!hook) return;
|
|
32998
|
+
if (shouldAwaitConfig) {
|
|
32999
|
+
await hook(arg);
|
|
33000
|
+
return;
|
|
33001
|
+
}
|
|
32913
33002
|
const logHookFailure = (error) => omDebug(`[OM:hooks] config-level ${name} hook failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
32914
33003
|
try {
|
|
32915
|
-
const
|
|
32916
|
-
if (
|
|
33004
|
+
const result = hook(arg);
|
|
33005
|
+
if (result && typeof result.then === "function") result.then(void 0, logHookFailure);
|
|
32917
33006
|
} catch (error) {
|
|
32918
33007
|
logHookFailure(error);
|
|
32919
33008
|
}
|
|
32920
33009
|
};
|
|
32921
33010
|
return {
|
|
32922
|
-
onObservationStart: () => {
|
|
32923
|
-
|
|
32924
|
-
callHooks?.onObservationStart?.();
|
|
33011
|
+
onObservationStart: async () => {
|
|
33012
|
+
await invokeConfigHook("onObservationStart", context);
|
|
33013
|
+
await callHooks?.onObservationStart?.();
|
|
32925
33014
|
},
|
|
32926
|
-
onObservationEnd: (result) => {
|
|
32927
|
-
|
|
33015
|
+
onObservationEnd: async (result) => {
|
|
33016
|
+
await invokeConfigHook("onObservationEnd", {
|
|
32928
33017
|
...context,
|
|
32929
33018
|
...result
|
|
32930
33019
|
});
|
|
32931
|
-
callHooks?.onObservationEnd?.(result);
|
|
33020
|
+
await callHooks?.onObservationEnd?.(result);
|
|
32932
33021
|
},
|
|
32933
|
-
onReflectionStart: () => {
|
|
32934
|
-
|
|
32935
|
-
callHooks?.onReflectionStart?.();
|
|
33022
|
+
onReflectionStart: async () => {
|
|
33023
|
+
await invokeConfigHook("onReflectionStart", context);
|
|
33024
|
+
await callHooks?.onReflectionStart?.();
|
|
32936
33025
|
},
|
|
32937
|
-
onReflectionEnd: (result) => {
|
|
32938
|
-
|
|
33026
|
+
onReflectionEnd: async (result) => {
|
|
33027
|
+
await invokeConfigHook("onReflectionEnd", {
|
|
32939
33028
|
...context,
|
|
32940
33029
|
...result
|
|
32941
33030
|
});
|
|
32942
|
-
callHooks?.onReflectionEnd?.(result);
|
|
33031
|
+
await callHooks?.onReflectionEnd?.(result);
|
|
32943
33032
|
}
|
|
32944
33033
|
};
|
|
32945
33034
|
}
|
|
@@ -32952,22 +33041,29 @@ ${formattedMessages}
|
|
|
32952
33041
|
* end hook reports `error` for failed cycles even though nothing throws.
|
|
32953
33042
|
*/
|
|
32954
33043
|
async runBufferedObservationCycle(context, run) {
|
|
32955
|
-
const hooks = this.composeHooks(void 0, context);
|
|
32956
|
-
hooks?.onObservationStart?.();
|
|
33044
|
+
const hooks = this.composeHooks(void 0, context, "non-blocking");
|
|
32957
33045
|
let runResult;
|
|
32958
33046
|
let runError;
|
|
33047
|
+
let lifecycleError;
|
|
32959
33048
|
try {
|
|
33049
|
+
await hooks?.onObservationStart?.();
|
|
32960
33050
|
runResult = await run();
|
|
32961
33051
|
return runResult;
|
|
32962
33052
|
} catch (error) {
|
|
33053
|
+
lifecycleError = error;
|
|
32963
33054
|
runError = error instanceof Error ? error : new Error(String(error));
|
|
32964
33055
|
throw error;
|
|
32965
33056
|
} finally {
|
|
32966
|
-
|
|
32967
|
-
|
|
32968
|
-
|
|
32969
|
-
|
|
32970
|
-
|
|
33057
|
+
try {
|
|
33058
|
+
await hooks?.onObservationEnd?.({
|
|
33059
|
+
usage: runResult?.usage,
|
|
33060
|
+
error: runError ?? runResult?.error,
|
|
33061
|
+
...runResult?.providerMetadata ? { providerMetadata: runResult.providerMetadata } : {}
|
|
33062
|
+
});
|
|
33063
|
+
} catch (endHookError) {
|
|
33064
|
+
if (lifecycleError === void 0) throw endHookError;
|
|
33065
|
+
omDebug(`[OM:hooks] async-buffer onObservationEnd hook failed after cycle failure: ${endHookError instanceof Error ? endHookError.message : String(endHookError)}`);
|
|
33066
|
+
}
|
|
32971
33067
|
}
|
|
32972
33068
|
}
|
|
32973
33069
|
/**
|
|
@@ -32995,18 +33091,21 @@ ${formattedMessages}
|
|
|
32995
33091
|
let observed = false;
|
|
32996
33092
|
let observationUsage;
|
|
32997
33093
|
let observationProviderMetadata;
|
|
33094
|
+
let observationError;
|
|
33095
|
+
let lifecycleError;
|
|
33096
|
+
let observationStarted = false;
|
|
32998
33097
|
let generationBefore = -1;
|
|
32999
|
-
|
|
33000
|
-
|
|
33001
|
-
|
|
33002
|
-
|
|
33003
|
-
|
|
33004
|
-
|
|
33005
|
-
|
|
33006
|
-
|
|
33007
|
-
|
|
33008
|
-
|
|
33009
|
-
|
|
33098
|
+
try {
|
|
33099
|
+
await this.withLock(lockKey, async () => {
|
|
33100
|
+
const freshRecord = await this.getOrCreateRecord(threadId, resourceId);
|
|
33101
|
+
generationBefore = freshRecord.generationCount;
|
|
33102
|
+
const unobservedMessages = messages ? this.getUnobservedMessages(messages, freshRecord) : await this.loadMessagesFromStorage(threadId, resourceId, freshRecord.lastObservedAt ? new Date(freshRecord.lastObservedAt) : void 0);
|
|
33103
|
+
if (!this.meetsObservationThreshold({
|
|
33104
|
+
record: freshRecord,
|
|
33105
|
+
unobservedTokens: await this.tokenCounter.countMessagesAsync(unobservedMessages)
|
|
33106
|
+
})) return;
|
|
33107
|
+
observationStarted = true;
|
|
33108
|
+
await hooks?.onObservationStart?.();
|
|
33010
33109
|
const result = await ObservationStrategy.create(this, {
|
|
33011
33110
|
record: freshRecord,
|
|
33012
33111
|
threadId,
|
|
@@ -33024,17 +33123,22 @@ ${formattedMessages}
|
|
|
33024
33123
|
observed = result.observed;
|
|
33025
33124
|
observationUsage = result.usage;
|
|
33026
33125
|
observationProviderMetadata = result.providerMetadata;
|
|
33027
|
-
}
|
|
33028
|
-
|
|
33029
|
-
|
|
33030
|
-
|
|
33031
|
-
|
|
33032
|
-
|
|
33033
|
-
|
|
33034
|
-
|
|
33035
|
-
|
|
33036
|
-
|
|
33037
|
-
|
|
33126
|
+
});
|
|
33127
|
+
} catch (error) {
|
|
33128
|
+
lifecycleError = error;
|
|
33129
|
+
observationError = error instanceof Error ? error : new Error(String(error));
|
|
33130
|
+
}
|
|
33131
|
+
if (observationStarted) try {
|
|
33132
|
+
await hooks?.onObservationEnd?.({
|
|
33133
|
+
usage: observationUsage,
|
|
33134
|
+
error: observationError,
|
|
33135
|
+
...observationProviderMetadata ? { providerMetadata: observationProviderMetadata } : {}
|
|
33136
|
+
});
|
|
33137
|
+
} catch (endHookError) {
|
|
33138
|
+
if (lifecycleError === void 0) throw endHookError;
|
|
33139
|
+
omDebug(`[OM:hooks] onObservationEnd hook failed after cycle failure: ${endHookError instanceof Error ? endHookError.message : String(endHookError)}`);
|
|
33140
|
+
}
|
|
33141
|
+
if (lifecycleError !== void 0) throw lifecycleError;
|
|
33038
33142
|
const record = await this.getOrCreateRecord(threadId, resourceId);
|
|
33039
33143
|
const reflected = record.generationCount > generationBefore && generationBefore >= 0;
|
|
33040
33144
|
if (observed) this.maybeTriggerCadenceCuration(threadId, resourceId, record, requestContext).catch((error) => {
|
|
@@ -33108,11 +33212,18 @@ ${formattedMessages}
|
|
|
33108
33212
|
resourceId,
|
|
33109
33213
|
trigger: "manual"
|
|
33110
33214
|
});
|
|
33111
|
-
hooks?.onReflectionStart?.();
|
|
33112
33215
|
let reflectionUsage;
|
|
33113
33216
|
let reflectionProviderMetadata;
|
|
33114
33217
|
let reflectionError;
|
|
33218
|
+
let lifecycleError;
|
|
33115
33219
|
try {
|
|
33220
|
+
try {
|
|
33221
|
+
await hooks?.onReflectionStart?.();
|
|
33222
|
+
} catch (error) {
|
|
33223
|
+
lifecycleError = error;
|
|
33224
|
+
reflectionError = error instanceof Error ? error : new Error(String(error));
|
|
33225
|
+
throw error;
|
|
33226
|
+
}
|
|
33116
33227
|
const thread = await this.storage.getThreadById({ threadId });
|
|
33117
33228
|
const previousOmMetadata = (0, _mastra_core_memory.getThreadOMMetadata)(thread?.metadata);
|
|
33118
33229
|
const priorExtractedValues = getPriorExtractedValues(previousOmMetadata, this.reflectionConfig.extractors);
|
|
@@ -33150,6 +33261,7 @@ ${formattedMessages}
|
|
|
33150
33261
|
};
|
|
33151
33262
|
} catch (error) {
|
|
33152
33263
|
reflectionError = error instanceof Error ? error : new Error(String(error));
|
|
33264
|
+
if (lifecycleError !== void 0) throw error;
|
|
33153
33265
|
omError("[OM] reflect() failed", error);
|
|
33154
33266
|
return {
|
|
33155
33267
|
reflected: false,
|
|
@@ -33157,13 +33269,25 @@ ${formattedMessages}
|
|
|
33157
33269
|
usage: void 0
|
|
33158
33270
|
};
|
|
33159
33271
|
} finally {
|
|
33160
|
-
|
|
33161
|
-
|
|
33162
|
-
|
|
33163
|
-
|
|
33164
|
-
}
|
|
33165
|
-
|
|
33166
|
-
|
|
33272
|
+
try {
|
|
33273
|
+
await this.storage.setReflectingFlag(record.id, false);
|
|
33274
|
+
} finally {
|
|
33275
|
+
unregisterOp(record.id, "reflecting");
|
|
33276
|
+
}
|
|
33277
|
+
let endHookError;
|
|
33278
|
+
try {
|
|
33279
|
+
await hooks?.onReflectionEnd?.({
|
|
33280
|
+
usage: reflectionUsage,
|
|
33281
|
+
error: reflectionError,
|
|
33282
|
+
...reflectionProviderMetadata ? { providerMetadata: reflectionProviderMetadata } : {}
|
|
33283
|
+
});
|
|
33284
|
+
} catch (error) {
|
|
33285
|
+
endHookError = error;
|
|
33286
|
+
}
|
|
33287
|
+
if (endHookError !== void 0) {
|
|
33288
|
+
if (lifecycleError === void 0) throw endHookError;
|
|
33289
|
+
omDebug(`[OM:hooks] onReflectionEnd hook failed after cycle failure: ${endHookError instanceof Error ? endHookError.message : String(endHookError)}`);
|
|
33290
|
+
}
|
|
33167
33291
|
}
|
|
33168
33292
|
}
|
|
33169
33293
|
/**
|
|
@@ -33455,7 +33579,9 @@ var ObservationalMemoryProcessor = class {
|
|
|
33455
33579
|
return messageList;
|
|
33456
33580
|
}
|
|
33457
33581
|
const { threadId, resourceId } = context;
|
|
33458
|
-
const
|
|
33582
|
+
const memoryContext = (0, _mastra_core_memory.parseMemoryRequestContext)(requestContext);
|
|
33583
|
+
const runState = memoryContext?.runState?.();
|
|
33584
|
+
const readOnly = memoryContext?.memoryConfig?.readOnly;
|
|
33459
33585
|
const actorModelContext = model?.modelId ? {
|
|
33460
33586
|
provider: model.provider,
|
|
33461
33587
|
modelId: model.modelId,
|
|
@@ -33472,7 +33598,8 @@ var ObservationalMemoryProcessor = class {
|
|
|
33472
33598
|
memory: this.memory,
|
|
33473
33599
|
messageList,
|
|
33474
33600
|
threadId,
|
|
33475
|
-
resourceId
|
|
33601
|
+
resourceId,
|
|
33602
|
+
runState
|
|
33476
33603
|
});
|
|
33477
33604
|
const systemMessages = ctx.omRecord ? await this.engine.buildContextSystemMessages({
|
|
33478
33605
|
threadId,
|
|
@@ -33513,7 +33640,7 @@ var ObservationalMemoryProcessor = class {
|
|
|
33513
33640
|
this.turn.sendStateSignal = args.sendStateSignal;
|
|
33514
33641
|
this.turn.agent = args.agent;
|
|
33515
33642
|
this.turn.requestContext = requestContext;
|
|
33516
|
-
await this.turn.start(this.memory);
|
|
33643
|
+
await this.turn.start(this.memory, runState);
|
|
33517
33644
|
if (stepNumber === 0 && this.temporalMarkers) await insertTemporalGapMarkers({
|
|
33518
33645
|
messageList,
|
|
33519
33646
|
sendSignal: args.sendSignal
|
|
@@ -34660,14 +34787,18 @@ ${workingMemory}`;
|
|
|
34660
34787
|
if (!this.threadConfig.workingMemory?.enabled) return null;
|
|
34661
34788
|
return extractWorkingMemoryContent(text)?.trim() ?? null;
|
|
34662
34789
|
}
|
|
34663
|
-
async getWorkingMemory({ threadId, resourceId, memoryConfig }) {
|
|
34790
|
+
async getWorkingMemory({ threadId, resourceId, memoryConfig, runState }) {
|
|
34664
34791
|
const config = this.getMergedThreadConfig(memoryConfig || {});
|
|
34665
34792
|
if (!config.workingMemory?.enabled) return null;
|
|
34666
34793
|
const scope = config.workingMemory.scope || "resource";
|
|
34667
34794
|
let workingMemoryData = null;
|
|
34668
34795
|
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'.");
|
|
34669
|
-
if (scope === "resource" && resourceId)
|
|
34670
|
-
|
|
34796
|
+
if (scope === "resource" && resourceId) {
|
|
34797
|
+
const loadWorkingMemory = async () => {
|
|
34798
|
+
return (await (await this.getMemoryStore()).getResourceById({ resourceId }))?.workingMemory || null;
|
|
34799
|
+
};
|
|
34800
|
+
workingMemoryData = runState ? await runState.load(`working-memory:resource:${resourceId}`, loadWorkingMemory) : await loadWorkingMemory();
|
|
34801
|
+
} else workingMemoryData = (runState?.threadLoaded ? runState.thread : await this.getThreadById({ threadId }))?.metadata?.workingMemory;
|
|
34671
34802
|
if (!workingMemoryData) return null;
|
|
34672
34803
|
return workingMemoryData;
|
|
34673
34804
|
}
|
|
@@ -34699,16 +34830,18 @@ ${workingMemory}`;
|
|
|
34699
34830
|
content: (config.workingMemory.template || this.defaultWorkingMemoryTemplate).trim()
|
|
34700
34831
|
};
|
|
34701
34832
|
}
|
|
34702
|
-
async getSystemMessage({ threadId, resourceId, memoryConfig }) {
|
|
34833
|
+
async getSystemMessage({ threadId, resourceId, memoryConfig, runState }) {
|
|
34703
34834
|
const config = this.getMergedThreadConfig(memoryConfig);
|
|
34704
34835
|
this.assertWorkingMemoryStateSignalsCompatibility(config);
|
|
34705
34836
|
if (!config.workingMemory?.enabled) return null;
|
|
34706
34837
|
if (config.workingMemory?.useStateSignals) return null;
|
|
34707
|
-
const
|
|
34838
|
+
const loadTemplate = () => this.getWorkingMemoryTemplate({ memoryConfig });
|
|
34839
|
+
const workingMemoryTemplate = runState ? await runState.load("working-memory:template", loadTemplate) : await loadTemplate();
|
|
34708
34840
|
const workingMemoryData = await this.getWorkingMemory({
|
|
34709
34841
|
threadId,
|
|
34710
34842
|
resourceId,
|
|
34711
|
-
memoryConfig: config
|
|
34843
|
+
memoryConfig: config,
|
|
34844
|
+
runState
|
|
34712
34845
|
});
|
|
34713
34846
|
if (!workingMemoryTemplate) return null;
|
|
34714
34847
|
const workingMemoryConfig = config.workingMemory;
|
|
@@ -34741,7 +34874,7 @@ ${workingMemory}`;
|
|
|
34741
34874
|
* ```
|
|
34742
34875
|
*/
|
|
34743
34876
|
async getContext(opts) {
|
|
34744
|
-
const { threadId, resourceId, memoryConfig } = opts;
|
|
34877
|
+
const { threadId, resourceId, memoryConfig, runState } = opts;
|
|
34745
34878
|
const config = this.getMergedThreadConfig(memoryConfig);
|
|
34746
34879
|
const memoryStore = await this.getMemoryStore();
|
|
34747
34880
|
const systemParts = [];
|
|
@@ -34751,10 +34884,14 @@ ${workingMemory}`;
|
|
|
34751
34884
|
let otherThreadsContext;
|
|
34752
34885
|
const omEngine = await this.omEngine;
|
|
34753
34886
|
if (omEngine) {
|
|
34754
|
-
|
|
34887
|
+
const loadOmRecord = () => omEngine.getRecord(threadId, resourceId);
|
|
34888
|
+
omRecord = runState ? await runState.load(`observational-memory:record:${threadId}:${resourceId ?? ""}`, loadOmRecord) : await loadOmRecord();
|
|
34755
34889
|
if (omRecord?.activeObservations) {
|
|
34756
34890
|
hasObservations = true;
|
|
34757
|
-
if (omEngine.scope === "resource" && resourceId)
|
|
34891
|
+
if (omEngine.scope === "resource" && resourceId) {
|
|
34892
|
+
const loadOtherThreadsContext = () => omEngine.getOtherThreadsContext(resourceId, threadId);
|
|
34893
|
+
otherThreadsContext = runState ? await runState.load(`observational-memory:other-threads:${resourceId}:${threadId}:${omRecord.lastObservedAt ?? ""}`, loadOtherThreadsContext) : await loadOtherThreadsContext();
|
|
34894
|
+
}
|
|
34758
34895
|
const obsSystemMessage = await omEngine.buildContextSystemMessage({
|
|
34759
34896
|
threadId,
|
|
34760
34897
|
resourceId,
|
|
@@ -34782,30 +34919,41 @@ ${workingMemory}`;
|
|
|
34782
34919
|
const workingMemoryMessage = await this.getSystemMessage({
|
|
34783
34920
|
threadId,
|
|
34784
34921
|
resourceId,
|
|
34785
|
-
memoryConfig: config
|
|
34922
|
+
memoryConfig: config,
|
|
34923
|
+
runState
|
|
34786
34924
|
});
|
|
34787
34925
|
if (workingMemoryMessage) systemParts.push(workingMemoryMessage);
|
|
34788
34926
|
let messages;
|
|
34789
34927
|
if (omEngine && omRecord) {
|
|
34790
34928
|
const dateFilter = omRecord.lastObservedAt ? { dateRange: { start: new Date(new Date(omRecord.lastObservedAt).getTime() + 1) } } : void 0;
|
|
34791
|
-
|
|
34792
|
-
|
|
34793
|
-
|
|
34794
|
-
|
|
34795
|
-
|
|
34796
|
-
|
|
34797
|
-
|
|
34798
|
-
|
|
34799
|
-
|
|
34800
|
-
|
|
34801
|
-
|
|
34802
|
-
|
|
34803
|
-
|
|
34804
|
-
|
|
34805
|
-
|
|
34806
|
-
|
|
34807
|
-
|
|
34808
|
-
|
|
34929
|
+
const boundary = omRecord.lastObservedAt ? new Date(omRecord.lastObservedAt).toISOString() : "";
|
|
34930
|
+
if (omEngine.scope === "resource" && resourceId) {
|
|
34931
|
+
const loadMessages = async () => {
|
|
34932
|
+
return (await memoryStore.listMessagesByResourceId({
|
|
34933
|
+
resourceId,
|
|
34934
|
+
orderBy: {
|
|
34935
|
+
field: "createdAt",
|
|
34936
|
+
direction: "ASC"
|
|
34937
|
+
},
|
|
34938
|
+
perPage: false,
|
|
34939
|
+
filter: dateFilter
|
|
34940
|
+
})).messages;
|
|
34941
|
+
};
|
|
34942
|
+
messages = runState ? await runState.load(`observational-memory:messages:resource:${resourceId}:${boundary}`, loadMessages) : await loadMessages();
|
|
34943
|
+
} else {
|
|
34944
|
+
const loadMessages = async () => {
|
|
34945
|
+
return (await memoryStore.listMessages({
|
|
34946
|
+
threadId,
|
|
34947
|
+
orderBy: {
|
|
34948
|
+
field: "createdAt",
|
|
34949
|
+
direction: "ASC"
|
|
34950
|
+
},
|
|
34951
|
+
perPage: false,
|
|
34952
|
+
filter: dateFilter
|
|
34953
|
+
})).messages;
|
|
34954
|
+
};
|
|
34955
|
+
messages = runState ? await runState.load(`observational-memory:messages:thread:${threadId}:${boundary}`, loadMessages) : await loadMessages();
|
|
34956
|
+
}
|
|
34809
34957
|
} else {
|
|
34810
34958
|
const lastMessages = config.lastMessages;
|
|
34811
34959
|
if (lastMessages === false) messages = [];
|
|
@@ -34893,6 +35041,7 @@ ${workingMemory}`;
|
|
|
34893
35041
|
instruction: omConfig.observation.instruction,
|
|
34894
35042
|
threadTitle: omConfig.observation.threadTitle,
|
|
34895
35043
|
observeAttachments: omConfig.observation.observeAttachments,
|
|
35044
|
+
continuationHints: omConfig.observation.continuationHints,
|
|
34896
35045
|
extract: omConfig.observation.extract
|
|
34897
35046
|
} : void 0,
|
|
34898
35047
|
reflection: omConfig.reflection ? {
|
|
@@ -34903,6 +35052,7 @@ ${workingMemory}`;
|
|
|
34903
35052
|
bufferActivation: omConfig.reflection.bufferActivation,
|
|
34904
35053
|
blockAfter: omConfig.reflection.blockAfter,
|
|
34905
35054
|
instruction: omConfig.reflection.instruction,
|
|
35055
|
+
continuationHints: omConfig.reflection.continuationHints,
|
|
34906
35056
|
extract: omConfig.reflection.extract
|
|
34907
35057
|
} : void 0
|
|
34908
35058
|
});
|
|
@@ -41073,6 +41223,7 @@ async function cancelResponseBody(response) {
|
|
|
41073
41223
|
var initialGlobalFetch = globalThis.fetch;
|
|
41074
41224
|
isNodeDefaultFetch(initialGlobalFetch);
|
|
41075
41225
|
function isNodeDefaultFetch(fetch) {
|
|
41226
|
+
if (typeof fetch !== "function") return false;
|
|
41076
41227
|
const source = Function.prototype.toString.call(fetch);
|
|
41077
41228
|
return source.includes("internal/deps/undici") || source.includes("lazy loading of undici");
|
|
41078
41229
|
}
|
|
@@ -46199,4 +46350,4 @@ const agentBuilderWorkflows = {
|
|
|
46199
46350
|
//#endregion
|
|
46200
46351
|
exports.agentBuilderWorkflows = agentBuilderWorkflows;
|
|
46201
46352
|
|
|
46202
|
-
//# sourceMappingURL=dist-
|
|
46353
|
+
//# sourceMappingURL=dist-Czh_Btxb.cjs.map
|