@mastra/memory 1.32.0 → 1.32.1-alpha.0

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.
@@ -23157,7 +23157,288 @@ async function summarizeConversation(opts) {
23157
23157
  };
23158
23158
  }
23159
23159
  //#endregion
23160
+ //#region src/tools/working-memory.ts
23161
+ const UPDATE_WORKING_MEMORY_TOOL_NAME = "updateWorkingMemory";
23162
+ const SET_WORKING_MEMORY_TOOL_NAME = "setWorkingMemory";
23163
+ /**
23164
+ * Deep merges two objects, with special handling for null values (delete) and arrays (replace).
23165
+ * - Object properties are recursively merged
23166
+ * - null values in the update will delete the corresponding property, even when the property
23167
+ * or its parent object does not exist yet (so padded nulls never get stored literally)
23168
+ * - Arrays are replaced entirely (not merged element-by-element)
23169
+ * - Primitive values are overwritten
23170
+ * - The returned object is always newly constructed and never aliases `update`
23171
+ */
23172
+ function deepMergeWorkingMemory(existing, update) {
23173
+ if (!update || typeof update !== "object" || Object.keys(update).length === 0) return existing && typeof existing === "object" ? { ...existing } : {};
23174
+ const result = { ...existing && typeof existing === "object" && !Array.isArray(existing) ? existing : {} };
23175
+ for (const key of Object.keys(update)) {
23176
+ const updateValue = update[key];
23177
+ const existingValue = result[key];
23178
+ if (updateValue === void 0) continue;
23179
+ if (updateValue === null) delete result[key];
23180
+ else if (Array.isArray(updateValue)) result[key] = updateValue;
23181
+ else if (typeof updateValue === "object") result[key] = deepMergeWorkingMemory(existingValue && typeof existingValue === "object" && !Array.isArray(existingValue) ? existingValue : void 0, updateValue);
23182
+ else result[key] = updateValue;
23183
+ }
23184
+ return result;
23185
+ }
23186
+ /** `.nullable()` wraps a schema as `anyOf: [schema, { type: 'null' }]`; unwrap it so its declared fields are visible. */
23187
+ function resolveNullableBranch(value, schema) {
23188
+ const branches = schema.anyOf ?? schema.oneOf;
23189
+ if (!Array.isArray(branches)) return schema;
23190
+ const kind = Array.isArray(value) ? "array" : "object";
23191
+ const matching = branches.filter((branch) => branch.type === kind);
23192
+ return matching.length === 1 ? matching[0] : schema;
23193
+ }
23194
+ function stripNullsFromOptional(value, rawSchema) {
23195
+ const schema = resolveNullableBranch(value, rawSchema);
23196
+ if (Array.isArray(value)) {
23197
+ const itemSchema = schema.items ?? {};
23198
+ return value.map((item) => stripNullsFromOptional(item, itemSchema));
23199
+ }
23200
+ if (typeof value === "object" && value !== null) {
23201
+ const properties = schema.properties ?? {};
23202
+ const required = schema.required ?? [];
23203
+ const result = {};
23204
+ for (const [key, propertyValue] of Object.entries(value)) {
23205
+ if (propertyValue === null && Object.hasOwn(properties, key) && !required.includes(key)) continue;
23206
+ result[key] = stripNullsFromOptional(propertyValue, properties[key] ?? {});
23207
+ }
23208
+ return result;
23209
+ }
23210
+ return value;
23211
+ }
23212
+ const updateWorkingMemoryTool = (memoryConfig) => {
23213
+ const schema = memoryConfig?.workingMemory?.schema;
23214
+ let inputSchema = {
23215
+ $schema: "http://json-schema.org/draft-07/schema#",
23216
+ type: "object",
23217
+ properties: { memory: {
23218
+ type: "string",
23219
+ description: `The Markdown formatted working memory content to store. This MUST be a string. Never pass an object.`
23220
+ } },
23221
+ required: ["memory"]
23222
+ };
23223
+ if (schema) {
23224
+ const standardSchema = isStandardSchemaWithJSON$1(schema) ? schema : toStandardSchema$1(schema);
23225
+ const jsonSchema = standardSchemaToJSONSchema(standardSchema, { io: "input" });
23226
+ delete jsonSchema.$schema;
23227
+ const wrappedJsonSchema = {
23228
+ $schema: "http://json-schema.org/draft-07/schema#",
23229
+ type: "object",
23230
+ description: "The JSON formatted working memory content to store.",
23231
+ properties: { memory: jsonSchema },
23232
+ required: ["memory"]
23233
+ };
23234
+ const validateMemory = (memoryValue) => standardSchema["~standard"].validate(memoryValue);
23235
+ const toWrappedResult = (result) => "issues" in result && result.issues ? result : { value: { memory: result.value } };
23236
+ inputSchema = { "~standard": {
23237
+ version: 1,
23238
+ vendor: "mastra",
23239
+ validate: (value) => {
23240
+ const memoryValue = stripNullsFromOptional(!!value && typeof value === "object" && !Array.isArray(value) && "memory" in value ? value.memory : value, jsonSchema);
23241
+ const result = validateMemory(memoryValue);
23242
+ return result instanceof Promise ? result.then(toWrappedResult) : toWrappedResult(result);
23243
+ },
23244
+ jsonSchema: {
23245
+ input: () => wrappedJsonSchema,
23246
+ output: () => wrappedJsonSchema
23247
+ }
23248
+ } };
23249
+ }
23250
+ const usesMergeSemantics = Boolean(schema);
23251
+ const useStateSignals = memoryConfig?.workingMemory?.useStateSignals === true;
23252
+ const stateSignalsPreamble = `The current working memory state is delivered to you each turn by the system inside a <working-memory>...</working-memory> block. That block is system-emitted state, NOT something the user typed — never describe it as the user sharing it. Read from it directly when answering. Only call this tool when the user provides genuinely NEW or CHANGED facts that should be persisted; do NOT call it to re-save unchanged data.`;
23253
+ return createTool({
23254
+ id: "update-working-memory",
23255
+ description: schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory — only include fields you want to add or update.` : `Update the working memory with new information. Data is merged with existing memory - only include fields you want to add or update. To preserve existing data, omit the field entirely. Arrays are replaced entirely when provided, so pass the complete array or omit it to keep the existing values.` : useStateSignals ? `${stateSignalsPreamble} Pass the full updated Markdown blob as a string in the memory field.` : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`,
23256
+ inputSchema,
23257
+ ...usesMergeSemantics ? { strict: false } : {},
23258
+ execute: async (inputData, context) => {
23259
+ const workingMemoryInput = inputData;
23260
+ const threadId = context?.agent?.threadId;
23261
+ const resourceId = context?.agent?.resourceId;
23262
+ const memory = context?.memory;
23263
+ if (!memory) throw new Error("Memory instance is required for working memory updates");
23264
+ const scope = memoryConfig?.workingMemory?.scope || "resource";
23265
+ if (scope === "thread" && !threadId) throw new Error("Thread ID is required for thread-scoped working memory updates");
23266
+ if (scope === "resource" && !resourceId) throw new Error("Resource ID is required for resource-scoped working memory updates");
23267
+ if (threadId) {
23268
+ let thread = await memory.getThreadById({ threadId });
23269
+ if (!thread) thread = await memory.createThread({
23270
+ threadId,
23271
+ resourceId,
23272
+ memoryConfig
23273
+ });
23274
+ if (thread.resourceId && resourceId && thread.resourceId !== resourceId) throw new Error(`Thread with id ${threadId} resourceId does not match the current resourceId ${resourceId}`);
23275
+ }
23276
+ let workingMemory;
23277
+ if (usesMergeSemantics) {
23278
+ const existingRaw = await memory.getWorkingMemory({
23279
+ threadId,
23280
+ resourceId,
23281
+ memoryConfig
23282
+ });
23283
+ let existingData = null;
23284
+ if (existingRaw) try {
23285
+ existingData = typeof existingRaw === "string" ? JSON.parse(existingRaw) : existingRaw;
23286
+ } catch {
23287
+ existingData = null;
23288
+ }
23289
+ const memoryInput = workingMemoryInput.memory;
23290
+ if (memoryInput === void 0 || memoryInput === null) return {
23291
+ success: true,
23292
+ message: "No memory data provided, existing memory unchanged."
23293
+ };
23294
+ let newData;
23295
+ if (typeof memoryInput === "string") try {
23296
+ newData = JSON.parse(memoryInput);
23297
+ } catch (parseError) {
23298
+ const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);
23299
+ throw new Error(`Failed to parse working memory input as JSON: ${errorMessage}. Raw input: ${memoryInput.length > 500 ? memoryInput.slice(0, 500) + "..." : memoryInput}`);
23300
+ }
23301
+ else newData = memoryInput;
23302
+ const mergedData = deepMergeWorkingMemory(existingData, newData);
23303
+ workingMemory = JSON.stringify(mergedData);
23304
+ } else {
23305
+ const memoryInput = workingMemoryInput.memory;
23306
+ workingMemory = typeof memoryInput === "string" ? memoryInput : JSON.stringify(memoryInput);
23307
+ const existingRaw = await memory.getWorkingMemory({
23308
+ threadId,
23309
+ resourceId,
23310
+ memoryConfig
23311
+ });
23312
+ if (existingRaw) {
23313
+ const template = await memory.getWorkingMemoryTemplate({ memoryConfig });
23314
+ if (template?.content) {
23315
+ const normalizedNew = workingMemory.replace(/\s+/g, " ").trim();
23316
+ const normalizedTemplate = template.content.replace(/\s+/g, " ").trim();
23317
+ const normalizedExisting = existingRaw.replace(/\s+/g, " ").trim();
23318
+ if (normalizedNew === normalizedTemplate && normalizedExisting !== normalizedTemplate) return {
23319
+ success: false,
23320
+ message: "Attempted to replace existing working memory with empty template. Update skipped to prevent data loss."
23321
+ };
23322
+ }
23323
+ }
23324
+ }
23325
+ await memory.updateWorkingMemory({
23326
+ threadId,
23327
+ resourceId,
23328
+ workingMemory,
23329
+ memoryConfig
23330
+ });
23331
+ return { success: true };
23332
+ }
23333
+ });
23334
+ };
23335
+ const __experimental_updateWorkingMemoryToolVNext = (config) => {
23336
+ return createTool({
23337
+ id: "update-working-memory",
23338
+ description: "Update the working memory with new information.",
23339
+ inputSchema: {
23340
+ $schema: "http://json-schema.org/draft-07/schema#",
23341
+ type: "object",
23342
+ properties: {
23343
+ newMemory: {
23344
+ type: "string",
23345
+ description: `The ${config.workingMemory?.schema ? "JSON" : "Markdown"} formatted working memory content to store`
23346
+ },
23347
+ searchString: {
23348
+ type: "string",
23349
+ description: "The working memory string to find. Will be replaced with the newMemory string. If this is omitted or doesn't exist, the newMemory string will be appended to the end of your working memory. Replacing single lines at a time is encouraged for greater accuracy. If updateReason is not 'append-new-memory', this search string must be provided or the tool call will be rejected."
23350
+ },
23351
+ updateReason: {
23352
+ type: "string",
23353
+ enum: [
23354
+ "append-new-memory",
23355
+ "clarify-existing-memory",
23356
+ "replace-irrelevant-memory"
23357
+ ],
23358
+ description: "The reason you're updating working memory. Passing any value other than 'append-new-memory' requires a searchString to be provided. Defaults to append-new-memory"
23359
+ }
23360
+ }
23361
+ },
23362
+ execute: async (inputData, context) => {
23363
+ const workingMemoryInput = inputData;
23364
+ const threadId = context?.agent?.threadId;
23365
+ const resourceId = context?.agent?.resourceId;
23366
+ const memory = context?.memory;
23367
+ if (!memory) throw new Error("Memory instance is required for working memory updates");
23368
+ const scope = config.workingMemory?.scope || "resource";
23369
+ if (scope === "thread" && !threadId) throw new Error("Thread ID is required for thread-scoped working memory updates");
23370
+ if (scope === "resource" && !resourceId) throw new Error("Resource ID is required for resource-scoped working memory updates");
23371
+ if (threadId) {
23372
+ let thread = await memory.getThreadById({ threadId });
23373
+ if (!thread) thread = await memory.createThread({
23374
+ threadId,
23375
+ resourceId,
23376
+ memoryConfig: config
23377
+ });
23378
+ if (thread.resourceId && resourceId && thread.resourceId !== resourceId) throw new Error(`Thread with id ${threadId} resourceId does not match the current resourceId ${resourceId}`);
23379
+ }
23380
+ const workingMemory = workingMemoryInput.newMemory || "";
23381
+ if (!workingMemoryInput.updateReason) workingMemoryInput.updateReason = `append-new-memory`;
23382
+ if (workingMemoryInput.searchString && config.workingMemory?.scope === `resource` && workingMemoryInput.updateReason === `replace-irrelevant-memory`) workingMemoryInput.searchString = void 0;
23383
+ if (workingMemoryInput.updateReason === `append-new-memory` && workingMemoryInput.searchString) workingMemoryInput.searchString = void 0;
23384
+ if (workingMemoryInput.updateReason !== `append-new-memory` && !workingMemoryInput.searchString) return {
23385
+ success: false,
23386
+ reason: `updateReason was ${workingMemoryInput.updateReason} but no searchString was provided. Unable to replace undefined with "${workingMemoryInput.newMemory}"`
23387
+ };
23388
+ const result = await memory.__experimental_updateWorkingMemoryVNext({
23389
+ threadId,
23390
+ resourceId,
23391
+ workingMemory,
23392
+ searchString: workingMemoryInput.searchString,
23393
+ memoryConfig: config
23394
+ });
23395
+ if (result) return result;
23396
+ return { success: true };
23397
+ }
23398
+ });
23399
+ };
23400
+ /**
23401
+ * Returns the working-memory tool plus the wire name it should be registered under.
23402
+ *
23403
+ * - Default delivery (`useStateSignals: false`): wire name `updateWorkingMemory`,
23404
+ * identical shape to today.
23405
+ * - State-signals delivery (`useStateSignals: true`): wire name `setWorkingMemory`.
23406
+ * The rename keeps legacy strip filters (which match the literal `updateWorkingMemory`)
23407
+ * from removing tool-call parts so they persist as a normal audit trail. Any
23408
+ * future state-signal-specific tweaks to the tool (e.g. delta-aware results,
23409
+ * scoped descriptions) belong here.
23410
+ *
23411
+ * The VNext vs default tool body decision is left to the caller because Memory
23412
+ * owns the `isVNextWorkingMemoryConfig` check; pass `vNext: true` to use the
23413
+ * search-and-replace shape.
23414
+ */
23415
+ function createWorkingMemoryTool(config, options = {}) {
23416
+ const useStateSignals = config.workingMemory?.useStateSignals === true;
23417
+ const tool = options.vNext ? __experimental_updateWorkingMemoryToolVNext(config) : updateWorkingMemoryTool(config);
23418
+ return {
23419
+ name: useStateSignals ? SET_WORKING_MEMORY_TOOL_NAME : UPDATE_WORKING_MEMORY_TOOL_NAME,
23420
+ tool
23421
+ };
23422
+ }
23423
+ //#endregion
23160
23424
  //#region src/processors/observational-memory/working-memory-extractor.ts
