🤯 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
✨ feat: user memory
Neko49ffcb5c0603
diff --git a/packages/const/src/userMemory.ts b/packages/const/src/userMemory.tsnew file mode 100644index 00000000000..da9a055964d--- /dev/null+++ b/packages/const/src/userMemory.ts@@ -0,0 +1,26 @@+import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_PROVIDER } from './settings';++export const DEFAULT_SEARCH_USER_MEMORY_TOP_K = {+ contexts: 0,+ experiences: 0,+ preferences: 3,+};+export interface UserMemoryConfigItem {+ model: string;+ provider: string;+}++export interface UserMemoryConfig {+ embeddingModel: UserMemoryConfigItem;+}++export const DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM: UserMemoryConfigItem = {+ model: DEFAULT_EMBEDDING_MODEL,+ provider: DEFAULT_EMBEDDING_PROVIDER,+};++export const DEFAULT_USER_MEMORY_CONFIG: UserMemoryConfig = {+ embeddingModel: DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM,+};++export const DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS = 1024;diff --git a/packages/database/src/repositories/aiInfra/index.ts b/packages/database/src/repositories/aiInfra/index.tsindex 5dc9826d403..b5bb825aef4 100644--- a/packages/database/src/repositories/aiInfra/index.ts+++ b/packages/database/src/repositories/aiInfra/index.ts@@ -5,13 +5,14 @@ import type {EnabledProvider,ProviderConfig,} from '@lobechat/types';-import { isEmpty } from 'lodash-es';+import { isEmpty } from 'es-toolkit/compat';import {AIChatModelCard,AiModelSourceEnum,AiProviderModelListItem,EnabledAiModel,} from 'model-bank';+import * as modelBank from 'model-bank';import pMap from 'p-map';import { DEFAULT_MODEL_PROVIDER_LIST } from '@/config/modelProviders';@@ -291,7 +292,7 @@ export class AiInfraRepos {};/**- * use in the `/settings?active=provider&provider=[id]` page+ * use in the `/settings/provider/[id]` page*/getAiProviderDetail = async (id: string, decryptor?: DecryptUserKeyVaults) => {const config = await this.aiProviderModel.getAiProviderById(id, decryptor);@@ -306,11 +307,9 @@ export class AiInfraRepos {providerId: string,): Promise<AiProviderModelListItem[] | undefined> => {try {- const modules = await import('model-bank');-// TODO: when model-bank is a separate module, we will try import from model-bank/[prividerId] again// @ts-expect-error providerId is string- const providerModels = modules[providerId];+ const providerModels = modelBank[providerId];// use the serverModelLists as the defined server model list// fallback to empty array for custom providerdiff --git a/packages/database/src/schemas/userMemories.ts b/packages/database/src/schemas/userMemories.tsindex d4532ca32a0..71020a613b4 100644--- a/packages/database/src/schemas/userMemories.ts+++ b/packages/database/src/schemas/userMemories.ts@@ -60,14 +60,8 @@ export const userMemoriesContexts = pgTable(metadata: jsonb('metadata').$type<Record<string, unknown>>(),tags: text('tags').array(),- associatedObjects:- jsonb('associated_objects').$type<- { extra?: Record<string, unknown>; name?: string; type?: string }[]- >(),- associatedSubjects:- jsonb('associated_subjects').$type<- { extra?: Record<string, unknown>; name?: string; type?: string }[]- >(),+ associatedObjects: jsonb('associated_objects').$type<{ extra?: Record<string, unknown>, name?: string, type?: string }[]>(),+ associatedSubjects: jsonb('associated_subjects').$type<{ extra?: Record<string, unknown>, name?: string, type?: string }[]>(),title: text('title'),description: text('description'),diff --git a/packages/database/src/utils/columns.ts b/packages/database/src/utils/columns.tsnew file mode 100644index 00000000000..6ecee77d01d--- /dev/null+++ b/packages/database/src/utils/columns.ts@@ -0,0 +1,25 @@+import { getTableColumns } from 'drizzle-orm';+import { PgTable } from 'drizzle-orm/pg-core';++export const selectNonVectorColumns = <T extends PgTable>(+ table: T,+): {+ [K in keyof T['_']['columns'] as K extends `${string}Vector`+ ? never+ : K extends `${string}Vector${number}`+ ? never+ : K]: T['_']['columns'][K];+} => {+ const columns = getTableColumns(table);+ const selection: Record<string, unknown> = {};++ for (const [key, column] of Object.entries(columns)) {+ if (column.getSQLType().toLowerCase().startsWith('vector')) {+ continue;+ }++ selection[key] = column;+ }++ return selection as any;+};diff --git a/packages/prompts/src/prompts/index.ts b/packages/prompts/src/prompts/index.tsindex 8f87a556f44..5ad8c8ae6f7 100644--- a/packages/prompts/src/prompts/index.ts+++ b/packages/prompts/src/prompts/index.ts@@ -3,6 +3,7 @@ export * from './files';export * from './groupChat';export * from './gtd';export * from './knowledgeBaseQA';+export * from './messagesToText';export * from './plugin';export * from './search';export * from './systemRole';diff --git a/packages/prompts/src/prompts/messagesToText/__snapshots__/index.test.ts.snap b/packages/prompts/src/prompts/messagesToText/__snapshots__/index.test.ts.snapnew file mode 100644index 00000000000..55569f89166--- /dev/null+++ b/packages/prompts/src/prompts/messagesToText/__snapshots__/index.test.ts.snap@@ -0,0 +1,40 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`conversationToText > should format a single message correctly 1`] = `+"<conversation>+<user>Hello, how are you?</user>+</conversation>"+`;++exports[`conversationToText > should format multiple messages correctly 1`] = `+"<conversation>+<user>Hello, how are you?</user>+<assistant>I am doing well, thank you!</assistant>+<user>What is the weather like?</user>+</conversation>"+`;++exports[`conversationToText > should handle empty messages array 1`] = `"<conversation/>"`;++exports[`conversationToText > should handle messages with different roles 1`] = `+"<conversation>+<system>You are a helpful assistant.</system>+<user>Tell me a joke.</user>+<assistant>Why did the chicken cross the road?</assistant>+</conversation>"+`;++exports[`conversationToText > should handle messages with special characters 1`] = `+"<conversation>+<user>What is 2 + 2?</user>+<assistant>The answer is 4.</assistant>+</conversation>"+`;++exports[`conversationToText > should handle multiline content 1`] = `+"<conversation>+<user>This is a multiline message.+It has multiple lines.+Line 3 here.</user>+</conversation>"+`;diff --git a/packages/prompts/src/prompts/messagesToText/index.test.ts b/packages/prompts/src/prompts/messagesToText/index.test.tsnew file mode 100644index 00000000000..5f53cf9db66--- /dev/null+++ b/packages/prompts/src/prompts/messagesToText/index.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest';++import { Message, conversationToText } from './index';++describe('conversationToText', () => {+ it('should format a single message correctly', () => {+ const messages: Message[] = [{ role: 'user', content: 'Hello, how are you?' }];++ const result = conversationToText(messages);++ expect(result).toMatchSnapshot();+ });++ it('should format multiple messages correctly', () => {+ const messages: Message[] = [+ { role: 'user', content: 'Hello, how are you?' },+ { role: 'assistant', content: 'I am doing well, thank you!' },+ { role: 'user', content: 'What is the weather like?' },+ ];++ const result = conversationToText(messages);++ expect(result).toMatchSnapshot();+ });++ it('should handle empty messages array', () => {+ const messages: Message[] = [];++ const result = conversationToText(messages);++ expect(result).toMatchSnapshot();+ });++ it('should handle messages with different roles', () => {+ const messages: Message[] = [+ { role: 'system', content: 'You are a helpful assistant.' },+ { role: 'user', content: 'Tell me a joke.' },+ { role: 'assistant', content: 'Why did the chicken cross the road?' },+ ];++ const result = conversationToText(messages);++ expect(result).toMatchSnapshot();+ });++ it('should handle messages with special characters', () => {+ const messages: Message[] = [+ { role: 'user', content: 'What is 2 + 2?' },+ { role: 'assistant', content: 'The answer is 4.' },+ ];++ const result = conversationToText(messages);++ expect(result).toMatchSnapshot();+ });++ it('should handle multiline content', () => {+ const messages: Message[] = [+ {+ role: 'user',+ content: `This is a multiline message.+It has multiple lines.+Line 3 here.`,+ },+ ];++ const result = conversationToText(messages);++ expect(result).toMatchSnapshot();+ });+});diff --git a/packages/prompts/src/prompts/messagesToText/index.ts b/packages/prompts/src/prompts/messagesToText/index.tsnew file mode 100644index 00000000000..fc8dee2b450--- /dev/null+++ b/packages/prompts/src/prompts/messagesToText/index.ts@@ -0,0 +1,17 @@+export interface Message {+ content: string;+ role: string;+}++/**+ * Convert conversation messages to XML-formatted text+ * @param messages - Array of message objects with role and content+ * @returns Formatted conversation text wrapped in chat_history tags+ */+export function conversationToText(messages: Message[]): string {+ return messages.length === 0+ ? `<conversation/>`+ : `<conversation>+${messages.map((m) => `<${m.role}>${m.content}</${m.role}>`).join('\n')}+</conversation>`;+}diff --git a/src/server/routers/lambda/userMemories.test.ts b/src/server/routers/lambda/userMemories.test.tsnew file mode 100644index 00000000000..2ced3b7bed9--- /dev/null+++ b/src/server/routers/lambda/userMemories.test.ts@@ -0,0 +1,372 @@+// @vitest-environment node+import { LayersEnum } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { getServerDB } from '@/database/core/db-adaptor';+import { UserMemoryModel } from '@/database/models/userMemory';+import { initModelRuntimeWithUserPayload } from '@/server/modules/ModelRuntime';++import { userMemoriesRouter } from './userMemories';++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(),+}));++vi.mock('@/server/globalConfig', () => ({+ getServerDefaultFilesConfig: vi.fn().mockReturnValue({+ embeddingModel: { model: 'text-embedding-3-small' },+ }),+}));++vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeWithUserPayload: vi.fn(),+}));++vi.mock('@lobechat/utils/server', () => ({+ getXorPayload: vi.fn().mockReturnValue({ userId: 'test-user' }),+}));++vi.mock('@/database/models/userMemory', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/database/models/userMemory')>();+ const mockUserMemoryModel: any = vi.fn();+ mockUserMemoryModel.parseDateFromString = actual.UserMemoryModel.parseDateFromString;+ return {+ ...actual,+ UserMemoryModel: mockUserMemoryModel,+ } satisfies typeof import('@/database/models/userMemory');+});++const embeddingsMock = vi.fn();+const mockCtx = { authorizationHeader: 'Bearer mock-token', userId: 'test-user' };++beforeEach(() => {+ vi.clearAllMocks();++ embeddingsMock.mockImplementation(async ({ input }: { input: string[] | string }) => {+ const items = Array.isArray(input) ? input : [input];+ return items.map((_, index) => [index + 1]);+ });++ vi.mocked(initModelRuntimeWithUserPayload).mockResolvedValue({+ embeddings: embeddingsMock,+ } as any);+});++describe('memoryRouter.reEmbedMemories', () => {+ it('re-embeds memories across tables and returns aggregate stats', async () => {+ const updateUserMemoryVectors = vi.fn().mockResolvedValue(undefined);+ const updateContextVectors = vi.fn().mockResolvedValue(undefined);+ const updatePreferenceVectors = vi.fn().mockResolvedValue(undefined);+ const updateIdentityVectors = vi.fn().mockResolvedValue(undefined);+ const updateExperienceVectors = vi.fn().mockResolvedValue(undefined);++ vi.mocked(UserMemoryModel).mockImplementation(+ () =>+ ({+ updateContextVectors,+ updateExperienceVectors,+ updateIdentityVectors,+ updatePreferenceVectors,+ updateUserMemoryVectors,+ }) as any,+ );++ const userMemoriesRows = [{ id: 'memory-1', details: 'detail text', summary: 'summary text' }];+ const contextsRows = [{ id: 'context-1', description: 'context text' }];+ const preferencesRows = [{ id: 'preference-1', conclusionDirectives: 'directive text' }];+ const identitiesRows = [{ id: 'identity-1', description: 'identity text' }];+ const experiencesRows = [+ {+ action: 'action text',+ id: 'experience-1',+ keyLearning: 'learning text',+ situation: 'situation text',+ },+ ];++ const dbStub = {+ query: {+ userMemories: {+ findMany: vi.fn().mockResolvedValue(userMemoriesRows),+ },+ userMemoriesContexts: {+ findMany: vi.fn().mockResolvedValue(contextsRows),+ },+ userMemoriesExperiences: {+ findMany: vi.fn().mockResolvedValue(experiencesRows),+ },+ userMemoriesIdentities: {+ findMany: vi.fn().mockResolvedValue(identitiesRows),+ },+ userMemoriesPreferences: {+ findMany: vi.fn().mockResolvedValue(preferencesRows),+ },+ },+ } as const;++ vi.mocked(getServerDB).mockResolvedValue(dbStub as any);++ const caller = userMemoriesRouter.createCaller(mockCtx as any);++ const result = await caller.reEmbedMemories();++ expect(result.success).toBe(true);+ expect(result.aggregate).toEqual({ failed: 0, skipped: 0, succeeded: 5, total: 5 });+ expect(result.results?.userMemories).toEqual({ failed: 0, skipped: 0, succeeded: 1, total: 1 });+ expect(result.results?.contexts).toEqual({ failed: 0, skipped: 0, succeeded: 1, total: 1 });+ expect(result.results?.preferences).toEqual({ failed: 0, skipped: 0, succeeded: 1, total: 1 });+ expect(result.results?.identities).toEqual({ failed: 0, skipped: 0, succeeded: 1, total: 1 });+ expect(result.results?.experiences).toEqual({ failed: 0, skipped: 0, succeeded: 1, total: 1 });++ expect(updateUserMemoryVectors).toHaveBeenCalledWith('memory-1', {+ detailsVector1024: [2],+ summaryVector1024: [1],+ });+ expect(updateContextVectors).toHaveBeenCalledWith('context-1', {+ descriptionVector: [1],+ });+ expect(updatePreferenceVectors).toHaveBeenCalledWith('preference-1', {+ conclusionDirectivesVector: [1],+ });+ expect(updateIdentityVectors).toHaveBeenCalledWith('identity-1', {+ descriptionVector: [1],+ });+ expect(updateExperienceVectors).toHaveBeenCalledWith('experience-1', {+ actionVector: [2],+ keyLearningVector: [3],+ situationVector: [1],+ });++ expect(embeddingsMock).toHaveBeenCalledTimes(5);+ });+});++describe('userMemories.queryMemories', () => {+ it('forwards filters and pagination to the model and returns the result', async () => {+ const queryMemories = vi.fn().mockResolvedValue({+ items: [{ id: 'mem-1' }],+ page: 2,+ pageSize: 5,+ total: 1,+ });++ vi.mocked(UserMemoryModel).mockImplementation(+ () =>+ ({+ queryMemories,+ }) as any,+ );++ vi.mocked(getServerDB).mockResolvedValue({+ query: {},+ } as any);++ const caller = userMemoriesRouter.createCaller(mockCtx as any);++ const input = {+ categories: ['work'],+ layer: 'context',+ order: 'asc' as const,+ page: 2,+ pageSize: 5,+ q: 'atlas',+ sort: 'scoreImpact' as const,+ tags: ['project'],+ types: ['topic'],+ };++ const result = await caller.queryMemories(input as any);++ expect(queryMemories).toHaveBeenCalledWith({+ ...input,+ order: 'asc',+ sort: 'scoreImpact',+ });+ expect(result).toEqual({+ items: [{ id: 'mem-1' }],+ page: 2,+ pageSize: 5,+ total: 1,+ });+ });++ it('applies default sort and order when not provided', async () => {+ const queryMemories = vi.fn().mockResolvedValue({+ items: [],+ page: 1,+ pageSize: 20,+ total: 0,+ });++ vi.mocked(UserMemoryModel).mockImplementation(+ () =>+ ({+ queryMemories,+ }) as any,+ );++ vi.mocked(getServerDB).mockResolvedValue({+ query: {},+ } as any);++ const caller = userMemoriesRouter.createCaller(mockCtx as any);++ await caller.queryMemories();++ expect(queryMemories).toHaveBeenCalledWith({+ order: 'desc',+ });+ });+});++describe('userMemories.getMemoryDetail', () => {+ it('forwards memory id to model and returns detail', async () => {+ const getMemoryDetail = vi.fn().mockResolvedValue({ id: 'mem-1', layer: 'experience' });++ vi.mocked(UserMemoryModel).mockImplementation(+ () =>+ ({+ getMemoryDetail,+ }) as any,+ );++ vi.mocked(getServerDB).mockResolvedValue({+ query: {},+ } as any);++ const caller = userMemoriesRouter.createCaller(mockCtx as any);++ const result = await caller.getMemoryDetail({+ id: 'mem-1',+ layer: LayersEnum.Experience,+ } as any);++ expect(getMemoryDetail).toHaveBeenCalledWith({+ id: 'mem-1',+ layer: LayersEnum.Experience,+ });+ expect(result).toEqual({ id: 'mem-1', layer: 'experience' });+ });++ it('returns null when model throws', async () => {+ const getMemoryDetail = vi.fn().mockRejectedValue(new Error('boom'));++ vi.mocked(UserMemoryModel).mockImplementation(+ () =>+ ({+ getMemoryDetail,+ }) as any,+ );++ vi.mocked(getServerDB).mockResolvedValue({+ query: {},+ } as any);++ const caller = userMemoriesRouter.createCaller(mockCtx as any);++ const result = await caller.getMemoryDetail({+ id: 'mem-1',+ layer: LayersEnum.Experience,+ } as any);++ expect(result).toBeNull();+ });+});++describe('userMemories.retrieveMemory', () => {+ it('returns aggregated memory search results', async () => {+ const searchWithEmbedding = vi.fn().mockResolvedValue({+ contexts: [+ {+ accessedAt: new Date('2024-01-01T00:00:00.000Z'),+ associatedObjects: [{ name: 'Roadmap' }],+ associatedSubjects: [{ name: 'Atlas Team' }],+ createdAt: new Date('2024-01-01T00:00:00.000Z'),+ currentStatus: 'active',+ description: 'Coordinating weekly syncs for Project Atlas',+ id: 'ctx-1',+ metadata: { priority: 'high' },+ scoreImpact: 0.9,+ scoreUrgency: 0.6,+ tags: ['project', 'atlas'],+ title: 'Project Atlas coordination',+ type: 'project',+ updatedAt: new Date('2024-01-02T00:00:00.000Z'),+ userMemoryIds: ['mem-1'],+ },+ ],+ experiences: [+ {+ accessedAt: new Date('2024-01-03T00:00:00.000Z'),+ action: 'Facilitated sprint planning',+ createdAt: new Date('2024-01-02T00:00:00.000Z'),+ id: 'exp-1',+ keyLearning: 'Team wants clearer milestones',+ metadata: { feedback: 'positive' },+ possibleOutcome: 'Improved roadmap transparency',+ reasoning: 'Helps unblock design team',+ scoreConfidence: 0.8,+ situation: 'Sprint 5 planning',+ tags: ['planning'],+ type: 'meeting',+ updatedAt: new Date('2024-01-02T12:00:00.000Z'),+ userMemoryId: 'mem-2',+ },+ ],+ preferences: [+ {+ accessedAt: new Date('2024-01-03T00:00:00.000Z'),+ conclusionDirectives: 'Always provide concise weekly status updates for Project Atlas',+ createdAt: new Date('2024-01-02T00:00:00.000Z'),+ id: 'pref-1',+ metadata: { channel: 'email' },+ scorePriority: 0.7,+ suggestions: ['Prepare summary every Friday'],+ tags: ['communication'],+ type: 'workflow',+ updatedAt: new Date('2024-01-02T12:00:00.000Z'),+ userMemoryId: 'mem-3',+ },+ ],+ });++ vi.mocked(UserMemoryModel).mockImplementation(+ () =>+ ({+ searchWithEmbedding,+ }) as any,+ );++ vi.mocked(getServerDB).mockResolvedValue({+ query: {},+ } as any);++ const caller = userMemoriesRouter.createCaller(mockCtx as any);++ const result = await caller.searchMemory({+ query: 'Project Atlas',+ topK: { contexts: 1, experiences: 1, preferences: 1 },+ });++ expect(embeddingsMock).toHaveBeenCalledTimes(1);+ expect(searchWithEmbedding.mock.calls[0][0]).toBeTypeOf('object');+ expect(searchWithEmbedding.mock.calls[0][0]).toStrictEqual({+ embedding: [1],+ limits: { contexts: 1, experiences: 1, preferences: 1 },+ });++ expect(result.contexts[0]).toMatchObject({+ id: 'ctx-1',+ title: 'Project Atlas coordination',+ currentStatus: 'active',+ });+ expect(result.experiences[0]).toMatchObject({+ id: 'exp-1',+ situation: 'Sprint 5 planning',+ });+ expect(result.preferences[0]).toMatchObject({+ id: 'pref-1',+ conclusionDirectives: 'Always provide concise weekly status updates for Project Atlas',+ });+ });+});diff --git a/src/server/routers/lambda/userMemories.ts b/src/server/routers/lambda/userMemories.tsnew file mode 100644index 00000000000..70e7ea1e6d1--- /dev/null+++ b/src/server/routers/lambda/userMemories.ts@@ -0,0 +1,1061 @@+import {+ DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,+ DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM,+} from '@lobechat/const';+import {+ AddIdentityActionSchema,+ ContextMemoryItemSchema,+ ExperienceMemoryItemSchema,+ PreferenceMemoryItemSchema,+ RemoveIdentityActionSchema,+ UpdateIdentityActionSchema,+} from '@lobechat/memory-user-memory';+import { type SQL, and, asc, eq, gte, lte } from 'drizzle-orm';+import { ModelProvider } from 'model-bank';+import pMap from 'p-map';+import { z } from 'zod';++import {+ IdentityEntryBasePayload,+ IdentityEntryPayload,+ UserMemoryModel,+} from '@/database/models/userMemory';+import {+ userMemories,+ userMemoriesContexts,+ userMemoriesExperiences,+ userMemoriesIdentities,+ userMemoriesPreferences,+} from '@/database/schemas';+import { authedProcedure, router } from '@/libs/trpc/lambda';+import { keyVaults, serverDatabase } from '@/libs/trpc/lambda/middleware';+import { getServerDefaultFilesConfig } from '@/server/globalConfig';+import { initModelRuntimeWithUserPayload } from '@/server/modules/ModelRuntime';+import { ClientSecretPayload } from '@/types/auth';+import { SearchMemoryResult, searchMemorySchema } from '@/types/userMemory';+import { LayersEnum } from '@/types/userMemory/shared';++const EMPTY_SEARCH_RESULT: SearchMemoryResult = {+ contexts: [],+ experiences: [],+ preferences: [],+};++type MemorySearchContext = {+ jwtPayload: ClientSecretPayload;+ memoryModel: UserMemoryModel;+};++type MemorySearchResult = Awaited<ReturnType<UserMemoryModel['searchWithEmbedding']>>;++const mapMemorySearchResult = (layeredResults: MemorySearchResult): SearchMemoryResult => {+ return {+ contexts: layeredResults.contexts.map((context) => ({+ accessedAt: context.accessedAt,+ associatedObjects: context.associatedObjects,+ associatedSubjects: context.associatedSubjects,+ createdAt: context.createdAt,+ currentStatus: context.currentStatus,+ description: context.description,+ id: context.id,+ metadata: context.metadata,+ scoreImpact: context.scoreImpact,+ scoreUrgency: context.scoreUrgency,+ tags: context.tags,+ title: context.title,+ type: context.type,+ updatedAt: context.updatedAt,+ userMemoryIds: Array.isArray(context.userMemoryIds)+ ? (context.userMemoryIds as string[])+ : null,+ })),+ experiences: layeredResults.experiences.map((experience) => ({+ accessedAt: experience.accessedAt,+ action: experience.action,+ createdAt: experience.createdAt,+ id: experience.id,+ keyLearning: experience.keyLearning,+ metadata: experience.metadata,+ possibleOutcome: experience.possibleOutcome,+ reasoning: experience.reasoning,+ scoreConfidence: experience.scoreConfidence,+ situation: experience.situation,+ tags: experience.tags,+ type: experience.type,+ updatedAt: experience.updatedAt,+ userMemoryId: experience.userMemoryId,+ })),+ preferences: layeredResults.preferences.map((preference) => ({+ accessedAt: preference.accessedAt,+ conclusionDirectives: preference.conclusionDirectives,+ createdAt: preference.createdAt,+ id: preference.id,+ metadata: preference.metadata,+ scorePriority: preference.scorePriority,+ suggestions: preference.suggestions,+ tags: preference.tags,+ type: preference.type,+ updatedAt: preference.updatedAt,+ userMemoryId: preference.userMemoryId,+ })),+ } satisfies SearchMemoryResult;+};++const searchUserMemories = async (+ ctx: MemorySearchContext,+ input: z.infer<typeof searchMemorySchema>,+): Promise<SearchMemoryResult> => {+ const agentRuntime = await initModelRuntimeWithUserPayload(ModelProvider.OpenAI, ctx.jwtPayload);++ const { model: embeddingModel } =+ getServerDefaultFilesConfig().embeddingModel || DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM;++ const queryEmbeddings = await agentRuntime.embeddings({+ dimensions: DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,+ input: input.query,+ model: embeddingModel,+ });++ const limits = {+ contexts: input.topK?.contexts,+ experiences: input.topK?.experiences,+ preferences: input.topK?.preferences,+ };++ const layeredResults = await ctx.memoryModel.searchWithEmbedding({+ embedding: queryEmbeddings?.[0],+ limits,+ });++ return mapMemorySearchResult(layeredResults);+};++const getEmbeddingRuntime = async (jwtPayload: ClientSecretPayload) => {+ const agentRuntime = await initModelRuntimeWithUserPayload(ModelProvider.OpenAI, jwtPayload);+ const { model: embeddingModel } =+ getServerDefaultFilesConfig().embeddingModel || DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM;++ return { agentRuntime, embeddingModel };+};++const createEmbedder = (agentRuntime: any, embeddingModel: string) => {+ return async (value?: string | null): Promise<number[] | undefined> => {+ if (!value || value.trim().length === 0) return undefined;++ const embeddings = await agentRuntime.embeddings({+ dimensions: DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,+ input: value,+ model: embeddingModel,+ });++ return embeddings?.[0];+ };+};++const REEMBED_TABLE_KEYS = [+ 'userMemories',+ 'contexts',+ 'preferences',+ 'identities',+ 'experiences',+] as const;+type ReEmbedTableKey = (typeof REEMBED_TABLE_KEYS)[number];++const reEmbedInputSchema = z.object({+ concurrency: z.coerce.number().int().min(1).max(50).optional(),+ endDate: z.coerce.date().optional(),+ limit: z.coerce.number().int().min(1).optional(),+ only: z.array(z.enum(REEMBED_TABLE_KEYS)).optional(),+ startDate: z.coerce.date().optional(),+});++interface ReEmbedStats {+ failed: number;+ skipped: number;+ succeeded: number;+ total: number;+}++const combineConditions = (conditions: Array<SQL | undefined>): SQL | undefined => {+ const filtered = conditions.filter((condition): condition is SQL => condition !== undefined);+ if (filtered.length === 0) return undefined;+ if (filtered.length === 1) return filtered[0];++ return and(...filtered);+};++const normalizeEmbeddable = (value?: string | null): string | undefined => {+ if (typeof value !== 'string') return undefined;+ const trimmed = value.trim();++ return trimmed.length > 0 ? trimmed : undefined;+};++const memoryProcedure = authedProcedure+ .use(serverDatabase)+ .use(keyVaults)+ .use(async (opts) => {+ const { ctx } = opts;+ return opts.next({+ ctx: {+ memoryModel: new UserMemoryModel(ctx.serverDB, ctx.userId),+ },+ });+ });++export const userMemoriesRouter = router({+ getMemoryDetail: memoryProcedure+ .input(z.object({ id: z.string(), layer: z.nativeEnum(LayersEnum) }))+ .query(async ({ ctx, input }) => {+ try {+ return await ctx.memoryModel.getMemoryDetail(input);+ } catch (error) {+ console.error('Failed to retrieve memory detail:', error);+ return null;+ }+ }),++ queryIdentityRoles: memoryProcedure+ .input(+ z+ .object({+ page: z.coerce.number().int().min(1).optional(),+ size: z.coerce.number().int().min(1).max(100).optional(),+ })+ .optional(),+ )+ .query(async ({ ctx, input }) => {+ try {+ return await ctx.memoryModel.queryIdentityRoles(input ?? {});+ } catch (error) {+ console.error('Failed to query identity roles:', error);+ return { roles: [], tags: [] };+ }+ }),++ queryMemories: memoryProcedure+ .input(+ z+ .object({+ categories: z.array(z.string()).optional(),+ layer: z.nativeEnum(LayersEnum).optional(),+ order: z.enum(['asc', 'desc']).optional(),+ page: z.coerce.number().int().min(1).optional(),+ pageSize: z.coerce.number().int().min(1).max(100).optional(),+ q: z.string().optional(),+ sort: z+ .enum(['scoreConfidence', 'scoreImpact', 'scorePriority', 'scoreUrgency'])+ .optional(),+ tags: z.array(z.string()).optional(),+ types: z.array(z.string()).optional(),+ })+ .optional(),+ )+ .query(async ({ ctx, input }) => {+ const params = input ?? {};+ const fallbackPage = params.page ?? 1;+ const fallbackPageSize = params.pageSize ?? 20;++ try {+ return await ctx.memoryModel.queryMemories({+ ...params,+ order: params.order ?? 'desc',+ sort: params.sort,+ });+ } catch (error) {+ console.error('Failed to query memories:', error);+ return { items: [], page: fallbackPage, pageSize: fallbackPageSize, total: 0 };+ }+ }),++ queryTags: memoryProcedure+ .input(+ z+ .object({+ layers: z.array(z.nativeEnum(LayersEnum)).optional(),+ page: z.coerce.number().int().min(1).optional(),+ size: z.coerce.number().int().min(1).max(100).optional(),+ })+ .optional(),+ )+ .query(async ({ ctx, input }) => {+ try {+ return await ctx.memoryModel.queryTags(input ?? {});+ } catch (error) {+ console.error('Failed to query memory tags:', error);+ return [];+ }+ }),++ // REVIEW:根据当前 topic 直接提取记忆+ // REVIEW: 我们需要一个既可以 cron 也可以主动用户触发进行「每日/每周/每隔一段时间的」记忆提取/生成的函数实现+ // REVIEW: 定时任务+ // 不用 tRPC,直接 server/service+ // 可以参考 https://github.com/lobehub/lobe-chat-cloud/blob/886ff2fcd44b7b00a3aa8906f84914a6dcaa1815/src/app/(backend)/cron/reset-budgets/route.ts#L214+ reEmbedMemories: memoryProcedure+ .input(reEmbedInputSchema.optional())+ .mutation(async ({ ctx, input }) => {+ try {+ const options = input ?? {};+ const { agentRuntime, embeddingModel } = await getEmbeddingRuntime(ctx.jwtPayload);+ const concurrency = options.concurrency ?? 10;+ const shouldProcess = (key: ReEmbedTableKey) =>+ !options.only || options.only.length === 0 || options.only.includes(key);++ const embedTexts = async (texts: string[]): Promise<number[][]> => {+ if (texts.length === 0) return [];++ const response = await agentRuntime.embeddings({+ dimensions: DEFAULT_USER_MEMORY_EMBEDDING_DIMENSIONS,+ input: texts,+ model: embeddingModel,+ });++ if (!response || response.length !== texts.length) {+ throw new Error('Embedding response length mismatch');+ }++ return response;+ };++ const results: Partial<Record<ReEmbedTableKey, ReEmbedStats>> = {};++ const run = async (key: ReEmbedTableKey, handler: () => Promise<ReEmbedStats>) => {+ if (!shouldProcess(key)) return;+ results[key] = await handler();+ };++ // Individual re-embed handlers are appended below.+ await run('userMemories', async () => {+ const where = combineConditions([+ eq(userMemories.userId, ctx.userId),+ options.startDate ? gte(userMemories.createdAt, options.startDate) : undefined,+ options.endDate ? lte(userMemories.createdAt, options.endDate) : undefined,+ ]);++ const rows = await ctx.serverDB.query.userMemories.findMany({+ columns: { details: true, id: true, summary: true },+ limit: options.limit,+ orderBy: [asc(userMemories.createdAt)],+ where,+ });++ let succeeded = 0;+ let failed = 0;+ let skipped = 0;++ await pMap(+ rows,+ async (row) => {+ const summaryText = normalizeEmbeddable(row.summary);+ const detailsText = normalizeEmbeddable(row.details);++ try {+ if (!summaryText && !detailsText) {+ await ctx.memoryModel.updateUserMemoryVectors(row.id, {+ detailsVector1024: null,+ summaryVector1024: null,+ });+ skipped += 1;+ return;+ }++ const inputs: string[] = [];+ if (summaryText) inputs.push(summaryText);+ if (detailsText) inputs.push(detailsText);++ const embeddings = await embedTexts(inputs);+ let embedIndex = 0;++ const summaryVector = summaryText ? (embeddings[embedIndex++] ?? null) : null;+ const detailsVector = detailsText ? (embeddings[embedIndex++] ?? null) : null;++ await ctx.memoryModel.updateUserMemoryVectors(row.id, {+ detailsVector1024: detailsVector,+ summaryVector1024: summaryVector,+ });++ succeeded += 1;+ } catch (err) {+ failed += 1;+ console.error(+ `[memoryRouter.reEmbed] Failed to re-embed user memory ${row.id}`,+ err,+ );+ }+ },+ { concurrency },+ );++ return {+ failed,+ skipped,+ succeeded,+ total: rows.length,+ } satisfies ReEmbedStats;+ });++ await run('contexts', async () => {+ const where = combineConditions([+ eq(userMemoriesContexts.userId, ctx.userId),+ options.startDate ? gte(userMemoriesContexts.createdAt, options.startDate) : undefined,+ options.endDate ? lte(userMemoriesContexts.createdAt, options.endDate) : undefined,+ ]);++ const rows = await ctx.serverDB.query.userMemoriesContexts.findMany({+ columns: { description: true, id: true },+ limit: options.limit,+ orderBy: [asc(userMemoriesContexts.createdAt)],+ where,+ });++ let succeeded = 0;+ let failed = 0;+ let skipped = 0;++ await pMap(+ rows,+ async (row) => {+ const description = normalizeEmbeddable(row.description);++ try {+ if (!description) {+ await ctx.memoryModel.updateContextVectors(row.id, {+ descriptionVector: null,+ });+ skipped += 1;+ return;+ }++ const [embedding] = await embedTexts([description]);++ await ctx.memoryModel.updateContextVectors(row.id, {+ descriptionVector: embedding ?? null,+ });+ succeeded += 1;+ } catch (err) {+ failed += 1;+ console.error(`[memoryRouter.reEmbed] Failed to re-embed context ${row.id}`, err);+ }+ },+ { concurrency },+ );++ return {+ failed,+ skipped,+ succeeded,+ total: rows.length,+ } satisfies ReEmbedStats;+ });++ await run('preferences', async () => {+ const where = combineConditions([+ eq(userMemoriesPreferences.userId, ctx.userId),+ options.startDate+ ? gte(userMemoriesPreferences.createdAt, options.startDate)+ : undefined,+ options.endDate ? lte(userMemoriesPreferences.createdAt, options.endDate) : undefined,+ ]);++ const rows = await ctx.serverDB.query.userMemoriesPreferences.findMany({+ columns: { conclusionDirectives: true, id: true },+ limit: options.limit,+ orderBy: [asc(userMemoriesPreferences.createdAt)],+ where,+ });++ let succeeded = 0;+ let failed = 0;+ let skipped = 0;++ await pMap(+ rows,+ async (row) => {+ const directives = normalizeEmbeddable(row.conclusionDirectives);++ try {+ if (!directives) {+ await ctx.memoryModel.updatePreferenceVectors(row.id, {+ conclusionDirectivesVector: null,+ });+ skipped += 1;+ return;+ }++ const [embedding] = await embedTexts([directives]);+ await ctx.memoryModel.updatePreferenceVectors(row.id, {+ conclusionDirectivesVector: embedding ?? null,+ });+ succeeded += 1;+ } catch (err) {+ failed += 1;+ console.error(+ `[memoryRouter.reEmbed] Failed to re-embed preference ${row.id}`,+ err,+ );+ }+ },+ { concurrency },+ );++ return {+ failed,+ skipped,+ succeeded,+ total: rows.length,+ } satisfies ReEmbedStats;+ });++ await run('identities', async () => {+ const where = combineConditions([+ eq(userMemoriesIdentities.userId, ctx.userId),+ options.startDate+ ? gte(userMemoriesIdentities.createdAt, options.startDate)+ : undefined,+ options.endDate ? lte(userMemoriesIdentities.createdAt, options.endDate) : undefined,+ ]);++ const rows = await ctx.serverDB.query.userMemoriesIdentities.findMany({+ columns: { description: true, id: true },+ limit: options.limit,+ orderBy: [asc(userMemoriesIdentities.createdAt)],+ where,+ });++ let succeeded = 0;+ let failed = 0;+ let skipped = 0;++ await pMap(+ rows,+ async (row) => {+ const description = normalizeEmbeddable(row.description);++ try {+ if (!description) {+ await ctx.memoryModel.updateIdentityVectors(row.id, {+ descriptionVector: null,+ });+ skipped += 1;+ return;+ }++ const [embedding] = await embedTexts([description]);+ await ctx.memoryModel.updateIdentityVectors(row.id, {+ descriptionVector: embedding ?? null,+ });+ succeeded += 1;+ } catch (err) {+ failed += 1;+ console.error(`[memoryRouter.reEmbed] Failed to re-embed identity ${row.id}`, err);+ }+ },+ { concurrency },+ );++ return {+ failed,+ skipped,+ succeeded,+ total: rows.length,+ } satisfies ReEmbedStats;+ });++ await run('experiences', async () => {+ const where = combineConditions([+ eq(userMemoriesExperiences.userId, ctx.userId),+ options.startDate+ ? gte(userMemoriesExperiences.createdAt, options.startDate)+ : undefined,+ options.endDate ? lte(userMemoriesExperiences.createdAt, options.endDate) : undefined,+ ]);++ const rows = await ctx.serverDB.query.userMemoriesExperiences.findMany({+ columns: { action: true, id: true, keyLearning: true, situation: true },+ limit: options.limit,+ orderBy: [asc(userMemoriesExperiences.createdAt)],+ where,+ });++ let succeeded = 0;+ let failed = 0;+ let skipped = 0;++ await pMap(+ rows,+ async (row) => {+ const situation = normalizeEmbeddable(row.situation);+ const action = normalizeEmbeddable(row.action);+ const keyLearning = normalizeEmbeddable(row.keyLearning);++ try {+ if (!situation && !action && !keyLearning) {+ await ctx.memoryModel.updateExperienceVectors(row.id, {+ actionVector: null,+ keyLearningVector: null,+ situationVector: null,+ });+ skipped += 1;+ return;+ }++ const inputs: string[] = [];+ if (situation) inputs.push(situation);+ if (action) inputs.push(action);+ if (keyLearning) inputs.push(keyLearning);++ const embeddings = await embedTexts(inputs);+ let embedIndex = 0;++ const situationVector = situation ? (embeddings[embedIndex++] ?? null) : null;+ const actionVector = action ? (embeddings[embedIndex++] ?? null) : null;+ const keyLearningVector = keyLearning ? (embeddings[embedIndex++] ?? null) : null;++ await ctx.memoryModel.updateExperienceVectors(row.id, {+ actionVector,+ keyLearningVector,+ situationVector,+ });+ succeeded += 1;+ } catch (err) {+ failed += 1;+ console.error(+ `[memoryRouter.reEmbed] Failed to re-embed experience ${row.id}`,+ err,+ );+ }+ },+ { concurrency },+ );++ return {+ failed,+ skipped,+ succeeded,+ total: rows.length,+ } satisfies ReEmbedStats;+ });++ const processedEntries = Object.entries(results) as Array<[ReEmbedTableKey, ReEmbedStats]>;++ if (processedEntries.length === 0) {+ return {+ message: 'No memory records matched re-embed criteria',+ results,+ success: true,+ };+ }++ const aggregate = processedEntries.reduce(+ (acc, [, stats]) => {+ acc.failed += stats.failed;+ acc.skipped += stats.skipped;+ acc.succeeded += stats.succeeded;+ acc.total += stats.total;++ return acc;+ },+ { failed: 0, skipped: 0, succeeded: 0, total: 0 },+ );++ const message =+ aggregate.total === 0+ ? 'No memory records required re-embedding'+ : `Re-embedded ${aggregate.succeeded} of ${aggregate.total} records`;++ return {+ aggregate,+ message,+ results,+ success: true,+ };+ } catch (error) {+ console.error('Failed to re-embed memories:', error);+ return {+ message: `Failed to re-embed memories: ${(error as Error).message}`,+ success: false,+ };+ }+ }),++ searchMemory: memoryProcedure.input(searchMemorySchema).query(async ({ input, ctx }) => {+ try {+ return await searchUserMemories(ctx, input);+ } catch (error) {+ console.error('Failed to retrieve memories:', error);+ return EMPTY_SEARCH_RESULT;+ }+ }),++ // REVIEW: 需要实现 tool memory api+ toolAddContextMemory: memoryProcedure+ .input(ContextMemoryItemSchema)+ .mutation(async ({ input, ctx }) => {+ try {+ const { agentRuntime, embeddingModel } = await getEmbeddingRuntime(ctx.jwtPayload);+ const embed = createEmbedder(agentRuntime, embeddingModel);++ const summaryEmbedding = await embed(input.summary);+ const detailsEmbedding = await embed(input.details);+ const contextDescriptionEmbedding = await embed(input.withContext.description);++ const { context, memory } = await ctx.memoryModel.createContextMemory({+ context: {+ associatedObjects:+ UserMemoryModel.parseAssociatedObjects(input.withContext.associatedObjects) ?? null,+ associatedSubjects:+ UserMemoryModel.parseAssociatedSubjects(input.withContext.associatedSubjects) ?? null,+ currentStatus: input.withContext.currentStatus ?? null,+ description: input.withContext.description ?? null,+ descriptionVector: contextDescriptionEmbedding ?? null,+ metadata: {},+ scoreImpact: input.withContext.scoreImpact ?? null,+ scoreUrgency: input.withContext.scoreUrgency ?? null,+ tags: input.tags ?? [],+ title: input.withContext.title ?? null,+ type: input.withContext.type ?? null,+ },+ details: input.details || '',+ detailsEmbedding,+ memoryCategory: input.memoryCategory,+ memoryLayer: input.memoryLayer,+ memoryType: input.memoryType,+ summary: input.summary,+ summaryEmbedding,+ title: input.title,+ });++ return {+ contextId: context.id,+ memoryId: memory.id,+ message: 'Memory saved successfully',+ success: true,+ };+ } catch (error) {+ console.error('Failed to save memory:', error);+ return {+ message: `Failed to save memory: ${(error as Error).message}`,+ success: false,+ };+ }+ }),++ toolAddExperienceMemory: memoryProcedure+ .input(ExperienceMemoryItemSchema)+ .mutation(async ({ input, ctx }) => {+ try {+ const { agentRuntime, embeddingModel } = await getEmbeddingRuntime(ctx.jwtPayload);+ const embed = createEmbedder(agentRuntime, embeddingModel);++ const summaryEmbedding = await embed(input.summary);+ const detailsEmbedding = await embed(input.details);+ const situationVector = await embed(input.withExperience.situation);+ const actionVector = await embed(input.withExperience.action);+ const keyLearningVector = await embed(input.withExperience.keyLearning);++ const { experience, memory } = await ctx.memoryModel.createExperienceMemory({+ details: input.details || '',+ detailsEmbedding,+ experience: {+ action: input.withExperience.action ?? null,+ actionVector: actionVector ?? null,+ keyLearning: input.withExperience.keyLearning ?? null,+ keyLearningVector: keyLearningVector ?? null,+ metadata: {},+ possibleOutcome: input.withExperience.possibleOutcome ?? null,+ reasoning: input.withExperience.reasoning ?? null,+ scoreConfidence: input.withExperience.scoreConfidence ?? null,+ situation: input.withExperience.situation ?? null,+ situationVector: situationVector ?? null,+ tags: input.tags ?? [],+ type: input.memoryType,+ },+ memoryCategory: input.memoryCategory,+ memoryLayer: input.memoryLayer,+ memoryType: input.memoryType,+ summary: input.summary,+ summaryEmbedding,+ title: input.title,+ });++ return {+ experienceId: experience.id,+ memoryId: memory.id,+ message: 'Memory saved successfully',+ success: true,+ };+ } catch (error) {+ console.error('Failed to save memory:', error);+ return {+ message: `Failed to save memory: ${(error as Error).message}`,+ success: false,+ };+ }+ }),++ toolAddIdentityMemory: memoryProcedure+ .input(AddIdentityActionSchema)+ .mutation(async ({ input, ctx }) => {+ try {+ const { agentRuntime, embeddingModel } = await getEmbeddingRuntime(ctx.jwtPayload);+ const embed = createEmbedder(agentRuntime, embeddingModel);++ const summaryEmbedding = await embed(input.summary);+ const detailsEmbedding = await embed(input.details);+ const descriptionEmbedding = await embed(input.withIdentity.description);++ const identityMetadata: Record<string, unknown> = {};+ if (+ input.withIdentity.scoreConfidence !== null &&+ input.withIdentity.scoreConfidence !== undefined+ ) {+ identityMetadata.scoreConfidence = input.withIdentity.scoreConfidence;+ }+ if (+ input.withIdentity.sourceEvidence !== null &&+ input.withIdentity.sourceEvidence !== undefined+ ) {+ identityMetadata.sourceEvidence = input.withIdentity.sourceEvidence;+ }++ const { identityId, userMemoryId } = await ctx.memoryModel.addIdentityEntry({+ base: {+ details: input.details,+ detailsVector1024: detailsEmbedding ?? null,+ memoryCategory: input.memoryCategory,+ memoryLayer: input.memoryLayer,+ memoryType: input.memoryType,+ metadata: Object.keys(identityMetadata).length > 0 ? identityMetadata : undefined,+ summary: input.summary,+ summaryVector1024: summaryEmbedding ?? null,+ tags: input.tags,+ title: input.title,+ },+ identity: {+ description: input.withIdentity.description,+ descriptionVector: descriptionEmbedding ?? null,+ episodicDate: input.withIdentity.episodicDate,+ metadata: Object.keys(identityMetadata).length > 0 ? identityMetadata : undefined,+ relationship: input.withIdentity.relationship,+ role: input.withIdentity.role,+ tags: input.tags,+ type: input.withIdentity.type,+ },+ });++ return {+ identityId,+ memoryId: userMemoryId,+ message: 'Identity memory saved successfully',+ success: true,+ };+ } catch (error) {+ console.error('Failed to save identity memory:', error);+ return {+ message: `Failed to save identity memory: ${(error as Error).message}`,+ success: false,+ };+ }+ }),++ toolAddPreferenceMemory: memoryProcedure+ .input(PreferenceMemoryItemSchema)+ .mutation(async ({ input, ctx }) => {+ try {+ const { agentRuntime, embeddingModel } = await getEmbeddingRuntime(ctx.jwtPayload);+ const embed = createEmbedder(agentRuntime, embeddingModel);++ const summaryEmbedding = await embed(input.summary);+ const detailsEmbedding = await embed(input.details);+ const conclusionVector = await embed(input.withPreference.conclusionDirectives);++ const suggestionsText =+ input.withPreference?.suggestions?.length && input.withPreference?.suggestions?.length > 0+ ? input.withPreference?.suggestions?.join('\n')+ : null;++ const metadata = {+ appContext: input.withPreference.appContext,+ extractedScopes: input.withPreference.extractedScopes,+ originContext: input.withPreference.originContext,+ } satisfies Record<string, unknown>;++ const { memory, preference } = await ctx.memoryModel.createPreferenceMemory({+ details: input.details || '',+ detailsEmbedding,+ memoryCategory: input.memoryCategory,+ memoryLayer: input.memoryLayer,+ memoryType: input.memoryType,+ preference: {+ conclusionDirectives: input.withPreference.conclusionDirectives || '',+ conclusionDirectivesVector: conclusionVector ?? null,+ metadata,+ scorePriority: input.withPreference.scorePriority ?? null,+ suggestions: suggestionsText,+ tags: input.tags,+ type: input.memoryType,+ },+ summary: input.summary,+ summaryEmbedding,+ title: input.title,+ });++ return {+ memoryId: memory.id,+ message: 'Memory saved successfully',+ preferenceId: preference.id,+ success: true,+ };+ } catch (error) {+ console.error('Failed to save memory:', error);+ return {+ message: `Failed to save memory: ${(error as Error).message}`,+ success: false,+ };+ }+ }),++ toolRemoveIdentityMemory: memoryProcedure+ .input(RemoveIdentityActionSchema)+ .mutation(async ({ input, ctx }) => {+ try {+ const removed = await ctx.memoryModel.removeIdentityEntry(input.id);++ if (!removed) {+ return {+ message: 'Identity memory not found',+ success: false,+ };+ }++ return {+ identityId: input.id,+ message: 'Identity memory removed successfully',+ reason: input.reason,+ success: true,+ };+ } catch (error) {+ console.error('Failed to remove identity memory:', error);+ return {+ message: `Failed to remove identity memory: ${(error as Error).message}`,+ success: false,+ };+ }+ }),++ toolSearchMemory: memoryProcedure.input(searchMemorySchema).query(async ({ input, ctx }) => {+ const result = await searchUserMemories(ctx, input);+ return result;+ }),++ toolUpdateIdentityMemory: memoryProcedure+ .input(UpdateIdentityActionSchema)+ .mutation(async ({ input, ctx }) => {+ try {+ const { agentRuntime, embeddingModel } = await getEmbeddingRuntime(ctx.jwtPayload);+ const embed = createEmbedder(agentRuntime, embeddingModel);++ let summaryVector1024: number[] | null | undefined;+ if (input.set.summary !== undefined) {+ const vector = await embed(input.set.summary);+ summaryVector1024 = vector ?? null;+ }++ let detailsVector1024: number[] | null | undefined;+ if (input.set.details !== undefined) {+ const vector = await embed(input.set.details);+ detailsVector1024 = vector ?? null;+ }++ let descriptionVector: number[] | null | undefined;+ if (input.set.withIdentity.description !== undefined) {+ const vector = await embed(input.set.withIdentity.description);+ descriptionVector = vector ?? null;+ }++ const metadataUpdates: Record<string, unknown> = {};+ if (Object.hasOwn(input.set.withIdentity, 'scoreConfidence')) {+ metadataUpdates.scoreConfidence = input.set.withIdentity.scoreConfidence ?? null;+ }+ if (Object.hasOwn(input.set.withIdentity, 'sourceEvidence')) {+ metadataUpdates.sourceEvidence = input.set.withIdentity.sourceEvidence ?? null;+ }++ const identityPayload: Partial<IdentityEntryPayload> = {};+ if (input.set.withIdentity.description !== undefined) {+ identityPayload.description = input.set.withIdentity.description;+ identityPayload.descriptionVector = descriptionVector;+ }+ if (input.set.withIdentity.episodicDate !== undefined) {+ identityPayload.episodicDate = input.set.withIdentity.episodicDate;+ }+ if (input.set.withIdentity.relationship !== undefined) {+ identityPayload.relationship = input.set.withIdentity.relationship;+ }+ if (input.set.withIdentity.role !== undefined) {+ identityPayload.role = input.set.withIdentity.role;+ }+ if (input.set.tags !== undefined) {+ identityPayload.tags = input.set.tags;+ }+ if (input.set.withIdentity.type !== undefined) {+ identityPayload.type = input.set.withIdentity.type;+ }+ if (Object.keys(metadataUpdates).length > 0) {+ identityPayload.metadata = metadataUpdates;+ }++ const basePayload: Partial<IdentityEntryBasePayload> = {};+ if (input.set.details !== undefined) {+ basePayload.details = input.set.details;+ basePayload.detailsVector1024 = detailsVector1024;+ }+ if (input.set.memoryCategory !== undefined) {+ basePayload.memoryCategory = input.set.memoryCategory;+ }+ if (input.set.memoryType !== undefined) {+ basePayload.memoryType = input.set.memoryType;+ }+ if (input.set.summary !== undefined) {+ basePayload.summary = input.set.summary;+ basePayload.summaryVector1024 = summaryVector1024;+ }+ if (input.set.tags !== undefined) {+ basePayload.tags = input.set.tags;+ }+ if (input.set.title !== undefined) {+ basePayload.title = input.set.title;+ }+ if (Object.keys(metadataUpdates).length > 0) {+ basePayload.metadata = metadataUpdates;+ }++ const updated = await ctx.memoryModel.updateIdentityEntry({+ base: Object.keys(basePayload).length > 0 ? basePayload : undefined,+ identity: Object.keys(identityPayload).length > 0 ? identityPayload : undefined,+ identityId: input.id,+ mergeStrategy: input.mergeStrategy,+ });++ if (!updated) {+ return {+ message: 'Identity memory not found',+ success: false,+ };+ }++ return {+ identityId: input.id,+ message: 'Identity memory updated successfully',+ success: true,+ };+ } catch (error) {+ console.error('Failed to update identity memory:', error);+ return {+ message: `Failed to update identity memory: ${(error as Error).message}`,+ success: false,+ };+ }+ }),+});diff --git a/src/server/routers/lambda/userMemory.ts b/src/server/routers/lambda/userMemory.tsnew file mode 100644index 00000000000..36669b3cb11--- /dev/null+++ b/src/server/routers/lambda/userMemory.ts@@ -0,0 +1,156 @@+import { CreateUserMemoryIdentitySchema, UpdateUserMemoryIdentitySchema } from '@lobechat/types';+import { z } from 'zod';++import { UserMemoryModel } from '@/database/models/userMemory';+import {+ UserMemoryContextModel,+ UserMemoryExperienceModel,+ UserMemoryIdentityModel,+ UserMemoryPreferenceModel,+} from '@/database/models/userMemory/index';+import { authedProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';++const userMemoryProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;++ return opts.next({+ ctx: {+ contextModel: new UserMemoryContextModel(ctx.serverDB, ctx.userId),+ experienceModel: new UserMemoryExperienceModel(ctx.serverDB, ctx.userId),+ identityModel: new UserMemoryIdentityModel(ctx.serverDB, ctx.userId),+ preferenceModel: new UserMemoryPreferenceModel(ctx.serverDB, ctx.userId),+ userMemoryModel: new UserMemoryModel(ctx.serverDB, ctx.userId),+ },+ });+});++export const userMemoryRouter = router({+ // ============ Identity CRUD ============++ createIdentity: userMemoryProcedure+ .input(CreateUserMemoryIdentitySchema)+ .mutation(async ({ ctx, input }) => {+ return ctx.userMemoryModel.addIdentityEntry({+ base: {},+ identity: {+ description: input.description,+ episodicDate: input.episodicDate,+ relationship: input.relationship,+ role: input.role,+ tags: input.extractedLabels,+ type: input.type,+ },+ });+ }),++ // ============ Context CRUD ============+ deleteContext: userMemoryProcedure+ .input(z.object({ id: z.string() }))+ .mutation(async ({ ctx, input }) => {+ return ctx.contextModel.delete(input.id);+ }),++ // ============ Experience CRUD ============+ deleteExperience: userMemoryProcedure+ .input(z.object({ id: z.string() }))+ .mutation(async ({ ctx, input }) => {+ return ctx.experienceModel.delete(input.id);+ }),++ deleteIdentity: userMemoryProcedure+ .input(z.object({ id: z.string() }))+ .mutation(async ({ ctx, input }) => {+ return ctx.userMemoryModel.removeIdentityEntry(input.id);+ }),++ // ============ Preference CRUD ============+ deletePreference: userMemoryProcedure+ .input(z.object({ id: z.string() }))+ .mutation(async ({ ctx, input }) => {+ return ctx.preferenceModel.delete(input.id);+ }),++ getContexts: userMemoryProcedure.query(async ({ ctx }) => {+ return ctx.userMemoryModel.searchContexts({});+ }),++ getExperiences: userMemoryProcedure.query(async ({ ctx }) => {+ return ctx.userMemoryModel.searchExperiences({});+ }),++ getIdentities: userMemoryProcedure.query(async ({ ctx }) => {+ return ctx.userMemoryModel.getAllIdentities();+ }),++ getPreferences: userMemoryProcedure.query(async ({ ctx }) => {+ return ctx.userMemoryModel.searchPreferences({});+ }),++ updateContext: userMemoryProcedure+ .input(+ z.object({+ data: z.object({+ currentStatus: z.string().optional(),+ description: z.string().optional(),+ title: z.string().optional(),+ }),+ id: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ return ctx.contextModel.update(input.id, input.data);+ }),++ updateExperience: userMemoryProcedure+ .input(+ z.object({+ data: z.object({+ action: z.string().optional(),+ keyLearning: z.string().optional(),+ situation: z.string().optional(),+ }),+ id: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ return ctx.experienceModel.update(input.id, input.data);+ }),++ updateIdentity: userMemoryProcedure+ .input(+ z.object({+ data: UpdateUserMemoryIdentitySchema,+ id: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ return ctx.userMemoryModel.updateIdentityEntry({+ identity: {+ description: input.data.description,+ episodicDate: input.data.episodicDate,+ relationship: input.data.relationship,+ role: input.data.role,+ tags: input.data.extractedLabels,+ type: input.data.type,+ },+ identityId: input.id,+ });+ }),++ updatePreference: userMemoryProcedure+ .input(+ z.object({+ data: z.object({+ conclusionDirectives: z.string().optional(),+ suggestions: z.string().optional(),+ }),+ id: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ return ctx.preferenceModel.update(input.id, input.data);+ }),+});++export type UserMemoryRouter = typeof userMemoryRouter;diff --git a/src/server/services/file/impls/s3.test.ts b/src/server/services/file/impls/s3.test.tsindex 32acf0ec02e..8771dbc2576 100644--- a/src/server/services/file/impls/s3.test.ts+++ b/src/server/services/file/impls/s3.test.ts@@ -18,7 +18,7 @@ vi.mock('@/envs/file', () => ({// 模拟 S3 类vi.mock('@/server/modules/S3', () => ({- S3: vi.fn().mockImplementation(() => ({+ FileS3: vi.fn().mockImplementation(() => ({createPreSignedUrlForPreview: vi.fn().mockResolvedValue('https://presigned.example.com/test.jpg'),diff --git a/src/server/services/file/impls/s3.ts b/src/server/services/file/impls/s3.tsindex 72de8af80a6..dde984fdd3f 100644--- a/src/server/services/file/impls/s3.ts+++ b/src/server/services/file/impls/s3.ts@@ -1,7 +1,7 @@import urlJoin from 'url-join';import { fileEnv } from '@/envs/file';-import { S3 } from '@/server/modules/S3';+import { FileS3 } from '@/server/modules/S3';import { FileServiceImpl } from './type';import { extractKeyFromUrlOrReturnOriginal } from './utils';@@ -10,10 +10,10 @@ import { extractKeyFromUrlOrReturnOriginal } from './utils';* S3-based file service implementation*/export class S3StaticFileImpl implements FileServiceImpl {- private readonly s3: S3;+ private readonly s3: FileS3;constructor() {- this.s3 = new S3();+ this.s3 = new FileS3();}async deleteFile(key: string) {