Skip to content

🤯 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.

🐛 fix(memory): accept partial identity updates and keep fields the model nulls (#20094)

Arvin Xuac2c235d28df
diff --git a/apps/server/src/routers/lambda/userMemories.ts b/apps/server/src/routers/lambda/userMemories.ts
index 98df2aab832..6313e529f1d 100644
--- a/apps/server/src/routers/lambda/userMemories.ts
+++ b/apps/server/src/routers/lambda/userMemories.ts
@@ -11,7 +11,7 @@ import {
ExperienceMemoryItemSchema,
PreferenceMemoryItemSchema,
RemoveIdentityActionSchema,
- UpdateIdentityActionSchema,
+ UpdateIdentityToolInputSchema,
} from '@lobechat/memory-user-memory';
import type { QueryTaxonomyOptionsResult, SearchMemoryResult } from '@lobechat/types';
import { LayersEnum, queryTaxonomyOptionsSchema, searchMemorySchema } from '@lobechat/types';
@@ -1316,7 +1316,7 @@ export const userMemoriesRouter = router({
}),
toolUpdateIdentityMemory: memoryWriteProcedure
- .input(UpdateIdentityActionSchema)
+ .input(UpdateIdentityToolInputSchema)
.mutation(async ({ input, ctx }) => {
try {
const { agentRuntime, embeddingModel } = await getEmbeddingRuntime(
@@ -1405,6 +1405,7 @@ export const userMemoriesRouter = router({
identity: Object.keys(identityPayload).length > 0 ? identityPayload : undefined,
identityId: input.id,
mergeStrategy: input.mergeStrategy,
+ preserveOmittedFields: true,
});
if (!updated) {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/memory.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/memory.test.ts
index 9f4985ef891..5601e5b67ef 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/memory.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/memory.test.ts
@@ -1,4 +1,5 @@
import type { LobeChatDatabase } from '@lobechat/database';
+import { MergeStrategyEnum } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ToolExecutionContext } from '../../types';
@@ -14,6 +15,7 @@ const mocks = vi.hoisted(() => ({
recordUserMemoryLexicalSearchDecision: vi.fn(),
searchMemory: vi.fn(),
shouldRunUserMemoryLexicalSearch: vi.fn(),
+ updateIdentityEntry: vi.fn(),
}));
vi.mock('@/database/models/userMemory', () => ({
@@ -22,6 +24,7 @@ vi.mock('@/database/models/userMemory', () => ({
UserMemoryModel: vi.fn().mockImplementation(function () {
return {
searchMemory: mocks.searchMemory,
+ updateIdentityEntry: mocks.updateIdentityEntry,
};
}),
}));
@@ -192,4 +195,30 @@ describe('memoryRuntime', () => {
source: 'tool',
});
});
+
+ // A tool call sends only the fields it changes; replace must not clear the rest.
+ it('updates only the identity fields the tool call sent, keeping the rest on replace', async () => {
+ mocks.embeddings.mockResolvedValueOnce([[0.1, 0.2, 0.3]]);
+ mocks.initModelRuntimeWithUserPayload.mockReturnValueOnce({
+ embeddings: mocks.embeddings,
+ });
+ mocks.updateIdentityEntry.mockResolvedValueOnce(true);
+
+ const runtime = await memoryRuntime.factory(createContext());
+
+ const result = await runtime.updateIdentityMemory({
+ id: 'mem_1',
+ mergeStrategy: MergeStrategyEnum.Replace,
+ set: { title: null, withIdentity: { description: null, role: 'lead maintainer' } },
+ });
+
+ expect(result.success).toBe(true);
+ expect(mocks.updateIdentityEntry).toHaveBeenCalledWith({
+ base: undefined,
+ identity: { role: 'lead maintainer' },
+ identityId: 'mem_1',
+ mergeStrategy: 'replace',
+ preserveOmittedFields: true,
+ });
+ });
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/memory.ts b/apps/server/src/services/toolExecution/serverRuntimes/memory.ts
index 579ed895fda..bbec4cea066 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/memory.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/memory.ts
@@ -13,7 +13,7 @@ import type {
ExperienceMemoryItemSchema,
PreferenceMemoryItemSchema,
RemoveIdentityActionSchema,
- UpdateIdentityActionSchema,
+ UpdateIdentityToolInputSchema,
} from '@lobechat/memory-user-memory/schemas';
import type {
AddActivityMemoryResult,
@@ -642,7 +642,7 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {
};
updateIdentityMemory = async (
- input: z.infer<typeof UpdateIdentityActionSchema>,
+ input: z.output<typeof UpdateIdentityToolInputSchema>,
): Promise<UpdateIdentityMemoryResult> => {
try {
const { agentRuntime, embeddingModel } = await getEmbeddingRuntime(
@@ -732,6 +732,7 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {
identity: Object.keys(identityPayload).length > 0 ? identityPayload : undefined,
identityId: input.id,
mergeStrategy: input.mergeStrategy,
+ preserveOmittedFields: true,
});
if (!updated) {
diff --git a/packages/builtin-tool-memory/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-memory/src/ExecutionRuntime/index.test.ts
index 3cba19f57ec..c04805161bd 100644
--- a/packages/builtin-tool-memory/src/ExecutionRuntime/index.test.ts
+++ b/packages/builtin-tool-memory/src/ExecutionRuntime/index.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
+import type { UpdateIdentityMemoryParams } from '../types';
import { MemoryExecutionRuntime, type MemoryRuntimeService } from './index';
const createService = (overrides: Partial<MemoryRuntimeService> = {}): MemoryRuntimeService =>
@@ -81,4 +82,101 @@ describe('MemoryExecutionRuntime', () => {
expect(result.content).toContain('addPreferenceMemory with error detail');
expect(addPreferenceMemory).not.toHaveBeenCalled();
});
+
+ describe('updateIdentityMemory', () => {
+ const run = async (params: unknown) => {
+ const updateIdentityMemory = vi
+ .fn()
+ .mockResolvedValue({ identityId: 'mem_1', message: 'updated', success: true });
+ const runtime = new MemoryExecutionRuntime({
+ service: createService({ updateIdentityMemory }),
+ });
+ const result = await runtime.updateIdentityMemory(params as UpdateIdentityMemoryParams);
+ return { result, updateIdentityMemory };
+ };
+
+ // The manifest only requires `set.withIdentity`, so a partial update is valid.
+ it('accepts a partial update that omits the optional fields', async () => {
+ const { result, updateIdentityMemory } = await run({
+ id: 'mem_1',
+ mergeStrategy: 'merge',
+ set: {
+ withIdentity: {
+ description: 'Senior platform engineer at Acme',
+ extractedLabels: ['platform-engineer'],
+ role: 'platform engineer',
+ },
+ },
+ });
+
+ expect(result.success).toBe(true);
+ expect(updateIdentityMemory).toHaveBeenCalledWith({
+ id: 'mem_1',
+ mergeStrategy: 'merge',
+ set: {
+ withIdentity: {
+ description: 'Senior platform engineer at Acme',
+ extractedLabels: ['platform-engineer'],
+ role: 'platform engineer',
+ },
+ },
+ });
+ });
+
+ // The manifest says "use null for omitting the field": a null must leave the
+ // stored value alone instead of being written over it.
+ it('treats null fields as omitted rather than as values to store', async () => {
+ const { result, updateIdentityMemory } = await run({
+ id: 'mem_1',
+ mergeStrategy: 'merge',
+ set: {
+ details: null,
+ memoryCategory: null,
+ memoryType: 'people',
+ summary: null,
+ tags: null,
+ title: null,
+ withIdentity: {
+ description: 'Married on 2026-08-22',
+ episodicDate: null,
+ extractedLabels: ['spouse'],
+ relationship: 'spouse',
+ role: 'wife',
+ scoreConfidence: 0.95,
+ sourceEvidence: null,
+ sourceIds: null,
+ type: null,
+ },
+ },
+ });
+
+ expect(result.success).toBe(true);
+ expect(updateIdentityMemory).toHaveBeenCalledWith({
+ id: 'mem_1',
+ mergeStrategy: 'merge',
+ set: {
+ memoryType: 'people',
+ withIdentity: {
+ description: 'Married on 2026-08-22',
+ extractedLabels: ['spouse'],
+ relationship: 'spouse',
+ role: 'wife',
+ scoreConfidence: 0.95,
+ },
+ },
+ });
+ });
+
+ it('still rejects an update without withIdentity', async () => {
+ const { result, updateIdentityMemory } = await run({
+ id: 'mem_1',
+ mergeStrategy: 'merge',
+ set: { description: 'flattened by mistake' },
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('withIdentity');
+ expect(updateIdentityMemory).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/packages/builtin-tool-memory/src/ExecutionRuntime/index.ts b/packages/builtin-tool-memory/src/ExecutionRuntime/index.ts
index c08fdd613f1..fbe0fa20332 100644
--- a/packages/builtin-tool-memory/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-memory/src/ExecutionRuntime/index.ts
@@ -5,7 +5,7 @@ import {
ExperienceMemoryItemSchema,
PreferenceMemoryItemSchema,
RemoveIdentityActionSchema,
- UpdateIdentityActionSchema,
+ UpdateIdentityToolInputSchema,
} from '@lobechat/memory-user-memory/schemas';
import { formatMemorySearchResults } from '@lobechat/prompts';
import type {
@@ -46,7 +46,7 @@ export interface MemoryRuntimeService {
) => Promise<RemoveIdentityMemoryResult>;
searchMemory: (params: SearchMemoryParams) => Promise<SearchMemoryResult>;
updateIdentityMemory: (
- params: z.infer<typeof UpdateIdentityActionSchema>,
+ params: z.output<typeof UpdateIdentityToolInputSchema>,
) => Promise<UpdateIdentityMemoryResult>;
}
@@ -240,11 +240,11 @@ export class MemoryExecutionRuntime {
}
async updateIdentityMemory(
- params: z.infer<typeof UpdateIdentityActionSchema>,
+ params: z.input<typeof UpdateIdentityToolInputSchema>,
): Promise<BuiltinServerRuntimeOutput> {
if (this.isReadOnly) return READ_ONLY_RESULT;
try {
- const input = UpdateIdentityActionSchema.parse(params);
+ const input = UpdateIdentityToolInputSchema.parse(params);
const result = await this.service.updateIdentityMemory(input);
if (!result.success) {
diff --git a/packages/builtin-tool-memory/src/executor/index.ts b/packages/builtin-tool-memory/src/executor/index.ts
index 77d0ef366ba..ed35dbd55fd 100644
--- a/packages/builtin-tool-memory/src/executor/index.ts
+++ b/packages/builtin-tool-memory/src/executor/index.ts
@@ -5,7 +5,7 @@ import type {
ExperienceMemoryItemSchema,
PreferenceMemoryItemSchema,
RemoveIdentityActionSchema,
- UpdateIdentityActionSchema,
+ UpdateIdentityToolInputSchema,
} from '@lobechat/memory-user-memory/schemas';
import type {
BuiltinToolContext,
@@ -118,7 +118,7 @@ class MemoryExecutor extends BaseExecutor<typeof MemoryApiName> {
};
updateIdentityMemory = async (
- params: z.infer<typeof UpdateIdentityActionSchema>,
+ params: z.input<typeof UpdateIdentityToolInputSchema>,
ctx?: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
this.ensureWritable(ctx?.agentId);
diff --git a/packages/builtin-tool-memory/src/types.ts b/packages/builtin-tool-memory/src/types.ts
index 42542aa9080..5dad5c4044f 100644
--- a/packages/builtin-tool-memory/src/types.ts
+++ b/packages/builtin-tool-memory/src/types.ts
@@ -5,7 +5,7 @@ import type {
ExperienceMemoryItemSchema,
PreferenceMemoryItemSchema,
RemoveIdentityActionSchema,
- UpdateIdentityActionSchema,
+ UpdateIdentityToolInputSchema,
} from '@lobechat/memory-user-memory/schemas';
import type { QueryTaxonomyOptionsResult, SearchMemoryResult } from '@lobechat/types';
import type { z } from 'zod';
@@ -100,7 +100,8 @@ export interface AddPreferenceMemoryState {
}
// Update Identity
-export type UpdateIdentityMemoryParams = z.infer<typeof UpdateIdentityActionSchema>;
+/** Raw tool arguments: the model may send null for fields it leaves unchanged. */
+export type UpdateIdentityMemoryParams = z.input<typeof UpdateIdentityToolInputSchema>;
export interface UpdateIdentityMemoryState {
identityId?: string;
}
diff --git a/packages/database/src/models/userMemory/__tests__/model.test.ts b/packages/database/src/models/userMemory/__tests__/model.test.ts
index f19b8b12351..94a69eb5988 100644
--- a/packages/database/src/models/userMemory/__tests__/model.test.ts
+++ b/packages/database/src/models/userMemory/__tests__/model.test.ts
@@ -8,7 +8,7 @@ import {
TypesEnum,
UserMemoryContextObjectType,
} from '@lobechat/types';
-import { eq } from 'drizzle-orm';
+import { eq, sql } from 'drizzle-orm';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
@@ -1472,6 +1472,144 @@ describe('UserMemoryModel', () => {
expect(updated?.role).toBeNull();
});
+ // Tool calls send only the fields they change, so replace must not null the rest.
+ it('keeps omitted identity fields on replace when preserveOmittedFields is set', async () => {
+ const { identityId } = await memoryModel.addIdentityEntry({
+ base: {},
+ identity: {
+ description: 'original desc',
+ relationship: RelationshipEnum.Self,
+ role: 'original role',
+ tags: ['maintainer', 'editor'],
+ type: IdentityTypeEnum.Professional,
+ },
+ });
+
+ const success = await memoryModel.updateIdentityEntry({
+ identity: { role: 'lead maintainer', tags: ['lead'] },
+ identityId,
+ mergeStrategy: MergeStrategyEnum.Replace,
+ preserveOmittedFields: true,
+ });
+
+ expect(success).toBe(true);
+ const updated = await serverDB.query.userMemoriesIdentities.findFirst({
+ where: eq(userMemoriesIdentities.id, identityId),
+ });
+ expect(updated?.role).toBe('lead maintainer');
+ // Replaced wholesale, not merged index by index.
+ expect(updated?.tags).toEqual(['lead']);
+ expect(updated?.description).toBe('original desc');
+ expect(updated?.relationship).toBe(RelationshipEnum.Self);
+ expect(updated?.type).toBe(IdentityTypeEnum.Professional);
+ });
+
+ // A tool update that names one metadata key must not drop the others.
+ it.each([MergeStrategyEnum.Replace, MergeStrategyEnum.Merge])(
+ 'keeps unmentioned metadata keys on a partial tool update (%s)',
+ async (mergeStrategy) => {
+ const { identityId, userMemoryId } = await memoryModel.addIdentityEntry({
+ base: { metadata: { scoreConfidence: 0.4, sourceEvidence: 'said so in chat' } },
+ identity: {
+ description: 'original desc',
+ metadata: { scoreConfidence: 0.4, sourceEvidence: 'said so in chat' },
+ role: 'original role',
+ },
+ });
+
+ const success = await memoryModel.updateIdentityEntry({
+ base: { metadata: { scoreConfidence: 0.9 } },
+ identity: { metadata: { scoreConfidence: 0.9 } },
+ identityId,
+ mergeStrategy,
+ preserveOmittedFields: true,
+ });
+
+ expect(success).toBe(true);
+ const identityRow = await serverDB.query.userMemoriesIdentities.findFirst({
+ where: eq(userMemoriesIdentities.id, identityId),
+ });
+ const baseRow = await serverDB.query.userMemories.findFirst({
+ where: eq(userMemories.id, userMemoryId),
+ });
+ expect(identityRow?.metadata).toEqual({
+ scoreConfidence: 0.9,
+ sourceEvidence: 'said so in chat',
+ });
+ expect(baseRow?.metadata).toEqual({
+ scoreConfidence: 0.9,
+ sourceEvidence: 'said so in chat',
+ });
+ expect(identityRow?.description).toBe('original desc');
+ },
+ );
+
+ // Another writer can change a different metadata key after this update loaded the row;
+ // merging in SQL must keep that key instead of writing back a stale snapshot.
+ it('keeps metadata keys written concurrently during a partial tool update', async () => {
+ const { identityId, userMemoryId } = await memoryModel.addIdentityEntry({
+ base: { metadata: { scoreConfidence: 0.4 } },
+ identity: { description: 'original desc', metadata: { scoreConfidence: 0.4 } },
+ });
+
+ const concurrentPatch = sql`'{"sourceEvidence":"written concurrently"}'::jsonb`;
+ const originalTransaction = serverDB.transaction.bind(serverDB);
+ const transactionSpy = vi.spyOn(serverDB, 'transaction').mockImplementationOnce(((
+ callback: (tx: unknown) => Promise<unknown>,
+ ) =>
+ originalTransaction(async (tx) => {
+ const interfered = new Set<unknown>();
+ // Land a competing write right before each of this update's own writes.
+ const wrappedTx = new Proxy(tx, {
+ get(target, prop) {
+ if (prop !== 'update') {
+ const value = Reflect.get(target, prop, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ }
+ return (table: typeof userMemories | typeof userMemoriesIdentities) => {
+ const builder = target.update(table);
+ if (interfered.has(table)) return builder;
+ interfered.add(table);
+ const rowId = table === userMemories ? userMemoryId : identityId;
+ return {
+ set: (values: never) => ({
+ where: (condition: never) =>
+ target
+ .update(table)
+ .set({
+ metadata: sql`coalesce(${table.metadata}, '{}'::jsonb) || ${concurrentPatch}`,
+ })
+ .where(eq(table.id, rowId))
+ .then(() => builder.set(values).where(condition)),
+ }),
+ };
+ };
+ },
+ });
+ return callback(wrappedTx);
+ })) as typeof serverDB.transaction);
+
+ const success = await memoryModel.updateIdentityEntry({
+ base: { metadata: { scoreConfidence: 0.9 } },
+ identity: { metadata: { scoreConfidence: 0.9 } },
+ identityId,
+ mergeStrategy: MergeStrategyEnum.Replace,
+ preserveOmittedFields: true,
+ });
+ transactionSpy.mockRestore();
+
+ expect(success).toBe(true);
+ const identityRow = await serverDB.query.userMemoriesIdentities.findFirst({
+ where: eq(userMemoriesIdentities.id, identityId),
+ });
+ const baseRow = await serverDB.query.userMemories.findFirst({
+ where: eq(userMemories.id, userMemoryId),
+ });
+ const expected = { scoreConfidence: 0.9, sourceEvidence: 'written concurrently' };
+ expect(identityRow?.metadata).toEqual(expected);
+ expect(baseRow?.metadata).toEqual(expected);
+ });
+
it('should not update other user identity', async () => {
const otherModel = new UserMemoryModel(serverDB, otherUserId);
const { identityId } = await otherModel.addIdentityEntry({
diff --git a/packages/database/src/models/userMemory/model.ts b/packages/database/src/models/userMemory/model.ts
index 038845bf4c5..dfaba9b3074 100644
--- a/packages/database/src/models/userMemory/model.ts
+++ b/packages/database/src/models/userMemory/model.ts
@@ -317,6 +317,12 @@ export interface UpdateIdentityEntryParams {
identity?: IdentityEntryPayload;
identityId: string;
mergeStrategy?: MergeStrategyEnum;
+ /**
+ * With `replace`, only overwrite the identity fields present in `identity` and keep the
+ * rest. Tool calls send just the fields they change; the extractor sends a full identity
+ * and relies on omitted fields being cleared, so it leaves this off.
+ */
+ preserveOmittedFields?: boolean;
}
export interface ContextEntryPayload {
@@ -430,6 +436,17 @@ export interface GetMemoryDetailParams {
layer: LayersEnum;
}
+const isPlainRecord = (value: unknown): value is Record<string, unknown> =>
+ !!value && typeof value === 'object' && !Array.isArray(value);
+
+/**
+ * Shallow-merge supplied metadata keys over the stored object inside the UPDATE itself, so
+ * concurrent partial updates of different keys cannot overwrite each other with a stale read.
+ * A stored value that is not a JSON object is treated as empty.
+ */
+const mergeMetadataKeysSql = (column: AnyColumn, supplied: Record<string, unknown>) =>
+ sql`(CASE WHEN jsonb_typeof(${column}) = 'object' THEN ${column} ELSE '{}'::jsonb END) || ${JSON.stringify(supplied)}::jsonb`;
+
export class UserMemoryModel {
static parseAssociatedObjects(value?: unknown): Record<string, unknown>[] {
if (!Array.isArray(value)) return [];
@@ -2385,7 +2402,14 @@ export class UserMemoryModel {
baseUpdate.updatedAt = new Date();
await tx
.update(userMemories)
- .set(baseUpdate)
+ .set(
+ params.preserveOmittedFields && isPlainRecord(baseUpdate.metadata)
+ ? {
+ ...baseUpdate,
+ metadata: mergeMetadataKeysSql(userMemories.metadata, baseUpdate.metadata),
+ }
+ : baseUpdate,
+ )
.where(and(eq(userMemories.id, identity.userMemoryId), this.memoryWhere(userMemories)));
}
}
@@ -2416,6 +2440,14 @@ export class UserMemoryModel {
? null
: (normalizeIdentityTypeValue(identity.type) ?? null),
};
+
+ if (params.preserveOmittedFields) {
+ for (const key of Object.keys(identityUpdate) as (keyof typeof identityUpdate)[]) {
+ if (identity[key as keyof IdentityEntryPayload] === undefined) {
+ delete identityUpdate[key];
+ }
+ }
+ }
} else {
identityUpdate = merge(identityUpdate, params.identity);
@@ -2446,7 +2478,19 @@ export class UserMemoryModel {
identityUpdate.updatedAt = new Date();
await tx
.update(userMemoriesIdentities)
- .set(identityUpdate)
+ .set(
+ // A partial tool update names only the metadata keys it changes (e.g.
+ // scoreConfidence); keep the other stored keys such as sourceEvidence.
+ params.preserveOmittedFields && isPlainRecord(identityUpdate.metadata)
+ ? {
+ ...identityUpdate,
+ metadata: mergeMetadataKeysSql(
+ userMemoriesIdentities.metadata,
+ identityUpdate.metadata,
+ ),
+ }
+ : identityUpdate,
+ )
.where(
and(
eq(userMemoriesIdentities.id, params.identityId),
diff --git a/packages/memory-user-memory/src/schemas/identity.ts b/packages/memory-user-memory/src/schemas/identity.ts
index 732d450c188..85dbe221cac 100644
--- a/packages/memory-user-memory/src/schemas/identity.ts
+++ b/packages/memory-user-memory/src/schemas/identity.ts
@@ -138,6 +138,55 @@ export const UpdateIdentityActionSchema = z
})
.strict();
+type WithoutNullFields<T> = { [K in keyof T]?: Exclude<T[K], null> };
+
+/** Drop null-valued keys, narrowing the nullable input shape to the optional output one. */
+const dropNullFields = <T extends Record<string, unknown>>(value: T) =>
+ Object.fromEntries(
+ Object.entries(value).filter(([, field]) => field !== null),
+ ) as WithoutNullFields<T>;
+
+/**
+ * Input of the updateIdentityMemory tool. The tool manifest only requires `set.withIdentity`
+ * and tells the model to "use null for omitting the field", so every other field is optional
+ * and a null leaves the stored value untouched instead of being written over it.
+ * UpdateIdentityActionSchema keeps every field present because the extractor feeds it to
+ * strict structured output, which requires that.
+ *
+ * Use `z.input` for the raw tool arguments (nulls allowed) and `z.output` for the parsed
+ * value handed to services (nulls dropped).
+ */
+export const UpdateIdentityToolInputSchema = z
+ .object({
+ id: z.string(),
+ mergeStrategy: z.nativeEnum(MergeStrategyEnum),
+ set: z
+ .object({
+ details: z.string().nullish(),
+ memoryCategory: z.string().nullish(),
+ memoryType: MemoryTypeSchema.nullish(),
+ summary: z.string().nullish(),
+ tags: z.array(z.string()).nullish(),
+ title: z.string().nullish(),
+ withIdentity: z
+ .object({
+ description: z.string().nullish(),
+ episodicDate: z.string().nullish(),
+ extractedLabels: z.array(z.string()).nullish(),
+ relationship: z.string().nullish(),
+ role: z.string().nullish(),
+ scoreConfidence: z.number().nullish(),
+ sourceIds: z.array(z.string()).nullish(),
+ sourceEvidence: z.string().nullish(),
+ type: z.string().nullish(),
+ })
+ .strict()
+ .transform(dropNullFields),
+ })
+ .transform(({ withIdentity, ...rest }) => ({ ...dropNullFields(rest), withIdentity })),
+ })
+ .strict();
+
export const RemoveIdentityActionSchema = z
.object({
id: z.string(),
@@ -171,4 +220,8 @@ export const WithIdentitySchema = z
export type IdentityActions = z.infer<typeof IdentityActionsSchema>;
export type AddIdentityAction = z.infer<typeof AddIdentityActionSchema>;
export type UpdateIdentityAction = z.infer<typeof UpdateIdentityActionSchema>;
+/** Raw tool arguments as the model sends them; nullable fields mean "leave unchanged". */
+export type UpdateIdentityToolInput = z.input<typeof UpdateIdentityToolInputSchema>;
+/** Parsed tool arguments with null fields dropped. */
+export type UpdateIdentityToolParsed = z.output<typeof UpdateIdentityToolInputSchema>;
export type RemoveIdentityAction = z.infer<typeof RemoveIdentityActionSchema>;
diff --git a/src/services/userMemory/index.ts b/src/services/userMemory/index.ts
index 620737dd09f..6c7f77ca5a0 100644
--- a/src/services/userMemory/index.ts
+++ b/src/services/userMemory/index.ts
@@ -5,7 +5,7 @@ import {
type ExperienceMemoryItemSchema,
type PreferenceMemoryItemSchema,
type RemoveIdentityActionSchema,
- type UpdateIdentityActionSchema,
+ type UpdateIdentityToolInputSchema,
} from '@lobechat/memory-user-memory/schemas';
import {
type ActivityListParams,
@@ -161,7 +161,7 @@ class UserMemoryService {
};
updateIdentityMemory = async (
- params: z.infer<typeof UpdateIdentityActionSchema>,
+ params: z.output<typeof UpdateIdentityToolInputSchema>,
): Promise<UpdateIdentityMemoryResult> => {
return lambdaClient.userMemories.toolUpdateIdentityMemory.mutate(params);
};