23425
+ /**
23426
+ * The structured-output schema for this extractor stays generic because every structured extractor shares one
23427
+ * response object: a strict working-memory schema there would make one invalid document fail every sibling
23428
+ * extractor. The configured schema is enforced here instead, with its own validator, before anything is stored.
23429
+ * Like the working memory tool, nulls in optional fields are treated as "not provided" rather than as invalid.
23430
+ */
23431
+ async function validateAgainstConfiguredSchema(schema, value) {
23432
+ const standardSchema = toStandardSchema$1(schema);
23433
+ const jsonSchema = standardSchemaToJSONSchema(standardSchema, { io: "input" });
23434
+ const result = await standardSchema["~standard"].validate(stripNullsFromOptional(value, jsonSchema));
23435
+ if (!result.issues) return result.value;
23436
+ const details = result.issues.map((issue) => {
23437
+ const path = issue.path?.map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".");
23438
+ return path ? `${path}: ${issue.message}` : issue.message;
23439
+ }).join("; ");
23440
+ throw new Error(`Working memory update does not match the configured schema, so it was not saved: ${details}`);
23441
+ }
23161
23442
  async function getWorkingMemoryDetails(context) {
23162
23443
  const memory = context.memory;
23163
23444
  const memoryConfig = parseMemoryRequestContext(context.requestContext)?.memoryConfig;
@@ -23202,9 +23483,13 @@ var WorkingMemoryExtractor = class extends Extractor {
23202
23483
  },
23203
23484
  onExtracted: async ({ current, memory, threadId, resourceId, requestContext }) => {
23204
23485
  const memoryConfig = parseMemoryRequestContext(requestContext)?.memoryConfig;
23205
- const config = memory.getMergedThreadConfig(memoryConfig ?? {});
23206
- if (Boolean(config.workingMemory?.schema) && current === null) return;
23207
- const workingMemory = typeof current === "string" ? current : JSON.stringify(current) ?? "";
23486
+ const configuredSchema = memory.getMergedThreadConfig(memoryConfig ?? {}).workingMemory?.schema;
23487
+ let document = current;
23488
+ if (configuredSchema) {
23489
+ if (current === null) return;
23490
+ document = await validateAgainstConfiguredSchema(configuredSchema, current);
23491
+ }
23492
+ const workingMemory = typeof document === "string" ? document : JSON.stringify(document) ?? "";
23208
23493
  if (!workingMemory.trim()) return;
23209
23494
  await memory.updateWorkingMemory({
23210
23495
  threadId,
@@ -23212,7 +23497,7 @@ var WorkingMemoryExtractor = class extends Extractor {
23212
23497
  workingMemory,
23213
23498
  memoryConfig
23214
23499
  });
23215
- return current;
23500
+ return document;
23216
23501
  }
23217
23502
  });
