🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(memory): validate memory tool arguments (#16802)
Nekoa33927c61dbe
diff --git a/packages/builtin-tool-memory/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-memory/src/ExecutionRuntime/index.test.tsnew file mode 100644index 00000000000..3cba19f57ec--- /dev/null+++ b/packages/builtin-tool-memory/src/ExecutionRuntime/index.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it, vi } from 'vitest';++import { MemoryExecutionRuntime, type MemoryRuntimeService } from './index';++const createService = (overrides: Partial<MemoryRuntimeService> = {}): MemoryRuntimeService =>+ ({+ addActivityMemory: vi.fn(),+ addContextMemory: vi.fn(),+ addExperienceMemory: vi.fn(),+ addIdentityMemory: vi.fn(),+ addPreferenceMemory: vi.fn(),+ queryTaxonomyOptions: vi.fn(),+ removeIdentityMemory: vi.fn(),+ searchMemory: vi.fn(),+ updateIdentityMemory: vi.fn(),+ ...overrides,+ }) as MemoryRuntimeService;++describe('MemoryExecutionRuntime', () => {+ it('normalizes missing preference sourceIds before calling the service', async () => {+ const addPreferenceMemory = vi.fn().mockResolvedValue({+ memoryId: 'memory-1',+ message: 'saved',+ preferenceId: 'preference-1',+ success: true,+ });+ const runtime = new MemoryExecutionRuntime({+ service: createService({ addPreferenceMemory }),+ });++ const result = await runtime.addPreferenceMemory({+ details: 'The user prefers concise answers.',+ memoryCategory: 'communication',+ memoryType: 'preference',+ summary: 'The user prefers concise answers.',+ tags: ['communication'],+ title: 'Concise answers',+ withPreference: {+ appContext: null,+ conclusionDirectives: 'Keep answers concise.',+ extractedLabels: ['concise'],+ extractedScopes: [],+ originContext: null,+ scorePriority: 0.7,+ suggestions: [],+ type: 'communication',+ },+ } as never);++ expect(result.success).toBe(true);+ expect(addPreferenceMemory).toHaveBeenCalledWith(expect.objectContaining({ sourceIds: [] }));+ });++ it('rejects invalid preference array fields before calling the service', async () => {+ const addPreferenceMemory = vi.fn();+ const runtime = new MemoryExecutionRuntime({+ service: createService({ addPreferenceMemory }),+ });++ const result = await runtime.addPreferenceMemory({+ details: 'The user prefers concise answers.',+ memoryCategory: 'communication',+ memoryType: 'preference',+ sourceIds: [],+ summary: 'The user prefers concise answers.',+ tags: 'communication',+ title: 'Concise answers',+ withPreference: {+ appContext: null,+ conclusionDirectives: 'Keep answers concise.',+ extractedLabels: ['concise'],+ extractedScopes: [],+ originContext: null,+ scorePriority: 0.7,+ suggestions: [],+ type: 'communication',+ },+ } as never);++ expect(result.success).toBe(false);+ expect(result.content).toContain('addPreferenceMemory with error detail');+ expect(addPreferenceMemory).not.toHaveBeenCalled();+ });+});diff --git a/packages/builtin-tool-memory/src/ExecutionRuntime/index.ts b/packages/builtin-tool-memory/src/ExecutionRuntime/index.tsindex b3ccd407bfb..c08fdd613f1 100644--- a/packages/builtin-tool-memory/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-memory/src/ExecutionRuntime/index.ts@@ -1,4 +1,4 @@-import type {+import {ActivityMemoryItemSchema,AddIdentityActionSchema,ContextMemoryItemSchema,@@ -119,14 +119,15 @@ export class MemoryExecutionRuntime {): Promise<BuiltinServerRuntimeOutput> {if (this.isReadOnly) return READ_ONLY_RESULT;try {- const result = await this.service.addContextMemory(params);+ const input = ContextMemoryItemSchema.parse(params);+ const result = await this.service.addContextMemory(input);if (!result.success) {return { content: result.message, success: false };}return {- content: `Context memory "${params.title}" saved with memoryId: "${result.memoryId}" and contextId: "${result.contextId}"`,+ content: `Context memory "${input.title}" saved with memoryId: "${result.memoryId}" and contextId: "${result.contextId}"`,state: { contextId: result.contextId, memoryId: result.memoryId },success: true,};@@ -143,14 +144,15 @@ export class MemoryExecutionRuntime {): Promise<BuiltinServerRuntimeOutput> {if (this.isReadOnly) return READ_ONLY_RESULT;try {- const result = await this.service.addActivityMemory(params);+ const input = ActivityMemoryItemSchema.parse(params);+ const result = await this.service.addActivityMemory(input);if (!result.success) {return { content: result.message, success: false };}return {- content: `Activity memory "${params.title}" saved with memoryId: "${result.memoryId}" and activityId: "${result.activityId}"`,+ content: `Activity memory "${input.title}" saved with memoryId: "${result.memoryId}" and activityId: "${result.activityId}"`,state: { activityId: result.activityId, memoryId: result.memoryId },success: true,};@@ -167,14 +169,15 @@ export class MemoryExecutionRuntime {): Promise<BuiltinServerRuntimeOutput> {if (this.isReadOnly) return READ_ONLY_RESULT;try {- const result = await this.service.addExperienceMemory(params);+ const input = ExperienceMemoryItemSchema.parse(params);+ const result = await this.service.addExperienceMemory(input);if (!result.success) {return { content: result.message, success: false };}return {- content: `Experience memory "${params.title}" saved with memoryId: "${result.memoryId}" and experienceId: "${result.experienceId}"`,+ content: `Experience memory "${input.title}" saved with memoryId: "${result.memoryId}" and experienceId: "${result.experienceId}"`,state: { experienceId: result.experienceId, memoryId: result.memoryId },success: true,};@@ -191,14 +194,15 @@ export class MemoryExecutionRuntime {): Promise<BuiltinServerRuntimeOutput> {if (this.isReadOnly) return READ_ONLY_RESULT;try {- const result = await this.service.addIdentityMemory(params);+ const input = AddIdentityActionSchema.parse(params);+ const result = await this.service.addIdentityMemory(input);if (!result.success) {return { content: result.message, success: false };}return {- content: `Identity memory "${params.title}" saved with memoryId: "${result.memoryId}" and identityId: "${result.identityId}"`,+ content: `Identity memory "${input.title}" saved with memoryId: "${result.memoryId}" and identityId: "${result.identityId}"`,state: { identityId: result.identityId, memoryId: result.memoryId },success: true,};@@ -215,14 +219,15 @@ export class MemoryExecutionRuntime {): Promise<BuiltinServerRuntimeOutput> {if (this.isReadOnly) return READ_ONLY_RESULT;try {- const result = await this.service.addPreferenceMemory(params);+ const input = PreferenceMemoryItemSchema.parse(params);+ const result = await this.service.addPreferenceMemory(input);if (!result.success) {return { content: result.message, success: false };}return {- content: `Preference memory "${params.title}" saved with memoryId: "${result.memoryId}" and preferenceId: "${result.preferenceId}"`,+ content: `Preference memory "${input.title}" saved with memoryId: "${result.memoryId}" and preferenceId: "${result.preferenceId}"`,state: { memoryId: result.memoryId, preferenceId: result.preferenceId },success: true,};@@ -239,15 +244,16 @@ export class MemoryExecutionRuntime {): Promise<BuiltinServerRuntimeOutput> {if (this.isReadOnly) return READ_ONLY_RESULT;try {- const result = await this.service.updateIdentityMemory(params);+ const input = UpdateIdentityActionSchema.parse(params);+ const result = await this.service.updateIdentityMemory(input);if (!result.success) {return { content: result.message, success: false };}return {- content: `Identity memory updated: ${params.id}`,- state: { identityId: params.id },+ content: `Identity memory updated: ${input.id}`,+ state: { identityId: input.id },success: true,};} catch (e) {@@ -263,15 +269,16 @@ export class MemoryExecutionRuntime {): Promise<BuiltinServerRuntimeOutput> {if (this.isReadOnly) return READ_ONLY_RESULT;try {- const result = await this.service.removeIdentityMemory(params);+ const input = RemoveIdentityActionSchema.parse(params);+ const result = await this.service.removeIdentityMemory(input);if (!result.success) {return { content: result.message, success: false };}return {- content: `Identity memory removed: ${params.id}\nReason: ${params.reason}`,- state: { identityId: params.id, reason: params.reason },+ content: `Identity memory removed: ${input.id}\nReason: ${input.reason}`,+ state: { identityId: input.id, reason: input.reason },success: true,};} catch (e) {diff --git a/packages/memory-user-memory/src/extractors/base.ts b/packages/memory-user-memory/src/extractors/base.tsindex 92589107a9b..8757ea9a28c 100644--- a/packages/memory-user-memory/src/extractors/base.ts+++ b/packages/memory-user-memory/src/extractors/base.ts@@ -62,7 +62,7 @@ export abstract class BaseMemoryExtractor<protected getPromptName(): string {return this.agent;}- protected abstract getResultSchema(): z.ZodType<TOutput> | undefined;+ protected abstract getResultSchema(): z.ZodType<TOutput, z.ZodTypeDef, unknown> | undefined;protected getSchema(_options: TExtractorTemplateProps): GenerateObjectSchema | undefined {const schema = this.getResultSchema();diff --git a/packages/memory-user-memory/src/schemas/context.ts b/packages/memory-user-memory/src/schemas/context.tsindex ddf44b7ade8..0c69df3feac 100644--- a/packages/memory-user-memory/src/schemas/context.ts+++ b/packages/memory-user-memory/src/schemas/context.ts@@ -82,6 +82,7 @@ export const ContextMemoryItemSchema = z.object({sourceIds: z.array(z.string()).nullable()+ .default(() => []).describe('Stable source message ids that support this memory'),summary: z.string().describe('Concise overview of this specific memory'),tags: z.array(z.string()).describe('User defined tags that summarize the context facets'),diff --git a/packages/memory-user-memory/src/schemas/experience.ts b/packages/memory-user-memory/src/schemas/experience.tsindex 06613fa01fd..216460968e9 100644--- a/packages/memory-user-memory/src/schemas/experience.ts+++ b/packages/memory-user-memory/src/schemas/experience.ts@@ -40,6 +40,7 @@ export const ExperienceMemoryItemSchema = z.object({sourceIds: z.array(z.string()).nullable()+ .default(() => []).describe('Stable source message ids that support this memory'),summary: z.string().describe('Concise overview of this specific memory'),tags: z.array(z.string()).describe('Model generated tags that summarize the experience facets'),diff --git a/packages/memory-user-memory/src/schemas/identity.ts b/packages/memory-user-memory/src/schemas/identity.tsindex 96c961af1ad..732d450c188 100644--- a/packages/memory-user-memory/src/schemas/identity.ts+++ b/packages/memory-user-memory/src/schemas/identity.ts@@ -48,7 +48,9 @@ export const AddIdentityActionSchema = ztags: z.array(z.string()).describe('Model generated tags that summarize the identity facets'),title: z.string()- .describe('Honorific-style, concise descriptor (strength + domain/milestone), avoid bare job titles; e.g., "Trusted open-source maintainer", "Specializes in low-latency infra", "Former Aliyun engineer", "Cares for rescue cats"'),+ .describe(+ 'Honorific-style, concise descriptor (strength + domain/milestone), avoid bare job titles; e.g., "Trusted open-source maintainer", "Specializes in low-latency infra", "Former Aliyun engineer", "Cares for rescue cats"',+ ),withIdentity: z.object({description: z.string(),@@ -57,11 +59,14 @@ export const AddIdentityActionSchema = zrelationship: RelationshipEnum,role: z.string()- .describe('Role explicitly mentioned for this identity entry (e.g., "platform engineer", "caregiver"); keep neutral and only use when evidence exists'),+ .describe(+ 'Role explicitly mentioned for this identity entry (e.g., "platform engineer", "caregiver"); keep neutral and only use when evidence exists',+ ),scoreConfidence: z.number(),sourceIds: z.array(z.string()).nullable()+ .default(() => []).describe('Stable source message ids that support this identity'),sourceEvidence: z.union([z.string(), z.null()]),type: IdentityTypeEnum,@@ -97,7 +102,9 @@ export const UpdateIdentityActionSchema = ztitle: z.string().nullable()- .describe('Honorific-style, concise descriptor (strength + domain/milestone), avoid bare job titles; e.g., "Trusted open-source maintainer", "Specializes in low-latency infra", "Former Aliyun engineer", "Cares for rescue cats"; use null for omitting the field'),+ .describe(+ 'Honorific-style, concise descriptor (strength + domain/milestone), avoid bare job titles; e.g., "Trusted open-source maintainer", "Specializes in low-latency infra", "Former Aliyun engineer", "Cares for rescue cats"; use null for omitting the field',+ ),withIdentity: z.object({description: z.string().nullable(),@@ -110,7 +117,9 @@ export const UpdateIdentityActionSchema = z.nullable(),role: z.string()- .describe('Role explicitly mentioned for this identity entry (e.g., "platform engineer", "caregiver"); keep existing when not updated; use null for omitting the field')+ .describe(+ 'Role explicitly mentioned for this identity entry (e.g., "platform engineer", "caregiver"); keep existing when not updated; use null for omitting the field',+ ).nullable(),scoreConfidence: z.number().nullable(),sourceIds: zdiff --git a/packages/memory-user-memory/src/schemas/preference.ts b/packages/memory-user-memory/src/schemas/preference.tsindex cb69e3fb29c..c50ff63e277 100644--- a/packages/memory-user-memory/src/schemas/preference.ts+++ b/packages/memory-user-memory/src/schemas/preference.ts@@ -69,6 +69,7 @@ export const PreferenceMemoryItemSchema = z.object({sourceIds: z.array(z.string()).nullable()+ .default(() => []).describe('Stable source message ids that support this memory'),summary: z.string().describe('Concise overview of this specific memory'),tags: z.array(z.string()).describe('Model generated tags that summarize the preference facets'),diff --git a/packages/memory-user-memory/src/schemas/sourceIds.test.ts b/packages/memory-user-memory/src/schemas/sourceIds.test.tsnew file mode 100644index 00000000000..ff13cd57aec--- /dev/null+++ b/packages/memory-user-memory/src/schemas/sourceIds.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from 'vitest';++import { ContextMemoryItemSchema } from './context';+import { ExperienceMemoryItemSchema } from './experience';+import { AddIdentityActionSchema } from './identity';+import { PreferenceMemoryItemSchema } from './preference';++describe('memory item sourceIds schemas', () => {+ it('defaults missing top-level sourceIds to an empty array', () => {+ const context = ContextMemoryItemSchema.safeParse({+ details: 'Project details',+ memoryCategory: 'work',+ memoryType: 'context',+ summary: 'The user is working on a project.',+ tags: ['project'],+ title: 'Project context',+ withContext: {+ associatedObjects: [],+ associatedSubjects: [],+ currentStatus: 'ongoing',+ description: 'The project is in progress.',+ labels: ['project'],+ scoreImpact: 0.7,+ scoreUrgency: 0.5,+ title: 'Project',+ type: 'project',+ },+ });++ const experience = ExperienceMemoryItemSchema.safeParse({+ details: 'Debugging details',+ memoryCategory: 'work',+ memoryType: 'other',+ summary: 'The user learned a debugging approach.',+ tags: ['debugging'],+ title: 'Debugging approach',+ withExperience: {+ action: 'Traced the data flow.',+ keyLearning: 'Validate inputs at boundaries.',+ knowledgeValueScore: 0.8,+ labels: ['debugging'],+ possibleOutcome: 'Fewer production regressions.',+ problemSolvingScore: 0.9,+ reasoning: 'The error came from malformed tool args.',+ scoreConfidence: 0.8,+ situation: 'A production memory tool failed.',+ type: 'debugging',+ },+ });++ const preference = PreferenceMemoryItemSchema.safeParse({+ details: 'The user prefers concise answers.',+ memoryCategory: 'communication',+ memoryType: 'preference',+ summary: 'The user prefers concise answers.',+ tags: ['communication'],+ title: 'Concise answers',+ withPreference: {+ appContext: null,+ conclusionDirectives: 'Keep answers concise.',+ extractedLabels: ['concise'],+ extractedScopes: [],+ originContext: null,+ scorePriority: 0.7,+ suggestions: [],+ type: 'communication',+ },+ });++ expect(context.success && context.data.sourceIds).toEqual([]);+ expect(experience.success && experience.data.sourceIds).toEqual([]);+ expect(preference.success && preference.data.sourceIds).toEqual([]);+ });++ it('defaults missing identity sourceIds to an empty array', () => {+ const result = AddIdentityActionSchema.safeParse({+ details: null,+ memoryCategory: 'professional',+ memoryType: 'fact',+ summary: 'The user works as a platform engineer.',+ tags: ['work'],+ title: 'Platform engineer',+ withIdentity: {+ description: 'The user works as a platform engineer.',+ episodicDate: null,+ extractedLabels: ['platform-engineer'],+ relationship: 'self',+ role: 'platform engineer',+ scoreConfidence: 0.8,+ sourceEvidence: null,+ type: 'professional',+ },+ });++ expect(result.success && result.data.withIdentity.sourceIds).toEqual([]);+ });+});