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(server/toolExecution): support server-owned memory embedding runtime (#14754)

Neko8618699888dd
diff --git a/src/server/services/toolExecution/serverRuntimes/__tests__/memory.test.ts b/src/server/services/toolExecution/serverRuntimes/__tests__/memory.test.ts
new file mode 100644
index 00000000000..a32189ffedf
--- /dev/null
+++ b/src/server/services/toolExecution/serverRuntimes/__tests__/memory.test.ts
@@ -0,0 +1,104 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { ToolExecutionContext } from '../../types';
+
+const mocks = vi.hoisted(() => ({
+ embeddings: vi.fn(),
+ initModelRuntimeFromDB: vi.fn(),
+ initModelRuntimeWithUserPayload: vi.fn(),
+ searchMemory: vi.fn(),
+}));
+
+vi.mock('@/database/models/userMemory', () => ({
+ UserMemoryModel: vi.fn().mockImplementation(() => ({
+ searchMemory: mocks.searchMemory,
+ })),
+}));
+
+vi.mock('@/database/schemas', () => ({
+ userSettings: { id: 'id' },
+}));
+
+vi.mock('@/server/globalConfig', () => ({
+ getServerDefaultFilesConfig: vi.fn(() => ({
+ embeddingModel: { model: 'default-embedding-model', provider: 'default-provider' },
+ })),
+}));
+
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: mocks.initModelRuntimeFromDB,
+ initModelRuntimeWithUserPayload: mocks.initModelRuntimeWithUserPayload,
+}));
+
+vi.mock('@/server/services/agentSignal/procedure', () => ({
+ emitToolOutcomeSafely: vi.fn(),
+ resolveToolOutcomeScope: vi.fn(() => ({ scope: 'user', scopeKey: 'user-1' })),
+}));
+
+vi.mock('@/server/services/agentSignal/store/adapters/redis/policyStateStore', () => ({
+ redisPolicyStateStore: {},
+}));
+
+const { memoryRuntime } = await import('../memory');
+
+const createContext = (): ToolExecutionContext => ({
+ memoryEmbeddingRuntime: {
+ model: 'server-embedding-model',
+ payload: {
+ apiKey: 'server-key',
+ baseURL: 'https://embedding.example.com/v1',
+ },
+ provider: 'server-provider',
+ },
+ serverDB: {
+ query: {
+ userSettings: {
+ findFirst: vi.fn(async () => undefined),
+ },
+ },
+ } as unknown as LobeChatDatabase,
+ toolManifestMap: {},
+ userId: 'synthetic-user',
+});
+
+describe('memoryRuntime', () => {
+ it('uses server-owned embedding runtime for memory search', async () => {
+ mocks.embeddings.mockResolvedValueOnce([[0.1, 0.2, 0.3]]);
+ mocks.initModelRuntimeWithUserPayload.mockReturnValueOnce({
+ embeddings: mocks.embeddings,
+ });
+ mocks.searchMemory.mockResolvedValueOnce({
+ activities: [],
+ contexts: [],
+ experiences: [],
+ identities: [],
+ preferences: [],
+ });
+
+ const runtime = await memoryRuntime.factory(createContext());
+
+ await runtime.searchUserMemory({ queries: ['renewal timeline'] });
+
+ expect(mocks.initModelRuntimeWithUserPayload).toHaveBeenCalledWith(
+ 'server-provider',
+ {
+ apiKey: 'server-key',
+ baseURL: 'https://embedding.example.com/v1',
+ },
+ { userId: 'synthetic-user' },
+ );
+ expect(mocks.initModelRuntimeFromDB).not.toHaveBeenCalled();
+ expect(mocks.embeddings).toHaveBeenCalledWith(
+ expect.objectContaining({
+ input: ['renewal timeline'],
+ model: 'server-embedding-model',
+ }),
+ expect.objectContaining({ user: 'synthetic-user' }),
+ );
+ expect(mocks.searchMemory).toHaveBeenCalledWith(
+ expect.objectContaining({ queries: ['renewal timeline'] }),
+ [[0.1, 0.2, 0.3]],
+ );
+ });
+});
diff --git a/src/server/services/toolExecution/serverRuntimes/memory.ts b/src/server/services/toolExecution/serverRuntimes/memory.ts
index 3e4c6dd5618..b44f4b19cd1 100644
--- a/src/server/services/toolExecution/serverRuntimes/memory.ts
+++ b/src/server/services/toolExecution/serverRuntimes/memory.ts
@@ -43,7 +43,10 @@ import {
} from '@/database/models/userMemory';
import { userSettings } from '@/database/schemas';
import { getServerDefaultFilesConfig } from '@/server/globalConfig';
-import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
+import {
+ initModelRuntimeFromDB,
+ initModelRuntimeWithUserPayload,
+} from '@/server/modules/ModelRuntime';
import {
emitToolOutcomeSafely,
resolveToolOutcomeScope,
@@ -51,6 +54,7 @@ import {
import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';
import { normalizeSearchMemoryParams } from '@/server/services/memory/userMemory/searchParams';
+import type { ToolExecutionMemoryEmbeddingRuntime } from '../types';
import type { ServerRuntimeRegistration } from './types';
type MemoryEffort = 'high' | 'low' | 'medium';
@@ -123,6 +127,7 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {
private toolCallId?: string;
private topicId?: string;
private memoryEffort: MemoryEffort;
+ private memoryEmbeddingRuntime?: ToolExecutionMemoryEmbeddingRuntime;
private userId: string;
constructor(options: {
@@ -130,6 +135,7 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {
emitOutcome?: typeof emitToolOutcomeSafely;
messageId?: string;
memoryEffort: MemoryEffort;
+ memoryEmbeddingRuntime?: ToolExecutionMemoryEmbeddingRuntime;
memoryModel: UserMemoryModel;
operationId?: string;
serverDB: LobeChatDatabase;
@@ -148,6 +154,7 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {
this.toolCallId = options.toolCallId;
this.topicId = options.topicId;
this.memoryEffort = options.memoryEffort;
+ this.memoryEmbeddingRuntime = options.memoryEmbeddingRuntime;
this.userId = options.userId;
}
@@ -192,10 +199,16 @@ class MemoryServerRuntimeService implements MemoryRuntimeService {
searchMemory = async (params: SearchMemoryParams): Promise<SearchMemoryResult> => {
const normalizedParams = normalizeSearchMemoryParams(params);
- const { provider, model: embeddingModel } =
+ const defaultEmbeddingConfig =
getServerDefaultFilesConfig().embeddingModel || DEFAULT_USER_MEMORY_EMBEDDING_MODEL_ITEM;
-
- const modelRuntime = await initModelRuntimeFromDB(this.serverDB, this.userId, provider);
+ const embeddingModel = this.memoryEmbeddingRuntime?.model ?? defaultEmbeddingConfig.model;
+ const modelRuntime = this.memoryEmbeddingRuntime
+ ? initModelRuntimeWithUserPayload(
+ this.memoryEmbeddingRuntime.provider,
+ this.memoryEmbeddingRuntime.payload,
+ { userId: this.userId },
+ )
+ : await initModelRuntimeFromDB(this.serverDB, this.userId, defaultEmbeddingConfig.provider);
const normalizedQueries = [
...new Set((normalizedParams.queries ?? []).map((query) => query.trim()).filter(Boolean)),
];
@@ -847,6 +860,7 @@ export const memoryRuntime: ServerRuntimeRegistration = {
emitOutcome: emitToolOutcomeSafely,
messageId: context.messageId,
memoryEffort,
+ memoryEmbeddingRuntime: context.memoryEmbeddingRuntime,
memoryModel,
operationId: context.operationId,
serverDB: context.serverDB,
diff --git a/src/server/services/toolExecution/types.ts b/src/server/services/toolExecution/types.ts
index e225be9e4e1..5f1a6056744 100644
--- a/src/server/services/toolExecution/types.ts
+++ b/src/server/services/toolExecution/types.ts
@@ -1,6 +1,15 @@
import { type LobeToolManifest } from '@lobechat/context-engine';
import { type LobeChatDatabase } from '@lobechat/database';
-import { type ChatToolPayload } from '@lobechat/types';
+import { type ChatToolPayload, type ClientSecretPayload } from '@lobechat/types';
+
+export interface ToolExecutionMemoryEmbeddingRuntime {
+ /** Embedding model id used by the memory search runtime. */
+ model: string;
+ /** Provider credentials/config supplied by the trusted server caller. */
+ payload: ClientSecretPayload;
+ /** Model provider used to initialize the embedding runtime. */
+ provider: string;
+}
export interface ToolExecutionContext {
/** Target device ID for device proxy tool calls */
@@ -11,6 +20,12 @@ export interface ToolExecutionContext {
documentId?: string | null;
/** Current group ID for group chat context */
groupId?: string | null;
+ /**
+ * Optional server-owned embedding runtime for memory search.
+ *
+ * Use when the acting user is synthetic and should not read user key vaults.
+ */
+ memoryEmbeddingRuntime?: ToolExecutionMemoryEmbeddingRuntime;
/** Memory tool permission from agent chat config */
memoryToolPermission?: 'read-only' | 'read-write';
/** Source user message ID used by Agent Signal procedure suppression. */