23218
23503
  }
@@ -24163,261 +24448,6 @@ const recallTool = (_memoryConfig, options) => {
24163
24448
  });
24164
24449
  };
24165
24450
  //#endregion
24166
- //#region src/tools/working-memory.ts
24167
- const UPDATE_WORKING_MEMORY_TOOL_NAME = "updateWorkingMemory";
24168
- const SET_WORKING_MEMORY_TOOL_NAME = "setWorkingMemory";
24169
- /**
24170
- * Deep merges two objects, with special handling for null values (delete) and arrays (replace).
24171
- * - Object properties are recursively merged
24172
- * - null values in the update will delete the corresponding property, even when the property
24173
- * or its parent object does not exist yet (so padded nulls never get stored literally)
24174
- * - Arrays are replaced entirely (not merged element-by-element)
24175
- * - Primitive values are overwritten
24176
- * - The returned object is always newly constructed and never aliases `update`
24177
- */
24178
- function deepMergeWorkingMemory(existing, update) {
24179
- if (!update || typeof update !== "object" || Object.keys(update).length === 0) return existing && typeof existing === "object" ? { ...existing } : {};
24180
- const result = { ...existing && typeof existing === "object" && !Array.isArray(existing) ? existing : {} };
24181
- for (const key of Object.keys(update)) {
24182
- const updateValue = update[key];
24183
- const existingValue = result[key];
24184
- if (updateValue === void 0) continue;
24185
- if (updateValue === null) delete result[key];
24186
- else if (Array.isArray(updateValue)) result[key] = updateValue;
24187
- else if (typeof updateValue === "object") result[key] = deepMergeWorkingMemory(existingValue && typeof existingValue === "object" && !Array.isArray(existingValue) ? existingValue : void 0, updateValue);
24188
- else result[key] = updateValue;
24189
- }
24190
- return result;
24191
- }
24192
- function stripNullsFromOptional(value, schema) {
24193
- if (Array.isArray(value)) {
24194
- const itemSchema = schema.items ?? {};
24195
- return value.map((item) => stripNullsFromOptional(item, itemSchema));
24196
- }
24197
- if (typeof value === "object" && value !== null) {
24198
- const properties = schema.properties ?? {};
24199
- const required = schema.required ?? [];
24200
- const result = {};
24201
- for (const [key, propertyValue] of Object.entries(value)) {
24202
- if (propertyValue === null && !required.includes(key)) continue;
24203
- result[key] = stripNullsFromOptional(propertyValue, properties[key] ?? {});
24204
- }
24205
- return result;
24206
- }
24207
- return value;
24208
- }
24209
- const updateWorkingMemoryTool = (memoryConfig) => {
24210
- const schema = memoryConfig?.workingMemory?.schema;
24211
- let inputSchema = {
24212
- $schema: "http://json-schema.org/draft-07/schema#",
24213
- type: "object",
24214
- properties: { memory: {
24215
- type: "string",
24216
- description: `The Markdown formatted working memory content to store. This MUST be a string. Never pass an object.`
24217
- } },
24218
- required: ["memory"]
24219
- };
24220
- if (schema) {
24221
- const standardSchema = isStandardSchemaWithJSON$1(schema) ? schema : toStandardSchema$1(schema);
24222
- const jsonSchema = standardSchemaToJSONSchema(standardSchema, { io: "input" });
24223
- delete jsonSchema.$schema;
24224
- const wrappedJsonSchema = {
24225
- $schema: "http://json-schema.org/draft-07/schema#",
24226
- type: "object",
24227
- description: "The JSON formatted working memory content to store.",
24228
- properties: { memory: jsonSchema },
24229
- required: ["memory"]
24230
- };
24231
- const validateMemory = (memoryValue) => standardSchema["~standard"].validate(memoryValue);
24232
- const toWrappedResult = (result) => "issues" in result && result.issues ? result : { value: { memory: result.value } };
24233
- inputSchema = { "~standard": {
24234
- version: 1,
24235
- vendor: "mastra",
24236
- validate: (value) => {
24237
- const memoryValue = stripNullsFromOptional(!!value && typeof value === "object" && !Array.isArray(value) && "memory" in value ? value.memory : value, jsonSchema);
24238
- const result = validateMemory(memoryValue);
24239
- return result instanceof Promise ? result.then(toWrappedResult) : toWrappedResult(result);
24240
- },
24241
- jsonSchema: {
24242
- input: () => wrappedJsonSchema,
24243
- output: () => wrappedJsonSchema
24244
- }
24245
- } };
24246
- }
24247
- const usesMergeSemantics = Boolean(schema);
24248
- const useStateSignals = memoryConfig?.workingMemory?.useStateSignals === true;
24249
- const stateSignalsPreamble = `The current working memory state is delivered to you each turn by the system inside a <working-memory>...</working-memory> block. That block is system-emitted state, NOT something the user typed — never describe it as the user sharing it. Read from it directly when answering. Only call this tool when the user provides genuinely NEW or CHANGED facts that should be persisted; do NOT call it to re-save unchanged data.`;
24250
- return createTool({
24251
- id: "update-working-memory",
24252
- description: schema ? useStateSignals ? `${stateSignalsPreamble} Data is merged with existing memory — only include fields you want to add or update.` : `Update the working memory with new information. Data is merged with existing memory - only include fields you want to add or update. To preserve existing data, omit the field entirely. Arrays are replaced entirely when provided, so pass the complete array or omit it to keep the existing values.` : useStateSignals ? `${stateSignalsPreamble} Pass the full updated Markdown blob as a string in the memory field.` : `Update the working memory with new information. Any data not included will be overwritten. Always pass data as string to the memory field. Never pass an object.`,
24253
- inputSchema,
24254
- ...usesMergeSemantics ? { strict: false } : {},
24255
- execute: async (inputData, context) => {
24256
- const workingMemoryInput = inputData;
24257
- const threadId = context?.agent?.threadId;
24258
- const resourceId = context?.agent?.resourceId;
24259
- const memory = context?.memory;
24260
- if (!memory) throw new Error("Memory instance is required for working memory updates");
24261
- const scope = memoryConfig?.workingMemory?.scope || "resource";
24262
- if (scope === "thread" && !threadId) throw new Error("Thread ID is required for thread-scoped working memory updates");
24263
- if (scope === "resource" && !resourceId) throw new Error("Resource ID is required for resource-scoped working memory updates");
24264
- if (threadId) {
24265
- let thread = await memory.getThreadById({ threadId });
24266
- if (!thread) thread = await memory.createThread({
24267
- threadId,
24268
- resourceId,
24269
- memoryConfig
24270
- });
24271
- if (thread.resourceId && resourceId && thread.resourceId !== resourceId) throw new Error(`Thread with id ${threadId} resourceId does not match the current resourceId ${resourceId}`);
24272
- }
24273
- let workingMemory;
24274
- if (usesMergeSemantics) {
24275
- const existingRaw = await memory.getWorkingMemory({
24276
- threadId,
24277
- resourceId,
24278
- memoryConfig
24279
- });
24280
- let existingData = null;
24281
- if (existingRaw) try {
24282
- existingData = typeof existingRaw === "string" ? JSON.parse(existingRaw) : existingRaw;
24283
- } catch {
24284
- existingData = null;
24285
- }
24286
- const memoryInput = workingMemoryInput.memory;
24287
- if (memoryInput === void 0 || memoryInput === null) return {
24288
- success: true,
24289
- message: "No memory data provided, existing memory unchanged."
24290
- };
24291
- let newData;
24292
- if (typeof memoryInput === "string") try {
24293
- newData = JSON.parse(memoryInput);
24294
- } catch (parseError) {
24295
- const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);
24296
- throw new Error(`Failed to parse working memory input as JSON: ${errorMessage}. Raw input: ${memoryInput.length > 500 ? memoryInput.slice(0, 500) + "..." : memoryInput}`);
24297
- }
24298
- else newData = memoryInput;
24299
- const mergedData = deepMergeWorkingMemory(existingData, newData);
24300
- workingMemory = JSON.stringify(mergedData);
24301
- } else {
24302
- const memoryInput = workingMemoryInput.memory;
24303
- workingMemory = typeof memoryInput === "string" ? memoryInput : JSON.stringify(memoryInput);
24304
- const existingRaw = await memory.getWorkingMemory({
24305
- threadId,
24306
- resourceId,
24307
- memoryConfig
24308
- });
24309
- if (existingRaw) {
24310
- const template = await memory.getWorkingMemoryTemplate({ memoryConfig });
24311
- if (template?.content) {
24312
- const normalizedNew = workingMemory.replace(/\s+/g, " ").trim();
24313
- const normalizedTemplate = template.content.replace(/\s+/g, " ").trim();
24314
- const normalizedExisting = existingRaw.replace(/\s+/g, " ").trim();
24315
- if (normalizedNew === normalizedTemplate && normalizedExisting !== normalizedTemplate) return {
24316
- success: false,
24317
- message: "Attempted to replace existing working memory with empty template. Update skipped to prevent data loss."
24318
- };
24319
- }
24320
- }
24321
- }
24322
- await memory.updateWorkingMemory({
24323
- threadId,
24324
- resourceId,
24325
- workingMemory,
24326
- memoryConfig
24327
- });
24328
- return { success: true };
24329
- }
24330
- });
24331
- };
24332
- const __experimental_updateWorkingMemoryToolVNext = (config) => {
24333
- return createTool({
24334
- id: "update-working-memory",
24335
- description: "Update the working memory with new information.",
24336
- inputSchema: {
24337
- $schema: "http://json-schema.org/draft-07/schema#",
24338
- type: "object",
24339
- properties: {
24340
- newMemory: {
24341
- type: "string",
24342
- description: `The ${config.workingMemory?.schema ? "JSON" : "Markdown"} formatted working memory content to store`
24343
- },
24344
- searchString: {
24345
- type: "string",
24346
- description: "The working memory string to find. Will be replaced with the newMemory string. If this is omitted or doesn't exist, the newMemory string will be appended to the end of your working memory. Replacing single lines at a time is encouraged for greater accuracy. If updateReason is not 'append-new-memory', this search string must be provided or the tool call will be rejected."
24347
- },
24348
- updateReason: {
24349
- type: "string",
24350
- enum: [
24351
- "append-new-memory",
24352
- "clarify-existing-memory",
24353
- "replace-irrelevant-memory"
24354
- ],
24355
- description: "The reason you're updating working memory. Passing any value other than 'append-new-memory' requires a searchString to be provided. Defaults to append-new-memory"
24356
- }
24357
- }
24358
- },
24359
- execute: async (inputData, context) => {
24360
- const workingMemoryInput = inputData;
24361
- const threadId = context?.agent?.threadId;
24362
- const resourceId = context?.agent?.resourceId;
24363
- const memory = context?.memory;
24364
- if (!memory) throw new Error("Memory instance is required for working memory updates");
24365
- const scope = config.workingMemory?.scope || "resource";
24366
- if (scope === "thread" && !threadId) throw new Error("Thread ID is required for thread-scoped working memory updates");
24367
- if (scope === "resource" && !resourceId) throw new Error("Resource ID is required for resource-scoped working memory updates");
24368
- if (threadId) {
24369
- let thread = await memory.getThreadById({ threadId });
24370
- if (!thread) thread = await memory.createThread({
24371
- threadId,
24372
- resourceId,
24373
- memoryConfig: config
24374
- });
24375
- if (thread.resourceId && resourceId && thread.resourceId !== resourceId) throw new Error(`Thread with id ${threadId} resourceId does not match the current resourceId ${resourceId}`);
24376
- }
24377
- const workingMemory = workingMemoryInput.newMemory || "";
24378
- if (!workingMemoryInput.updateReason) workingMemoryInput.updateReason = `append-new-memory`;
24379
- if (workingMemoryInput.searchString && config.workingMemory?.scope === `resource` && workingMemoryInput.updateReason === `replace-irrelevant-memory`) workingMemoryInput.searchString = void 0;
24380
- if (workingMemoryInput.updateReason === `append-new-memory` && workingMemoryInput.searchString) workingMemoryInput.searchString = void 0;
24381
- if (workingMemoryInput.updateReason !== `append-new-memory` && !workingMemoryInput.searchString) return {
24382
- success: false,
24383
- reason: `updateReason was ${workingMemoryInput.updateReason} but no searchString was provided. Unable to replace undefined with "${workingMemoryInput.newMemory}"`
24384
- };
24385
- const result = await memory.__experimental_updateWorkingMemoryVNext({
24386
- threadId,
24387
- resourceId,
24388
- workingMemory,
24389
- searchString: workingMemoryInput.searchString,
24390
- memoryConfig: config
24391
- });
24392
- if (result) return result;
24393
- return { success: true };
24394
- }
24395
- });
24396
- };
24397
- /**
24398
- * Returns the working-memory tool plus the wire name it should be registered under.
24399
- *
24400
- * - Default delivery (`useStateSignals: false`): wire name `updateWorkingMemory`,
24401
- * identical shape to today.
24402
- * - State-signals delivery (`useStateSignals: true`): wire name `setWorkingMemory`.
24403
- * The rename keeps legacy strip filters (which match the literal `updateWorkingMemory`)
24404
- * from removing tool-call parts so they persist as a normal audit trail. Any
24405
- * future state-signal-specific tweaks to the tool (e.g. delta-aware results,
24406
- * scoped descriptions) belong here.
24407
- *
24408
- * The VNext vs default tool body decision is left to the caller because Memory
24409
- * owns the `isVNextWorkingMemoryConfig` check; pass `vNext: true` to use the
24410
- * search-and-replace shape.
24411
- */
24412
- function createWorkingMemoryTool(config, options = {}) {
24413
- const useStateSignals = config.workingMemory?.useStateSignals === true;
24414
- const tool = options.vNext ? __experimental_updateWorkingMemoryToolVNext(config) : updateWorkingMemoryTool(config);
24415
- return {
24416
- name: useStateSignals ? SET_WORKING_MEMORY_TOOL_NAME : UPDATE_WORKING_MEMORY_TOOL_NAME,
24417
- tool
24418
- };
24419
- }
24420
- //#endregion
24421
24451
  //#region src/processors/working-memory-state/processor.ts
