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.

🔧 chore: update config

arvinxx96c1379e9c20
diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.ts
index 9c1818b0675..82180085bec 100644
--- a/packages/database/src/models/__tests__/agent.test.ts
+++ b/packages/database/src/models/__tests__/agent.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { INBOX_SESSION_ID } from '@lobechat/const';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -79,10 +80,10 @@ describe('AgentModel', () => {
const result = await agentModel.getAgentConfigById(agentId);
- expect(result).toBeDefined();
- expect(result.id).toBe(agentId);
- expect(result.knowledgeBases).toHaveLength(1);
- expect(result.files).toHaveLength(1);
+ expect(result).not.toBeNull();
+ expect(result!.id).toBe(agentId);
+ expect(result!.knowledgeBases).toHaveLength(1);
+ expect(result!.files).toHaveLength(1);
});
it('should fetch and include document content for enabled files', async () => {
@@ -103,10 +104,10 @@ describe('AgentModel', () => {
const result = await agentModel.getAgentConfigById(agentId);
- expect(result).toBeDefined();
- expect(result.files).toHaveLength(1);
- expect(result.files[0].content).toBe('This is document content');
- expect(result.files[0].enabled).toBe(true);
+ expect(result).not.toBeNull();
+ expect(result!.files).toHaveLength(1);
+ expect(result!.files[0].content).toBe('This is document content');
+ expect(result!.files[0].enabled).toBe(true);
});
it('should not include content for disabled files', async () => {
@@ -127,10 +128,10 @@ describe('AgentModel', () => {
const result = await agentModel.getAgentConfigById(agentId);
- expect(result).toBeDefined();
- expect(result.files).toHaveLength(1);
- expect(result.files[0].content).toBeUndefined();
- expect(result.files[0].enabled).toBe(false);
+ expect(result).not.toBeNull();
+ expect(result!.files).toHaveLength(1);
+ expect(result!.files[0].content).toBeUndefined();
+ expect(result!.files[0].enabled).toBe(false);
});
it('should handle files without documents', async () => {
@@ -140,9 +141,9 @@ describe('AgentModel', () => {
const result = await agentModel.getAgentConfigById(agentId);
- expect(result).toBeDefined();
- expect(result.files).toHaveLength(1);
- expect(result.files[0].content).toBeUndefined();
+ expect(result).not.toBeNull();
+ expect(result!.files).toHaveLength(1);
+ expect(result!.files[0].content).toBeUndefined();
});
it('should handle agent with no files', async () => {
@@ -151,8 +152,89 @@ describe('AgentModel', () => {
const result = await agentModel.getAgentConfigById(agentId);
+ expect(result).not.toBeNull();
+ expect(result!.files).toHaveLength(0);
+ });
+ });
+
+ describe('getAgentConfig', () => {
+ it('should find agent by ID', async () => {
+ const agentId = 'test-agent-by-id';
+ await serverDB.insert(agents).values({ id: agentId, userId });
+
+ const result = await agentModel.getAgentConfig(agentId);
+
+ expect(result).toBeDefined();
+ expect(result?.id).toBe(agentId);
+ });
+
+ it('should find agent by slug when ID does not match', async () => {
+ const agentId = 'test-agent-slug';
+ const slug = 'my-agent-slug';
+ await serverDB.insert(agents).values({ id: agentId, slug, userId });
+
+ const result = await agentModel.getAgentConfig(slug);
+
+ expect(result).toBeDefined();
+ expect(result?.id).toBe(agentId);
+ expect(result?.slug).toBe(slug);
+ });
+
+ it('should return null when neither ID nor slug matches', async () => {
+ const result = await agentModel.getAgentConfig('non-existent-id-or-slug');
+
+ expect(result).toBeNull();
+ });
+
+ it('should not find agent by slug from another user', async () => {
+ const agentId = 'test-agent-other-user';
+ const slug = 'shared-slug';
+ // Create agent with same slug but different user
+ await serverDB.insert(agents).values({ id: agentId, slug, userId: userId2 });
+
+ const result = await agentModel.getAgentConfig(slug);
+
+ expect(result).toBeNull();
+ });
+
+ it('should find agent by ID even if it belongs to another user', async () => {
+ const agentId = 'test-agent-cross-user';
+ await serverDB.insert(agents).values({ id: agentId, userId: userId2 });
+
+ // ID lookup should work across users (ID is globally unique)
+ const result = await agentModel.getAgentConfig(agentId);
+
+ expect(result).toBeDefined();
+ expect(result?.id).toBe(agentId);
+ });
+
+ it('should prefer ID match over slug match', async () => {
+ // Create two agents: one with ID "abc", another with slug "abc"
+ const agent1Id = 'abc';
+ const agent2Id = 'different-id';
+ await serverDB.insert(agents).values({ id: agent1Id, userId });
+ await serverDB.insert(agents).values({ id: agent2Id, slug: 'abc', userId });
+
+ const result = await agentModel.getAgentConfig('abc');
+
+ // Should return the agent matched by ID, not slug
expect(result).toBeDefined();
- expect(result.files).toHaveLength(0);
+ expect(result?.id).toBe(agent1Id);
+ });
+
+ it('should enrich agent with knowledge when found', async () => {
+ const agentId = 'test-agent-with-knowledge';
+ await serverDB.insert(agents).values({ id: agentId, userId });
+ await serverDB
+ .insert(agentsKnowledgeBases)
+ .values({ agentId, knowledgeBaseId: 'kb1', userId });
+ await serverDB.insert(agentsFiles).values({ agentId, fileId: '1', userId });
+
+ const result = await agentModel.getAgentConfig(agentId);
+
+ expect(result).toBeDefined();
+ expect(result?.knowledgeBases).toHaveLength(1);
+ expect(result?.files).toHaveLength(1);
});
});
@@ -442,6 +524,245 @@ describe('AgentModel', () => {
});
});
+ describe('update', () => {
+ it('should update agent fields and set updatedAt', async () => {
+ const agent = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Original Title' })
+ .returning()
+ .then((res) => res[0]);
+
+ const originalUpdatedAt = agent.updatedAt;
+
+ // Wait a bit to ensure time difference
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ await agentModel.update(agent.id, { title: 'Updated Title', description: 'New description' });
+
+ const result = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+
+ expect(result?.title).toBe('Updated Title');
+ expect(result?.description).toBe('New description');
+ expect(result?.updatedAt.getTime()).toBeGreaterThan(originalUpdatedAt.getTime());
+ });
+
+ it('should not update another user agent', async () => {
+ const agent = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Original Title' })
+ .returning()
+ .then((res) => res[0]);
+
+ await agentModel2.update(agent.id, { title: 'Hacked Title' });
+
+ const result = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+
+ expect(result?.title).toBe('Original Title');
+ });
+ });
+
+ describe('touchUpdatedAt', () => {
+ it('should only update updatedAt without changing other fields', async () => {
+ const agent = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'My Agent', description: 'My Description' })
+ .returning()
+ .then((res) => res[0]);
+
+ const originalUpdatedAt = agent.updatedAt;
+
+ // Wait a bit to ensure time difference
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ await agentModel.touchUpdatedAt(agent.id);
+
+ const result = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+
+ expect(result?.title).toBe('My Agent');
+ expect(result?.description).toBe('My Description');
+ expect(result?.updatedAt.getTime()).toBeGreaterThan(originalUpdatedAt.getTime());
+ });
+
+ it('should not touch another user agent updatedAt', async () => {
+ const agent = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'My Agent' })
+ .returning()
+ .then((res) => res[0]);
+
+ const originalUpdatedAt = agent.updatedAt;
+
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ await agentModel2.touchUpdatedAt(agent.id);
+
+ const result = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+
+ expect(result?.updatedAt.getTime()).toBe(originalUpdatedAt.getTime());
+ });
+ });
+
+ describe('delete', () => {
+ it('should delete an agent and its associated session', async () => {
+ // Create agent and session
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Test Agent' })
+ .returning();
+ const [session] = await serverDB
+ .insert(sessions)
+ .values({ userId, type: 'agent' })
+ .returning();
+ await serverDB
+ .insert(agentsToSessions)
+ .values({ agentId: agent.id, sessionId: session.id, userId });
+
+ // Delete the agent
+ await agentModel.delete(agent.id);
+
+ // Verify agent is deleted
+ const deletedAgent = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+ expect(deletedAgent).toBeUndefined();
+
+ // Verify session is deleted
+ const deletedSession = await serverDB.query.sessions.findFirst({
+ where: eq(sessions.id, session.id),
+ });
+ expect(deletedSession).toBeUndefined();
+
+ // Verify agentsToSessions link is deleted
+ const deletedLink = await serverDB.query.agentsToSessions.findFirst({
+ where: eq(agentsToSessions.agentId, agent.id),
+ });
+ expect(deletedLink).toBeUndefined();
+ });
+
+ it('should delete an agent with multiple sessions', async () => {
+ // Create agent with multiple sessions
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Multi-session Agent' })
+ .returning();
+ const [session1] = await serverDB
+ .insert(sessions)
+ .values({ userId, type: 'agent' })
+ .returning();
+ const [session2] = await serverDB
+ .insert(sessions)
+ .values({ userId, type: 'agent' })
+ .returning();
+ await serverDB.insert(agentsToSessions).values([
+ { agentId: agent.id, sessionId: session1.id, userId },
+ { agentId: agent.id, sessionId: session2.id, userId },
+ ]);
+
+ // Delete the agent
+ await agentModel.delete(agent.id);
+
+ // Verify all are deleted
+ const deletedAgent = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+ expect(deletedAgent).toBeUndefined();
+
+ const remainingSessions = await serverDB.query.sessions.findMany({
+ where: eq(sessions.userId, userId),
+ });
+ expect(remainingSessions).toHaveLength(0);
+ });
+
+ it('should delete an agent without any sessions', async () => {
+ // Create agent without session
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'No-session Agent' })
+ .returning();
+
+ // Delete the agent
+ await agentModel.delete(agent.id);
+
+ // Verify agent is deleted
+ const deletedAgent = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+ expect(deletedAgent).toBeUndefined();
+ });
+
+ it('should not delete another user agent', async () => {
+ // Create agent for user1
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'User1 Agent' })
+ .returning();
+ const [session] = await serverDB
+ .insert(sessions)
+ .values({ userId, type: 'agent' })
+ .returning();
+ await serverDB
+ .insert(agentsToSessions)
+ .values({ agentId: agent.id, sessionId: session.id, userId });
+
+ // Try to delete with user2's model
+ await agentModel2.delete(agent.id);
+
+ // Verify agent still exists
+ const existingAgent = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+ expect(existingAgent).toBeDefined();
+ expect(existingAgent?.title).toBe('User1 Agent');
+
+ // Verify session still exists
+ const existingSession = await serverDB.query.sessions.findFirst({
+ where: eq(sessions.id, session.id),
+ });
+ expect(existingSession).toBeDefined();
+ });
+
+ it('should delete agent files and knowledge bases associations', async () => {
+ // Create agent with files and knowledge bases
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Agent with knowledge' })
+ .returning();
+ await serverDB.insert(agentsFiles).values({ agentId: agent.id, fileId: '1', userId });
+ await serverDB
+ .insert(agentsKnowledgeBases)
+ .values({ agentId: agent.id, knowledgeBaseId: 'kb1', userId });
+
+ // Delete the agent
+ await agentModel.delete(agent.id);
+
+ // Verify agent is deleted
+ const deletedAgent = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+ expect(deletedAgent).toBeUndefined();
+
+ // Verify agentsFiles are deleted (cascade)
+ const remainingFiles = await serverDB.query.agentsFiles.findMany({
+ where: eq(agentsFiles.agentId, agent.id),
+ });
+ expect(remainingFiles).toHaveLength(0);
+
+ // Verify agentsKnowledgeBases are deleted (cascade)
+ const remainingKBs = await serverDB.query.agentsKnowledgeBases.findMany({
+ where: eq(agentsKnowledgeBases.agentId, agent.id),
+ });
+ expect(remainingKBs).toHaveLength(0);
+ });
+ });
+
describe('toggleFile', () => {
it('should toggle the enabled status of an agent file association', async () => {
const agent = await serverDB
@@ -485,4 +806,511 @@ describe('AgentModel', () => {
expect(result?.enabled).toBe(true);
});
});
+
+ describe('updateConfig', () => {
+ it('should update agent config and set updatedAt', async () => {
+ const agent = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Original Title', model: 'gpt-3.5-turbo' })
+ .returning()
+ .then((res) => res[0]);
+
+ const originalUpdatedAt = agent.updatedAt;
+
+ // Wait a bit to ensure time difference
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ await agentModel.updateConfig(agent.id, { title: 'Updated Title', model: 'gpt-4' });
+
+ const result = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+
+ expect(result?.title).toBe('Updated Title');
+ expect(result?.model).toBe('gpt-4');
+ expect(result?.updatedAt.getTime()).toBeGreaterThan(originalUpdatedAt.getTime());
+ });
+
+ it('should update updatedAt even when only updating meta fields like avatar', async () => {
+ const agent = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Test Agent', avatar: 'old-avatar' })
+ .returning()
+ .then((res) => res[0]);
+
+ const originalUpdatedAt = agent.updatedAt;
+
+ // Wait a bit to ensure time difference
+ await new Promise((resolve) => setTimeout(resolve, 10));
+
+ await agentModel.updateConfig(agent.id, { avatar: 'new-avatar' });
+
+ const result = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+
+ expect(result?.avatar).toBe('new-avatar');
+ expect(result?.title).toBe('Test Agent'); // Should preserve other fields
+ expect(result?.updatedAt.getTime()).toBeGreaterThan(originalUpdatedAt.getTime());
+ });
+
+ it('should not update another user agent', async () => {
+ const agent = await serverDB
+ .insert(agents)
+ .values({ userId, title: 'Original Title' })
+ .returning()
+ .then((res) => res[0]);
+
+ await agentModel2.updateConfig(agent.id, { title: 'Hacked Title' });
+
+ const result = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+
+ expect(result?.title).toBe('Original Title');
+ });
+ });
+
+ describe('create', () => {
+ it('should create a virtual agent without session', async () => {
+ const config = {
+ title: 'Virtual Agent',
+ description: 'A virtual group member',
+ model: 'gpt-4',
+ provider: 'openai',
+ virtual: true,
+ };
+
+ const result = await agentModel.create(config);
+
+ expect(result).toBeDefined();
+ expect(result.title).toBe('Virtual Agent');
+ expect(result.description).toBe('A virtual group member');
+ expect(result.model).toBe('gpt-4');
+ expect(result.provider).toBe('openai');
+ expect(result.virtual).toBe(true);
+ expect(result.userId).toBe(userId);
+
+ // Verify no session was created
+ const sessionLinks = await serverDB.query.agentsToSessions.findMany({
+ where: eq(agentsToSessions.agentId, result.id),
+ });
+ expect(sessionLinks).toHaveLength(0);
+ });
+
+ it('should create agent with default virtual=false', async () => {
+ const config = {
+ title: 'Normal Agent',
+ };
+
+ const result = await agentModel.create(config);
+
+ expect(result).toBeDefined();
+ expect(result.title).toBe('Normal Agent');
+ expect(result.virtual).toBe(false);
+ });
+
+ it('should create agent with all optional fields', async () => {
+ const config = {
+ title: 'Full Agent',
+ description: 'Full description',
+ avatar: 'avatar-url',
+ backgroundColor: '#ffffff',
+ model: 'gpt-4',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant',
+ tags: ['tag1', 'tag2'],
+ plugins: ['plugin1'],
+ openingMessage: 'Hello!',
+ openingQuestions: ['Question 1', 'Question 2'],
+ virtual: true,
+ };
+
+ const result = await agentModel.create(config);
+
+ expect(result.title).toBe('Full Agent');
+ expect(result.description).toBe('Full description');
+ expect(result.avatar).toBe('avatar-url');
+ expect(result.backgroundColor).toBe('#ffffff');
+ expect(result.model).toBe('gpt-4');
+ expect(result.provider).toBe('openai');
+ expect(result.systemRole).toBe('You are a helpful assistant');
+ expect(result.tags).toEqual(['tag1', 'tag2']);
+ expect(result.plugins).toEqual(['plugin1']);
+ expect(result.openingMessage).toBe('Hello!');
+ expect(result.openingQuestions).toEqual(['Question 1', 'Question 2']);
+ expect(result.virtual).toBe(true);
+ });
+
+ it('should create agent with custom id', async () => {
+ const customId = 'custom-agent-id-123';
+ const config = {
+ id: customId,
+ title: 'Custom ID Agent',
+ };
+
+ const result = await agentModel.create(config);
+
+ expect(result.id).toBe(customId);
+ });
+
+ it('should create multiple agents for the same user', async () => {
+ const agent1 = await agentModel.create({ title: 'Agent 1', virtual: true });
+ const agent2 = await agentModel.create({ title: 'Agent 2', virtual: true });
+
+ expect(agent1.id).not.toBe(agent2.id);
+
+ const allAgents = await serverDB.query.agents.findMany({
+ where: eq(agents.userId, userId),
+ });
+ expect(allAgents.length).toBeGreaterThanOrEqual(2);
+ });
+ });
+
+ describe('batchCreate', () => {
+ it('should batch create multiple virtual agents', async () => {
+ const configs = [
+ { title: 'Agent 1', model: 'gpt-4', virtual: true },
+ { title: 'Agent 2', model: 'gpt-3.5-turbo', virtual: true },
+ { title: 'Agent 3', model: 'claude-3', virtual: true },
+ ];
+
+ const results = await agentModel.batchCreate(configs);
+
+ expect(results).toHaveLength(3);
+ expect(results[0].title).toBe('Agent 1');
+ expect(results[1].title).toBe('Agent 2');
+ expect(results[2].title).toBe('Agent 3');
+ results.forEach((agent) => {
+ expect(agent.userId).toBe(userId);
+ expect(agent.virtual).toBe(true);
+ });
+ });
+
+ it('should return empty array for empty input', async () => {
+ const results = await agentModel.batchCreate([]);
+
+ expect(results).toEqual([]);
+ });
+
+ it('should batch create agents with different configs', async () => {
+ const configs = [
+ {
+ title: 'Full Agent',
+ description: 'Full description',
+ model: 'gpt-4',
+ provider: 'openai',
+ systemRole: 'You are helpful',
+ virtual: true,
+ },
+ {
+ title: 'Minimal Agent',
+ virtual: true,
+ },
+ ];
+
+ const results = await agentModel.batchCreate(configs);
+
+ expect(results).toHaveLength(2);
+ expect(results[0].description).toBe('Full description');
+ expect(results[0].systemRole).toBe('You are helpful');
+ expect(results[1].description).toBeNull();
+ expect(results[1].systemRole).toBeNull();
+ });
+
+ it('should handle model type conversion in batch', async () => {
+ const configs = [
+ { title: 'Agent 1', model: 'gpt-4' },
+ { title: 'Agent 2', model: undefined },
+ { title: 'Agent 3' },
+ ];
+
+ const results = await agentModel.batchCreate(configs);
+
+ expect(results[0].model).toBe('gpt-4');
+ expect(results[1].model).toBeNull();
+ expect(results[2].model).toBeNull();
+ });
+ });
+
+ describe('getBuiltinAgent', () => {
+ describe('inbox compatibility', () => {
+ it('should return existing inbox agent directly if slug exists in agents table', async () => {
+ // Create an agent with slug='inbox'
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ slug: INBOX_SESSION_ID,
+ userId,
+ model: 'gpt-4',
+ })
+ .returning();
+
+ const result = await agentModel.getBuiltinAgent(INBOX_SESSION_ID);
+
+ expect(result).toBeDefined();
+ expect(result?.id).toBe(agent.id);
+ expect(result?.slug).toBe(INBOX_SESSION_ID);
+ });
+
+ it('should find inbox from legacy session and update agent slug', async () => {
+ // Create legacy format: session(slug=inbox) + agent(no slug) + relation
+ const [session] = await serverDB
+ .insert(sessions)
+ .values({
+ slug: INBOX_SESSION_ID,
+ userId,
+ type: 'agent',
+ })
+ .returning();
+
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ userId,
+ model: 'gpt-4',
+ // Note: no slug set
+ })
+ .returning();
+
+ await serverDB.insert(agentsToSessions).values({
+ sessionId: session.id,
+ agentId: agent.id,
+ userId,
+ });
+
+ const result = await agentModel.getBuiltinAgent(INBOX_SESSION_ID);
+
+ // Should return the agent and update its slug
+ expect(result).toBeDefined();
+ expect(result?.id).toBe(agent.id);
+ expect(result?.slug).toBe(INBOX_SESSION_ID);
+
+ // Verify the slug was updated in database
+ const updatedAgent = await serverDB.query.agents.findFirst({
+ where: eq(agents.id, agent.id),
+ });
+ expect(updatedAgent?.slug).toBe(INBOX_SESSION_ID);
+ });
+
+ it('should create new inbox agent if no legacy data exists', async () => {
+ const result = await agentModel.getBuiltinAgent(INBOX_SESSION_ID);
+
+ expect(result).toBeDefined();
+ expect(result?.slug).toBe(INBOX_SESSION_ID);
+ expect(result?.virtual).toBe(true);
+ });
+
+ it('should return the same agent on subsequent calls (idempotent)', async () => {
+ // First call - creates the agent
+ const result1 = await agentModel.getBuiltinAgent(INBOX_SESSION_ID);
+
+ // Second call - should return the same agent
+ const result2 = await agentModel.getBuiltinAgent(INBOX_SESSION_ID);
+
+ expect(result1?.id).toBe(result2?.id);
+ expect(result1?.slug).toBe(result2?.slug);
+ });
+
+ it('should not affect other users inbox agent', async () => {
+ // User1 creates inbox via legacy method
+ const [session] = await serverDB
+ .insert(sessions)
+ .values({
+ slug: INBOX_SESSION_ID,
+ userId,
+ type: 'agent',
+ })
+ .returning();
+
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ userId,
+ model: 'gpt-4',
+ })
+ .returning();
+
+ await serverDB.insert(agentsToSessions).values({
+ sessionId: session.id,
+ agentId: agent.id,
+ userId,
+ });
+
+ // User2 gets their inbox (should create a new one)
+ const result2 = await agentModel2.getBuiltinAgent(INBOX_SESSION_ID);
+
+ // User1 gets their inbox
+ const result1 = await agentModel.getBuiltinAgent(INBOX_SESSION_ID);
+
+ // Should be different agents
+ expect(result1?.id).toBe(agent.id);
+ expect(result2?.id).not.toBe(agent.id);
+
+ // Both should have slug='inbox'
+ expect(result1?.slug).toBe(INBOX_SESSION_ID);
+ expect(result2?.slug).toBe(INBOX_SESSION_ID);
+ });
+ });
+
+ describe('other builtin agents', () => {
+ it('should return null for unknown slug', async () => {
+ const result = await agentModel.getBuiltinAgent('unknown-agent-slug');
+
+ expect(result).toBeNull();
+ });
+
+ it('should create page-agent builtin agent', async () => {
+ const result = await agentModel.getBuiltinAgent('page-agent');
+
+ expect(result).toBeDefined();
+ expect(result?.slug).toBe('page-agent');
+ expect(result?.virtual).toBe(true);
+ });
+ });
+ });
+
+ describe('queryAgents', () => {
+ it('should return non-virtual agents for the user', async () => {
+ // Create non-virtual agents
+ await agentModel.create({
+ title: 'Agent 1',
+ description: 'First agent',
+ avatar: 'avatar1',
+ backgroundColor: '#ff0000',
+ virtual: false,
+ });
+ await agentModel.create({
+ title: 'Agent 2',
+ description: 'Second agent',
+ avatar: 'avatar2',
+ backgroundColor: '#00ff00',
+ virtual: false,
+ });
+
+ const result = await agentModel.queryAgents();
+
+ expect(result.length).toBeGreaterThanOrEqual(2);
+ expect(result.some((a: { title: string | null }) => a.title === 'Agent 1')).toBe(true);
+ expect(result.some((a: { title: string | null }) => a.title === 'Agent 2')).toBe(true);
+ // Check that only required fields are returned
+ expect(result[0]).toHaveProperty('id');
+ expect(result[0]).toHaveProperty('title');
+ expect(result[0]).toHaveProperty('description');
+ expect(result[0]).toHaveProperty('avatar');
+ expect(result[0]).toHaveProperty('backgroundColor');
+ });
+
+ it('should exclude virtual agents', async () => {
+ // Create a virtual agent
+ await agentModel.create({
+ title: 'Virtual Agent',
+ virtual: true,
+ });
+ // Create a non-virtual agent
+ await agentModel.create({
+ title: 'Regular Agent',
+ virtual: false,
+ });
+
+ const result = await agentModel.queryAgents();
+
+ expect(result.some((a: { title: string | null }) => a.title === 'Virtual Agent')).toBe(false);
+ expect(result.some((a: { title: string | null }) => a.title === 'Regular Agent')).toBe(true);
+ });
+
+ it('should only return agents for the current user', async () => {
+ // Create agent for user 1
+ await agentModel.create({
+ title: 'User1 Agent',
+ virtual: false,
+ });
+ // Create agent for user 2
+ await agentModel2.create({
+ title: 'User2 Agent',
+ virtual: false,
+ });
+
+ const result1 = await agentModel.queryAgents();
+ const result2 = await agentModel2.queryAgents();
+
+ expect(result1.some((a: { title: string | null }) => a.title === 'User1 Agent')).toBe(true);
+ expect(result1.some((a: { title: string | null }) => a.title === 'User2 Agent')).toBe(false);
+ expect(result2.some((a: { title: string | null }) => a.title === 'User2 Agent')).toBe(true);
+ expect(result2.some((a: { title: string | null }) => a.title === 'User1 Agent')).toBe(false);
+ });
+
+ it('should return empty array when no agents exist', async () => {
+ // Use a new user with no agents
+ const emptyUserId = 'empty-user-id';
+ await serverDB.insert(users).values({ id: emptyUserId });
+ const emptyAgentModel = new AgentModel(serverDB, emptyUserId);
+
+ const result = await emptyAgentModel.queryAgents();
+
+ expect(result).toEqual([]);
+ });
+
+ it('should handle agents with null virtual field (treat as non-virtual)', async () => {
+ // Directly insert agent with null virtual (simulating legacy data)
+ await serverDB.insert(agents).values({
+ id: 'null-virtual-agent',
+ title: 'Null Virtual Agent',
+ userId,
+ virtual: null as unknown as boolean,
+ });
+
+ const result = await agentModel.queryAgents();
+
+ expect(result.some((a: { title: string | null }) => a.title === 'Null Virtual Agent')).toBe(
+ true,
+ );
+ });
+
+ it('should filter by keyword in title and description', async () => {
+ await agentModel.create({
+ title: 'Code Assistant',
+ description: 'Helps with coding',
+ virtual: false,
+ });
+ await agentModel.create({
+ title: 'Writer',
+ description: 'Helps with writing tasks',
+ virtual: false,
+ });
+ await agentModel.create({
+ title: 'Designer',
+ description: 'Helps with design code review',
+ virtual: false,
+ });
+
+ // Search by title
+ const codeResults = await agentModel.queryAgents({ keyword: 'Code' });
+ expect(codeResults.some((a: { title: string | null }) => a.title === 'Code Assistant')).toBe(
+ true,
+ );
+ expect(codeResults.some((a: { title: string | null }) => a.title === 'Designer')).toBe(true); // matches 'code' in description
+ expect(codeResults.some((a: { title: string | null }) => a.title === 'Writer')).toBe(false);
+
+ // Search by description
+ const writingResults = await agentModel.queryAgents({ keyword: 'writing' });
+ expect(writingResults.some((a: { title: string | null }) => a.title === 'Writer')).toBe(true);
+ });
+
+ it('should respect limit and offset parameters', async () => {
+ // Create multiple agents
+ for (let i = 1; i <= 5; i++) {
+ await agentModel.create({
+ title: `Agent ${i}`,
+ virtual: false,
+ });
+ }
+
+ const limitedResults = await agentModel.queryAgents({ limit: 2 });
+ expect(limitedResults.length).toBe(2);
+
+ const offsetResults = await agentModel.queryAgents({ limit: 2, offset: 2 });
+ expect(offsetResults.length).toBe(2);
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/chatGroup.test.ts b/packages/database/src/models/__tests__/chatGroup.test.ts
index 07d03aa0c15..fe0e72acdec 100644
--- a/packages/database/src/models/__tests__/chatGroup.test.ts
+++ b/packages/database/src/models/__tests__/chatGroup.test.ts
@@ -152,17 +152,17 @@ describe('ChatGroupModel', () => {
expect(result).toHaveLength(2);
const group1 = result.find((g) => g.id === 'group-1');
- expect(group1?.members).toHaveLength(2);
- expect(group1?.members.map((m: any) => m.title)).toEqual(
+ expect(group1?.agents).toHaveLength(2);
+ expect(group1?.agents.map((m: any) => m.title)).toEqual(
expect.arrayContaining(['Agent 1', 'Agent 2']),
);
const group2 = result.find((g) => g.id === 'group-2');
- expect(group2?.members).toHaveLength(1);
- expect(group2?.members[0].title).toBe('Agent 3');
+ expect(group2?.agents).toHaveLength(1);
+ expect(group2?.agents[0].title).toBe('Agent 3');
});
- it('should return groups with empty members array when no agents assigned', async () => {
+ it('should return groups with empty agents array when no agents assigned', async () => {
await serverDB.insert(chatGroups).values({
id: 'group-no-agents',
userId,
@@ -172,7 +172,7 @@ describe('ChatGroupModel', () => {
const result = await chatGroupModel.queryWithMemberDetails();
expect(result).toHaveLength(1);
- expect(result[0].members).toEqual([]);
+ expect(result[0].agents).toEqual([]);
});
it('should return empty array when no groups exist', async () => {
@@ -410,12 +410,12 @@ describe('ChatGroupModel', () => {
'agent-3',
]);
- const connectedAgents = toRelationAgents(result);
- expect(connectedAgents).toHaveLength(3);
- expect(connectedAgents.map((a) => a.agentId)).toEqual(['agent-1', 'agent-2', 'agent-3']);
+ expect(result.added).toHaveLength(3);
+ expect(result.added.map((a) => a.agentId)).toEqual(['agent-1', 'agent-2', 'agent-3']);
+ expect(result.existing).toHaveLength(0);
});
- it('should throw when adding duplicate agents', async () => {
+ it('should skip existing agents and only add new ones', async () => {
// Create test data
await serverDB.transaction(async (trx) => {
await trx.insert(chatGroups).values({
@@ -437,19 +437,22 @@ describe('ChatGroupModel', () => {
});
});
- await expect(
- chatGroupModel.addAgentsToGroup('existing-agent-group', ['existing-agent', 'new-agent']),
- ).rejects.toThrow();
+ const result = await chatGroupModel.addAgentsToGroup('existing-agent-group', [
+ 'existing-agent',
+ 'new-agent',
+ ]);
- const groupAgents = toRelationAgents(
- await chatGroupModel.getGroupAgents('existing-agent-group'),
- );
+ // Should only add new-agent, and report existing-agent as skipped
+ expect(result.added).toHaveLength(1);
+ expect(result.added[0].agentId).toBe('new-agent');
+ expect(result.existing).toEqual(['existing-agent']);
- expect(groupAgents).toHaveLength(1);
- expect(groupAgents[0]?.agentId).toBe('existing-agent');
+ // Verify total agents in group
+ const groupAgents = await chatGroupModel.getGroupAgents('existing-agent-group');
+ expect(groupAgents).toHaveLength(2);
});
- it('should throw when all agents already exist', async () => {
+ it('should return empty added array when all agents already exist', async () => {
// Create test data
await serverDB.transaction(async (trx) => {
await trx.insert(chatGroups).values({
@@ -471,9 +474,10 @@ describe('ChatGroupModel', () => {
});
});
- await expect(
- chatGroupModel.addAgentsToGroup('all-existing-group', ['existing-only']),
- ).rejects.toThrow();
+ const result = await chatGroupModel.addAgentsToGroup('all-existing-group', ['existing-only']);
+
+ expect(result.added).toHaveLength(0);
+ expect(result.existing).toEqual(['existing-only']);
});
it('should throw error for non-existent group', async () => {
@@ -527,6 +531,119 @@ describe('ChatGroupModel', () => {
});
});
+ describe('removeAgentsFromGroup', () => {
+ it('should remove multiple agents from group', async () => {
+ // Create test data
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(chatGroups).values({
+ id: 'batch-remove-group',
+ userId,
+ title: 'Batch Remove Group',
+ });
+
+ await trx.insert(agentsTable).values([
+ { id: 'agent-to-remove-1', userId, title: 'Agent 1' },
+ { id: 'agent-to-remove-2', userId, title: 'Agent 2' },
+ { id: 'agent-to-keep', userId, title: 'Agent to Keep' },
+ ]);
+
+ await trx.insert(chatGroupsAgents).values([
+ { chatGroupId: 'batch-remove-group', agentId: 'agent-to-remove-1', userId },
+ { chatGroupId: 'batch-remove-group', agentId: 'agent-to-remove-2', userId },
+ { chatGroupId: 'batch-remove-group', agentId: 'agent-to-keep', userId },
+ ]);
+ });
+
+ await chatGroupModel.removeAgentsFromGroup('batch-remove-group', [
+ 'agent-to-remove-1',
+ 'agent-to-remove-2',
+ ]);
+
+ // Verify only the specified agents were removed
+ const groupAgents = toRelationAgents(
+ await chatGroupModel.getGroupAgents('batch-remove-group'),
+ );
+ expect(groupAgents).toHaveLength(1);
+ expect(groupAgents[0]?.agentId).toBe('agent-to-keep');
+ });
+
+ it('should handle empty agentIds array gracefully', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(chatGroups).values({
+ id: 'empty-remove-group',
+ userId,
+ title: 'Empty Remove Group',
+ });
+
+ await trx.insert(agentsTable).values({
+ id: 'agent-stays',
+ userId,
+ title: 'Agent Stays',
+ });
+
+ await trx.insert(chatGroupsAgents).values({
+ chatGroupId: 'empty-remove-group',
+ agentId: 'agent-stays',
+ userId,
+ });
+ });
+
+ // Should not throw error and should not remove any agents
+ await expect(
+ chatGroupModel.removeAgentsFromGroup('empty-remove-group', []),
+ ).resolves.not.toThrow();
+
+ const groupAgents = toRelationAgents(
+ await chatGroupModel.getGroupAgents('empty-remove-group'),
+ );
+ expect(groupAgents).toHaveLength(1);
+ });
+
+ it('should handle removing non-existent agents gracefully', async () => {
+ await serverDB.insert(chatGroups).values({
+ id: 'no-match-group',
+ userId,
+ title: 'No Match Group',
+ });
+
+ // Should not throw error
+ await expect(
+ chatGroupModel.removeAgentsFromGroup('no-match-group', [
+ 'non-existent-1',
+ 'non-existent-2',
+ ]),
+ ).resolves.not.toThrow();
+ });
+
+ it('should remove all agents when all are specified', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(chatGroups).values({
+ id: 'remove-all-group',
+ userId,
+ title: 'Remove All Group',
+ });
+
+ await trx.insert(agentsTable).values([
+ { id: 'remove-all-1', userId, title: 'Remove All 1' },
+ { id: 'remove-all-2', userId, title: 'Remove All 2' },
+ ]);
+
+ await trx.insert(chatGroupsAgents).values([
+ { chatGroupId: 'remove-all-group', agentId: 'remove-all-1', userId },
+ { chatGroupId: 'remove-all-group', agentId: 'remove-all-2', userId },
+ ]);
+ });
+
+ await chatGroupModel.removeAgentsFromGroup('remove-all-group', [
+ 'remove-all-1',
+ 'remove-all-2',
+ ]);
+
+ const groupAgents = await chatGroupModel.getGroupAgents('remove-all-group');
+ expect(groupAgents).toHaveLength(0);
+ });
+ });
+
describe('updateAgentInGroup', () => {
it('should update agent settings in group', async () => {
// Create test data
diff --git a/packages/database/src/models/__tests__/user.test.ts b/packages/database/src/models/__tests__/user.test.ts
index 658fa58911d..0425422c001 100644
--- a/packages/database/src/models/__tests__/user.test.ts
+++ b/packages/database/src/models/__tests__/user.test.ts
@@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { nextauthAccounts, userSettings, users } from '../../schemas';
import { LobeChatDatabase } from '../../type';
-import { UserModel, UserNotFoundError } from '../user';
+import { ListUsersForMemoryExtractorCursor, UserModel, UserNotFoundError } from '../user';
import { getTestDB } from './_util';
const userId = 'user-model-test';
@@ -368,5 +368,27 @@ describe('UserModel', () => {
).rejects.toThrow(UserNotFoundError);
});
});
+
+ describe('listUsersForMemoryExtractor', () => {
+ it('should paginate users by createdAt and id', async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([
+ { id: 'u1', createdAt: new Date('2024-01-01T00:00:00Z') },
+ { id: 'u2', createdAt: new Date('2024-01-02T00:00:00Z') },
+ { id: 'u3', createdAt: new Date('2024-01-03T00:00:00Z') },
+ ]);
+
+ const page1 = await UserModel.listUsersForMemoryExtractor(serverDB, { limit: 1 });
+ expect(page1.map((u) => u.id)).toEqual(['u1']);
+
+ const cursor: ListUsersForMemoryExtractorCursor = {
+ createdAt: page1[0].createdAt,
+ id: page1[0].id,
+ };
+
+ const page2 = await UserModel.listUsersForMemoryExtractor(serverDB, { cursor, limit: 10 });
+ expect(page2.map((u) => u.id)).toEqual(['u2', 'u3']);
+ });
+ });
});
});
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index 53f4ddb29aa..ab7c94be45a 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -1,6 +1,12 @@
-import { and, desc, eq, inArray } from 'drizzle-orm';
+import { getAgentPersistConfig } from '@lobechat/builtin-agents';
+import { INBOX_SESSION_ID } from '@lobechat/const';
+import { and, desc, eq, ilike, inArray, isNull, or } from 'drizzle-orm';
+import type { PartialDeep } from 'type-fest';
+
+import { merge } from '@/utils/merge';
import {
+ AgentItem,
agents,
agentsFiles,
agentsKnowledgeBases,
@@ -8,6 +14,7 @@ import {
documents,
files,
knowledgeBases,
+ sessions,
} from '../schemas';
import { LobeChatDatabase } from '../type';
@@ -23,7 +30,68 @@ export class AgentModel {
getAgentConfigById = async (id: string) => {
const agent = await this.db.query.agents.findFirst({ where: eq(agents.id, id) });
- const knowledge = await this.getAgentAssignedKnowledge(id);
+ if (!agent) return null;
+
+ return this.enrichAgentWithKnowledge(agent);
+ };
+
+ /**
+ * Query non-virtual agents with optional keyword filter.
+ * Returns minimal agent info (id, title, description, avatar, backgroundColor).
+ * Excludes virtual agents (like inbox, supervisors, etc).
+ */
+ queryAgents = async (params?: { keyword?: string; limit?: number; offset?: number }) => {
+ const { keyword, limit = 9999, offset = 0 } = params ?? {};
+ // Include agents where virtual is false OR null (legacy data without virtual field)
+ const baseConditions = and(
+ eq(agents.userId, this.userId),
+ or(eq(agents.virtual, false), isNull(agents.virtual)),
+ );
+
+ // Add keyword search condition if provided
+ const searchCondition = keyword
+ ? and(
+ baseConditions,
+ or(ilike(agents.title, `%${keyword}%`), ilike(agents.description, `%${keyword}%`)),
+ )
+ : baseConditions;
+
+ return this.db
+ .select({
+ avatar: agents.avatar,
+ backgroundColor: agents.backgroundColor,
+ description: agents.description,
+ id: agents.id,
+ title: agents.title,
+ })
+ .from(agents)
+ .where(searchCondition)
+ .orderBy(desc(agents.updatedAt))
+ .limit(limit)
+ .offset(offset);
+ };
+
+ /**
+ * Get agent config by ID or slug (single query with OR condition)
+ */
+ getAgentConfig = async (idOrSlug: string) => {
+ const agent = await this.db.query.agents.findFirst({
+ where: or(
+ eq(agents.id, idOrSlug),
+ and(eq(agents.slug, idOrSlug), eq(agents.userId, this.userId)),
+ ),
+ });
+
+ if (!agent) return null;
+
+ return this.enrichAgentWithKnowledge(agent);
+ };
+
+ /**
+ * Enrich agent with knowledge base and files data
+ */
+ private enrichAgentWithKnowledge = async (agent: AgentItem) => {
+ const knowledge = await this.getAgentAssignedKnowledge(agent.id);
// Fetch document content for enabled files
const enabledFileIds = knowledge.files
@@ -168,6 +236,41 @@ export class AgentModel {
);
};
+ /**
+ * Delete an agent and its associated session.
+ * This will cascade delete messages, topics, etc. through the session deletion.
+ */
+ delete = async (agentId: string) => {
+ return this.db.transaction(async (trx) => {
+ // 1. Get associated session IDs
+ const links = await trx
+ .select({ sessionId: agentsToSessions.sessionId })
+ .from(agentsToSessions)
+ .where(
+ and(eq(agentsToSessions.agentId, agentId), eq(agentsToSessions.userId, this.userId)),
+ );
+
+ const sessionIds = links.map((link) => link.sessionId);
+
+ // 2. Delete links in agentsToSessions
+ await trx
+ .delete(agentsToSessions)
+ .where(
+ and(eq(agentsToSessions.agentId, agentId), eq(agentsToSessions.userId, this.userId)),
+ );
+
+ // 3. Delete associated sessions (this will cascade delete messages, topics, etc.)
+ if (sessionIds.length > 0) {
+ await trx
+ .delete(sessions)
+ .where(and(inArray(sessions.id, sessionIds), eq(sessions.userId, this.userId)));
+ }
+
+ // 4. Delete the agent itself
+ return trx.delete(agents).where(and(eq(agents.id, agentId), eq(agents.userId, this.userId)));
+ });
+ };
+
toggleFile = async (agentId: string, fileId: string, enabled?: boolean) => {
return this.db
.update(agentsFiles)
@@ -180,4 +283,196 @@ export class AgentModel {
),
);
};
+
+ /**
+ * Create an agent record only (without creating a session).
+ * This is used for creating virtual agents (e.g., group chat members).
+ */
+ create = async (config: Partial<AgentItem>): Promise<AgentItem> => {
+ const [result] = await this.db
+ .insert(agents)
+ .values([
+ {
+ ...config,
+ model: typeof config.model === 'string' ? config.model : null,
+ userId: this.userId,
+ },
+ ])
+ .returning();
+
+ return result;
+ };
+
+ /**
+ * Batch create multiple agents (without sessions).
+ * Used for creating multiple virtual agents at once (e.g., group chat members).
+ */
+ batchCreate = async (configs: Partial<AgentItem>[]): Promise<AgentItem[]> => {
+ if (configs.length === 0) return [];
+
+ return this.db
+ .insert(agents)
+ .values(
+ configs.map((config) => ({
+ ...config,
+ model: typeof config.model === 'string' ? config.model : null,
+ userId: this.userId,
+ })),
+ )
+ .returning();
+ };
+
+ update = async (agentId: string, data: Partial<AgentItem>) => {
+ return this.db
+ .update(agents)
+ .set({ ...data, updatedAt: new Date() })
+ .where(and(eq(agents.id, agentId), eq(agents.userId, this.userId)));
+ };
+
+ touchUpdatedAt = async (agentId: string) => {
+ return this.update(agentId, {});
+ };
+
+ /**
+ * Check if an agent with the given marketIdentifier already exists
+ * @returns true if exists, false otherwise
+ */
+ checkByMarketIdentifier = async (marketIdentifier: string): Promise<boolean> => {
+ const result = await this.db.query.agents.findFirst({
+ where: and(eq(agents.marketIdentifier, marketIdentifier), eq(agents.userId, this.userId)),
+ });
+ return !!result;
+ };
+
+ /**
+ * Get an agent by marketIdentifier
+ * If multiple agents match, returns the most recently updated one
+ * @returns agent id if exists, null otherwise
+ */
+ getAgentByMarketIdentifier = async (marketIdentifier: string): Promise<string | null> => {
+ const result = await this.db.query.agents.findFirst({
+ columns: { id: true },
+ orderBy: (agents, { desc }) => [desc(agents.updatedAt)],
+ where: and(eq(agents.marketIdentifier, marketIdentifier), eq(agents.userId, this.userId)),
+ });
+ return result?.id ?? null;
+ };
+
+ updateConfig = async (agentId: string, data: PartialDeep<AgentItem> | undefined | null) => {
+ if (!data || Object.keys(data).length === 0) return;
+
+ const agent = await this.db.query.agents.findFirst({
+ where: and(eq(agents.id, agentId), eq(agents.userId, this.userId)),
+ });
+
+ if (!agent) return;
+
+ // First process the params field: undefined means delete, null means disable flag
+ const existingParams = agent.params ?? {};
+ const updatedParams: Record<string, any> = { ...existingParams };
+
+ if (data.params) {
+ const incomingParams = data.params as Record<string, any>;
+ Object.keys(incomingParams).forEach((key) => {
+ const incomingValue = incomingParams[key];
+
+ // undefined means explicitly delete this field
+ if (incomingValue === undefined) {
+ delete updatedParams[key];
+ return;
+ }
+
+ // All other values (including null) are directly overwritten, null means disable this param on the frontend
+ updatedParams[key] = incomingValue;
+ });
+ }
+
+ // Build data to be merged, excluding params (processed separately)
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { params: _params, ...restData } = data;
+ const mergedValue = merge(agent, restData);
+
+ // Apply the processed parameters
+ mergedValue.params = Object.keys(updatedParams).length > 0 ? updatedParams : undefined;
+
+ // Final cleanup: ensure no undefined or null values enter the database
+ if (mergedValue.params) {
+ const params = mergedValue.params as Record<string, any>;
+ Object.keys(params).forEach((key) => {
+ if (params[key] === undefined) {
+ delete params[key];
+ }
+ });
+ if (Object.keys(params).length === 0) {
+ mergedValue.params = undefined;
+ }
+ }
+
+ // Remove timestamp fields to let Drizzle's $onUpdate handle them automatically
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const { updatedAt: _, accessedAt: __, createdAt: ___, ...updateData } = mergedValue;
+
+ return this.db
+ .update(agents)
+ .set(updateData)
+ .where(and(eq(agents.id, agentId), eq(agents.userId, this.userId)));
+ };
+
+ /**
+ * Get a builtin agent by slug, creating it if it doesn't exist.
+ * Builtin agents are standalone agents not bound to sessions.
+ *
+ */
+ getBuiltinAgent = async (slug: string): Promise<AgentItem | null> => {
+ // 1. First try to find existing agent by slug
+ const existing = await this.db.query.agents.findFirst({
+ where: and(eq(agents.slug, slug), eq(agents.userId, this.userId)),
+ });
+
+ if (existing) return existing;
+
+ // For inbox agent, it has special compatibility handling:
+ // Historical inbox was stored as session with slug='inbox' and linked agent via agentsToSessions
+ // If found, update the agent's slug to 'inbox' for future direct queries
+ if (slug === INBOX_SESSION_ID) {
+ // Use join query for better performance instead of multiple findFirst calls
+ const result = await this.db
+ .select({ agent: agents })
+ .from(sessions)
+ .innerJoin(agentsToSessions, eq(sessions.id, agentsToSessions.sessionId))
+ .innerJoin(agents, eq(agentsToSessions.agentId, agents.id))
+ .where(and(eq(sessions.slug, INBOX_SESSION_ID), eq(sessions.userId, this.userId)))
+ .limit(1);
+
+ if (result.length > 0 && result[0].agent) {
+ // Update the agent's slug to 'inbox' for future direct queries
+ // Use both id and userId to ensure we only update current user's agent
+ const [updatedAgent] = await this.db
+ .update(agents)
+ .set({ slug: INBOX_SESSION_ID, virtual: true })
+ .where(eq(agents.id, result[0].agent.id))
+ .returning();
+
+ return updatedAgent;
+ }
+ }
+
+ // 3. Check if this is a known builtin agent
+ const persistConfig = getAgentPersistConfig(slug);
+ if (!persistConfig) return null;
+
+ // 4. Create the builtin agent with persist config
+ const result = await this.db
+ .insert(agents)
+ .values({
+ model: persistConfig.model,
+ provider: persistConfig.provider,
+ slug: persistConfig.slug,
+ userId: this.userId,
+ virtual: true,
+ })
+ .returning();
+
+ return result[0];
+ };
}
diff --git a/packages/types/src/agent/chatConfig.ts b/packages/types/src/agent/chatConfig.ts
index 90bc3a0eb6a..130126c92aa 100644
--- a/packages/types/src/agent/chatConfig.ts
+++ b/packages/types/src/agent/chatConfig.ts
@@ -9,8 +9,6 @@ export interface WorkingModel {
}
export interface LobeAgentChatConfig {
- displayMode?: 'chat' | 'docs';
-
enableAutoCreateTopic?: boolean;
autoCreateTopicThreshold: number;
@@ -77,7 +75,6 @@ export interface LobeAgentChatConfig {
export const AgentChatConfigSchema = z.object({
autoCreateTopicThreshold: z.number().default(2),
disableContextCaching: z.boolean().optional(),
- displayMode: z.enum(['chat', 'docs']).optional(),
enableAutoCreateTopic: z.boolean().optional(),
enableCompressHistory: z.boolean().optional(),
enableHistoryCount: z.boolean().optional(),
diff --git a/packages/types/src/agent/item.ts b/packages/types/src/agent/item.ts
index 5db3e5b57b0..61093ba7703 100644
--- a/packages/types/src/agent/item.ts
+++ b/packages/types/src/agent/item.ts
@@ -7,10 +7,20 @@ import { LobeAgentChatConfig } from './chatConfig';
import { LobeAgentTTSConfig } from './tts';
export interface LobeAgentConfig {
+ avatar?: string;
+
chatConfig: LobeAgentChatConfig;
+
+ /**
+ * 编辑器内容(JSON 格式)
+ * 用于保存富文本编辑器的完整状态,包括 mention 等特殊节点
+ */
+ editorData?: any;
+ enableAgentMode?: boolean;
fewShots?: FewShots;
files?: FileItem[];
id?: string;
+
/**
* knowledge bases
*/
@@ -72,8 +82,11 @@ export interface AgentItem {
clientId?: string | null;
createdAt: Date;
description?: string | null;
+ editorData?: any | null;
fewShots?: any | null;
id: string;
+ /** Market agent identifier for published agents */
+ marketIdentifier?: string | null;
model?: string | null;
openingMessage?: string | null;
openingQuestions?: string[];
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 0c7a2e3f02d..2ef6e864396 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -1,12 +1,13 @@
export * from './agent';
+export * from './agentGroup';
export * from './aiChat';
export * from './aiProvider';
export * from './artifact';
export * from './asyncTask';
export * from './auth';
-export * from './chatGroup';
export * from './chunk';
export * from './clientDB';
+export * from './conversation';
export * from './discover';
export * from './document';
export * from './eval';
@@ -14,6 +15,7 @@ export * from './export';
export * from './fetch';
export * from './files';
export * from './generation';
+export * from './home';
export * from './hotkey';
export * from './importer';
export * from './knowledgeBase';
@@ -26,10 +28,12 @@ export * from './search';
export * from './serverConfig';
export * from './service';
export * from './session';
+export * from './stepContext';
export * from './tableViewer';
export * from './tool';
export * from './topic';
export * from './user';
+export * from './userMemory';
// FIXME: I think we need a refactor for the "openai" types
// it more likes the UI message payload
export * from './openai/chat';
@@ -37,4 +41,5 @@ export * from './openai/plugin';
export * from './subscription';
export * from './trace';
export * from './userMemory';
+export * from './util';
export * from './zustand';
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index 93da2c0d534..05026e1f0b2 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -10,6 +10,30 @@ import {
UserSystemAgentConfig,
} from './user/settings';
+export type GlobalMemoryLayer = 'context' | 'experience' | 'identity' | 'preference';
+
+export interface MemoryAgentPublicConfig {
+ baseURL?: string;
+ contextLimit?: number;
+ model?: string;
+ provider?: string;
+}
+
+export interface MemoryLayerExtractorPublicConfig extends MemoryAgentPublicConfig {
+ layers?: Partial<Record<GlobalMemoryLayer, string>>;
+}
+
+export interface GlobalMemoryExtractionConfig {
+ agentGateKeeper: MemoryAgentPublicConfig;
+ agentLayerExtractor: MemoryLayerExtractorPublicConfig;
+ concurrency?: number;
+ embedding?: MemoryAgentPublicConfig;
+}
+
+export interface GlobalMemoryConfig {
+ userMemory?: GlobalMemoryExtractionConfig;
+}
+
export interface ServerModelProviderConfig {
enabled?: boolean;
enabledModels?: string[];
@@ -33,6 +57,7 @@ export interface GlobalServerConfig {
*/
enabledOAuthSSO?: boolean;
image?: PartialDeep<UserImageConfig>;
+ memory?: GlobalMemoryConfig;
oAuthSSOProviders?: string[];
systemAgent?: PartialDeep<UserSystemAgentConfig>;
telemetry: {
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index 5f790ae75d9..4fd95aaaf42 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -1,6 +1,7 @@
import { ReactNode } from 'react';
import { z } from 'zod';
+import type { RuntimeStepContext } from '../stepContext';
import { HumanInterventionConfigSchema, HumanInterventionPolicySchema } from './intervention';
import type { HumanInterventionConfig, HumanInterventionPolicy } from './intervention';
@@ -36,6 +37,16 @@ const MetaSchema = z.object({
title: z.string(),
});
+/**
+ * Control the render display behavior for tool results
+ * - 'collapsed': Default collapsed, user can expand (default)
+ * - 'expand': Default expanded, user can collapse
+ * - 'alwaysExpand': Always expanded, user cannot collapse
+ */
+export type RenderDisplayControl = 'alwaysExpand' | 'collapsed' | 'expand';
+
+export const RenderDisplayControlSchema = z.enum(['collapsed', 'expand', 'alwaysExpand']);
+
export interface LobeChatPluginApi {
description: string;
/**
@@ -53,6 +64,15 @@ export interface LobeChatPluginApi {
humanIntervention?: HumanInterventionConfig;
name: string;
parameters: Record<string, any>;
+ /**
+ * Control the render display behavior for tool results
+ * - 'collapsed': Default collapsed, user can expand (default)
+ * - 'expand': Default expanded, user can collapse
+ * - 'alwaysExpand': Always expanded, user cannot collapse
+ *
+ * @default 'collapsed'
+ */
+ renderDisplayControl?: RenderDisplayControl;
url?: string;
}
@@ -61,6 +81,7 @@ export const LobeChatPluginApiSchema = z.object({
humanIntervention: HumanInterventionConfigSchema.optional(),
name: z.string(),
parameters: z.record(z.string(), z.any()),
+ renderDisplayControl: RenderDisplayControlSchema.optional(),
url: z.string().optional(),
});
@@ -123,6 +144,10 @@ export interface BuiltinRenderProps<Arguments = any, State = any, Content = any>
messageId: string;
pluginError?: any;
pluginState?: State;
+ /**
+ * The tool call ID from the assistant message
+ */
+ toolCallId?: string;
}
export type BuiltinRender = <A = any, S = any, C = any>(
@@ -159,6 +184,389 @@ export interface BuiltinInterventionProps<Arguments = any> {
args: Arguments;
identifier?: string;
messageId: string;
+ /**
+ * Callback to update the arguments before approval
+ * This is called when the user modifies the intervention content
+ * The approve action will wait for this async callback to complete
+ */
+ onArgsChange?: (args: Arguments) => void | Promise<void>;
+ /**
+ * Register a callback to be called before approval
+ * Used by intervention components that need to flush pending saves (e.g., debounced saves)
+ * before the approve action proceeds
+ * @param id - Unique identifier for the callback (for reliable cleanup)
+ * @param callback - The callback to execute before approval
+ * @returns Cleanup function to unregister the callback
+ */
+ registerBeforeApprove?: (id: string, callback: () => void | Promise<void>) => () => void;
}
export type BuiltinIntervention = (props: BuiltinInterventionProps) => ReactNode;
+
+// ==================== Executor Types ====================
+
+/**
+ * Result returned by builtin tool executors
+ */
+export interface BuiltinToolResult {
+ /**
+ * The content to display in the tool message
+ */
+ content?: string;
+
+ /**
+ * Error information if the tool execution failed
+ */
+ error?: {
+ body?: any;
+ message: string;
+ type: string;
+ };
+
+ /**
+ * Metadata to attach to the tool message
+ * Used to mark messages for special handling (e.g., agentCouncil for parallel display)
+ */
+ metadata?: Record<string, any>;
+
+ /**
+ * Plugin state for UI rendering
+ */
+ state?: any;
+
+ /**
+ * Whether to stop the current execution flow
+ * - true: Stop execution (e.g., speak/broadcast in group management)
+ * - false/undefined: Continue execution
+ */
+ stop?: boolean;
+
+ /**
+ * Whether the tool execution was successful
+ */
+ success: boolean;
+}
+
+/**
+ * Context passed to builtin tool executors
+ */
+export interface BuiltinToolContext {
+ /**
+ * The current agent ID executing this tool (supervisor agent in group context)
+ * Used to identify which agent called the tool for orchestration purposes
+ */
+ agentId?: string;
+
+ /**
+ * The current group ID (only available in group chat context)
+ * Used by group management tools to access group member information
+ */
+ groupId?: string;
+
+ /**
+ * Group orchestration callbacks (only available in group chat context)
+ * Used by group management tools to trigger the next orchestration phase
+ */
+ groupOrchestration?: GroupOrchestrationCallbacks;
+
+ /**
+ * The tool message ID
+ */
+ messageId: string;
+
+ /**
+ * Optional callback for streaming updates
+ * Only needed for tools that support streaming output
+ */
+ onStreamingUpdate?: (chunk: string) => Promise<void>;
+
+ /**
+ * The current operation ID (for abort signal)
+ */
+ operationId?: string;
+
+ /**
+ * Current plugin state for this tool message
+ * Use `stepContext` instead for cross-message state
+ */
+ pluginState?: Record<string, unknown>;
+
+ /**
+ * Register a callback to execute after AgentRuntime completes
+ * Used for actions that should happen after the current execution flow finishes
+ * to avoid race conditions with message updates
+ */
+ registerAfterCompletion?: (callback: AfterCompletionCallback) => void;
+
+ /**
+ * AbortSignal for cancellation detection
+ */
+ signal?: AbortSignal;
+
+ /**
+ * Step context computed at the beginning of each step
+ * Contains dynamic state like GTD todos that changes between steps
+ * Computed by AgentRuntime and passed to Tool Executors
+ */
+ stepContext?: RuntimeStepContext;
+
+ /**
+ * The current topic ID (only available when operating within a topic)
+ * Used by tools that need to create messages or operations within a topic
+ */
+ topicId?: string | null;
+}
+
+/**
+ * Callback type for after-completion actions
+ */
+export type AfterCompletionCallback = () => void | Promise<void>;
+
+/**
+ * Base params for group orchestration callbacks
+ */
+export interface GroupOrchestrationBaseParams {
+ /**
+ * The supervisor agent ID (the one who called this tool)
+ */
+ supervisorAgentId: string;
+}
+
+/**
+ * Params for triggerSpeak callback
+ */
+export interface TriggerSpeakParams extends GroupOrchestrationBaseParams {
+ /**
+ * The agent ID to speak
+ */
+ agentId: string;
+ /**
+ * Optional instruction for the agent
+ */
+ instruction?: string;
+ /**
+ * If true, the orchestration will end after this agent responds,
+ * without calling the supervisor again.
+ */
+ skipCallSupervisor?: boolean;
+}
+
+/**
+ * Params for triggerBroadcast callback
+ */
+export interface TriggerBroadcastParams extends GroupOrchestrationBaseParams {
+ /**
+ * Array of agent IDs to broadcast to
+ */
+ agentIds: string[];
+ /**
+ * Optional instruction for the agents
+ */
+ instruction?: string;
+ /**
+ * If true, the orchestration will end after all agents respond,
+ * without calling the supervisor again.
+ */
+ skipCallSupervisor?: boolean;
+ /**
+ * The tool message ID that triggered the broadcast
+ * Used as parentId for agent responses to build correct message tree
+ */
+ toolMessageId: string;
+}
+
+/**
+ * Params for triggerDelegate callback
+ */
+export interface TriggerDelegateParams extends GroupOrchestrationBaseParams {
+ /**
+ * The agent ID to delegate to
+ */
+ agentId: string;
+ /**
+ * Optional reason for delegation
+ */
+ reason?: string;
+}
+
+/**
+ * Params for triggerExecuteTask callback
+ */
+export interface TriggerExecuteTaskParams extends GroupOrchestrationBaseParams {
+ /**
+ * The agent ID to execute the task
+ */
+ agentId: string;
+ /**
+ * If true, the orchestration will end after the task completes,
+ * without calling the supervisor again.
+ */
+ skipCallSupervisor?: boolean;
+ /**
+ * The task description for the agent
+ */
+ task: string;
+ /**
+ * Optional timeout in milliseconds
+ */
+ timeout?: number;
+ /**
+ * The tool message ID that triggered the task
+ */
+ toolMessageId: string;
+}
+
+/**
+ * Group Orchestration callbacks for group management tools
+ * These callbacks are used to trigger the next phase in multi-agent orchestration
+ */
+export interface GroupOrchestrationCallbacks {
+ /**
+ * Trigger broadcast to multiple agents
+ */
+ triggerBroadcast: (params: TriggerBroadcastParams) => Promise<void>;
+
+ /**
+ * Trigger delegate to a specific agent
+ */
+ triggerDelegate: (params: TriggerDelegateParams) => Promise<void>;
+
+ /**
+ * Trigger async task execution for an agent
+ */
+ triggerExecuteTask: (params: TriggerExecuteTaskParams) => Promise<void>;
+
+ /**
+ * Trigger speak to a specific agent
+ */
+ triggerSpeak: (params: TriggerSpeakParams) => Promise<void>;
+}
+
+/**
+ * Builtin tool executor function type
+ */
+export type BuiltinToolExecutor<TParams = any> = (
+ params: TParams,
+ ctx: BuiltinToolContext,
+) => Promise<BuiltinToolResult>;
+
+/**
+ * Interface for builtin tool executor class
+ * Each executor class should implement this interface
+ */
+export interface IBuiltinToolExecutor {
+ /**
+ * Get all supported API names
+ *
+ * @returns Array of supported API names
+ */
+ getApiNames(): string[];
+
+ /**
+ * Check if this executor supports the given API
+ *
+ * @param apiName - The API name to check
+ * @returns Whether the API is supported
+ */
+ hasApi(apiName: string): boolean;
+
+ /**
+ * The tool identifier (e.g., 'lobe-group-management')
+ */
+ readonly identifier: string;
+
+ /**
+ * Invoke a specific API of this tool
+ *
+ * @param apiName - The API name to invoke
+ * @param params - Parameters for the API
+ * @param ctx - Execution context
+ * @returns The execution result
+ */
+ invoke(apiName: string, params: any, ctx: BuiltinToolContext): Promise<BuiltinToolResult>;
+}
+
+/**
+ * Base Executor Class
+ *
+ * Provides automatic invoke/hasApi/getApiNames implementation.
+ * Subclasses only need to define business methods.
+ *
+ * Usage:
+ * ```typescript
+ * class MyExecutor extends BaseExecutor<typeof MyApiName> {
+ * readonly identifier = 'my-tool';
+ * protected readonly apiEnum = MyApiName;
+ *
+ * myMethod = async (params: MyParams, ctx: BuiltinToolContext) => {
+ * // business logic
+ * return { success: true, content: 'result' };
+ * };
+ * }
+ * ```
+ */
+export abstract class BaseExecutor<
+ TApiEnum extends Record<string, string>,
+> implements IBuiltinToolExecutor {
+ /**
+ * The tool identifier (e.g., 'lobe-group-management')
+ */
+ abstract readonly identifier: string;
+
+ /**
+ * The API name enum for this executor
+ * Used to validate API names and auto-discover methods
+ */
+ protected abstract readonly apiEnum: TApiEnum;
+
+ /**
+ * Invoke a specific API of this tool
+ * Automatically routes to the corresponding method
+ */
+ invoke = async (
+ apiName: string,
+ params: any,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ // Validate API name
+ if (!this.hasApi(apiName)) {
+ return {
+ error: {
+ message: `Unknown API: ${apiName}`,
+ type: 'ApiNotFound',
+ },
+ success: false,
+ };
+ }
+
+ // Get the method from this instance
+ const method = (this as any)[apiName];
+
+ if (typeof method !== 'function') {
+ return {
+ error: {
+ message: `Method not implemented: ${apiName}`,
+ type: 'MethodNotImplemented',
+ },
+ success: false,
+ };
+ }
+
+ // Invoke the method
+ return method(params, ctx);
+ };
+
+ /**
+ * Check if this executor supports the given API
+ */
+ hasApi(apiName: string): boolean {
+ return Object.values(this.apiEnum).includes(apiName);
+ }
+
+ /**
+ * Get all supported API names
+ */
+ getApiNames(): string[] {
+ return Object.values(this.apiEnum);
+ }
+}
diff --git a/packages/types/src/tool/intervention.ts b/packages/types/src/tool/intervention.ts
index 341ffe15781..d42a1354cad 100644
--- a/packages/types/src/tool/intervention.ts
+++ b/packages/types/src/tool/intervention.ts
@@ -5,9 +5,10 @@ import { z } from 'zod';
*/
export type HumanInterventionPolicy =
| 'never' // Never intervene, auto-execute
- | 'required'; // Always require intervention
+ | 'required' // Need intervention (can be bypassed by user's auto-run mode)
+ | 'always'; // Always need intervention (cannot be bypassed by auto-run mode)
-export const HumanInterventionPolicySchema = z.enum(['never', 'required']);
+export const HumanInterventionPolicySchema = z.enum(['never', 'required', 'always']);
/**
* Argument Matcher for parameter-level filtering
diff --git a/packages/types/src/util.ts b/packages/types/src/util.ts
new file mode 100644
index 00000000000..87ec9c0c0c3
--- /dev/null
+++ b/packages/types/src/util.ts
@@ -0,0 +1,2 @@
+export type Primitive = number | string | boolean | undefined | null | any[];
+export type Optional<T, K extends keyof T> = { [P in K]?: T[P] } & { [P in Exclude<keyof T, K>]: T[P] extends Primitive ? T[P] : Optional<T[P], keyof T[P] & K> };