24422
24452
  /**
24423
24453
  * WorkingMemoryStateProcessor
@@ -34010,6 +34040,6 @@ Notes:
34010
34040
  }
34011
34041
  };
34012
34042
  //#endregion
34013
- export { formatMessagesForObserver as A, OBSERVATION_CONTEXT_PROMPT_THREAD as B, SUMMARIZE_THREAD_DEFAULTS as C, buildObserverPrompt as D, OBSERVER_SYSTEM_PROMPT as E, parseAnchorId as F, StaleKnowledgeSemanticIndexError as G, getObservationContextPrompt as H, stripEphemeralAnchorIds as I, SUBCONSCIOUS_ACTIVITY_STATE_ID as J, SubconsciousRemindExtractor as K, OBSERVATIONAL_MEMORY_DEFAULTS as L, optimizeObservationsForContext as M, parseObserverOutput as N, buildObserverSystemPrompt as O, injectAnchorIds as P, Extractor as Q, OBSERVATION_CONTEXT_INSTRUCTIONS as R, WorkingMemoryExtractor as S, TokenCounter as T, Subconscious as U, OBSERVATION_CONTINUATION_HINT as V, KnowledgeSemanticIndexCoordinator as W, publishSubconsciousActivity as X, buildSubconsciousActivitySnapshot as Y, renderSubconsciousActivity as Z, wrapInObservationGroup as _, extractWorkingMemoryContent as a, WorkingMemoryStateProcessor as b, getObservationsAsOf as c, combineObservationGroupRanges as d, deriveObservationGroupProvenance as f, stripObservationGroups as g, renderObservationGroupsForReflection as h, WorkingMemory as i, hasCurrentTaskSection as j, extractCurrentTask as k, ObservationalMemoryProcessor as l, reconcileObservationGroupsFromReflection as m, MessageHistory$1 as n, extractWorkingMemoryTags as o, parseObservationGroups as p, ModelByInputTokens as q, SemanticRecall as r, removeWorkingMemoryTags as s, Memory as t, ObservationalMemory as u, WORKING_MEMORY_STATE_ID as v, summarizeConversation as w, deepMergeWorkingMemory as x, WORKING_MEMORY_STATE_PROCESSOR_ID as y, OBSERVATION_CONTEXT_PROMPT as z };
34043
+ export { formatMessagesForObserver as A, OBSERVATION_CONTEXT_PROMPT_THREAD as B, SUMMARIZE_THREAD_DEFAULTS as C, buildObserverPrompt as D, OBSERVER_SYSTEM_PROMPT as E, parseAnchorId as F, StaleKnowledgeSemanticIndexError as G, getObservationContextPrompt as H, stripEphemeralAnchorIds as I, SUBCONSCIOUS_ACTIVITY_STATE_ID as J, SubconsciousRemindExtractor as K, OBSERVATIONAL_MEMORY_DEFAULTS as L, optimizeObservationsForContext as M, parseObserverOutput as N, buildObserverSystemPrompt as O, injectAnchorIds as P, Extractor as Q, OBSERVATION_CONTEXT_INSTRUCTIONS as R, deepMergeWorkingMemory as S, TokenCounter as T, Subconscious as U, OBSERVATION_CONTINUATION_HINT as V, KnowledgeSemanticIndexCoordinator as W, publishSubconsciousActivity as X, buildSubconsciousActivitySnapshot as Y, renderSubconsciousActivity as Z, wrapInObservationGroup as _, extractWorkingMemoryContent as a, WorkingMemoryStateProcessor as b, getObservationsAsOf as c, combineObservationGroupRanges as d, deriveObservationGroupProvenance as f, stripObservationGroups as g, renderObservationGroupsForReflection as h, WorkingMemory as i, hasCurrentTaskSection as j, extractCurrentTask as k, ObservationalMemoryProcessor as l, reconcileObservationGroupsFromReflection as m, MessageHistory$1 as n, extractWorkingMemoryTags as o, parseObservationGroups as p, ModelByInputTokens as q, SemanticRecall as r, removeWorkingMemoryTags as s, Memory as t, ObservationalMemory as u, WORKING_MEMORY_STATE_ID as v, summarizeConversation as w, WorkingMemoryExtractor as x, WORKING_MEMORY_STATE_PROCESSOR_ID as y, OBSERVATION_CONTEXT_PROMPT as z };
34014
34044
 
34015
- //# sourceMappingURL=src-B0ISVOJX.js.map
34045
+ //# sourceMappingURL=src-DsewkOlu.js.map