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.

♻️ refactor(database): split the 3199-line agent model into cohesive modules (#21139)

Arvin Xu29e90872c79b
diff --git a/packages/database/src/models/__tests__/agent.characterization.test.ts b/packages/database/src/models/__tests__/agent.characterization.test.ts
new file mode 100644
index 00000000000..6d1834be45b
--- /dev/null
+++ b/packages/database/src/models/__tests__/agent.characterization.test.ts
@@ -0,0 +1,404 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agents,
+ agentsToSessions,
+ sessionGroups,
+ sessions,
+ users,
+ workspaces,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import * as agentModule from '../agent';
+import { AgentModel } from '../agent';
+import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from '../agentCopyJob';
+import { AGENT_TRANSFER_IN_PROGRESS, AgentTransferJobModel } from '../agentTransferJob';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'agent-char-user';
+const otherUserId = 'agent-char-other';
+
+/** Former private helpers; excluded so the pin only covers the public surface. */
+const PRIVATE_MEMBERS = new Set([
+ 'agentsFilesOwnership',
+ 'agentsKnowledgeBasesOwnership',
+ 'agentsToSessionsOwnership',
+ 'assertFixedExecutionTarget',
+ 'assertNotAgentBuilderProtectedWrite',
+ 'assertSessionGroupAssignable',
+ 'assertWorkspaceDeviceBinding',
+ 'buildQueryAgentsWhere',
+ 'collectBoundDeviceIds',
+ 'documentsOwnership',
+ 'enrichAgentWithKnowledge',
+ 'findOwnedGroupMemberships',
+ 'ownership',
+ 'queryGroupMemberships',
+ 'sanitizeAgencyConfigForWorkspace',
+ 'sessionsOwnership',
+ 'stripImmutableFields',
+ 'stripReservedSlug',
+ 'trashScope',
+ 'withWorkspaceSelectionPolicyDefaults',
+]);
+
+const PUBLIC_METHODS = [
+ 'assertDeletable',
+ 'batchCreate',
+ 'batchDelete',
+ 'checkByMarketIdentifier',
+ 'countAgents',
+ 'create',
+ 'createAgentFiles',
+ 'createAgentKnowledgeBase',
+ 'delete',
+ 'deleteAgentFile',
+ 'deleteAgentKnowledgeBase',
+ 'duplicate',
+ 'existsById',
+ 'existsOwnedById',
+ 'findAgentIdsBySessionIds',
+ 'findBySessionId',
+ 'findSessionIdsByAgentIds',
+ 'findTrashedByIds',
+ 'getAgentAgencyConfig',
+ 'getAgentAssignedKnowledge',
+ 'getAgentAvatarsByIds',
+ 'getAgentByForkedFromIdentifier',
+ 'getAgentByMarketIdentifier',
+ 'getAgentConfig',
+ 'getAgentConfigById',
+ 'getAgentDisplayFields',
+ 'getAgentModelConfig',
+ 'getAgentSnapshotForTaskCreate',
+ 'getAgentVisibility',
+ 'getAgentVisibilityMeta',
+ 'getAssignableSessionGroupVisibility',
+ 'getBuiltinAgent',
+ 'getGroupMembershipImpact',
+ 'getTopicShareSubject',
+ 'hasTrashedOwner',
+ 'listMessengerBindableAgents',
+ 'lockTrashedForPurge',
+ 'publishToWorkspace',
+ 'purge',
+ 'queryAgents',
+ 'queryBoundToDevice',
+ 'rank',
+ 'resolveIdBySlug',
+ 'restore',
+ 'setVisibility',
+ 'softDelete',
+ 'toggleFile',
+ 'toggleKnowledgeBase',
+ 'touchUpdatedAt',
+ 'transferAgent',
+ 'transferAgentOwnership',
+ 'transferAgents',
+ 'transferHasForeignRows',
+ 'update',
+ 'updateConfig',
+ 'updateSessionGroupId',
+ 'updateSlug',
+];
+
+const deletedAt = new Date('2026-01-01T00:00:00.000Z');
+
+let workspaceId = '';
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ const [ws] = await serverDB
+ .insert(workspaces)
+ .values({ name: 'agent-char-ws', primaryOwnerId: userId, slug: 'agent-char-ws' })
+ .returning();
+ workspaceId = ws.id;
+
+ await serverDB.insert(agents).values([
+ {
+ agencyConfig: { heterogeneousProvider: { type: 'claude-code' } } as any,
+ id: 'own-public',
+ slug: 'own-public-slug',
+ title: 'Own public',
+ userId,
+ visibility: 'public',
+ },
+ {
+ id: 'own-private',
+ slug: 'own-private-slug',
+ title: 'Own private',
+ userId,
+ visibility: 'private',
+ },
+ { id: 'foreign', slug: 'foreign-slug', title: 'Foreign', userId: otherUserId },
+ {
+ id: 'ws-member-private',
+ slug: 'ws-member-private-slug',
+ title: 'Workspace member private',
+ userId: otherUserId,
+ visibility: 'private',
+ workspaceId,
+ },
+ {
+ id: 'ws-member-public',
+ slug: 'ws-member-public-slug',
+ title: 'Workspace member public',
+ userId: otherUserId,
+ visibility: 'public',
+ workspaceId,
+ },
+ ]);
+ await serverDB.insert(sessions).values([
+ { id: 'own-session', userId },
+ { id: 'foreign-session', userId: otherUserId },
+ ]);
+ await serverDB.insert(agentsToSessions).values([
+ { agentId: 'own-public', sessionId: 'own-session', userId },
+ { agentId: 'foreign', sessionId: 'foreign-session', userId: otherUserId },
+ ]);
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await serverDB.delete(users);
+});
+
+describe('AgentModel - characterization', () => {
+ describe('public surface', () => {
+ it('exposes the same instance methods', () => {
+ const model = new AgentModel(serverDB, userId);
+ const methods = Object.keys(model)
+ .filter((key) => typeof (model as any)[key] === 'function')
+ .filter((key) => !PRIVATE_MEMBERS.has(key))
+ .sort();
+
+ expect(methods).toEqual(PUBLIC_METHODS);
+ });
+
+ it('keeps the runtime exports', () => {
+ expect(Object.keys(agentModule).sort()).toEqual([
+ 'AGENT_OWNED_BY_GROUP',
+ 'AGENT_OWNERSHIP_STALE',
+ 'AGENT_SHARED_TRANSFER_BLOCKED',
+ 'AgentModel',
+ 'AgentOwnedByGroupError',
+ ]);
+ expect(agentModule.AGENT_OWNED_BY_GROUP).toBe('AGENT_OWNED_BY_GROUP');
+ expect(agentModule.AGENT_OWNERSHIP_STALE).toBe('AGENT_OWNERSHIP_STALE');
+ expect(agentModule.AGENT_SHARED_TRANSFER_BLOCKED).toBe('AGENT_SHARED_TRANSFER_BLOCKED');
+
+ const error = new agentModule.AgentOwnedByGroupError([]);
+ expect(error).toBeInstanceOf(Error);
+ expect(error.message).toBe('AGENT_OWNED_BY_GROUP');
+ expect(error.name).toBe('AgentOwnedByGroupError');
+ expect(error.groups).toEqual([]);
+ });
+ });
+
+ describe('scoped reads', () => {
+ it('getAgentVisibility reads only owned rows', async () => {
+ const model = new AgentModel(serverDB, userId);
+
+ expect(await model.getAgentVisibility('own-public')).toBe('public');
+ expect(await model.getAgentVisibility('own-private')).toBe('private');
+ expect(await model.getAgentVisibility('foreign')).toBeNull();
+ });
+
+ it('getAgentAgencyConfig resolves by id or slug within scope', async () => {
+ const model = new AgentModel(serverDB, userId);
+
+ expect(await model.getAgentAgencyConfig('own-public')).toEqual({
+ heterogeneousProvider: { type: 'claude-code' },
+ });
+ expect(await model.getAgentAgencyConfig('own-public-slug')).toEqual({
+ heterogeneousProvider: { type: 'claude-code' },
+ });
+ expect(await model.getAgentAgencyConfig('own-private')).toBeNull();
+ expect(await model.getAgentAgencyConfig('foreign-slug')).toBeNull();
+ });
+
+ it('getAgentVisibilityMeta returns slug, author and visibility', async () => {
+ const model = new AgentModel(serverDB, userId);
+
+ expect(await model.getAgentVisibilityMeta('own-private')).toEqual({
+ slug: 'own-private-slug',
+ userId,
+ visibility: 'private',
+ });
+ expect(await model.getAgentVisibilityMeta('foreign')).toBeNull();
+ });
+
+ it('resolveIdBySlug trims, and ignores blank or foreign slugs', async () => {
+ const model = new AgentModel(serverDB, userId);
+
+ expect(await model.resolveIdBySlug(' own-public-slug ')).toBe('own-public');
+ expect(await model.resolveIdBySlug(' ')).toBeNull();
+ expect(await model.resolveIdBySlug('foreign-slug')).toBeNull();
+ });
+
+ it('getTopicShareSubject is owner-scoped personally and workspace-scoped in a workspace', async () => {
+ const personal = new AgentModel(serverDB, userId);
+ expect(await personal.getTopicShareSubject('own-public')).toEqual({
+ agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },
+ userId,
+ workspaceId: null,
+ });
+ expect(await personal.getTopicShareSubject('foreign')).toBeNull();
+
+ // Workspace mode matches on workspace only β€” even another member's private agent.
+ const member = new AgentModel(serverDB, userId, workspaceId);
+ expect(await member.getTopicShareSubject('ws-member-private')).toEqual({
+ agencyConfig: null,
+ userId: otherUserId,
+ workspaceId,
+ });
+ expect(await member.getTopicShareSubject('own-public')).toBeNull();
+ });
+
+ it('getAssignableSessionGroupVisibility returns the group bucket or throws', async () => {
+ await serverDB.insert(sessionGroups).values([
+ { id: 'own-group', name: 'Own', userId },
+ { id: 'own-private-group', name: 'Own private', userId, visibility: 'private' },
+ { id: 'foreign-group', name: 'Foreign', userId: otherUserId },
+ ]);
+ const model = new AgentModel(serverDB, userId);
+
+ expect(await model.getAssignableSessionGroupVisibility('own-group')).toBe('public');
+ expect(await model.getAssignableSessionGroupVisibility('own-private-group')).toBe('private');
+ await expect(model.getAssignableSessionGroupVisibility('foreign-group')).rejects.toThrow(
+ 'Session group foreign-group not found in current scope',
+ );
+ });
+
+ it('maps agents and legacy sessions both ways within scope', async () => {
+ const model = new AgentModel(serverDB, userId);
+
+ expect(await model.findSessionIdsByAgentIds([])).toEqual([]);
+ expect(await model.findSessionIdsByAgentIds(['own-public', 'foreign'])).toEqual([
+ 'own-session',
+ ]);
+ expect(await model.findAgentIdsBySessionIds([])).toEqual([]);
+ expect(await model.findAgentIdsBySessionIds(['own-session', 'foreign-session'])).toEqual([
+ 'own-public',
+ ]);
+ });
+ });
+
+ describe('recycle bin', () => {
+ const liveIds = async () =>
+ (await serverDB.select({ id: agents.id, isDeleted: agents.isDeleted }).from(agents))
+ .filter((row) => !row.isDeleted)
+ .map((row) => row.id)
+ .sort();
+
+ it('softDelete stamps only owned rows', async () => {
+ const model = new AgentModel(serverDB, userId);
+
+ expect(await model.softDelete([], { deletedAt })).toEqual([]);
+ const trashed = await model.softDelete(['own-public', 'foreign'], { deletedAt });
+
+ expect(trashed.map((row) => row.id)).toEqual(['own-public']);
+ expect(trashed[0].isDeleted).toBe(true);
+ expect(trashed[0].deletedAt).toEqual(deletedAt);
+ });
+
+ it('softDelete with restrictToCreator skips teammates in a workspace', async () => {
+ const owner = new AgentModel(serverDB, userId, workspaceId);
+
+ expect(
+ await owner.softDelete(['ws-member-public'], { deletedAt, restrictToCreator: true }),
+ ).toEqual([]);
+ expect(
+ (await owner.softDelete(['ws-member-public'], { deletedAt })).map((row) => row.id),
+ ).toEqual(['ws-member-public']);
+ });
+
+ it('hasTrashedOwner follows the agent id or the legacy session link', async () => {
+ const model = new AgentModel(serverDB, userId);
+
+ expect(await model.hasTrashedOwner({})).toBe(false);
+ expect(await model.hasTrashedOwner({ agentId: 'own-public' })).toBe(false);
+
+ await model.softDelete(['own-public'], { deletedAt });
+
+ expect(await model.hasTrashedOwner({ agentId: 'own-public' })).toBe(true);
+ expect(await model.hasTrashedOwner({ sessionId: 'own-session' })).toBe(true);
+ expect(await model.hasTrashedOwner({ agentId: null, sessionId: null })).toBe(false);
+ });
+
+ it('findTrashedByIds / lockTrashedForPurge / restore / purge only touch trashed owned rows', async () => {
+ const model = new AgentModel(serverDB, userId);
+ await model.softDelete(['own-public', 'own-private'], { deletedAt });
+
+ expect(await model.findTrashedByIds([])).toEqual([]);
+ expect(
+ (await model.findTrashedByIds(['own-public', 'foreign'])).map((row) => row.id),
+ ).toEqual(['own-public']);
+ expect(await model.lockTrashedForPurge([])).toEqual([]);
+ expect(
+ await serverDB.transaction(async (tx) =>
+ new AgentModel(tx as unknown as LobeChatDatabase, userId).lockTrashedForPurge([
+ 'own-private',
+ 'foreign',
+ ]),
+ ),
+ ).toEqual(['own-private']);
+
+ expect(await model.restore([])).toEqual([]);
+ expect((await model.restore(['own-private', 'foreign'])).map((row) => row.id)).toEqual([
+ 'own-private',
+ ]);
+ expect((await model.findTrashedByIds(['own-private'])).length).toBe(0);
+
+ expect(await model.purge([])).toEqual([]);
+ expect(await model.purge(['own-public', 'own-private', 'foreign'])).toEqual(['own-public']);
+ expect(await liveIds()).toEqual([
+ 'foreign',
+ 'own-private',
+ 'ws-member-private',
+ 'ws-member-public',
+ ]);
+ const links = await serverDB
+ .select({ agentId: agentsToSessions.agentId })
+ .from(agentsToSessions)
+ .where(eq(agentsToSessions.sessionId, 'own-session'));
+ expect(links).toEqual([]);
+ });
+ });
+
+ describe('assertDeletable', () => {
+ it('passes with no pending job, with or without a transaction', async () => {
+ const model = new AgentModel(serverDB, userId);
+
+ await expect(model.assertDeletable([])).resolves.toBeUndefined();
+ await expect(model.assertDeletable(['own-public'])).resolves.toBeUndefined();
+ await expect(
+ serverDB.transaction((tx) => model.assertDeletable(['own-public'], tx)),
+ ).resolves.toBeUndefined();
+ });
+
+ it.each([
+ ['a pending transfer job', 'transfer', AGENT_TRANSFER_IN_PROGRESS],
+ ['a pending transfer remap', 'remap', AGENT_TRANSFER_IN_PROGRESS],
+ ['a pending copy job', 'copy', AGENT_COPY_IN_PROGRESS],
+ ] as const)('rejects while there is %s', async (_name, kind, message) => {
+ vi.spyOn(AgentTransferJobModel, 'hasPendingJobForAgents').mockResolvedValue(
+ kind === 'transfer',
+ );
+ vi.spyOn(AgentTransferJobModel, 'hasPendingRemapForSourceAgents').mockResolvedValue(
+ kind === 'remap',
+ );
+ vi.spyOn(AgentCopyJobModel, 'hasPendingCopyJobForSourceAgents').mockResolvedValue(
+ kind === 'copy',
+ );
+ const model = new AgentModel(serverDB, userId);
+
+ await expect(model.assertDeletable(['own-public'])).rejects.toThrow(message);
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.ts
index b76d9f75442..44cbcb399f0 100644
--- a/packages/database/src/models/__tests__/agent.test.ts
+++ b/packages/database/src/models/__tests__/agent.test.ts
@@ -3292,9 +3292,9 @@ describe('AgentModel', () => {
.values({ systemRole: 'OLD PROMPT', userId })
.returning();
- const original = (agentModel as any).assertWorkspaceDeviceBinding.bind(agentModel);
+ const original = (agentModel as any).ctx.assertWorkspaceDeviceBinding;
const spy = vi
- .spyOn(agentModel as any, 'assertWorkspaceDeviceBinding')
+ .spyOn((agentModel as any).ctx, 'assertWorkspaceDeviceBinding')
.mockImplementationOnce(async (...args: unknown[]) => {
await agentModel.update(agent.id, { editorData: null, systemRole: 'NEW PROMPT' });
return original(...args);
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
deleted file mode 100644
index c3a2dc7cb8b..00000000000
--- a/packages/database/src/models/agent.ts
+++ /dev/null
@@ -1,3199 +0,0 @@
-import { BUILTIN_AGENT_SLUGS, getAgentPersistConfig } from '@lobechat/builtin-agents';
-import {
- DEFAULT_INBOX_TITLE,
- INBOX_SESSION_ID,
- isHeterogeneousAgentModelId,
-} from '@lobechat/const';
-import type {
- AgentRankItem,
- AgentTopicShareSubject,
- DeviceBoundAgentItem,
- LobeAgentAgencyConfig,
-} from '@lobechat/types';
-import {
- applyWorkingDirByDevicePatch,
- DEFAULT_WORKSPACE_AGENT_SELECTION_POLICIES,
- getHeterogeneousTaskModelProvider,
-} from '@lobechat/types';
-import { toRecord } from '@lobechat/utils/object';
-import { TRPCError } from '@trpc/server';
-import {
- and,
- asc,
- count,
- desc,
- eq,
- gt,
- ilike,
- inArray,
- isNull,
- like,
- ne,
- notInArray,
- or,
- sql,
-} from 'drizzle-orm';
-import type { PartialDeep } from 'type-fest';
-
-import { merge } from '@/utils/merge';
-
-import type { AgentItem } from '../schemas';
-import {
- agentBotProviders,
- agentCronJobs,
- agentLabelAssignments,
- agents,
- agentsFiles,
- agentShares,
- agentsKnowledgeBases,
- agentsToSessions,
- briefs,
- chatGroups,
- chatGroupsAgents,
- devices,
- documents,
- expertiseBindings,
- expertiseDomains,
- expertiseInsights,
- expertiseRuns,
- files,
- knowledgeBases,
- messages,
- projectAgents,
- projects,
- sessionGroups,
- sessions,
- taskComments,
- taskDependencies,
- taskDocuments,
- tasks,
- taskTopics,
- threads,
- topicDocuments,
- topics,
-} from '../schemas';
-import type { LobeChatDatabase, Transaction } from '../type';
-import {
- collectBoundDeviceIds,
- sanitizeAgencyConfigsForWorkspace,
-} from '../utils/agencyConfigDevices';
-import {
- rehomeAgentConnectorsForRecipient,
- rehomeAgentConnectorsForScopeTransfer,
-} from '../utils/agentConnectors';
-import {
- moveAgentDocumentsForScopeTransfer,
- rehomeAgentDocumentsForRecipient,
-} from '../utils/agentDocumentsOwnership';
-import { rehomeAgentExpertiseForRecipient } from '../utils/agentExpertise';
-import {
- detachAgentKnowledgeMountsForRecipient,
- rehomeRetainedAgentKnowledgeMounts,
-} from '../utils/agentKnowledgeMounts';
-import { rehomeAgentLabelsForRecipient } from '../utils/agentLabelsOwnership';
-import { rehomeAgentQuotaBindingsForRecipient } from '../utils/agentQuotaBindings';
-import { notFileBackedPlaceholder } from '../utils/fileBackedPlaceholder';
-import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';
-import { resolveGroupMembershipType } from '../utils/groupMembership';
-import { normalizeInboxAgentMeta } from '../utils/inboxAgent';
-import { readOriginalCharCount } from '../utils/parsedDocument';
-import { sanitizeAgentApiConfig } from '../utils/sanitizeAgentApiConfig';
-import { notShareVisitorTopic } from '../utils/shareVisitor';
-import {
- isTrashed,
- notTrashed,
- restoreStamp,
- type SoftDeleteOptions,
- trashStamp,
-} from '../utils/softDelete';
-import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
-import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from './agentCopyJob';
-import {
- AGENT_TRANSFER_IN_PROGRESS,
- AgentTransferJobModel,
- getAgentTransferSyncMessageThreshold,
- rewriteMessageScopeForTopics,
- rewriteResidualMessageScope,
-} from './agentTransferJob';
-import {
- hasForeignTopicComments,
- syncTopicCommentsOnTopicTransfer,
- TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS,
-} from './topicComment';
-
-/**
- * Fields the Agent Builder's own row (`slug = BUILTIN_AGENT_SLUGS.agentBuilder`) must never
- * carry. Its `persist` config only stores `model`/`provider`/`chatConfig` β€” title, avatar,
- * systemRole, etc. are rendered from i18n / the static systemRoleTemplate at runtime, never
- * from this row.
- *
- * Before PR #16420, `lobe-agent-management`'s self-management prompt could make the builder
- * mistake an ambiguous "update this" request for editing itself instead of the target agent.
- * Depending on caller (browser client tool executor vs. gateway server runtime in
- * `apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts`), these fields can
- * arrive through *either* `AgentModel.update()` or `updateConfig()` β€” e.g. the gateway's
- * `updatePrompt` writes `systemRole` via `update()`, while the browser client's meta editor
- * writes `title`/`avatar`/etc. via `updateConfig()`. So both methods must strip the full list,
- * not just the fields each historically happened to receive. Clients on builds older than
- * PR #16420 can still hit this path, so enforce it here (the single write chokepoint)
- * regardless of caller.
- *
- * Such a write is rejected, not silently trimmed: the writer is almost always aiming at a
- * different agent (the one the builder is editing), and a trimmed write still reports
- * success β€” the caller would believe the prompt/name landed when nothing changed.
- */
-const AGENT_BUILDER_PROTECTED_FIELDS = [
- 'title',
- 'name',
- 'description',
- 'avatar',
- 'backgroundColor',
- 'tags',
- 'marketIdentifier',
- 'systemRole',
-] as const;
-
-const assertNoAgentBuilderProtectedFields = (data: Record<string, unknown>) => {
- const fields = AGENT_BUILDER_PROTECTED_FIELDS.filter((field) => data[field] !== undefined);
- if (fields.length === 0) return;
-
- throw new TRPCError({
- code: 'FORBIDDEN',
- message:
- `The Agent Builder's own ${fields.join(', ')} cannot be changed, so nothing was updated. ` +
- 'Target the agent being edited instead.',
- });
-};
-
-/**
- * Fields that define a row's identity, scope and provisioning status. Every one of
- * them feeds authorization β€” `slug` + `virtual` classify collaborative builtins,
- * `userId` is authorship, `workspaceId` is the tenancy boundary, and `visibility`
- * has dedicated creator/owner-gated endpoints β€” so an update must never carry them. `updateConfig` merges whatever the passthrough config endpoint
- * receives, which would otherwise let a member with edit access declassify, orphan
- * or rehome a shared builtin through the very path that was opened for editing it.
- *
- * Creation is different: it legitimately assigns `slug` (random by default) and
- * takes `userId` / `workspaceId` from the trusted context via
- * `buildWorkspacePayload`, so only reserved slugs are filtered there.
- */
-const IMMUTABLE_AGENT_FIELDS = [
- 'createdAt',
- 'id',
- // Folder placement is shared state and has its own validated path
- // (`updateSessionGroupId`), which checks the target is visible in scope and
- // matches the agent's visibility bucket. Riding along in a config patch
- // would skip both, leaving the shared row in a folder the sidebar cannot
- // resolve β€” it then renders in Ungrouped for every member.
- 'sessionGroupId',
- 'slug',
- 'userId',
- 'virtual',
- // `visibility` has its own authorization rules (`setVisibility` is creator /
- // workspace-owner gated, `publishToWorkspace` is creator-only), so it must not
- // ride along in a config patch: a member with edit access on a collaborative
- // builtin could otherwise flip it to `private`, hiding the shared row from
- // everyone else while its workspace slug stays occupied β€” nothing can
- // reprovision it.
- 'visibility',
- 'workspaceId',
-] as const;
-
-/**
- * Accepted shape for a user-chosen slug: lowercase words joined by single
- * hyphens, matching what `randomSlug` generates. No underscores β€” the agent
- * route tells an id from a slug by the underscore in every generated id.
- */
-const AGENT_SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
-
-/** Slugs owned by builtin provisioning; user input must never set one. */
-const RESERVED_AGENT_SLUGS: ReadonlySet<string> = new Set<string>(
- Object.values(BUILTIN_AGENT_SLUGS),
-);
-
-/** One chat group an agent belongs to, as surfaced by the transfer guards. */
-/**
- * A row of {@link AgentModel.queryBoundToDevice}: display fields plus the
- * stored routing config and ownership needed to resolve the caller's
- * effective target.
- */
-export interface DeviceBindingCandidate extends DeviceBoundAgentItem {
- agencyConfig: LobeAgentAgencyConfig | null;
- userId: string;
- workspaceId: string | null;
-}
-
-export interface AgentGroupMembershipRef {
- agentId: string;
- /** `null` when the group is not visible to the caller (see the read below). */
- groupAvatar: string | null;
- groupBackgroundColor: string | null;
- /**
- * `null` when the group is not visible to the caller. The id is identity
- * too: the membership still counts toward the guard, but a private group's
- * identifier is no more the caller's to read than its name.
- */
- groupId: string | null;
- /** `null` when the group is not visible to the caller (see the read below). */
- groupTitle: string | null;
- /**
- * Whether the caller may see this group at all. Carried explicitly because a
- * `null` title is otherwise ambiguous β€” a group can simply be untitled β€” and
- * telling someone a group of theirs is "one you cannot see" is worse than
- * saying nothing.
- */
- groupVisible: boolean;
-}
-
-export const AGENT_OWNED_BY_GROUP = 'AGENT_OWNED_BY_GROUP';
-
-/**
- * Ownership handover rejected: the agent's owner changed (or the agent left
- * the workspace) between the transfer request and its acceptance.
- */
-export const AGENT_OWNERSHIP_STALE = 'AGENT_OWNERSHIP_STALE';
-
-/**
- * A share binds its grants, billing scope and visitor history to the current
- * agent owner and workspace. Transfers remain unsupported while any share row
- * exists, including paused shares; disabling a link must not bypass the guard.
- */
-export const AGENT_SHARED_TRANSFER_BLOCKED = 'AGENT_SHARED_TRANSFER_BLOCKED';
-
-/**
- * Refusal to move an agent that belongs to a chat group rather than to the
- * user. Carries the groups so the caller can say WHICH ones, the way the
- * existing visibility guards do β€” "cannot move this agent" with no reason is
- * a dead end for the person looking at it.
- */
-export class AgentOwnedByGroupError extends Error {
- constructor(readonly groups: AgentGroupMembershipRef[]) {
- super(AGENT_OWNED_BY_GROUP);
- this.name = 'AgentOwnedByGroupError';
- }
-}
-
-interface AgentTransferOptions {
- rejectForeignTopicCommentAuthors?: boolean;
-}
-
-export class AgentModel {
- private userId: string;
- private db: LobeChatDatabase;
- private workspaceId?: string;
-
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
- this.userId = userId;
- this.db = db;
- this.workspaceId = workspaceId;
- }
-
- /**
- * New workspace agents persist both selection policies instead of relying
- * on the intentionally different legacy fallbacks for missing values.
- */
- private withWorkspaceSelectionPolicyDefaults = (
- agencyConfig: LobeAgentAgencyConfig | null | undefined,
- ): LobeAgentAgencyConfig | null | undefined => {
- if (!this.workspaceId) return agencyConfig;
-
- return {
- ...DEFAULT_WORKSPACE_AGENT_SELECTION_POLICIES,
- ...agencyConfig,
- };
- };
-
- /**
- * Rank the user's agents by topic count (agent usage ranking). Counts topics
- * directly via `topics.agentId`, so it is agent-native β€” no sessionId. Mirrors
- * the recents filter: real agents plus the inbox, excluding other virtual agents.
- *
- * Share-visitor topics are excluded from the count: they carry the creator's
- * `userId` (so the plain join would count them) but reflect visitor usage,
- * not the creator's own β€” same rule as `TopicModel.rank` and every other
- * creator-facing aggregate (see `notShareVisitorTopic`). Applied in the join
- * condition rather than `where` so agents whose ONLY topics are visitor ones
- * still drop out via the `count > 0` guard instead of being filtered away
- * before grouping.
- */
- rank = async (limit: number = 10): Promise<AgentRankItem[]> => {
- const rows = await this.db
- .select({
- avatar: agents.avatar,
- backgroundColor: agents.backgroundColor,
- count: count(topics.id).as('count'),
- id: agents.id,
- name: agents.name,
- slug: agents.slug,
- title: agents.title,
- })
- .from(agents)
- .leftJoin(
- topics,
- and(eq(topics.agentId, agents.id), notShareVisitorTopic(), notTrashed(topics.isDeleted)),
- )
- .where(and(this.ownership(), or(eq(agents.slug, INBOX_SESSION_ID), ne(agents.virtual, true))))
- .groupBy(agents.id)
- .having(({ count }) => gt(count, 0))
- .orderBy(desc(sql`count`))
- .limit(limit);
-
- return rows.map(({ slug, ...row }) => normalizeInboxAgentMeta(row, { slug }));
- };
-
- /**
- * Candidate agents for a device's "bound agents" list: agents whose stored
- * agency config routes execution there (`device`, or a desktop `local` pick,
- * which also records its own `boundDeviceId`), plus `extraAgentIds` β€” agents
- * a caller's per-agent device override may route there. Candidates pass the
- * same visibility gate, so an id the caller cannot see is dropped rather
- * than leaked.
- *
- * The routing fields ride along because the stored config is only a
- * baseline: the caller merges their own override over it (see
- * `resolveAgentAgencyConfig`) and keeps the agents whose EFFECTIVE target
- * is still this device.
- */
- queryBoundToDevice = async (
- deviceId: string,
- extraAgentIds: string[] = [],
- ): Promise<DeviceBindingCandidate[]> => {
- const boundHere = and(
- sql`${agents.agencyConfig} ->> 'boundDeviceId' = ${deviceId}`,
- sql`${agents.agencyConfig} ->> 'executionTarget' IN ('device', 'local')`,
- );
-
- const rows = await this.db
- .select({
- agencyConfig: agents.agencyConfig,
- avatar: agents.avatar,
- backgroundColor: agents.backgroundColor,
- id: agents.id,
- name: agents.name,
- slug: agents.slug,
- title: agents.title,
- userId: agents.userId,
- visibility: agents.visibility,
- workspaceId: agents.workspaceId,
- })
- .from(agents)
- .where(
- and(
- this.ownership(),
- or(eq(agents.slug, INBOX_SESSION_ID), ne(agents.virtual, true)),
- extraAgentIds.length > 0 ? or(boundHere, inArray(agents.id, extraAgentIds)) : boundHere,
- ),
- )
- .orderBy(desc(agents.updatedAt));
-
- return rows.map(({ slug, ...row }) => normalizeInboxAgentMeta(row, { slug }));
- };
-
- /**
- * Compat-mode ownership predicate for the `agents` table.
- * - team mode (workspaceId set): `workspace_id = ?` plus visibility-aware
- * filtering β€” public agents are visible to every member, private agents
- * are only visible to their creator.
- * - personal mode: `user_id = ? AND workspace_id IS NULL`.
- */
- private ownership = () =>
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- {
- isDeleted: agents.isDeleted,
- userId: agents.userId,
- workspaceId: agents.workspaceId,
- visibility: agents.visibility,
- },
- );
-
- /**
- * {@link ownership} without the recycle-bin filter β€” restore / purge / the
- * trash pre-flight lock only.
- */
- private trashScope = () =>
- buildWorkspaceWhere(
- { includeTrashed: true, userId: this.userId, workspaceId: this.workspaceId },
- {
- isDeleted: agents.isDeleted,
- userId: agents.userId,
- workspaceId: agents.workspaceId,
- visibility: agents.visibility,
- },
- );
-
- /** Same predicate but for the `sessions` table (used in delete cascade). */
- private sessionsOwnership = () =>
- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, sessions);
-
- /** Ownership predicates for the agent join/related tables. */
- private documentsOwnership = () =>
- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, documents);
-
- private agentsFilesOwnership = () =>
- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentsFiles);
-
- private agentsKnowledgeBasesOwnership = () =>
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- agentsKnowledgeBases,
- );
-
- private agentsToSessionsOwnership = () =>
- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentsToSessions);
-
- private collectBoundDeviceIds = (
- agencyConfig: PartialDeep<LobeAgentAgencyConfig> | null | undefined,
- ): string[] => collectBoundDeviceIds(agencyConfig);
-
- /**
- * Shared ownership-rehoming device sanitation β€” see
- * `sanitizeAgencyConfigsForWorkspace` in `utils/agencyConfigDevices`.
- */
- private sanitizeAgencyConfigForWorkspace = (
- db: LobeChatDatabase | Transaction,
- targetWorkspaceId: string,
- agencyConfigs: Array<LobeAgentAgencyConfig | null | undefined>,
- options?: { viewerUserId?: string },
- ): Promise<Array<LobeAgentAgencyConfig | null>> =>
- sanitizeAgencyConfigsForWorkspace(db, targetWorkspaceId, agencyConfigs, options);
-
- /**
- * Enforce: a workspace-scoped agent may only bind devices enrolled in the
- * same workspace. Personal devices (workspace_id IS NULL) are reachable only
- * by their owning user, so a workspace member who isn't that owner would get
- * a broken agent. Rejects at write time rather than at execution time.
- *
- * Only device ids INTRODUCED by this patch are checked β€” ids already present
- * in `storedConfig` are grandfathered. Client patches spread the whole stored
- * `agencyConfig` (device picker, working-dir writes), so a legacy
- * personal-device reference left from before the agent joined the workspace
- * (or before this guard existed) would otherwise poison every future save,
- * including binding a perfectly valid workspace device.
- *
- * No-op when `agentWorkspaceId` is null (personal agent β€” any device OK) or
- * when the patch carries no new device ids.
- */
- private assertWorkspaceDeviceBinding = async (
- agentWorkspaceId: string | null,
- agencyConfig: PartialDeep<LobeAgentAgencyConfig> | null | undefined,
- storedConfig?: LobeAgentAgencyConfig | null,
- ): Promise<void> => {
- if (!agentWorkspaceId) return;
- const existing = new Set(this.collectBoundDeviceIds(storedConfig));
- const candidates = this.collectBoundDeviceIds(agencyConfig).filter((id) => !existing.has(id));
- if (candidates.length === 0) return;
-
- const rows = await this.db
- .select({ deviceId: devices.deviceId })
- .from(devices)
- .where(and(eq(devices.workspaceId, agentWorkspaceId), inArray(devices.deviceId, candidates)));
- const allowed = new Set(rows.map((r) => r.deviceId));
- const invalid = candidates.find((id) => !allowed.has(id));
- if (invalid) {
- throw new TRPCError({
- cause: { data: { code: 'WorkspaceAgentRequiresWorkspaceDevice', deviceId: invalid } },
- code: 'FORBIDDEN',
- message:
- 'Workspace agent can only bind devices enrolled in the same workspace. ' +
- 'Enroll the device to the workspace, or pick a workspace device.',
- });
- }
- };
-
- /**
- * A fixed workspace agent is a shared execution contract. It may use any
- * server-resolvable shared target; a concrete device additionally has to be
- * public in the same workspace. Use one generic device error for
- * missing/private/cross-workspace rows so the write path never reveals a
- * device the caller cannot otherwise see.
- */
- private assertFixedExecutionTarget = async (
- agentWorkspaceId: string | null,
- agencyConfig: LobeAgentAgencyConfig | null | undefined,
- ): Promise<void> => {
- if (!agentWorkspaceId || agencyConfig?.executionTargetSelectionPolicy !== 'fixed') return;
-
- if (
- !agencyConfig.executionTarget ||
- !['auto', 'device', 'none', 'sandbox'].includes(agencyConfig.executionTarget)
- ) {
- throw new TRPCError({
- cause: { data: { code: 'FixedAgentRequiresSharedExecutionTarget' } },
- code: 'BAD_REQUEST',
- message: 'A fixed workspace agent requires a shared execution target.',
- });
- }
-
- if (agencyConfig.executionTarget !== 'device') return;
-
- if (!agencyConfig.boundDeviceId) {
- throw new TRPCError({
- cause: { data: { code: 'FixedAgentRequiresDeviceTarget' } },
- code: 'BAD_REQUEST',
- message: 'A fixed device target requires a bound device.',
- });
- }
-
- const row = await this.db.query.devices.findFirst({
- columns: { deviceId: true },
- where: and(
- eq(devices.workspaceId, agentWorkspaceId),
- eq(devices.deviceId, agencyConfig.boundDeviceId),
- eq(devices.visibility, 'public'),
- ),
- });
-
- if (!row) {
- throw new TRPCError({
- cause: { data: { code: 'FixedAgentRequiresPublicWorkspaceDevice' } },
- code: 'PRECONDITION_FAILED',
- message: 'A fixed workspace agent requires a public device from the same workspace.',
- });
- }
- };
-
- getAgentConfigById = async (id: string) => {
- const agent = await this.db.query.agents.findFirst({
- where: and(eq(agents.id, id), this.ownership()),
- });
-
- if (!agent) return null;
-
- return this.enrichAgentWithKnowledge(agent);
- };
-
- /**
- * The three fields a sender-identity snapshot needs, projected and scoped by
- * the model's ownership filter, or `null` when the agent is missing or not
- * visible to the current caller.
- *
- * Deliberately not {@link getAgentConfigById}: that one enriches the agent
- * with its assigned knowledge and loads every enabled file's row and content,
- * which is a lot of I/O to render a label. Callers that only display who an
- * agent is β€” attribution, receipts β€” should use this.
- */
- getAgentDisplayFields = async (
- id: string,
- ): Promise<{ avatar: null | string; name: null | string; title: null | string } | null> => {
- const rows = await this.db
- .select({ avatar: agents.avatar, name: agents.name, title: agents.title })
- .from(agents)
- .where(and(eq(agents.id, id), this.ownership()))
- .limit(1);
-
- return rows[0] ?? null;
- };
-
- /**
- * Returns the agent's visibility, scoped by the model's ownership filter, or
- * `null` when the agent is missing or not visible to the current caller.
- * Used by the task service to inherit a private agent's visibility onto
- * tasks created against it.
- */
- getAgentVisibility = async (id: string): Promise<'private' | 'public' | null> => {
- const rows = await this.db
- .select({ visibility: agents.visibility })
- .from(agents)
- .where(and(eq(agents.id, id), this.ownership()))
- .limit(1);
- return (rows[0]?.visibility as 'private' | 'public' | undefined) ?? null;
- };
-
- existsById = async (id: string): Promise<boolean> => {
- const rows = await this.db
- .select({ id: agents.id })
- .from(agents)
- .where(and(eq(agents.id, id), this.ownership()))
- .limit(1);
-
- return rows.length > 0;
- };
-
- /**
- * Stricter than {@link existsById}: the agent must be owned (created) by this
- * user, regardless of workspace visibility. `existsById` uses the visibility
- * -aware ownership predicate, so a *public* workspace agent created by another
- * member also returns true β€” which is only "can see", not "can edit". Callers
- * that bind credentials/config to an agent (e.g. agent-scoped connectors) must
- * use this so a member can't attach an account to someone else's shared agent.
- */
- existsOwnedById = async (id: string): Promise<boolean> => {
- const rows = await this.db
- .select({ id: agents.id })
- .from(agents)
- .where(and(eq(agents.id, id), eq(agents.userId, this.userId), notTrashed(agents.isDeleted)))
- .limit(1);
-
- return rows.length > 0;
- };
-
- /**
- * Lightweight lookup of an agent's currently-configured model + provider,
- * used to snapshot the model into a task config so later changes to the
- * agent's default model don't silently affect already-created tasks.
- * Returns null when the agent has no model/provider set, or the agent
- * cannot be found for this user.
- */
- getAgentModelConfig = async (
- idOrSlug: string,
- ): Promise<{ model: string; provider: string } | null> => {
- const rows = await this.db
- .select({ model: agents.model, provider: agents.provider })
- .from(agents)
- .where(and(this.ownership(), or(eq(agents.id, idOrSlug), eq(agents.slug, idOrSlug))))
- .limit(1);
-
- const row = rows[0];
- if (!row || !row.model || !row.provider) return null;
- return { model: row.model, provider: row.provider };
- };
-
- /**
- * Single-SELECT lookup of an agent's `agencyConfig`.
- *
- * The task runner needs the target the agent would use on its own β€” and
- * whether a workspace author FIXED it β€” to tell a task-level pin the run will
- * use from one the runtime replaces (see `resolveRunDeviceId`). The enriched
- * `getAgentConfig` would drag knowledge/file queries into every run.
- */
- getAgentAgencyConfig = async (idOrSlug: string): Promise<LobeAgentAgencyConfig | null> => {
- const rows = await this.db
- .select({ agencyConfig: agents.agencyConfig })
- .from(agents)
- .where(and(this.ownership(), or(eq(agents.id, idOrSlug), eq(agents.slug, idOrSlug))))
- .limit(1);
-
- return rows[0]?.agencyConfig ?? null;
- };
-
- /**
- * Single-SELECT lookup of the fields `TaskService.createTask` needs in one
- * round-trip: the model/provider snapshot (for `task.config`) and the
- * visibility (for inference + cross-table invariant assertion). Replaces
- * the previous two-query path (`getAgentModelConfig` + `getAgentVisibility`).
- *
- * Returns `null` when the agent is not visible to the current caller. When
- * found, `snapshot` is non-null only if both `model` and `provider` are set
- * β€” same contract as `getAgentModelConfig`.
- *
- * Use when:
- * - Creating a Task with inherited defaults or a native model-only override.
- *
- * Expects:
- * - An Agent ID or slug within the caller's visibility scope.
- *
- * Returns:
- * - The unchanged runtime snapshot and visibility, plus the model override provider
- * for native or personal API Tasks. Null preserves missing/server-default API bindings.
- */
- getAgentSnapshotForTaskCreate = async (
- idOrSlug: string,
- ): Promise<{
- /** Provider for model-only Tasks; null rejects inferred API bindings, absent for regular Agents. */
- modelOverrideProvider?: string | null;
- snapshot: { model: string; provider: string } | null;
- visibility: 'private' | 'public';
- } | null> => {
- const rows = await this.db
- .select({
- agencyConfig: agents.agencyConfig,
- model: agents.model,
- provider: agents.provider,
- visibility: agents.visibility,
- })
- .from(agents)
- .where(and(this.ownership(), or(eq(agents.id, idOrSlug), eq(agents.slug, idOrSlug))))
- .limit(1);
-
- const row = rows[0];
- if (!row) return null;
- const snapshot =
- row.model && row.provider ? { model: row.model, provider: row.provider } : null;
- const modelOverrideProvider = getHeterogeneousTaskModelProvider(
- row.agencyConfig?.heterogeneousProvider,
- );
- return {
- ...(modelOverrideProvider !== undefined ? { modelOverrideProvider } : {}),
- snapshot,
- visibility: row.visibility as 'private' | 'public',
- };
- };
-
- /**
- * Build the where condition shared by queryAgents / countAgents: the current
- * user's agents, with optional keyword filter.
- *
- * Virtual rows are infrastructure (group-built members, supervisors) and stay
- * excluded. That includes the inbox (Lobe AI): it is the product-owned
- * assistant, so including it is a deliberate choice every caller makes with
- * `includeInbox: true` β€” never something a generic agent lookup inherits. The
- * default is therefore the long-standing behavior (real, user-created agents
- * only), so callers that never asked for the inbox β€” older clients, the
- * CRUD/management tool runtimes, group pickers β€” keep it out instead of
- * discovering a row they cannot delete or add.
- *
- * When a caller does opt in, the inbox joins the page inside the where clause
- * rather than being filtered afterwards, so `limit` is never spent on an inbox
- * the caller would drop.
- */
- private buildQueryAgentsWhere = (keyword?: string, includeInbox = false) => {
- // Include agents where virtual is false OR null (legacy data without virtual
- // field), plus the inbox when the caller opts into it.
- const baseConditions = and(
- this.ownership(),
- includeInbox
- ? or(eq(agents.virtual, false), isNull(agents.virtual), eq(agents.slug, INBOX_SESSION_ID))
- : or(eq(agents.virtual, false), isNull(agents.virtual)),
- );
-
- // `name` is the user-facing display name (see `agents.name`); resolving the
- // label the UI shows is the primary way users and tools find an agent, so
- // the keyword must match it alongside `title`/`description`.
- if (!keyword) return baseConditions;
-
- // An inbox with a blank title is shown as `DEFAULT_INBOX_TITLE` only after
- // the query (see `normalizeInboxAgentMeta`), so the raw `title` column can't
- // match it β€” match that default label here instead.
- const matchesDefaultInboxTitle =
- includeInbox && DEFAULT_INBOX_TITLE.toLowerCase().includes(keyword.toLowerCase());
-
- return and(
- baseConditions,
- or(
- ilike(agents.title, `%${keyword}%`),
- ilike(agents.name, `%${keyword}%`),
- ilike(agents.description, `%${keyword}%`),
- matchesDefaultInboxTitle
- ? and(
- eq(agents.slug, INBOX_SESSION_ID),
- or(isNull(agents.title), sql`trim(${agents.title}) = ''`),
- )
- : undefined,
- ),
- );
- };
-
- /**
- * Query the user's agents with an optional keyword filter.
- * Returns minimal agent info (id, title, name, description, avatar,
- * backgroundColor), plus `userId`/`visibility` so callers can gate per-agent
- * actions (e.g. transfer is creator/primary-owner only), a compact
- * `heteroType` derived from `agencyConfig` so callers can tell which results
- * are heterogeneous (external CLI/device) agents, and `isInbox` so callers can
- * recognize the product-owned inbox (Lobe AI) without re-deriving it from a
- * slug the row shape no longer carries.
- * Excludes virtual agents (supervisors, group-built members) and, unless the
- * caller opts in with `includeInbox: true`, the product-owned inbox (Lobe AI).
- * See `buildQueryAgentsWhere`.
- */
- queryAgents = async (params?: {
- includeInbox?: boolean;
- keyword?: string;
- limit?: number;
- offset?: number;
- }) => {
- const { includeInbox = false, keyword, limit = 9999, offset = 0 } = params ?? {};
- const searchCondition = this.buildQueryAgentsWhere(keyword, includeInbox);
-
- const rows = await this.db
- .select({
- agencyConfig: agents.agencyConfig,
- avatar: agents.avatar,
- backgroundColor: agents.backgroundColor,
- description: agents.description,
- id: agents.id,
- name: agents.name,
- slug: agents.slug,
- title: agents.title,
- userId: agents.userId,
- visibility: agents.visibility,
- })
- .from(agents)
- .where(searchCondition)
- .orderBy(desc(agents.updatedAt))
- .limit(limit)
- .offset(offset);
-
- // Surface only the hetero runtime type, not the full agencyConfig payload.
- return rows.map(({ slug, agencyConfig, ...row }) => ({
- ...normalizeInboxAgentMeta(
- { ...row, heteroType: agencyConfig?.heterogeneousProvider?.type },
- { slug },
- ),
- // When the caller opted in, the inbox is the only virtual row this query
- // keeps, and `slug` is consumed above rather than returned β€” so the flag
- // is what lets callers pin or annotate Lobe AI without re-deriving it.
- isInbox: slug === INBOX_SESSION_ID,
- }));
- };
-
- /**
- * Count the agents matching the same conditions as queryAgents β€” the inbox is
- * counted only when the caller opts in with `includeInbox: true`, other
- * virtual rows always excluded β€” so the count stays a faithful total for
- * paginated callers and for the assistants stats.
- * Used to report real totals (and pagination) when queryAgents is limited.
- * Accepts the same date filters as SessionModel.count so callers can compare
- * current vs. prior-period totals without falling back to the legacy
- * sessions table.
- */
- countAgents = async (params?: {
- endDate?: string;
- includeInbox?: boolean;
- keyword?: string;
- range?: [string, string];
- startDate?: string;
- }): Promise<number> => {
- const result = await this.db
- .select({ count: count() })
- .from(agents)
- .where(
- genWhere([
- this.buildQueryAgentsWhere(params?.keyword, params?.includeInbox ?? false),
- params?.range
- ? genRangeWhere(params.range, agents.createdAt, (date) => date.toDate())
- : undefined,
- params?.endDate
- ? genEndDateWhere(params.endDate, agents.createdAt, (date) => date.toDate())
- : undefined,
- params?.startDate
- ? genStartDateWhere(params.startDate, agents.createdAt, (date) => date.toDate())
- : undefined,
- ]),
- );
-
- return result[0]?.count ?? 0;
- };
-
- /**
- * Get minimal agent info (avatar, title, backgroundColor) by IDs.
- * For inbox agent (slug='inbox'), falls back to LobeAI defaults when avatar/title are missing.
- */
- getAgentAvatarsByIds = async (ids: string[]) => {
- if (ids.length === 0) return [];
-
- const rows = await this.db
- .select({
- avatar: agents.avatar,
- backgroundColor: agents.backgroundColor,
- id: agents.id,
- name: agents.name,
- slug: agents.slug,
- title: agents.title,
- })
- .from(agents)
- .where(and(this.ownership(), inArray(agents.id, ids)));
-
- return rows.map(({ slug, ...row }) => normalizeInboxAgentMeta(row, { slug }));
- };
-
- /**
- * List agents bindable by the System Bot messenger picker: real agents plus
- * the inbox (other virtual agents excluded), ordered by `updatedAt DESC` with
- * the inbox pinned to the top.
- *
- * Returns `name` and `title` separately β€” resolving them into one label is the
- * caller's job (see `agentDisplayName`), since only the caller knows whether it
- * can render an i18n fallback. `title` is still normalized here for the inbox
- * (LobeAI default) and falls back to `options.fallbackTitle` when blank
- * (default `null`, so a client caller can supply its own i18n default).
- */
- listMessengerBindableAgents = async (options?: {
- fallbackTitle?: string | null;
- }): Promise<
- Array<{
- avatar: string | null;
- backgroundColor: string | null;
- id: string;
- isInbox: boolean;
- isPrivate: boolean;
- name: string | null;
- title: string | null;
- }>
- > => {
- const fallbackTitle = options?.fallbackTitle ?? null;
-
- const rows = await this.db
- .select({
- avatar: agents.avatar,
- backgroundColor: agents.backgroundColor,
- id: agents.id,
- name: agents.name,
- slug: agents.slug,
- title: agents.title,
- visibility: agents.visibility,
- })
- .from(agents)
- .where(and(this.ownership(), or(ne(agents.virtual, true), eq(agents.slug, INBOX_SESSION_ID))))
- .orderBy(desc(agents.updatedAt));
-
- const normalized = rows
- .filter((row) => row.id)
- .map(({ slug, visibility, ...row }) => {
- const meta = normalizeInboxAgentMeta(row, { slug });
- return {
- avatar: meta.avatar,
- backgroundColor: meta.backgroundColor,
- id: meta.id,
- isInbox: slug === INBOX_SESSION_ID,
- // Only meaningful in workspace mode: the ownership predicate already
- // scopes visible private rows to the caller, so `isPrivate` means
- // "the caller's own private agent in this workspace". Personal-mode
- // rows are all implicitly private, so the flag stays false there to
- // signal "no grouping needed".
- isPrivate: Boolean(this.workspaceId) && visibility === 'private',
- name: meta.name ?? null,
- // The inbox title is already resolved by normalizeInboxAgentMeta; any
- // other blank title falls back to the caller-provided default.
- title: meta.title?.trim() || fallbackTitle,
- };
- });
-
- // Pin the inbox agent to the top regardless of updatedAt β€” it's the
- // implicit "default" agent and should always be the first option.
- const inboxIdx = normalized.findIndex((row) => row.isInbox);
- if (inboxIdx > 0) {
- const [inbox] = normalized.splice(inboxIdx, 1);
- normalized.unshift(inbox);
- }
-
- return normalized;
- };
-
- /**
- * Get agent config by ID or slug (single query with OR condition)
- */
- getAgentConfig = async (idOrSlug: string) => {
- // Prefer an exact ID match over a slug match. The combined `or(id, slug)`
- // query has no inherent ordering, so resolve ID first for determinism.
- const agent =
- (await this.db.query.agents.findFirst({
- where: and(this.ownership(), eq(agents.id, idOrSlug)),
- })) ??
- (await this.db.query.agents.findFirst({
- where: and(this.ownership(), eq(agents.slug, idOrSlug)),
- }));
-
- 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);
- const normalizedAgent = normalizeInboxAgentMeta(agent, { slug: agent.slug });
-
- // Fetch document content for enabled files
- const enabledFileIds = knowledge.files
- .filter((f) => f.enabled)
- .map((f) => f.id)
- .filter((id) => id !== undefined);
- let files: Array<
- (typeof knowledge.files)[number] & { content?: string | null; originalCharCount?: number }
- > = knowledge.files;
-
- if (enabledFileIds.length > 0) {
- const documentsData = await this.db.query.documents.findMany({
- // A file can own several documents; take the oldest, like `DocumentModel.findByFileId`
- // (which `readAttachment` pages through), so the preview and its continuation agree.
- orderBy: [asc(documents.createdAt), asc(documents.id)],
- where: and(
- this.documentsOwnership(),
- inArray(documents.fileId, enabledFileIds),
- notFileBackedPlaceholder(),
- ),
- });
-
- const documentMap = new Map<string | null, (typeof documentsData)[number]>();
- for (const doc of documentsData) {
- if (!documentMap.has(doc.fileId)) documentMap.set(doc.fileId, doc);
- }
- files = knowledge.files.map((file) => {
- const document = file.enabled && file.id ? documentMap.get(file.id) : undefined;
- return {
- ...file,
- content: document?.content,
- originalCharCount: readOriginalCharCount(document?.metadata),
- };
- });
- }
-
- return { ...normalizedAgent, ...knowledge, files };
- };
-
- getAgentAssignedKnowledge = async (id: string) => {
- // The junction tables carry the mount (created by whoever wired the agent
- // to the KB / file); the ownership() predicates below match the caller's
- // own mount rows within the same workspace.
- //
- // The joined `knowledgeBases` / `files` rows also need a visibility guard
- // in the `leftJoin` ON clause: without it, a KB or file that was later
- // flipped back to `private` via `setVisibility` would keep
- // leaking its name / description into every mounted-agent view across the
- // workspace. Enforcing the guard on the ON clause (rather than WHERE)
- // keeps the mount row in the result but nulls out the referenced entity β€”
- // callers can then treat `id === null` as "unavailable" and render a
- // placeholder in the editor list, while `resolveAgentKnowledgeBaseIds` in
- // the runtime naturally skips such rows via its `k.id` filter.
- const [knowledgeBaseResult, fileResult] = await Promise.all([
- this.db
- .select({ enabled: agentsKnowledgeBases.enabled, knowledgeBases })
- .from(agentsKnowledgeBases)
- .where(and(eq(agentsKnowledgeBases.agentId, id), this.agentsKnowledgeBasesOwnership()))
- .orderBy(desc(agentsKnowledgeBases.createdAt))
- .leftJoin(
- knowledgeBases,
- and(
- eq(knowledgeBases.id, agentsKnowledgeBases.knowledgeBaseId),
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- knowledgeBases,
- ),
- ),
- ),
- this.db
- .select({ enabled: agentsFiles.enabled, files })
- .from(agentsFiles)
- .where(and(eq(agentsFiles.agentId, id), this.agentsFilesOwnership()))
- .orderBy(desc(agentsFiles.createdAt))
- .leftJoin(
- files,
- and(
- eq(files.id, agentsFiles.fileId),
- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, files),
- ),
- ),
- ]);
-
- return {
- files: fileResult.map((item) => ({
- ...item.files,
- enabled: item.enabled,
- })),
- knowledgeBases: knowledgeBaseResult.map((item) => ({
- ...item.knowledgeBases,
- enabled: item.enabled,
- })),
- };
- };
-
- /**
- * Find agent by session id
- */
- findBySessionId = async (sessionId: string) => {
- const item = await this.db.query.agentsToSessions.findFirst({
- where: and(eq(agentsToSessions.sessionId, sessionId), this.agentsToSessionsOwnership()),
- });
-
- if (!item) return;
-
- const agentId = item.agentId;
-
- return this.getAgentConfigById(agentId);
- };
-
- createAgentKnowledgeBase = async (
- agentId: string,
- knowledgeBaseId: string,
- enabled: boolean = true,
- ) => {
- return this.db
- .insert(agentsKnowledgeBases)
- .values(
- buildWorkspacePayload(
- { userId: this.userId, workspaceId: this.workspaceId },
- { agentId, enabled, knowledgeBaseId },
- ),
- );
- };
-
- deleteAgentKnowledgeBase = async (agentId: string, knowledgeBaseId: string) => {
- return this.db
- .delete(agentsKnowledgeBases)
- .where(
- and(
- eq(agentsKnowledgeBases.agentId, agentId),
- eq(agentsKnowledgeBases.knowledgeBaseId, knowledgeBaseId),
- this.agentsKnowledgeBasesOwnership(),
- ),
- );
- };
-
- toggleKnowledgeBase = async (agentId: string, knowledgeBaseId: string, enabled?: boolean) => {
- return this.db
- .update(agentsKnowledgeBases)
- .set({ enabled })
- .where(
- and(
- eq(agentsKnowledgeBases.agentId, agentId),
- eq(agentsKnowledgeBases.knowledgeBaseId, knowledgeBaseId),
- this.agentsKnowledgeBasesOwnership(),
- ),
- );
- };
-
- createAgentFiles = async (agentId: string, fileIds: string[], enabled: boolean = true) => {
- // Exclude the fileIds that already exist in agentsFiles, and then insert them
- const existingFiles = await this.db
- .select({ id: agentsFiles.fileId })
- .from(agentsFiles)
- .where(
- and(
- eq(agentsFiles.agentId, agentId),
- this.agentsFilesOwnership(),
- inArray(agentsFiles.fileId, fileIds),
- ),
- );
-
- const existingFilesIds = new Set(existingFiles.map((item) => item.id));
-
- const needToInsertFileIds = fileIds.filter((fileId) => !existingFilesIds.has(fileId));
-
- if (needToInsertFileIds.length === 0) return;
-
- return this.db
- .insert(agentsFiles)
- .values(
- needToInsertFileIds.map((fileId) =>
- buildWorkspacePayload(
- { userId: this.userId, workspaceId: this.workspaceId },
- { agentId, enabled, fileId },
- ),
- ),
- );
- };
-
- deleteAgentFile = async (agentId: string, fileId: string) => {
- return this.db
- .delete(agentsFiles)
- .where(
- and(
- eq(agentsFiles.agentId, agentId),
- eq(agentsFiles.fileId, fileId),
- this.agentsFilesOwnership(),
- ),
- );
- };
-
- /**
- * 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) => {
- // Lock the agent row BEFORE consulting the pending-copy guard β€” same
- // lock-then-guard order as transferAgents. A concurrent copy enqueue
- // locks the same source rows, so the guard here cannot run in the window
- // where the enqueue's job row exists but is not yet committed.
- const [locked] = await trx
- .select({ id: agents.id, slug: agents.slug })
- .from(agents)
- .where(and(eq(agents.id, agentId), this.ownership()))
- .for('update');
-
- // Builtins (the inbox, the agent builders) are provisioned per user and
- // carry `virtual` exactly like a group's own members. Deleting one takes
- // its linked session and every conversation with it, and nothing can
- // recreate them β€” refuse here, the same way `addAgentsToGroup` refuses to
- // seat one. This only guards callers of `AgentModel.delete`; paths that
- // delete `agents` rows directly (e.g. the OpenAPI `migrateSessionTo`
- // delete) bypass it.
- if (locked?.slug && RESERVED_AGENT_SLUGS.has(locked.slug)) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'A builtin agent cannot be deleted',
- });
- }
-
- // The junction records every agent an unfinished job still maps, a
- // copy's TARGET included β€” and a group copy's drain writes those ids into
- // `messages.agent_id`. Deleting one leaves the queue rows behind, so the
- // drain hits a missing-agent FK and retries forever, stranding the copied
- // conversations as pending. Distinct from the source guard below: a copy
- // registers only its target here.
- if (await AgentTransferJobModel.hasPendingJobForAgents(trx, [agentId])) {
- throw new Error(AGENT_TRANSFER_IN_PROGRESS);
- }
-
- // Not covered above: a group transfer that left this agent behind and
- // took a clone does NOT register it as a covered agent (it never moved).
- // But its id is still the live value of `messages.agent_id` on every
- // topic the drain has not reached yet, and that column cascades β€” so
- // deleting it now would destroy the moved group history the remap is
- // partway through rescuing.
- if (await AgentTransferJobModel.hasPendingRemapForSourceAgents(trx, [agentId])) {
- throw new Error(AGENT_TRANSFER_IN_PROGRESS);
- }
-
- // A pending copy job still reads this agent's topics β€” deleting it would
- // cascade them away and the copy would silently complete with empty
- // conversations. Surface the in-progress state instead.
- if (await AgentCopyJobModel.hasPendingCopyJobForSourceAgents(trx, [agentId])) {
- throw new Error(AGENT_COPY_IN_PROGRESS);
- }
-
- // 1. Get associated session IDs
- const links = await trx
- .select({ sessionId: agentsToSessions.sessionId })
- .from(agentsToSessions)
- .where(and(eq(agentsToSessions.agentId, agentId), this.agentsToSessionsOwnership()));
-
- const sessionIds = links.map((link) => link.sessionId);
-
- // 2. Delete links in agentsToSessions
- await trx
- .delete(agentsToSessions)
- .where(and(eq(agentsToSessions.agentId, agentId), this.agentsToSessionsOwnership()));
-
- // 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), this.sessionsOwnership()));
- }
-
- // 4. Delete the agent itself
- return trx.delete(agents).where(and(eq(agents.id, agentId), this.ownership()));
- });
- };
-
- // **************** Recycle bin *************** //
-
- /**
- * Same pre-flight as {@link delete}: an agent whose history is mid-copy or
- * mid-transfer must not disappear from under the job. Runs the guards under
- * the same row lock so the check cannot race an enqueue. Throws
- * `AGENT_TRANSFER_IN_PROGRESS` / `AGENT_COPY_IN_PROGRESS`.
- */
- assertDeletable = async (agentIds: string[], trx?: Transaction) => {
- if (agentIds.length === 0) return;
- const run = async (tx: Transaction | LobeChatDatabase) => {
- await tx
- .select({ id: agents.id })
- .from(agents)
- .where(and(inArray(agents.id, agentIds), this.trashScope()))
- .for('update');
- if (await AgentTransferJobModel.hasPendingJobForAgents(tx, agentIds)) {
- throw new Error(AGENT_TRANSFER_IN_PROGRESS);
- }
- if (await AgentTransferJobModel.hasPendingRemapForSourceAgents(tx, agentIds)) {
- throw new Error(AGENT_TRANSFER_IN_PROGRESS);
- }
- if (await AgentCopyJobModel.hasPendingCopyJobForSourceAgents(tx, agentIds)) {
- throw new Error(AGENT_COPY_IN_PROGRESS);
- }
- };
- return trx ? run(trx) : run(this.db);
- };
-
- /** Legacy session shells linked to the given agents (used to stamp `topics.session_id` rows). */
- findSessionIdsByAgentIds = async (agentIds: string[]): Promise<string[]> => {
- if (agentIds.length === 0) return [];
- const links = await this.db
- .select({ sessionId: agentsToSessions.sessionId })
- .from(agentsToSessions)
- .where(and(inArray(agentsToSessions.agentId, agentIds), this.agentsToSessionsOwnership()));
- return [...new Set(links.map((link) => link.sessionId))];
- };
-
- /** Agents linked to the given legacy session shells β€” the reverse of {@link findSessionIdsByAgentIds}. */
- findAgentIdsBySessionIds = async (sessionIds: string[]): Promise<string[]> => {
- if (sessionIds.length === 0) return [];
- const links = await this.db
- .select({ agentId: agentsToSessions.agentId })
- .from(agentsToSessions)
- .where(
- and(inArray(agentsToSessions.sessionId, sessionIds), this.agentsToSessionsOwnership()),
- );
- return [...new Set(links.map((link) => link.agentId))];
- };
-
- /**
- * Whether the agent that owns a row is sitting in the bin β€” reached either
- * directly (`agent_id`) or, for legacy rows that only carry `session_id`,
- * through the session shell's agent link. Restoring such a row first would
- * bring it back under an invisible container.
- */
- hasTrashedOwner = async (owner: {
- agentId?: string | null;
- sessionId?: string | null;
- }): Promise<boolean> => {
- const agentIds = [
- ...(owner.agentId ? [owner.agentId] : []),
- ...(owner.sessionId ? await this.findAgentIdsBySessionIds([owner.sessionId]) : []),
- ];
- return (await this.findTrashedByIds([...new Set(agentIds)])).length > 0;
- };
-
- /**
- * Move agents to the recycle bin. Only the `agents` rows are stamped here β€”
- * the server-side trash handler cascades to sessions / topics through their
- * own models so the registry can record each child.
- */
- softDelete = async (agentIds: string[], options: SoftDeleteOptions): Promise<AgentItem[]> => {
- if (agentIds.length === 0) return [];
- return this.db
- .update(agents)
- .set(trashStamp(options.deletedAt))
- .where(
- and(
- inArray(agents.id, agentIds),
- this.ownership(),
- options.restrictToCreator ? eq(agents.userId, this.userId) : undefined,
- ),
- )
- .returning();
- };
-
- restore = async (agentIds: string[]): Promise<AgentItem[]> => {
- if (agentIds.length === 0) return [];
- return this.db
- .update(agents)
- .set(restoreStamp())
- .where(and(inArray(agents.id, agentIds), this.trashScope(), isTrashed(agents.isDeleted)))
- .returning();
- };
-
- findTrashedByIds = async (agentIds: string[]): Promise<AgentItem[]> => {
- if (agentIds.length === 0) return [];
- return this.db
- .select()
- .from(agents)
- .where(and(inArray(agents.id, agentIds), this.trashScope(), isTrashed(agents.isDeleted)));
- };
-
- /**
- * Lock the given agents for a purge and return the ones still in the bin.
- * Run inside the caller's transaction: the row lock holds until the purge
- * commits, so a restore racing it waits and then finds nothing to restore,
- * while a restore that already committed makes this return no ids.
- */
- lockTrashedForPurge = async (agentIds: string[]): Promise<string[]> => {
- if (agentIds.length === 0) return [];
- const stamped = await this.db
- .select({ id: agents.id })
- .from(agents)
- .where(and(inArray(agents.id, agentIds), this.trashScope(), isTrashed(agents.isDeleted)))
- .for('update');
- return stamped.map((row) => row.id);
- };
-
- /**
- * Hard delete for the purge sweep: the agent rows and their session links,
- * still-stamped rows only. FK cascades take topics / messages / threads.
- * The legacy session shells are another aggregate β€” the trash handler
- * drops them through `SessionModel` in the same transaction.
- */
- purge = async (agentIds: string[]): Promise<string[]> => {
- if (agentIds.length === 0) return [];
- await this.db
- .delete(agentsToSessions)
- .where(and(inArray(agentsToSessions.agentId, agentIds), this.agentsToSessionsOwnership()));
- const rows = await this.db
- .delete(agents)
- .where(and(inArray(agents.id, agentIds), this.trashScope(), isTrashed(agents.isDeleted)))
- .returning({ id: agents.id });
- return rows.map((row) => row.id);
- };
-
- /**
- * Batch delete agents by IDs.
- * This is a simpler delete that only removes the agent records.
- * Use this for virtual agents that don't have associated sessions.
- */
- batchDelete = async (agentIds: string[]) => {
- if (agentIds.length === 0) return;
-
- return this.db.delete(agents).where(and(this.ownership(), inArray(agents.id, agentIds)));
- };
-
- toggleFile = async (agentId: string, fileId: string, enabled?: boolean) => {
- return this.db
- .update(agentsFiles)
- .set({ enabled })
- .where(
- and(
- eq(agentsFiles.agentId, agentId),
- eq(agentsFiles.fileId, fileId),
- this.agentsFilesOwnership(),
- ),
- );
- };
-
- /**
- * Builtin slugs are not decoration: `getBuiltinAgent` resolves infrastructure
- * agents BY slug, and authorization treats the collaborative ones as workspace
- * resources (`canPerformResourceAction`). A user-created row must therefore
- * never claim one β€” otherwise a member could squat `inbox` / `agent-builder`
- * before the real row is provisioned and have their own agent adopted as the
- * workspace's, with the shared-resource permissions that come with it.
- *
- * Every user-controlled write funnels through `create` / `batchCreate` (group
- * member batch-create takes a caller-supplied `slug`, as do imports and market
- * installs) or through `update` / `updateConfig` (the passthrough config
- * endpoint accepts one too β€” renaming an existing row is the same squat).
- * Builtin provisioning bypasses all four by inserting/updating directly inside
- * `getBuiltinAgent`, so dropping the field here closes every caller path at
- * once; on create the column's own default then assigns a random slug.
- */
- private stripImmutableFields = <T extends Record<string, any>>(data: T): T => {
- const carried = IMMUTABLE_AGENT_FIELDS.filter((field) => field in data);
- if (carried.length === 0) return data;
-
- const next = { ...data };
- for (const field of carried) delete next[field];
- return next;
- };
-
- private stripReservedSlug = <T extends { slug?: string | null }>(config: T): T => {
- if (!config.slug || !RESERVED_AGENT_SLUGS.has(config.slug)) return config;
- return { ...config, slug: undefined };
- };
-
- /**
- * Create an agent record only (without creating a session).
- * This is used for creating virtual agents (e.g., group chat members).
- */
- create = async (input: Partial<AgentItem>): Promise<AgentItem> => {
- const config = this.stripReservedSlug(input);
- const agencyConfig = this.withWorkspaceSelectionPolicyDefaults(
- sanitizeAgentApiConfig(config.agencyConfig),
- );
-
- await this.assertWorkspaceDeviceBinding(this.workspaceId ?? null, agencyConfig);
- await this.assertFixedExecutionTarget(this.workspaceId ?? null, agencyConfig);
-
- const [result] = await this.db
- .insert(agents)
- .values([
- buildWorkspacePayload(
- { userId: this.userId, workspaceId: this.workspaceId },
- {
- ...config,
- agencyConfig,
- model: typeof config.model === 'string' ? config.model : null,
- },
- ),
- ])
- .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 [];
-
- const normalizedConfigs = configs.map((config) => ({
- ...this.stripReservedSlug(config),
- agencyConfig: this.withWorkspaceSelectionPolicyDefaults(
- sanitizeAgentApiConfig(config.agencyConfig),
- ),
- }));
-
- await Promise.all(
- normalizedConfigs.flatMap((config) => [
- this.assertWorkspaceDeviceBinding(this.workspaceId ?? null, config.agencyConfig),
- this.assertFixedExecutionTarget(this.workspaceId ?? null, config.agencyConfig),
- ]),
- );
-
- return this.db
- .insert(agents)
- .values(
- normalizedConfigs.map((config) =>
- buildWorkspacePayload(
- { userId: this.userId, workspaceId: this.workspaceId },
- {
- ...config,
- model: typeof config.model === 'string' ? config.model : null,
- },
- ),
- ),
- )
- .returning();
- };
-
- update = async (agentId: string, data: Partial<AgentItem>) => {
- const apiSafeData = Object.hasOwn(data, 'agencyConfig')
- ? { ...data, agencyConfig: sanitizeAgentApiConfig(data.agencyConfig) }
- : data;
- const sanitizedData = this.stripImmutableFields(apiSafeData);
- await this.assertNotAgentBuilderProtectedWrite(agentId, sanitizedData);
-
- return this.db
- .update(agents)
- .set({ ...sanitizedData, updatedAt: new Date() })
- .where(and(eq(agents.id, agentId), this.ownership()));
- };
-
- /**
- * Reject a write of fields the Agent Builder's own row must never carry (see
- * {@link AGENT_BUILDER_PROTECTED_FIELDS}). Only looks up the target row's `slug` when the
- * incoming patch actually touches a protected field, so normal updates pay no extra query.
- */
- private assertNotAgentBuilderProtectedWrite = async (
- agentId: string,
- data: Record<string, unknown>,
- ) => {
- if (!AGENT_BUILDER_PROTECTED_FIELDS.some((field) => data[field] !== undefined)) return;
-
- const agent = await this.db.query.agents.findFirst({
- columns: { slug: true },
- where: and(eq(agents.id, agentId), this.ownership()),
- });
-
- if (agent?.slug === BUILTIN_AGENT_SLUGS.agentBuilder) assertNoAgentBuilderProtectedFields(data);
- };
-
- /**
- * Publish a private agent into the workspace. The `user_id = ?` +
- * `visibility = 'private'` guards lock the operation to the creator's own
- * still-private agent. The inverse transition (public β†’ private) goes
- * through {@link setVisibility}, which the router gates to the creator or
- * a workspace owner.
- *
- * Use the existing `update` to change other fields; visibility is the only
- * one with these authorization rules.
- */
- publishToWorkspace = async (agentId: string) => {
- const agent = await this.db.query.agents.findFirst({
- columns: { agencyConfig: true, sessionGroupId: true, workspaceId: true },
- where: and(
- eq(agents.id, agentId),
- this.ownership(),
- eq(agents.userId, this.userId),
- eq(agents.visibility, 'private'),
- ),
- });
-
- if (!agent) {
- throw new Error('Agent not found, already published, or access denied');
- }
-
- // Re-check at the publication boundary. A legacy/stale fixed target may
- // predate the config-write guard; a concrete device must never be exposed
- // when workspace members cannot resolve it.
- await this.assertFixedExecutionTarget(agent.workspaceId, agent.agencyConfig);
-
- // Rehome exactly as `setVisibility` does: a folder cannot mix
- // visibilities, so publishing out of a private Category releases the
- // folder. Left in place the agent would be public while its folder is not,
- // and the sidebar would show it in Ungrouped rather than where it was
- // published from.
- const clearGroup = agent.sessionGroupId
- ? await this.getAssignableSessionGroupVisibility(agent.sessionGroupId)
- .then((visibility) => visibility !== 'public')
- .catch(() => true)
- : false;
-
- const [result] = await this.db
- .update(agents)
- .set({
- updatedAt: new Date(),
- visibility: 'public',
- ...(clearGroup ? { sessionGroupId: null } : {}),
- })
- .where(
- and(
- eq(agents.id, agentId),
- this.ownership(),
- eq(agents.userId, this.userId),
- eq(agents.visibility, 'private'),
- ),
- )
- .returning();
-
- if (!result) {
- throw new Error('Agent not found, already published, or access denied');
- }
-
- return result;
- };
-
- /**
- * Lightweight lookup used to authorize visibility changes: the agent's
- * creator, slug and current visibility, scoped by the ownership predicate
- * (other members' private agents resolve to `null`).
- */
- /**
- * The topic-share policy and creator of one agent.
- *
- * Deliberately scoped by workspace rather than by {@link ownership}: this
- * answers "what did the author decide for this agent", which must not depend
- * on whether the *caller* can see the row. A visibility-scoped miss would
- * return `null` and fail open, handing a restricted agent's topics back to
- * every member.
- */
- getTopicShareSubject = async (id: string): Promise<AgentTopicShareSubject | null> => {
- const rows = await this.db
- .select({
- agencyConfig: agents.agencyConfig,
- userId: agents.userId,
- workspaceId: agents.workspaceId,
- })
- .from(agents)
- .where(
- and(
- eq(agents.id, id),
- this.workspaceId ? eq(agents.workspaceId, this.workspaceId) : this.ownership(),
- ),
- )
- .limit(1);
-
- return rows[0] ?? null;
- };
-
- getAgentVisibilityMeta = async (
- id: string,
- ): Promise<{ slug: string | null; userId: string; visibility: 'private' | 'public' } | null> => {
- const rows = await this.db
- .select({ slug: agents.slug, userId: agents.userId, visibility: agents.visibility })
- .from(agents)
- .where(and(eq(agents.id, id), this.ownership()))
- .limit(1);
- const row = rows[0];
- if (!row) return null;
- return {
- slug: row.slug,
- userId: row.userId,
- visibility: (row.visibility as 'private' | 'public' | null) ?? 'public',
- };
- };
-
- /**
- * Bidirectional visibility switch. Authorization (creator OR
- * workspace owner, builtin agents excluded) is the router's responsibility β€”
- * this method only applies the ownership-scoped write.
- *
- * Uses UPDATE … RETURNING instead of a follow-up SELECT: when a workspace
- * owner demotes another member's agent to private, the post-update row no
- * longer matches the visibility-aware ownership predicate, so a read-back
- * would return 0 rows even though the write succeeded (same pattern as
- * TaskModel.updateVisibility).
- */
- setVisibility = async (agentId: string, visibility: 'private' | 'public') => {
- // A sidebar folder cannot mix visibilities (HomeRepository.processAgentList
- // buckets grouped items by item visibility under same-visibility groups),
- // so an agent crossing scopes while keyed to a group of the OLD scope
- // would be emitted nowhere and vanish from the sidebar. Rehome it to the
- // ungrouped section of its new scope when the group no longer matches.
- const [current] = await this.db
- .select({
- agencyConfig: agents.agencyConfig,
- groupVisibility: sessionGroups.visibility,
- workspaceId: agents.workspaceId,
- })
- .from(agents)
- .leftJoin(sessionGroups, eq(agents.sessionGroupId, sessionGroups.id))
- .where(and(eq(agents.id, agentId), this.ownership()))
- .limit(1);
-
- // `publishAgentToWorkspace` is the normal client path, but keep the
- // bidirectional visibility mutation equally safe for direct API callers.
- if (visibility === 'public' && current) {
- await this.assertFixedExecutionTarget(current.workspaceId, current.agencyConfig);
- }
-
- const groupVisibility = current?.groupVisibility as 'private' | 'public' | null | undefined;
- const clearGroup = groupVisibility != null && groupVisibility !== visibility;
-
- const [updated] = await this.db
- .update(agents)
- .set({
- updatedAt: new Date(),
- visibility,
- ...(clearGroup ? { sessionGroupId: null } : {}),
- })
- .where(and(eq(agents.id, agentId), this.ownership()))
- .returning();
- return updated ?? null;
- };
-
- 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), this.ownership()),
- });
- 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), this.ownership()),
- });
- return result?.id ?? null;
- };
-
- /**
- * Get an agent by the forkedFromIdentifier stored in params
- * @param forkedFromIdentifier - The source agent's market identifier
- * @returns agent id if exists, null otherwise
- */
- getAgentByForkedFromIdentifier = async (forkedFromIdentifier: string): Promise<string | null> => {
- const result = await this.db.query.agents.findFirst({
- columns: { id: true },
- orderBy: (agents, { desc }) => [desc(agents.updatedAt)],
- where: and(
- this.ownership(),
- sql`${agents.params}->>'forkedFromIdentifier' = ${forkedFromIdentifier}`,
- ),
- });
- return result?.id ?? null;
- };
-
- updateConfig = async (
- agentId: string,
- input: PartialDeep<AgentItem> | undefined | null,
- replaceWorkingDirDeviceIds?: string[],
- ) => {
- if (!input || Object.keys(input).length === 0) return;
-
- const data = this.stripImmutableFields(input);
-
- const agent = await this.db.query.agents.findFirst({
- where: and(eq(agents.id, agentId), this.ownership()),
- });
-
- if (!agent) return;
-
- await this.assertWorkspaceDeviceBinding(
- agent.workspaceId,
- data.agencyConfig,
- agent.agencyConfig,
- );
-
- // 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)
-
- const { params: _params, ...restData } = data;
-
- // See AGENT_BUILDER_PROTECTED_FIELDS: some callers (e.g. the browser client's meta
- // editor) route title/avatar/etc. through updateConfig() rather than update().
- if (agent.slug === BUILTIN_AGENT_SLUGS.agentBuilder) {
- assertNoAgentBuilderProtectedFields(restData as Record<string, unknown>);
- }
-
- // Only the columns this patch touches are written back. The row was read
- // before the awaits above, so writing the whole merged row would restore
- // any column another writer committed in between β€” e.g. a parallel
- // `updatePrompt` losing its new systemRole to a concurrent config write.
- const touchedColumns = new Set<string>(Object.keys(restData));
- if (data.params) touchedColumns.add('params');
-
- const mergedValue = merge(agent, restData);
-
- // API bindings follow updateConfig's partial deep-merge contract. A user-provider patch must
- // only clear the deployment discriminator retained from a previous server-default binding.
- const apiConfigPatch = toRecord(data.agencyConfig?.heterogeneousProvider?.apiConfig);
- const mergedApiConfig = toRecord(mergedValue.agencyConfig?.heterogeneousProvider?.apiConfig);
- if (
- apiConfigPatch &&
- apiConfigPatch.source !== 'server-default' &&
- typeof apiConfigPatch.providerId === 'string' &&
- mergedApiConfig
- ) {
- delete mergedApiConfig.source;
- }
-
- mergedValue.agencyConfig = sanitizeAgentApiConfig(mergedValue.agencyConfig) ?? null;
-
- // The inbox is LobeHub's built-in default cloud agent; it must never be
- // turned into a heterogeneous (external-CLI) agent. Two independent inputs can
- // flip it β€” a stray `agencyConfig.heterogeneousProvider`, and a legacy hetero
- // `model` id, which AiAgentService still treats as heterogeneous on its own even
- // without a provider config. Either one
- // reroutes the whole chat surface through the device gateway and breaks it with
- // GATEWAY_NOT_CONFIGURED, so sanitize both at this write chokepoint regardless
- // of caller (mirrors AGENT_BUILDER_PROTECTED_FIELDS).
- if (agent.slug === INBOX_SESSION_ID) {
- if (mergedValue.agencyConfig?.heterogeneousProvider) {
- delete mergedValue.agencyConfig.heterogeneousProvider;
- touchedColumns.add('agencyConfig');
- }
- if (isHeterogeneousAgentModelId(mergedValue.model)) {
- mergedValue.model = null;
- touchedColumns.add('model');
- }
- }
-
- // A character sheet is authored as a whole: the studio reads the current
- // profile and writes the version it wants. Deep-merging it would make a
- // cleared trait or a removed artwork impossible to express, since a missing
- // key reads as "leave it alone". Same reasoning as the graph below.
- if (Object.hasOwn(data, 'profile')) {
- mergedValue.profile = data.profile as AgentItem['profile'];
- }
-
- // A AgentGraph is a complete executable document, not a partial config
- // patch β€” replace it wholesale instead of deep-merging. The Graph Agent
- // (agencyConfig.graph) is the agent's behavior body; legacy clients may
- // still send `chatConfig.graph`, so write it through to `agencyConfig.graph`
- // (and forward the switch) to migrate the row on the next write.
- if (data.agencyConfig && Object.hasOwn(data.agencyConfig, 'graph')) {
- mergedValue.agencyConfig = {
- ...mergedValue.agencyConfig,
- graph: data.agencyConfig.graph,
- } as AgentItem['agencyConfig'];
- // An explicit agency-level graph β€” including `null` to clear it β€” takes
- // ownership of the graph: drop the legacy chatConfig fields so the
- // runtime's `??` fallback cannot resurrect an old snapshot.
- if (mergedValue.chatConfig) {
- touchedColumns.add('chatConfig');
- const {
- graph: _legacyGraph,
- enableGraphMode: _legacyEnableGraphMode,
- ...restChatConfig
- } = mergedValue.chatConfig as Record<string, unknown>;
- mergedValue.chatConfig = restChatConfig as AgentItem['chatConfig'];
- }
- } else if (data.chatConfig && Object.hasOwn(data.chatConfig, 'graph')) {
- touchedColumns.add('agencyConfig');
- const legacyChatConfig = data.chatConfig as Record<string, unknown>;
- mergedValue.agencyConfig = {
- ...mergedValue.agencyConfig,
- graph: legacyChatConfig.graph,
- ...(Object.hasOwn(legacyChatConfig, 'enableGraphMode') && {
- enableGraphMode: legacyChatConfig.enableGraphMode,
- }),
- } as AgentItem['agencyConfig'];
- const {
- graph: _legacyGraph,
- enableGraphMode: _legacyEnableGraphMode,
- ...restChatConfig
- } = (mergedValue.chatConfig ?? {}) as Record<string, unknown>;
- mergedValue.chatConfig = restChatConfig as AgentItem['chatConfig'];
- }
-
- // Apply the processed parameters
- mergedValue.params = Object.keys(updatedParams).length > 0 ? updatedParams : undefined;
-
- // Opt-in replacement prevents old clients' complete cached maps from
- // deleting Git metadata on devices they did not actually edit.
- applyWorkingDirByDevicePatch(
- mergedValue.agencyConfig,
- data.agencyConfig,
- replaceWorkingDirDeviceIds,
- );
-
- await this.assertFixedExecutionTarget(agent.workspaceId, mergedValue.agencyConfig);
-
- // 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;
- }
- }
-
- // Timestamp fields are left to Drizzle's $onUpdate.
- touchedColumns.delete('updatedAt');
- touchedColumns.delete('accessedAt');
- touchedColumns.delete('createdAt');
-
- const updateData = Object.fromEntries(
- Object.entries(mergedValue).filter(([column]) => touchedColumns.has(column)),
- ) as Partial<typeof mergedValue>;
- if (!Object.values(updateData).some((value) => value !== undefined)) return;
-
- return this.db
- .update(agents)
- .set(updateData)
- .where(and(eq(agents.id, agentId), this.ownership()));
- };
-
- /**
- * Update the sessionGroupId for an agent
- */
- /**
- * A move target must be a folder the caller can actually see, and a *public*
- * agent may only sit in a *public* folder β€” otherwise the agent stays
- * visible to the workspace while its folder does not, and everyone else
- * silently finds it in Ungrouped. Private agents are only visible to their
- * owner, so any folder that owner can see is fine.
- */
- /**
- * Resolve a folder the caller may put an item in, returning its visibility.
- * Shared by the move guard and the create path β€” both need the same
- * "visible in scope" check, and create additionally derives the new agent's
- * visibility from the result.
- */
- getAssignableSessionGroupVisibility = async (
- sessionGroupId: string,
- ): Promise<'private' | 'public'> => {
- const [group] = await this.db
- .select({ visibility: sessionGroups.visibility })
- .from(sessionGroups)
- .where(
- and(
- eq(sessionGroups.id, sessionGroupId),
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- {
- isDeleted: sessionGroups.isDeleted,
- userId: sessionGroups.userId,
- visibility: sessionGroups.visibility,
- workspaceId: sessionGroups.workspaceId,
- },
- ),
- ),
- )
- .limit(1);
-
- if (!group) throw new Error(`Session group ${sessionGroupId} not found in current scope`);
-
- return group.visibility as 'private' | 'public';
- };
-
- private assertSessionGroupAssignable = async (agentId: string, sessionGroupId: string) => {
- const groupVisibility = await this.getAssignableSessionGroupVisibility(sessionGroupId);
- const group = { visibility: groupVisibility };
-
- if (!this.workspaceId) return;
-
- const [agent] = await this.db
- .select({ visibility: agents.visibility })
- .from(agents)
- .where(and(eq(agents.id, agentId), this.ownership()))
- .limit(1);
-
- // Buckets must match exactly, not merely "public agent needs a public
- // folder". `processAgentList` resolves a private item's folder only against
- // the private folder set and a public item's only against the public one,
- // so a mismatch in either direction renders as Ungrouped rather than in
- // the folder the user picked.
- if (agent && agent.visibility !== group.visibility)
- throw new Error(
- `A ${agent.visibility} agent cannot be moved into a ${group.visibility} folder`,
- );
- };
-
- updateSessionGroupId = async (agentId: string, sessionGroupId: string | null) => {
- // The column is workspace-shared, so an unvalidated target corrupts the
- // sidebar for everyone, not just the caller. The foreign key only proves
- // the folder exists: another workspace's folder, or another member's
- // private one, passes it happily and then renders as Ungrouped for every
- // member who cannot see it.
- if (sessionGroupId) await this.assertSessionGroupAssignable(agentId, sessionGroupId);
-
- const result = await this.db
- .update(agents)
- .set({ sessionGroupId, updatedAt: new Date() })
- .where(and(eq(agents.id, agentId), this.ownership()))
- .returning();
-
- return result[0];
- };
-
- /**
- * Duplicate an agent.
- * Returns the new agent ID.
- */
- duplicate = async (agentId: string, newTitle?: string): Promise<{ agentId: string } | null> => {
- // Get the source agent
- const sourceAgent = await this.db.query.agents.findFirst({
- where: and(eq(agents.id, agentId), this.ownership()),
- });
-
- if (!sourceAgent) return null;
-
- // The copy is owned by the caller, so device references must be resolvable
- // by the caller too. A public workspace agent may still carry a legacy
- // personal-device `boundDeviceId` / `workingDirByDevice` that `updateConfig`
- // grandfathers; duplicating it verbatim would point the new agent at a
- // device outside the workspace instead of defaulting to the caller's own
- // device. Sanitize exactly like `transferAgents` does when moving into a
- // workspace. Personal-scope copies keep existing bindings (any device is
- // reachable there).
- const agencyConfig = this.workspaceId
- ? (
- await this.sanitizeAgencyConfigForWorkspace(this.db, this.workspaceId, [
- sourceAgent.agencyConfig,
- ])
- )[0]
- : (sourceAgent.agencyConfig ?? null);
-
- // Create new agent with explicit include fields
- const [newAgent] = await this.db
- .insert(agents)
- .values(
- buildWorkspacePayload(
- { userId: this.userId, workspaceId: this.workspaceId },
- {
- // Agency config (heterogeneous provider, execution target, device
- // binding, sub-agent defaults, verify rubric...). Duplicating must
- // preserve it, otherwise a heterogeneous agent is copied as a plain
- // one and its external runtime config is silently lost.
- agencyConfig,
- avatar: sourceAgent.avatar,
- backgroundColor: sourceAgent.backgroundColor,
- chatConfig: sourceAgent.chatConfig,
- description: sourceAgent.description,
- fewShots: sourceAgent.fewShots,
- model: sourceAgent.model,
- openingMessage: sourceAgent.openingMessage,
- openingQuestions: sourceAgent.openingQuestions,
- params: sourceAgent.params,
- pinned: sourceAgent.pinned,
- // Config
- plugins: sourceAgent.plugins,
- provider: sourceAgent.provider,
-
- // Session group. Visibility has to travel with it: the column
- // defaults to `public`, and now that folder placement is shared and
- // authoritative, a private agent duplicated into its private folder
- // would be published to the workspace and still render in Ungrouped,
- // since a public item resolves only against public folders.
- sessionGroupId: sourceAgent.sessionGroupId,
- visibility: sourceAgent.visibility,
- systemRole: sourceAgent.systemRole,
-
- tags: sourceAgent.tags,
- // Metadata
- title: newTitle || (sourceAgent.title ? `${sourceAgent.title} (Copy)` : 'Copy'),
- tts: sourceAgent.tts,
- },
- ),
- )
- .returning();
-
- return { agentId: newAgent.id };
- };
-
- /**
- * Resolve a user-facing slug to its agent id, scoped by the caller's ownership
- * predicate. Returns `null` when no visible agent owns that slug β€” callers must
- * treat that as "not found" and must NOT distinguish it from "exists but not
- * yours", or the endpoint becomes an existence oracle for other users' agents.
- */
- resolveIdBySlug = async (slug: string): Promise<string | null> => {
- const trimmed = slug.trim();
- if (!trimmed) return null;
-
- const rows = await this.db
- .select({ id: agents.id })
- .from(agents)
- .where(and(this.ownership(), eq(agents.slug, trimmed)))
- .limit(1);
-
- return rows[0]?.id ?? null;
- };
-
- /**
- * Rename an agent's url slug.
- *
- * Deliberately its own method rather than a field on `updateConfig`: `slug`
- * stays in {@link IMMUTABLE_AGENT_FIELDS} so it can never ride along in a
- * passthrough config patch. Renaming needs validation the config path has no
- * place for β€” shape, reserved builtin slugs, and a uniqueness scope that
- * differs between personal and workspace rows.
- *
- * Returns a discriminated result instead of throwing so the caller can render
- * a field-level message; only a genuinely missing agent throws.
- */
- updateSlug = async (
- agentId: string,
- slug: string,
- ): Promise<{ reason?: 'builtin' | 'invalid' | 'reserved' | 'taken'; success: boolean }> => {
- const next = slug.trim().toLowerCase();
-
- if (!AGENT_SLUG_PATTERN.test(next)) return { reason: 'invalid', success: false };
-
- const current = await this.db.query.agents.findFirst({
- columns: { slug: true },
- where: and(eq(agents.id, agentId), this.ownership()),
- });
- if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
- if (current.slug === next) return { success: true };
-
- // A builtin agent IS its slug: `getBuiltinAgent` resolves it by that string,
- // so renaming one away would silently mint a second, empty inbox / page
- // agent and strand the original's history on an ordinary agent.
- if (current.slug && RESERVED_AGENT_SLUGS.has(current.slug))
- return { reason: 'builtin', success: false };
- if (RESERVED_AGENT_SLUGS.has(next)) return { reason: 'reserved', success: false };
-
- // Check within the same scope the unique indexes use, so the pre-check and
- // the constraint agree. The insert can still lose a race, hence the catch.
- const clash = await this.db
- .select({ id: agents.id })
- .from(agents)
- .where(and(this.ownership(), eq(agents.slug, next)))
- .limit(1);
- if (clash.length > 0) return { reason: 'taken', success: false };
-
- try {
- await this.db
- .update(agents)
- .set({ slug: next, updatedAt: new Date() })
- .where(and(eq(agents.id, agentId), this.ownership()));
- } catch {
- // Unique violation from a concurrent rename β€” same user-facing outcome.
- return { reason: 'taken', success: false };
- }
-
- return { success: true };
- };
-
- /**
- * 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> => {
- const persistConfig = getAgentPersistConfig(slug);
-
- // 1. First try to find existing agent by slug
- const existing = await this.db.query.agents.findFirst({
- where: and(eq(agents.slug, slug), this.ownership()),
- });
-
- if (existing) {
- if (persistConfig?.chatConfig) {
- const [updated] = await this.db
- .update(agents)
- .set({ chatConfig: persistConfig.chatConfig })
- .where(eq(agents.id, existing.id))
- .returning();
- return normalizeInboxAgentMeta(updated ?? existing, { slug: existing.slug });
- }
- return normalizeInboxAgentMeta(existing, { slug: existing.slug });
- }
-
- // 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), this.sessionsOwnership()))
- .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 normalizeInboxAgentMeta(updatedAgent, { slug: updatedAgent.slug });
- }
- }
-
- // 3. Check if this is a known builtin agent
- if (!persistConfig) return null;
-
- // 4. Create the builtin agent with persist config.
- // Idempotent under concurrent callers: two parallel requests for the same
- // (userId, slug) both see no existing row and race to insert. Without
- // `onConflictDoNothing`, the loser hits the `agents_slug_user_id_unique`
- // constraint; with it, the loser's `.returning()` is empty and we re-read
- // the row that won.
- // Bare `onConflictDoNothing()` (no target) does NOT pin an arbiter index,
- // so it works whether `agents_slug_user_id_unique` is the legacy full
- // unique or the migration-0109 partial (WHERE workspace_id IS NULL) β€” this
- // is the transition-safe form while 0109 rolls out. Tighten back to a
- // partitioned { target, where } once 0109 has flipped the index in every
- // environment. Payload still carries workspaceId so workspace-scoped
- // builtin agents land in the right workspace.
- const result = await this.db
- .insert(agents)
- .values(
- buildWorkspacePayload(
- { userId: this.userId, workspaceId: this.workspaceId },
- {
- agencyConfig: this.withWorkspaceSelectionPolicyDefaults(undefined),
- chatConfig: persistConfig.chatConfig,
- model: persistConfig.model,
- provider: persistConfig.provider,
- slug: persistConfig.slug,
- virtual: true,
- },
- ),
- )
- .onConflictDoNothing()
- .returning();
-
- if (result[0]) return normalizeInboxAgentMeta(result[0], { slug: result[0].slug });
-
- const agent = await this.db.query.agents.findFirst({
- where: and(eq(agents.slug, slug), this.ownership()),
- });
-
- return agent ? normalizeInboxAgentMeta(agent, { slug: agent.slug }) : null;
- };
-
- /**
- * Transfer an agent and all its associated data to a different workspace or personal account.
- * Runs in a single transaction to ensure atomicity.
- *
- * When moving into a workspace, `targetVisibility` picks the resulting scope
- * within that workspace (`private` = only the target user sees it,
- * `public` = every member does). Ignored when moving to a personal account.
- */
- /**
- * Whether the agent's transfer cascade (topics / messages / threads / tasks
- * linked to it) contains rows created by someone else. Transfers rehome every
- * cascaded row, so non-owner members must not move an agent that carries
- * teammates' conversations.
- */
- transferHasForeignRows = async (agentId: string | string[]): Promise<boolean> => {
- const agentIds = Array.isArray(agentId) ? agentId : [agentId];
- if (agentIds.length === 0) return false;
-
- const links = await this.db
- .select({ sessionId: agentsToSessions.sessionId })
- .from(agentsToSessions)
- .where(inArray(agentsToSessions.agentId, agentIds));
- const sessionIds = [...new Set(links.map((link) => link.sessionId))];
-
- // A member who merely opened the shared agent already owns a linked
- // session, even with no topics/messages yet β€” the transfer would rewrite
- // that session row too.
- if (sessionIds.length > 0) {
- const [foreignSession] = await this.db
- .select({ id: sessions.id })
- .from(sessions)
- .where(and(inArray(sessions.id, sessionIds), ne(sessions.userId, this.userId)))
- .limit(1);
- if (foreignSession) return true;
- }
-
- const topicWhere =
- sessionIds.length > 0
- ? or(inArray(topics.sessionId, sessionIds), inArray(topics.agentId, agentIds))
- : inArray(topics.agentId, agentIds);
- const [foreignTopic] = await this.db
- .select({ id: topics.id })
- .from(topics)
- .where(and(topicWhere, ne(topics.userId, this.userId)))
- .limit(1);
- if (foreignTopic) return true;
-
- // Comments move (or die, when the target is personal scope) with their
- // topics β€” a teammate's comment on the caller's own topic is still their
- // work. NULL authors (deleted accounts) count as foreign too.
- if (await hasForeignTopicComments(this.db, this.userId, topicWhere!)) return true;
-
- const messageWhere =
- sessionIds.length > 0
- ? or(inArray(messages.sessionId, sessionIds), inArray(messages.agentId, agentIds))
- : inArray(messages.agentId, agentIds);
- const [foreignMessage] = await this.db
- .select({ id: messages.id })
- .from(messages)
- .where(and(messageWhere, ne(messages.userId, this.userId)))
- .limit(1);
- if (foreignMessage) return true;
-
- const [foreignThread] = await this.db
- .select({ id: threads.id })
- .from(threads)
- .where(and(inArray(threads.agentId, agentIds), ne(threads.userId, this.userId)))
- .limit(1);
- if (foreignThread) return true;
-
- const [foreignTask] = await this.db
- .select({ id: tasks.id })
- .from(tasks)
- .where(
- and(
- or(inArray(tasks.assigneeAgentId, agentIds), inArray(tasks.createdByAgentId, agentIds)),
- ne(tasks.createdByUserId, this.userId),
- ),
- )
- .limit(1);
- return !!foreignTask;
- };
-
- /**
- * Chat-group memberships of the given agents, split by who owns the
- * membership.
- *
- * Read from the RAW junction rows: whether an agent may move is a fact about
- * the data, not about what the caller happens to see, and a group hidden
- * from them would otherwise silently drop out of the guard. Only the TITLE is
- * gated on visibility β€” a private group's name is its members' business β€”
- * which is why `groupTitle` is nullable.
- */
- private queryGroupMemberships = async (
- executor: Transaction | LobeChatDatabase,
- agentIds: string[],
- ): Promise<{ blocked: AgentGroupMembershipRef[]; leaving: AgentGroupMembershipRef[] }> => {
- if (agentIds.length === 0) return { blocked: [], leaving: [] };
-
- const rows = await executor
- .select({
- agentId: chatGroupsAgents.agentId,
- avatar: chatGroups.avatar,
- backgroundColor: chatGroups.backgroundColor,
- groupId: chatGroups.id,
- role: chatGroupsAgents.role,
- slug: agents.slug,
- title: chatGroups.title,
- virtual: agents.virtual,
- visible: sql<boolean>`(${buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- {
- isDeleted: chatGroups.isDeleted,
- userId: chatGroups.userId,
- visibility: chatGroups.visibility,
- workspaceId: chatGroups.workspaceId,
- },
- )})`,
- })
- .from(chatGroupsAgents)
- .innerJoin(chatGroups, eq(chatGroupsAgents.chatGroupId, chatGroups.id))
- .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
- .where(inArray(chatGroupsAgents.agentId, agentIds));
-
- const blocked: AgentGroupMembershipRef[] = [];
- const leaving: AgentGroupMembershipRef[] = [];
-
- for (const row of rows) {
- // Identity is withheld as a unit: a hidden group leaks neither its name
- // nor its avatar. The membership itself still counts toward the guard.
- const ref: AgentGroupMembershipRef = {
- agentId: row.agentId,
- groupAvatar: row.visible ? row.avatar : null,
- groupBackgroundColor: row.visible ? row.backgroundColor : null,
- // Withheld as a unit β€” id included. This is the one place these refs
- // are built, so the transfer error's `groups` payload is covered too.
- groupId: row.visible ? row.groupId : null,
- groupTitle: row.visible ? row.title : null,
- groupVisible: !!row.visible,
- };
-
- if (resolveGroupMembershipType(row) === 'owned') blocked.push(ref);
- else leaving.push(ref);
- }
-
- return { blocked, leaving };
- };
-
- private findOwnedGroupMemberships = async (
- executor: Transaction | LobeChatDatabase,
- agentIds: string[],
- ): Promise<AgentGroupMembershipRef[]> =>
- (await this.queryGroupMemberships(executor, agentIds)).blocked;
-
- /**
- * What moving these agents would do to the chat groups they are in, asked
- * BEFORE the move so the UI can block or confirm.
- *
- * `blocked` refuses the transfer outright (see the guard in
- * {@link transferAgents}); `leaving` is the silent side effect the user is
- * entitled to see first β€” a transfer drops every group link the agent holds,
- * and until now did so without a word.
- *
- * Reports only on agents the caller can already see, so the endpoint cannot
- * be used to probe which groups an arbitrary agent id sits in. The scoping
- * lives HERE rather than in the router because {@link queryGroupMemberships}
- * is deliberately unscoped β€” the transfer guard has to see a membership even
- * in a group hidden from the caller β€” and that difference is too easy to
- * lose track of one call site away.
- */
- getGroupMembershipImpact = async (
- agentIds: string[],
- ): Promise<{ blocked: AgentGroupMembershipRef[]; leaving: AgentGroupMembershipRef[] }> => {
- const uniqueIds = [...new Set(agentIds)];
- if (uniqueIds.length === 0) return { blocked: [], leaving: [] };
-
- // One query for the whole batch: the endpoint accepts up to 100 ids, and a
- // visibility probe per id is 100 round trips for a modal that opens on a
- // click.
- const visibleRows = await this.db
- .select({ id: agents.id })
- .from(agents)
- .where(and(inArray(agents.id, uniqueIds), this.ownership()));
-
- return this.queryGroupMemberships(
- this.db,
- visibleRows.map((row) => row.id),
- );
- };
-
- transferAgent = async (
- agentId: string,
- targetWorkspaceId: string | null,
- targetUserId: string,
- targetVisibility?: 'private' | 'public',
- options: AgentTransferOptions = {},
- ): Promise<{ agentId: string; slug: string | null; transferJobId: string | null }> => {
- const [result] = await this.transferAgents(
- [agentId],
- targetWorkspaceId,
- targetUserId,
- targetVisibility,
- options,
- );
- return result;
- };
-
- /**
- * Batch variant of {@link transferAgent}: moves several agents (and their
- * cascaded topics / messages / threads / tasks / …) in ONE transaction, with
- * every large-table UPDATE issued once via `inArray` instead of once per
- * agent. All-or-nothing: a failure on any agent rolls back the whole batch.
- */
- transferAgents = async (
- agentIds: string[],
- targetWorkspaceId: string | null,
- targetUserId: string,
- targetVisibility?: 'private' | 'public',
- options: AgentTransferOptions = {},
- ): Promise<{ agentId: string; slug: string | null; transferJobId: string | null }[]> => {
- if (agentIds.length === 0) return [];
-
- return this.db.transaction(async (trx) => {
- // 1. Verify all agents exist and belong to current scope. FOR UPDATE so
- // two concurrent transfers of the same agent serialize HERE, before the
- // pending-job guard below: the loser re-reads after the winner commits
- // and either no longer finds the agent in its scope, or sees the
- // winner's freshly inserted job. Without the lock both would pass the
- // guard first (check-then-act) and enqueue duplicate jobs.
- const foundAgents = await trx
- .select()
- .from(agents)
- .where(and(inArray(agents.id, agentIds), this.ownership()))
- .for('update');
- if (foundAgents.length !== new Set(agentIds).size) throw new Error('Agent not found');
- const agentById = new Map(foundAgents.map((agent) => [agent.id, agent]));
-
- // 1a. An unfinished backfill still owns these agents' message rewrite β€”
- // a second transfer would race it (and re-enqueue topics the first job
- // is still draining). Runs under the row locks above, so the check is
- // race-free against a concurrent transfer's own job insert.
- if (await AgentTransferJobModel.hasPendingJobForAgents(trx, agentIds)) {
- throw new Error(AGENT_TRANSFER_IN_PROGRESS);
- }
-
- // 1b. A pending copy job reads from these agents' topics by id β€” moving
- // them to another scope would make it drain empty topics. Copy jobs
- // register only their TARGET agents in the junction, so the source side
- // needs its own payload-based guard.
- if (await AgentCopyJobModel.hasPendingCopyJobForSourceAgents(trx, agentIds)) {
- throw new Error(AGENT_COPY_IN_PROGRESS);
- }
-
- // 1c. A group-owned agent has no existence apart from its group: the
- // synthetic supervisor, and members built through the group builder.
- // Step 14 below drops every chat-group link the moved agents hold, which
- // for an owned member means the group silently loses it β€” and for a
- // supervisor means the group is left headless, at which point
- // `findByIdWithAgents` quietly mints a blank replacement and the
- // configured systemRole/model are gone for good.
- //
- // Refuse instead, naming the groups so the caller can act. Nothing in the
- // product can reach this: owned implies `virtual`, and `queryAgents`
- // filters virtual agents out of every transfer surface. It is a guard
- // against a caller that reaches the model directly.
- const ownedGroups = await this.findOwnedGroupMemberships(trx, agentIds);
- if (ownedGroups.length > 0) throw new AgentOwnedByGroupError(ownedGroups);
-
- // 1d. Keep the share owner and tenancy stable. Check paused shares too:
- // disabling a link retains its grants and visitor history. The Agent row
- // lock also serializes this guard with AgentShareModel.create.
- const [existingShare] = await trx
- .select({ id: agentShares.id })
- .from(agentShares)
- .where(inArray(agentShares.agentId, agentIds))
- .limit(1);
- if (existingShare) throw new Error(AGENT_SHARED_TRANSFER_BLOCKED);
-
- // 2. Resolve slug conflicts in the target scope with a single query:
- // fetch every existing slug that could collide (exact match or
- // `<slug>-<n>` suffix), then pick free suffixes in memory. Agents
- // inside the batch also compete with each other for the same slug.
- const targetScopeWhere = targetWorkspaceId
- ? eq(agents.workspaceId, targetWorkspaceId)
- : and(eq(agents.userId, targetUserId), isNull(agents.workspaceId));
- const sluggedAgents = foundAgents.filter((agent) => agent.slug);
- const resolvedSlugs = new Map<string, string | null>();
- if (sluggedAgents.length > 0) {
- const conflictRows = await trx
- .select({ slug: agents.slug })
- .from(agents)
- .where(
- and(
- targetScopeWhere,
- notInArray(agents.id, agentIds),
- or(
- ...sluggedAgents.map((agent) =>
- or(eq(agents.slug, agent.slug!), like(agents.slug, `${agent.slug}-%`)),
- ),
- ),
- ),
- );
- const taken = new Set(conflictRows.map((row) => row.slug));
- for (const agent of sluggedAgents) {
- let slug = agent.slug!;
- if (taken.has(slug)) {
- let suffix = 1;
- while (suffix < 100) {
- const candidate = `${slug}-${suffix}`;
- if (!taken.has(candidate)) {
- slug = candidate;
- break;
- }
- suffix++;
- }
- }
- taken.add(slug);
- resolvedSlugs.set(agent.id, slug);
- }
- }
-
- // 3. Build ownership update payload
- const ownershipUpdate = {
- userId: targetUserId,
- workspaceId: targetWorkspaceId,
- };
-
- // 3a. Strip stale device bindings when moving INTO a workspace: any
- // boundDeviceId / workingDirByDevice entry that isn't enrolled in the
- // target workspace is silently dropped. Otherwise the moved agent would
- // reference a device only the previous owner can reach. Moving to a
- // personal scope (`targetWorkspaceId === null`) keeps existing bindings.
- // Device rows for the whole batch are fetched with one query.
- const resolvedAgencyConfigs = new Map<string, LobeAgentAgencyConfig | null>();
- if (targetWorkspaceId) {
- const cleanedConfigs = await this.sanitizeAgencyConfigForWorkspace(
- trx,
- targetWorkspaceId,
- foundAgents.map((agent) => agent.agencyConfig),
- );
- foundAgents.forEach((agent, index) =>
- resolvedAgencyConfigs.set(agent.id, cleanedConfigs[index]),
- );
- }
-
- // 4. Update the agent records. slug / agencyConfig differ per agent, so
- // these are per-row PK updates (cheap); the large cascaded tables
- // below are still one bulk UPDATE each.
- // Only apply visibility when moving into a workspace β€” visibility is
- // a no-op in personal scope where every row is implicitly private.
- // `sessionGroupId` is cleared because sidebar folders belong to the
- // source scope (same rationale as dropping chatGroupsAgents below);
- // a stale reference would orphan the agent out of the target sidebar.
- const visibilityUpdate =
- targetWorkspaceId && targetVisibility ? { visibility: targetVisibility } : {};
- for (const agent of foundAgents) {
- await trx
- .update(agents)
- .set({
- ...ownershipUpdate,
- ...visibilityUpdate,
- agencyConfig: targetWorkspaceId
- ? (resolvedAgencyConfigs.get(agent.id) ?? null)
- : (agent.agencyConfig ?? null),
- // Pins are shared state now, exactly like the folder above: a pin
- // the previous owner set for themselves would arrive as a pin for
- // every member of the target workspace. Both belong to the source
- // scope and are dropped with it.
- pinned: false,
- sessionGroupId: null,
- slug: resolvedSlugs.get(agent.id) ?? agent.slug,
- // A scope transfer does not make the agent's content newer. Keep the
- // original recency so home/search ordering is not reshuffled.
- updatedAt: agents.updatedAt,
- })
- .where(eq(agents.id, agent.id));
- }
-
- // 5. Update sessions linked via agentsToSessions
- const links = await trx
- .select({ sessionId: agentsToSessions.sessionId })
- .from(agentsToSessions)
- .where(inArray(agentsToSessions.agentId, agentIds));
-
- const sessionIds = [...new Set(links.map((l) => l.sessionId))];
-
- if (sessionIds.length > 0) {
- // `groupId` is cleared for the same reason as the agent's
- // `sessionGroupId`: folders stay in the source scope.
- await trx
- .update(sessions)
- .set({ ...ownershipUpdate, groupId: null, updatedAt: sessions.updatedAt })
- .where(inArray(sessions.id, sessionIds));
- }
-
- await trx
- .update(agentsToSessions)
- .set(ownershipUpdate)
- .where(inArray(agentsToSessions.agentId, agentIds));
-
- // 5b. Drop label assignments. Unlike sessions, these cannot travel: a
- // label belongs to the source registry, and the target scope has its own
- // (or none). Re-homing them would need a name-matched label in the
- // target, which is a merge decision, not a transfer one. Leaving them
- // instead would keep inflating the source label's usage count and make
- // the labels reappear if the agent ever moves back β€” same reasoning as
- // the device bindings stripped above.
- await trx
- .delete(agentLabelAssignments)
- .where(inArray(agentLabelAssignments.agentId, agentIds));
-
- // 6. Update topics (linked via sessionId or agentId)
- const topicCondition =
- sessionIds.length > 0
- ? or(inArray(topics.sessionId, sessionIds), inArray(topics.agentId, agentIds))
- : inArray(topics.agentId, agentIds);
-
- // Create locks the topic before inserting a comment. Lock every topic in
- // the same order before the authoritative transfer authorization check,
- // so either the create becomes visible here or it observes the moved
- // scope and fails after this transaction commits.
- await trx
- .select({ id: topics.id })
- .from(topics)
- .where(topicCondition!)
- .orderBy(asc(topics.id))
- .for('update');
-
- if (
- options.rejectForeignTopicCommentAuthors &&
- (await hasForeignTopicComments(trx, this.userId, topicCondition!))
- ) {
- throw new Error(TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS);
- }
- const movedTopics = await trx
- .update(topics)
- .set({ ...ownershipUpdate, updatedAt: topics.updatedAt })
- .where(topicCondition!)
- .returning({ id: topics.id, updatedAt: topics.updatedAt });
- const movedTopicIds = movedTopics.map((topic) => topic.id);
-
- // 6a. Topic comments denormalize the topic's workspaceId β€” move them
- // with the topic (or drop them when leaving workspace scope entirely),
- // otherwise workspace-filtered comment reads go stale. See the helper doc.
- await syncTopicCommentsOnTopicTransfer(trx, movedTopicIds, targetWorkspaceId);
-
- // 7. Message scope rewrite β€” fast/slow split. Rewriting a message row
- // maintains every message index (incl. the multi-GB BM25 index), so a
- // heavy agent's history cannot be rewritten inside this transaction:
- // above the threshold the rewrite is recorded as an async backfill job
- // (drained topic-by-topic; see AgentTransferJobModel) and the rows keep
- // their source-scope snapshot until the job reaches them.
- //
- // Both paths anchor on the moved topics (plus a topicless residual by
- // session/agent linkage) rather than the legacy session/agent-only
- // condition, so topic-only rows (OpenAPI create shape) and the message
- // child tables move too instead of stranding in the source scope.
- const messageCondition =
- sessionIds.length > 0
- ? or(inArray(messages.sessionId, sessionIds), inArray(messages.agentId, agentIds))
- : inArray(messages.agentId, agentIds);
- const [{ affectedMessages }] = await trx
- .select({ affectedMessages: count() })
- .from(messages)
- .where(
- movedTopicIds.length > 0
- ? or(inArray(messages.topicId, movedTopicIds), messageCondition!)
- : messageCondition!,
- );
-
- const targetScope = { userId: targetUserId, workspaceId: targetWorkspaceId };
- let transferJobId: string | null = null;
- if (affectedMessages <= getAgentTransferSyncMessageThreshold()) {
- await rewriteMessageScopeForTopics(trx, movedTopicIds, targetScope);
- await rewriteResidualMessageScope(trx, { agentIds, sessionIds }, targetScope);
- } else {
- transferJobId = await AgentTransferJobModel.createJob(trx, {
- agentIds,
- sessionIds,
- source: { userId: this.userId, workspaceId: this.workspaceId ?? null },
- target: targetScope,
- topics: movedTopics.map((topic) => ({ activityAt: topic.updatedAt, id: topic.id })),
- });
- }
-
- // 8. Update threads (linked via agentId)
- await trx
- .update(threads)
- .set({ ...ownershipUpdate, updatedAt: threads.updatedAt })
- .where(inArray(threads.agentId, agentIds));
-
- // 9. Update agent files associations
- await trx
- .update(agentsFiles)
- .set({ ...ownershipUpdate, updatedAt: agentsFiles.updatedAt })
- .where(inArray(agentsFiles.agentId, agentIds));
-
- // 10. Update agent knowledge base associations
- await trx
- .update(agentsKnowledgeBases)
- .set({ ...ownershipUpdate, updatedAt: agentsKnowledgeBases.updatedAt })
- .where(inArray(agentsKnowledgeBases.agentId, agentIds));
-
- // 11. Update agent cron jobs
- await trx
- .update(agentCronJobs)
- .set({ ...ownershipUpdate, updatedAt: agentCronJobs.updatedAt })
- .where(inArray(agentCronJobs.agentId, agentIds));
-
- // 12. Update tasks assigned to or created by these agents. The scheduled
- // task dispatcher uses `createdByUserId` as the execution owner, so tasks
- // must move with the agent instead of staying under the old owner.
- // Visibility is cascaded to tasks and child rows so a `private` transfer
- // does not leak previously-personal task data to every workspace member:
- // personal rows keep the schema default (`visibility='public'`) but ignore
- // it, whereas workspace rows honor it β€” without this cascade a `private`
- // transfer would silently downgrade to workspace-public.
- const movedTasks = await trx
- .update(tasks)
- .set({
- createdByUserId: targetUserId,
- updatedAt: tasks.updatedAt,
- workspaceId: targetWorkspaceId,
- ...visibilityUpdate,
- })
- .where(
- or(inArray(tasks.assigneeAgentId, agentIds), inArray(tasks.createdByAgentId, agentIds)),
- )
- .returning({ id: tasks.id });
- const movedTaskIds = movedTasks.map((task) => task.id);
-
- if (movedTaskIds.length > 0) {
- await trx
- .update(taskDependencies)
- .set({ ...ownershipUpdate, ...visibilityUpdate })
- .where(inArray(taskDependencies.taskId, movedTaskIds));
- await trx
- .update(taskTopics)
- .set({ ...ownershipUpdate, ...visibilityUpdate, updatedAt: taskTopics.updatedAt })
- .where(inArray(taskTopics.taskId, movedTaskIds));
- await trx
- .update(taskComments)
- .set({ ...ownershipUpdate, ...visibilityUpdate, updatedAt: taskComments.updatedAt })
- .where(inArray(taskComments.taskId, movedTaskIds));
- await trx.update(briefs).set(ownershipUpdate).where(inArray(briefs.taskId, movedTaskIds));
- }
-
- await trx.update(briefs).set(ownershipUpdate).where(inArray(briefs.agentId, agentIds));
-
- // 13. Move expertise owned exclusively by these agents. The domain is
- // the ownership root for lessons, hits and snapshots, so those rows keep
- // their IDs and follow it without per-table rewrites. Runs additionally
- // carry their own scope for attribution and must be re-scoped explicitly.
- // A domain
- // that is also bound to a carrier outside this transfer is shared state
- // and must stay in the source scope; only the moved agent's binding is
- // re-scoped in that case.
- const boundExpertiseDomains = await trx
- .select({ domainId: expertiseBindings.domainId })
- .from(expertiseBindings)
- .innerJoin(expertiseDomains, eq(expertiseDomains.id, expertiseBindings.domainId))
- .where(
- and(
- inArray(expertiseBindings.agentId, agentIds),
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- expertiseDomains,
- ),
- ),
- );
- const candidateDomainIds = [...new Set(boundExpertiseDomains.map((row) => row.domainId))];
-
- await trx
- .update(expertiseBindings)
- .set({ workspaceId: targetWorkspaceId, updatedAt: expertiseBindings.updatedAt })
- .where(inArray(expertiseBindings.agentId, agentIds));
-
- if (candidateDomainIds.length > 0) {
- const bindings = await trx
- .select({
- agentId: expertiseBindings.agentId,
- boundUserId: expertiseBindings.boundUserId,
- boundWorkspaceId: expertiseBindings.boundWorkspaceId,
- domainId: expertiseBindings.domainId,
- projectId: expertiseBindings.projectId,
- })
- .from(expertiseBindings)
- .where(inArray(expertiseBindings.domainId, candidateDomainIds));
- const movedAgentIds = new Set(agentIds);
- const transferableDomainIds = candidateDomainIds.filter((domainId) =>
- bindings
- .filter((binding) => binding.domainId === domainId)
- .every(
- (binding) =>
- binding.agentId !== null &&
- movedAgentIds.has(binding.agentId) &&
- binding.projectId === null &&
- binding.boundWorkspaceId === null &&
- binding.boundUserId === null,
- ),
- );
-
- if (transferableDomainIds.length > 0) {
- await trx
- .update(expertiseDomains)
- .set({ ...ownershipUpdate, updatedAt: expertiseDomains.updatedAt })
- .where(inArray(expertiseDomains.id, transferableDomainIds));
- await trx
- .update(expertiseInsights)
- .set({ ...ownershipUpdate, updatedAt: expertiseInsights.updatedAt })
- .where(inArray(expertiseInsights.domainId, transferableDomainIds));
- await trx
- .update(expertiseRuns)
- .set({ ...ownershipUpdate, updatedAt: expertiseRuns.updatedAt })
- .where(inArray(expertiseRuns.domainId, transferableDomainIds));
- }
- }
-
- // 14. Update agent bot providers (transfer, not delete)
- await trx
- .update(agentBotProviders)
- .set({ ...ownershipUpdate, updatedAt: agentBotProviders.updatedAt })
- .where(inArray(agentBotProviders.agentId, agentIds));
-
- // 14a. Agent-scoped connectors (custom plugins) ride along, or every
- // custom tool the agent carries stops resolving in the target scope.
- // Same-owner rows keep their credentials; a target owner change strips
- // them to reauthorization shells (member-handover policy).
- await rehomeAgentConnectorsForScopeTransfer(trx, {
- agentIds,
- targetUserId,
- targetWorkspaceId,
- });
-
- // 14b. Agent documents (Skills / VFS files) ride along: dedicated
- // agent-created documents move with binding + history, associated
- // personal documents stay behind with their binding detached. Without
- // this the agent's Documents list arrives empty and the files strand in
- // the source scope's Resource list.
- const movedDocumentIds = await moveAgentDocumentsForScopeTransfer(trx, {
- agentIds,
- movedTaskIds,
- movedTopicIds,
- targetUserId,
- targetVisibility,
- targetWorkspaceId,
- });
-
- // 14c. Topic- and task-document junction rows denormalize the owner
- // scope, but a junction only resolves when BOTH it and its document pass
- // the target predicate β€” `TopicDocumentModel.findByTopicId` and
- // `TaskModel.getDocumentsPinnedSince` join the two. So the split can only
- // be decided once 14b has said which documents actually moved: links
- // whose document rode along follow their topic/task, and the rest are
- // detached. Kept, they would be rows no scope can resolve β€” invisible in
- // the target, orphaned in the source once their topic/task left it.
- if (movedTopicIds.length > 0) {
- const onMovedTopics = inArray(topicDocuments.topicId, movedTopicIds);
- if (movedDocumentIds.length > 0) {
- await trx
- .update(topicDocuments)
- .set(ownershipUpdate)
- .where(and(onMovedTopics, inArray(topicDocuments.documentId, movedDocumentIds)));
- }
- await trx
- .delete(topicDocuments)
- .where(
- movedDocumentIds.length > 0
- ? and(onMovedTopics, notInArray(topicDocuments.documentId, movedDocumentIds))
- : onMovedTopics,
- );
- }
-
- if (movedTaskIds.length > 0) {
- const onMovedTasks = inArray(taskDocuments.taskId, movedTaskIds);
- if (movedDocumentIds.length > 0) {
- await trx
- .update(taskDocuments)
- .set({ ...ownershipUpdate, ...visibilityUpdate })
- .where(and(onMovedTasks, inArray(taskDocuments.documentId, movedDocumentIds)));
- }
- await trx
- .delete(taskDocuments)
- .where(
- movedDocumentIds.length > 0
- ? and(onMovedTasks, notInArray(taskDocuments.documentId, movedDocumentIds))
- : onMovedTasks,
- );
- }
-
- // 15. Leave every chat group: a group belongs to the source scope, and a
- // roster row pointing at an agent that now lives elsewhere would render
- // as a member nobody in either scope can use. Guard 1c above has already
- // rejected the memberships where leaving would damage the GROUP, so
- // everything reaching here is a `referenced` link the caller confirmed.
- await trx.delete(chatGroupsAgents).where(inArray(chatGroupsAgents.agentId, agentIds));
-
- return agentIds.map((id) => ({
- agentId: id,
- slug: resolvedSlugs.get(id) ?? agentById.get(id)?.slug ?? null,
- transferJobId,
- }));
- });
- };
-
- /**
- * Same-workspace ownership handover: the recipient of an accepted transfer
- * request becomes the agent's owner. Deliberately NOT {@link transferAgents}:
- * the agent stays in its workspace, so nothing about scope changes β€” slug,
- * visibility, permission rows, group links, labels and every member's
- * conversations all stay put β€” conversation history never changes author on
- * a member handover.
- *
- * Runs inside the caller's transaction: the caller flips the transfer
- * request's status in the same `trx`, so a stale/raced accept rolls both
- * back together.
- */
- transferAgentOwnership = async (
- trx: Transaction,
- params: {
- agentId: string;
- /** The owner recorded on the transfer request; a mismatch means the request is stale. */
- fromUserId: string;
- toUserId: string;
- },
- ): Promise<void> => {
- const { agentId, fromUserId, toUserId } = params;
- if (!this.workspaceId) throw new Error(AGENT_OWNERSHIP_STALE);
-
- // FOR UPDATE: serialize against a concurrent cross-scope transfer or a
- // second accept; the loser re-reads and fails the staleness check below.
- const [agent] = await trx
- .select()
- .from(agents)
- .where(and(eq(agents.id, agentId), eq(agents.workspaceId, this.workspaceId)))
- .for('update');
- if (!agent || agent.userId !== fromUserId) throw new Error(AGENT_OWNERSHIP_STALE);
-
- // An unfinished backfill still rewrites rows toward the OLD owner's
- // request; hand the agent over only once it has drained (same guards as
- // the cross-scope transfer).
- if (await AgentTransferJobModel.hasPendingJobForAgents(trx, [agentId])) {
- throw new Error(AGENT_TRANSFER_IN_PROGRESS);
- }
- if (await AgentCopyJobModel.hasPendingCopyJobForSourceAgents(trx, [agentId])) {
- throw new Error(AGENT_COPY_IN_PROGRESS);
- }
-
- // Mirror of cross-scope guard 1c: an agent with an OWNED group membership
- // (virtual member, or a supervisor) has no life apart from its group β€”
- // handing it to another member would leave the group broken or headless.
- const ownedGroups = await this.findOwnedGroupMemberships(trx, [agentId]);
- if (ownedGroups.length > 0) throw new AgentOwnedByGroupError(ownedGroups);
-
- /** Reject before mutation so the transfer request and share remain unchanged. */
- const [existingShare] = await trx
- .select({ id: agentShares.id })
- .from(agentShares)
- .where(eq(agentShares.agentId, agentId))
- .limit(1);
- if (existingShare) throw new Error(AGENT_SHARED_TRANSFER_BLOCKED);
-
- // A PRIVATE agent stops resolving for everyone but the recipient. Groups
- // that reference it and are NOT the recipient's would render a silent hole
- // in their roster; leave those groups explicitly instead (the manifest
- // surfaces the count to both parties before commit).
- if (agent.visibility === 'private') {
- const groupLinks = await trx
- .select({ groupId: chatGroupsAgents.chatGroupId, groupOwnerId: chatGroups.userId })
- .from(chatGroupsAgents)
- .innerJoin(chatGroups, eq(chatGroupsAgents.chatGroupId, chatGroups.id))
- .where(eq(chatGroupsAgents.agentId, agentId));
- const leavingGroupIds = groupLinks
- .filter((link) => link.groupOwnerId !== toUserId)
- .map((link) => link.groupId);
- if (leavingGroupIds.length > 0) {
- await trx
- .delete(chatGroupsAgents)
- .where(
- and(
- eq(chatGroupsAgents.agentId, agentId),
- inArray(chatGroupsAgents.chatGroupId, leavingGroupIds),
- ),
- );
- }
-
- // Same policy for PROJECTS that attached this private agent: project
- // agent listings apply member-agent visibility, so other members'
- // projects would keep a silent hole. Leave them explicitly; the
- // manifest surfaces the count to both parties.
- const projectLinks = await trx
- .select({ linkId: projectAgents.id, projectOwnerId: projects.userId })
- .from(projectAgents)
- .innerJoin(projects, eq(projectAgents.projectId, projects.id))
- .where(eq(projectAgents.agentId, agentId));
- const leavingProjectLinkIds = projectLinks
- .filter((link) => link.projectOwnerId !== toUserId)
- .map((link) => link.linkId);
- if (leavingProjectLinkIds.length > 0) {
- await trx.delete(projectAgents).where(inArray(projectAgents.id, leavingProjectLinkIds));
- }
- }
-
- // Re-home device bindings: a boundDeviceId / workingDirByDevice entry (or
- // a fixed device policy) pointing at the previous owner's personal device
- // would leave the recipient's runs unroutable. Same sanitation as moving
- // an agent into a workspace.
- const [cleanedAgencyConfig] = await this.sanitizeAgencyConfigForWorkspace(
- trx,
- this.workspaceId,
- [agent.agencyConfig],
- // The recipient is the new author: bindings to another member's PRIVATE
- // workspace device are as unreachable for them as a personal device.
- { viewerUserId: toUserId },
- );
-
- // An ownership flip does not make the agent's content newer. `clientId`
- // is cleared: it identifies the row to the CREATOR's client-side sync and
- // is unique per (clientId, userId) β€” if the recipient already owns an
- // agent with the same value, keeping it would abort every accept attempt.
- await trx
- .update(agents)
- .set({
- agencyConfig: cleanedAgencyConfig,
- clientId: null,
- updatedAt: agents.updatedAt,
- userId: toUserId,
- })
- .where(eq(agents.id, agentId));
-
- // Owner-attributed runtime rows travel with the agent: cron jobs and bot
- // providers execute AS their `userId`, so rows the previous owner set up
- // must re-home or the transferred bot keeps running as the former member
- // (and dies with their account). They arrive DISABLED β€” nothing may run
- // silently under the recipient's identity and budget; re-enabling in the
- // agent's settings is their explicit consent. Only the previous owner's
- // rows move β€” teammates' schedules stay theirs, untouched.
- await trx
- .update(agentCronJobs)
- .set({ enabled: false, updatedAt: agentCronJobs.updatedAt, userId: toUserId })
- .where(and(eq(agentCronJobs.agentId, agentId), eq(agentCronJobs.userId, fromUserId)));
- await trx
- .update(agentBotProviders)
- .set({ enabled: false, updatedAt: agentBotProviders.updatedAt, userId: toUserId })
- .where(and(eq(agentBotProviders.agentId, agentId), eq(agentBotProviders.userId, fromUserId)));
- // Quota account bindings (and exclusively-consumed provider accounts)
- // re-home: both cascade on user deletion. See the util.
- await rehomeAgentQuotaBindingsForRecipient(trx, {
- agentIds: [agentId],
- fromUserId,
- recipientId: toUserId,
- });
-
- // Label assignments (and exclusively-assigned backing labels) re-home:
- // both cascade on user deletion. See the util.
- await rehomeAgentLabelsForRecipient(trx, {
- agentIds: [agentId],
- fromUserId,
- recipientId: toUserId,
- });
-
- // Tasks stay with their creators β€” moving `createdByUserId` would break
- // in-flight run identity and split task subtrees across owners. What DOES
- // change: a PRIVATE agent stops resolving for everyone but the recipient,
- // so tasks other users had assigned to it would fail every scheduled run
- // with NOT_FOUND. Detach those assignments instead β€” the schedule goes
- // quiet (visible in the task list) rather than erroring; a public agent's
- // tasks keep working and are left untouched.
- if (agent.visibility === 'private') {
- await trx
- .update(tasks)
- .set({ assigneeAgentId: null, updatedAt: tasks.updatedAt })
- .where(and(eq(tasks.assigneeAgentId, agentId), ne(tasks.createdByUserId, toUserId)));
- }
-
- // Knowledge mounts whose KB / file the recipient cannot access (private to
- // another member) would survive as dead links: the knowledge runtime
- // silently filters them out and the agent stops using that knowledge with
- // no visible cause. Detach them instead β€” the manifest surfaces the count
- // to both parties before acceptance.
- await detachAgentKnowledgeMountsForRecipient(trx, {
- agentIds: [agentId],
- recipientId: toUserId,
- workspaceId: this.workspaceId,
- });
- // The retained mounts the previous owner created re-home to the recipient:
- // the junction `user_id` cascades on user deletion, and knowledge wired to
- // the agent must not die with the previous owner's account.
- await rehomeRetainedAgentKnowledgeMounts(trx, {
- agentIds: [agentId],
- fromUserId,
- recipientId: toUserId,
- workspaceId: this.workspaceId,
- });
-
- // Connectors: OAuth credentials are personal identity and never travel.
- // Agent-owned rows re-home as disconnected shells the recipient must
- // reauthorize; other members' mounted rows unmount. See the util.
- await rehomeAgentConnectorsForRecipient(trx, {
- agentIds: [agentId],
- recipientId: toUserId,
- });
-
- // Expertise: the agent's learned domains resolve through the viewer's
- // visibility filter β€” agent-exclusive private domains re-home, shared
- // ones unbind explicitly. See the util.
- await rehomeAgentExpertiseForRecipient(trx, {
- agentIds: [agentId],
- recipientId: toUserId,
- workspaceId: this.workspaceId,
- });
-
- // VFS documents / skills: dedicated files re-home with the agent (their
- // user_id cascades on user deletion); ASSOCIATED personal documents never
- // change owner β€” invisible-to-recipient bindings detach explicitly.
- await rehomeAgentDocumentsForRecipient(trx, {
- agentIds: [agentId],
- fromUserId,
- recipientId: toUserId,
- workspaceId: this.workspaceId,
- });
- };
-}
diff --git a/packages/database/src/models/agent/constants.ts b/packages/database/src/models/agent/constants.ts
new file mode 100644
index 00000000000..fe6c2866f70
--- /dev/null
+++ b/packages/database/src/models/agent/constants.ts
@@ -0,0 +1,6 @@
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+
+/** Slugs owned by builtin provisioning; user input must never set one. */
+export const RESERVED_AGENT_SLUGS: ReadonlySet<string> = new Set<string>(
+ Object.values(BUILTIN_AGENT_SLUGS),
+);
diff --git a/packages/database/src/models/agent/context.ts b/packages/database/src/models/agent/context.ts
new file mode 100644
index 00000000000..a6d3af3fb43
--- /dev/null
+++ b/packages/database/src/models/agent/context.ts
@@ -0,0 +1,255 @@
+import type { LobeAgentAgencyConfig } from '@lobechat/types';
+import { DEFAULT_WORKSPACE_AGENT_SELECTION_POLICIES } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import type { SQL } from 'drizzle-orm';
+import { and, eq, inArray } from 'drizzle-orm';
+import type { PartialDeep } from 'type-fest';
+
+import {
+ agents,
+ agentsFiles,
+ agentsKnowledgeBases,
+ agentsToSessions,
+ devices,
+ documents,
+ sessions,
+} from '../../schemas';
+import type { LobeChatDatabase, Transaction } from '../../type';
+import {
+ collectBoundDeviceIds,
+ sanitizeAgencyConfigsForWorkspace,
+} from '../../utils/agencyConfigDevices';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+
+/**
+ * The state and scope predicates every `AgentModel` operation shares. Built once
+ * per model instance; the operation modules receive it as their first argument.
+ */
+export interface AgentModelContext {
+ agentsFilesOwnership: () => SQL | undefined;
+ agentsKnowledgeBasesOwnership: () => SQL | undefined;
+ agentsToSessionsOwnership: () => SQL | undefined;
+ assertFixedExecutionTarget: (
+ agentWorkspaceId: string | null,
+ agencyConfig: LobeAgentAgencyConfig | null | undefined,
+ ) => Promise<void>;
+ assertWorkspaceDeviceBinding: (
+ agentWorkspaceId: string | null,
+ agencyConfig: PartialDeep<LobeAgentAgencyConfig> | null | undefined,
+ storedConfig?: LobeAgentAgencyConfig | null,
+ ) => Promise<void>;
+ collectBoundDeviceIds: (
+ agencyConfig: PartialDeep<LobeAgentAgencyConfig> | null | undefined,
+ ) => string[];
+ db: LobeChatDatabase;
+ documentsOwnership: () => SQL | undefined;
+ ownership: () => SQL | undefined;
+ sanitizeAgencyConfigForWorkspace: (
+ db: LobeChatDatabase | Transaction,
+ targetWorkspaceId: string,
+ agencyConfigs: Array<LobeAgentAgencyConfig | null | undefined>,
+ options?: { viewerUserId?: string },
+ ) => Promise<Array<LobeAgentAgencyConfig | null>>;
+ sessionsOwnership: () => SQL | undefined;
+ trashScope: () => SQL | undefined;
+ userId: string;
+ withWorkspaceSelectionPolicyDefaults: (
+ agencyConfig: LobeAgentAgencyConfig | null | undefined,
+ ) => LobeAgentAgencyConfig | null | undefined;
+ workspaceId?: string;
+}
+
+export const createAgentModelContext = ({
+ db,
+ userId,
+ workspaceId,
+}: Pick<AgentModelContext, 'db' | 'userId' | 'workspaceId'>): AgentModelContext => {
+ const ctx: AgentModelContext = {
+ db,
+ userId,
+ workspaceId,
+
+ /**
+ * Compat-mode ownership predicate for the `agents` table.
+ * - team mode (workspaceId set): `workspace_id = ?` plus visibility-aware
+ * filtering β€” public agents are visible to every member, private agents
+ * are only visible to their creator.
+ * - personal mode: `user_id = ? AND workspace_id IS NULL`.
+ */
+ ownership: () =>
+ buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ isDeleted: agents.isDeleted,
+ userId: agents.userId,
+ workspaceId: agents.workspaceId,
+ visibility: agents.visibility,
+ },
+ ),
+
+ /**
+ * {@link ownership} without the recycle-bin filter β€” restore / purge / the
+ * trash pre-flight lock only.
+ */
+ trashScope: () =>
+ buildWorkspaceWhere(
+ { includeTrashed: true, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ isDeleted: agents.isDeleted,
+ userId: agents.userId,
+ workspaceId: agents.workspaceId,
+ visibility: agents.visibility,
+ },
+ ),
+
+ /** Same predicate but for the `sessions` table (used in delete cascade). */
+ sessionsOwnership: () =>
+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, sessions),
+
+ /** Ownership predicates for the agent join/related tables. */
+ documentsOwnership: () =>
+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, documents),
+
+ agentsFilesOwnership: () =>
+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, agentsFiles),
+
+ agentsKnowledgeBasesOwnership: () =>
+ buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ agentsKnowledgeBases,
+ ),
+
+ agentsToSessionsOwnership: () =>
+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, agentsToSessions),
+
+ /**
+ * New workspace agents persist both selection policies instead of relying
+ * on the intentionally different legacy fallbacks for missing values.
+ */
+ withWorkspaceSelectionPolicyDefaults: (
+ agencyConfig: LobeAgentAgencyConfig | null | undefined,
+ ): LobeAgentAgencyConfig | null | undefined => {
+ if (!ctx.workspaceId) return agencyConfig;
+
+ return {
+ ...DEFAULT_WORKSPACE_AGENT_SELECTION_POLICIES,
+ ...agencyConfig,
+ };
+ },
+
+ collectBoundDeviceIds: (
+ agencyConfig: PartialDeep<LobeAgentAgencyConfig> | null | undefined,
+ ): string[] => collectBoundDeviceIds(agencyConfig),
+
+ /**
+ * Shared ownership-rehoming device sanitation β€” see
+ * `sanitizeAgencyConfigsForWorkspace` in `utils/agencyConfigDevices`.
+ */
+ sanitizeAgencyConfigForWorkspace: (
+ db: LobeChatDatabase | Transaction,
+ targetWorkspaceId: string,
+ agencyConfigs: Array<LobeAgentAgencyConfig | null | undefined>,
+ options?: { viewerUserId?: string },
+ ): Promise<Array<LobeAgentAgencyConfig | null>> =>
+ sanitizeAgencyConfigsForWorkspace(db, targetWorkspaceId, agencyConfigs, options),
+
+ /**
+ * Enforce: a workspace-scoped agent may only bind devices enrolled in the
+ * same workspace. Personal devices (workspace_id IS NULL) are reachable only
+ * by their owning user, so a workspace member who isn't that owner would get
+ * a broken agent. Rejects at write time rather than at execution time.
+ *
+ * Only device ids INTRODUCED by this patch are checked β€” ids already present
+ * in `storedConfig` are grandfathered. Client patches spread the whole stored
+ * `agencyConfig` (device picker, working-dir writes), so a legacy
+ * personal-device reference left from before the agent joined the workspace
+ * (or before this guard existed) would otherwise poison every future save,
+ * including binding a perfectly valid workspace device.
+ *
+ * No-op when `agentWorkspaceId` is null (personal agent β€” any device OK) or
+ * when the patch carries no new device ids.
+ */
+ assertWorkspaceDeviceBinding: async (
+ agentWorkspaceId: string | null,
+ agencyConfig: PartialDeep<LobeAgentAgencyConfig> | null | undefined,
+ storedConfig?: LobeAgentAgencyConfig | null,
+ ): Promise<void> => {
+ if (!agentWorkspaceId) return;
+ const existing = new Set(ctx.collectBoundDeviceIds(storedConfig));
+ const candidates = ctx.collectBoundDeviceIds(agencyConfig).filter((id) => !existing.has(id));
+ if (candidates.length === 0) return;
+
+ const rows = await ctx.db
+ .select({ deviceId: devices.deviceId })
+ .from(devices)
+ .where(
+ and(eq(devices.workspaceId, agentWorkspaceId), inArray(devices.deviceId, candidates)),
+ );
+ const allowed = new Set(rows.map((r) => r.deviceId));
+ const invalid = candidates.find((id) => !allowed.has(id));
+ if (invalid) {
+ throw new TRPCError({
+ cause: { data: { code: 'WorkspaceAgentRequiresWorkspaceDevice', deviceId: invalid } },
+ code: 'FORBIDDEN',
+ message:
+ 'Workspace agent can only bind devices enrolled in the same workspace. ' +
+ 'Enroll the device to the workspace, or pick a workspace device.',
+ });
+ }
+ },
+
+ /**
+ * A fixed workspace agent is a shared execution contract. It may use any
+ * server-resolvable shared target; a concrete device additionally has to be
+ * public in the same workspace. Use one generic device error for
+ * missing/private/cross-workspace rows so the write path never reveals a
+ * device the caller cannot otherwise see.
+ */
+ assertFixedExecutionTarget: async (
+ agentWorkspaceId: string | null,
+ agencyConfig: LobeAgentAgencyConfig | null | undefined,
+ ): Promise<void> => {
+ if (!agentWorkspaceId || agencyConfig?.executionTargetSelectionPolicy !== 'fixed') return;
+
+ if (
+ !agencyConfig.executionTarget ||
+ !['auto', 'device', 'none', 'sandbox'].includes(agencyConfig.executionTarget)
+ ) {
+ throw new TRPCError({
+ cause: { data: { code: 'FixedAgentRequiresSharedExecutionTarget' } },
+ code: 'BAD_REQUEST',
+ message: 'A fixed workspace agent requires a shared execution target.',
+ });
+ }
+
+ if (agencyConfig.executionTarget !== 'device') return;
+
+ if (!agencyConfig.boundDeviceId) {
+ throw new TRPCError({
+ cause: { data: { code: 'FixedAgentRequiresDeviceTarget' } },
+ code: 'BAD_REQUEST',
+ message: 'A fixed device target requires a bound device.',
+ });
+ }
+
+ const row = await ctx.db.query.devices.findFirst({
+ columns: { deviceId: true },
+ where: and(
+ eq(devices.workspaceId, agentWorkspaceId),
+ eq(devices.deviceId, agencyConfig.boundDeviceId),
+ eq(devices.visibility, 'public'),
+ ),
+ });
+
+ if (!row) {
+ throw new TRPCError({
+ cause: { data: { code: 'FixedAgentRequiresPublicWorkspaceDevice' } },
+ code: 'PRECONDITION_FAILED',
+ message: 'A fixed workspace agent requires a public device from the same workspace.',
+ });
+ }
+ },
+ };
+
+ return ctx;
+};
diff --git a/packages/database/src/models/agent/create.ts b/packages/database/src/models/agent/create.ts
new file mode 100644
index 00000000000..e03d3c6547c
--- /dev/null
+++ b/packages/database/src/models/agent/create.ts
@@ -0,0 +1,271 @@
+import { getAgentPersistConfig } from '@lobechat/builtin-agents';
+import { INBOX_SESSION_ID } from '@lobechat/const';
+import { and, eq } from 'drizzle-orm';
+import pMap from 'p-map';
+
+import type { AgentItem } from '../../schemas';
+import { agents, agentsToSessions, sessions } from '../../schemas';
+import { normalizeInboxAgentMeta } from '../../utils/inboxAgent';
+import { sanitizeAgentApiConfig } from '../../utils/sanitizeAgentApiConfig';
+import { buildWorkspacePayload } from '../../utils/workspace';
+import { RESERVED_AGENT_SLUGS } from './constants';
+import { type AgentModelContext } from './context';
+
+export const stripReservedSlug = <T extends { slug?: string | null }>(config: T): T => {
+ if (!config.slug || !RESERVED_AGENT_SLUGS.has(config.slug)) return config;
+ return { ...config, slug: undefined };
+};
+
+/**
+ * Create an agent record only (without creating a session).
+ * This is used for creating virtual agents (e.g., group chat members).
+ */
+export const create = async (
+ ctx: AgentModelContext,
+ input: Partial<AgentItem>,
+): Promise<AgentItem> => {
+ const config = stripReservedSlug(input);
+ const agencyConfig = ctx.withWorkspaceSelectionPolicyDefaults(
+ sanitizeAgentApiConfig(config.agencyConfig),
+ );
+
+ await ctx.assertWorkspaceDeviceBinding(ctx.workspaceId ?? null, agencyConfig);
+ await ctx.assertFixedExecutionTarget(ctx.workspaceId ?? null, agencyConfig);
+
+ const [result] = await ctx.db
+ .insert(agents)
+ .values([
+ buildWorkspacePayload(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ ...config,
+ agencyConfig,
+ model: typeof config.model === 'string' ? config.model : null,
+ },
+ ),
+ ])
+ .returning();
+
+ return result;
+};
+
+/**
+ * Batch create multiple agents (without sessions).
+ * Used for creating multiple virtual agents at once (e.g., group chat members).
+ */
+export const batchCreate = async (
+ ctx: AgentModelContext,
+ configs: Partial<AgentItem>[],
+): Promise<AgentItem[]> => {
+ if (configs.length === 0) return [];
+
+ const normalizedConfigs = configs.map((config) => ({
+ ...stripReservedSlug(config),
+ agencyConfig: ctx.withWorkspaceSelectionPolicyDefaults(
+ sanitizeAgentApiConfig(config.agencyConfig),
+ ),
+ }));
+
+ // Each config's assertions read device bindings / execution targets; cap
+ // the fan-out so a large batch cannot open 2Γ—N concurrent queries.
+ await pMap(
+ normalizedConfigs,
+ (config) =>
+ Promise.all([
+ ctx.assertWorkspaceDeviceBinding(ctx.workspaceId ?? null, config.agencyConfig),
+ ctx.assertFixedExecutionTarget(ctx.workspaceId ?? null, config.agencyConfig),
+ ]),
+ { concurrency: 5 },
+ );
+
+ return ctx.db
+ .insert(agents)
+ .values(
+ normalizedConfigs.map((config) =>
+ buildWorkspacePayload(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ ...config,
+ model: typeof config.model === 'string' ? config.model : null,
+ },
+ ),
+ ),
+ )
+ .returning();
+};
+
+/**
+ * Duplicate an agent.
+ * Returns the new agent ID.
+ */
+export const duplicate = async (
+ ctx: AgentModelContext,
+ agentId: string,
+ newTitle?: string,
+): Promise<{ agentId: string } | null> => {
+ // Get the source agent
+ const sourceAgent = await ctx.db.query.agents.findFirst({
+ where: and(eq(agents.id, agentId), ctx.ownership()),
+ });
+
+ if (!sourceAgent) return null;
+
+ // The copy is owned by the caller, so device references must be resolvable
+ // by the caller too. A public workspace agent may still carry a legacy
+ // personal-device `boundDeviceId` / `workingDirByDevice` that `updateConfig`
+ // grandfathers; duplicating it verbatim would point the new agent at a
+ // device outside the workspace instead of defaulting to the caller's own
+ // device. Sanitize exactly like `transferAgents` does when moving into a
+ // workspace. Personal-scope copies keep existing bindings (any device is
+ // reachable there).
+ const agencyConfig = ctx.workspaceId
+ ? (
+ await ctx.sanitizeAgencyConfigForWorkspace(ctx.db, ctx.workspaceId, [
+ sourceAgent.agencyConfig,
+ ])
+ )[0]
+ : (sourceAgent.agencyConfig ?? null);
+
+ // Create new agent with explicit include fields
+ const [newAgent] = await ctx.db
+ .insert(agents)
+ .values(
+ buildWorkspacePayload(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ // Agency config (heterogeneous provider, execution target, device
+ // binding, sub-agent defaults, verify rubric...). Duplicating must
+ // preserve it, otherwise a heterogeneous agent is copied as a plain
+ // one and its external runtime config is silently lost.
+ agencyConfig,
+ avatar: sourceAgent.avatar,
+ backgroundColor: sourceAgent.backgroundColor,
+ chatConfig: sourceAgent.chatConfig,
+ description: sourceAgent.description,
+ fewShots: sourceAgent.fewShots,
+ model: sourceAgent.model,
+ openingMessage: sourceAgent.openingMessage,
+ openingQuestions: sourceAgent.openingQuestions,
+ params: sourceAgent.params,
+ pinned: sourceAgent.pinned,
+ // Config
+ plugins: sourceAgent.plugins,
+ provider: sourceAgent.provider,
+
+ // Session group. Visibility has to travel with it: the column
+ // defaults to `public`, and now that folder placement is shared and
+ // authoritative, a private agent duplicated into its private folder
+ // would be published to the workspace and still render in Ungrouped,
+ // since a public item resolves only against public folders.
+ sessionGroupId: sourceAgent.sessionGroupId,
+ visibility: sourceAgent.visibility,
+ systemRole: sourceAgent.systemRole,
+
+ tags: sourceAgent.tags,
+ // Metadata
+ title: newTitle || (sourceAgent.title ? `${sourceAgent.title} (Copy)` : 'Copy'),
+ tts: sourceAgent.tts,
+ },
+ ),
+ )
+ .returning();
+
+ return { agentId: newAgent.id };
+};
+
+/**
+ * Get a builtin agent by slug, creating it if it doesn't exist.
+ * Builtin agents are standalone agents not bound to sessions.
+ *
+ */
+export const getBuiltinAgent = async (
+ ctx: AgentModelContext,
+ slug: string,
+): Promise<AgentItem | null> => {
+ const persistConfig = getAgentPersistConfig(slug);
+
+ // 1. First try to find existing agent by slug
+ const existing = await ctx.db.query.agents.findFirst({
+ where: and(eq(agents.slug, slug), ctx.ownership()),
+ });
+
+ if (existing) {
+ if (persistConfig?.chatConfig) {
+ const [updated] = await ctx.db
+ .update(agents)
+ .set({ chatConfig: persistConfig.chatConfig })
+ .where(eq(agents.id, existing.id))
+ .returning();
+ return normalizeInboxAgentMeta(updated ?? existing, { slug: existing.slug });
+ }
+ return normalizeInboxAgentMeta(existing, { slug: existing.slug });
+ }
+
+ // 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 ctx.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), ctx.sessionsOwnership()))
+ .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 ctx.db
+ .update(agents)
+ .set({ slug: INBOX_SESSION_ID, virtual: true })
+ .where(eq(agents.id, result[0].agent.id))
+ .returning();
+
+ return normalizeInboxAgentMeta(updatedAgent, { slug: updatedAgent.slug });
+ }
+ }
+
+ // 3. Check if this is a known builtin agent
+ if (!persistConfig) return null;
+
+ // 4. Create the builtin agent with persist config.
+ // Idempotent under concurrent callers: two parallel requests for the same
+ // (userId, slug) both see no existing row and race to insert. Without
+ // `onConflictDoNothing`, the loser hits the `agents_slug_user_id_unique`
+ // constraint; with it, the loser's `.returning()` is empty and we re-read
+ // the row that won.
+ // Bare `onConflictDoNothing()` (no target) does NOT pin an arbiter index,
+ // so it works whether `agents_slug_user_id_unique` is the legacy full
+ // unique or the migration-0109 partial (WHERE workspace_id IS NULL) β€” this
+ // is the transition-safe form while 0109 rolls out. Tighten back to a
+ // partitioned { target, where } once 0109 has flipped the index in every
+ // environment. Payload still carries workspaceId so workspace-scoped
+ // builtin agents land in the right workspace.
+ const result = await ctx.db
+ .insert(agents)
+ .values(
+ buildWorkspacePayload(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ agencyConfig: ctx.withWorkspaceSelectionPolicyDefaults(undefined),
+ chatConfig: persistConfig.chatConfig,
+ model: persistConfig.model,
+ provider: persistConfig.provider,
+ slug: persistConfig.slug,
+ virtual: true,
+ },
+ ),
+ )
+ .onConflictDoNothing()
+ .returning();
+
+ if (result[0]) return normalizeInboxAgentMeta(result[0], { slug: result[0].slug });
+
+ const agent = await ctx.db.query.agents.findFirst({
+ where: and(eq(agents.slug, slug), ctx.ownership()),
+ });
+
+ return agent ? normalizeInboxAgentMeta(agent, { slug: agent.slug }) : null;
+};
diff --git a/packages/database/src/models/agent/delete.ts b/packages/database/src/models/agent/delete.ts
new file mode 100644
index 00000000000..6658e2cd963
--- /dev/null
+++ b/packages/database/src/models/agent/delete.ts
@@ -0,0 +1,77 @@
+import { and, inArray } from 'drizzle-orm';
+
+import { agents, agentsToSessions } from '../../schemas';
+import type { LobeChatDatabase, Transaction } from '../../type';
+import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from '../agentCopyJob';
+import { AGENT_TRANSFER_IN_PROGRESS, AgentTransferJobModel } from '../agentTransferJob';
+import { type AgentModelContext } from './context';
+
+// **************** Recycle bin *************** //
+
+/**
+ * Same pre-flight as {@link delete}: an agent whose history is mid-copy or
+ * mid-transfer must not disappear from under the job. Runs the guards under
+ * the same row lock so the check cannot race an enqueue. Throws
+ * `AGENT_TRANSFER_IN_PROGRESS` / `AGENT_COPY_IN_PROGRESS`.
+ */
+export const assertDeletable = async (
+ ctx: AgentModelContext,
+ agentIds: string[],
+ trx?: Transaction,
+) => {
+ if (agentIds.length === 0) return;
+ const run = async (tx: Transaction | LobeChatDatabase) => {
+ await tx
+ .select({ id: agents.id })
+ .from(agents)
+ .where(and(inArray(agents.id, agentIds), ctx.trashScope()))
+ .for('update');
+ if (await AgentTransferJobModel.hasPendingJobForAgents(tx, agentIds)) {
+ throw new Error(AGENT_TRANSFER_IN_PROGRESS);
+ }
+ if (await AgentTransferJobModel.hasPendingRemapForSourceAgents(tx, agentIds)) {
+ throw new Error(AGENT_TRANSFER_IN_PROGRESS);
+ }
+ if (await AgentCopyJobModel.hasPendingCopyJobForSourceAgents(tx, agentIds)) {
+ throw new Error(AGENT_COPY_IN_PROGRESS);
+ }
+ };
+ return trx ? run(trx) : run(ctx.db);
+};
+
+/** Legacy session shells linked to the given agents (used to stamp `topics.session_id` rows). */
+export const findSessionIdsByAgentIds = async (
+ ctx: AgentModelContext,
+ agentIds: string[],
+): Promise<string[]> => {
+ if (agentIds.length === 0) return [];
+ const links = await ctx.db
+ .select({ sessionId: agentsToSessions.sessionId })
+ .from(agentsToSessions)
+ .where(and(inArray(agentsToSessions.agentId, agentIds), ctx.agentsToSessionsOwnership()));
+ return [...new Set(links.map((link) => link.sessionId))];
+};
+
+/** Agents linked to the given legacy session shells β€” the reverse of {@link findSessionIdsByAgentIds}. */
+export const findAgentIdsBySessionIds = async (
+ ctx: AgentModelContext,
+ sessionIds: string[],
+): Promise<string[]> => {
+ if (sessionIds.length === 0) return [];
+ const links = await ctx.db
+ .select({ agentId: agentsToSessions.agentId })
+ .from(agentsToSessions)
+ .where(and(inArray(agentsToSessions.sessionId, sessionIds), ctx.agentsToSessionsOwnership()));
+ return [...new Set(links.map((link) => link.agentId))];
+};
+
+/**
+ * Batch delete agents by IDs.
+ * This is a simpler delete that only removes the agent records.
+ * Use this for virtual agents that don't have associated sessions.
+ */
+export const batchDelete = async (ctx: AgentModelContext, agentIds: string[]) => {
+ if (agentIds.length === 0) return;
+
+ return ctx.db.delete(agents).where(and(ctx.ownership(), inArray(agents.id, agentIds)));
+};
diff --git a/packages/database/src/models/agent/errors.ts b/packages/database/src/models/agent/errors.ts
new file mode 100644
index 00000000000..2c609fede78
--- /dev/null
+++ b/packages/database/src/models/agent/errors.ts
@@ -0,0 +1,29 @@
+import { type AgentGroupMembershipRef } from './types';
+
+export const AGENT_OWNED_BY_GROUP = 'AGENT_OWNED_BY_GROUP';
+
+/**
+ * Ownership handover rejected: the agent's owner changed (or the agent left
+ * the workspace) between the transfer request and its acceptance.
+ */
+export const AGENT_OWNERSHIP_STALE = 'AGENT_OWNERSHIP_STALE';
+
+/**
+ * A share binds its grants, billing scope and visitor history to the current
+ * agent owner and workspace. Transfers remain unsupported while any share row
+ * exists, including paused shares; disabling a link must not bypass the guard.
+ */
+export const AGENT_SHARED_TRANSFER_BLOCKED = 'AGENT_SHARED_TRANSFER_BLOCKED';
+
+/**
+ * Refusal to move an agent that belongs to a chat group rather than to the
+ * user. Carries the groups so the caller can say WHICH ones, the way the
+ * existing visibility guards do β€” "cannot move this agent" with no reason is
+ * a dead end for the person looking at it.
+ */
+export class AgentOwnedByGroupError extends Error {
+ constructor(readonly groups: AgentGroupMembershipRef[]) {
+ super(AGENT_OWNED_BY_GROUP);
+ this.name = 'AgentOwnedByGroupError';
+ }
+}
diff --git a/packages/database/src/models/agent/find.ts b/packages/database/src/models/agent/find.ts
new file mode 100644
index 00000000000..9d7294cd33b
--- /dev/null
+++ b/packages/database/src/models/agent/find.ts
@@ -0,0 +1,299 @@
+import type { AgentTopicShareSubject, LobeAgentAgencyConfig } from '@lobechat/types';
+import { getHeterogeneousTaskModelProvider } from '@lobechat/types';
+import { and, eq, or, sql } from 'drizzle-orm';
+
+import { agents } from '../../schemas';
+import { notTrashed } from '../../utils/softDelete';
+import { type AgentModelContext } from './context';
+
+/**
+ * The three fields a sender-identity snapshot needs, projected and scoped by
+ * the model's ownership filter, or `null` when the agent is missing or not
+ * visible to the current caller.
+ *
+ * Deliberately not {@link getAgentConfigById}: that one enriches the agent
+ * with its assigned knowledge and loads every enabled file's row and content,
+ * which is a lot of I/O to render a label. Callers that only display who an
+ * agent is β€” attribution, receipts β€” should use this.
+ */
+export const getAgentDisplayFields = async (
+ ctx: AgentModelContext,
+ id: string,
+): Promise<{ avatar: null | string; name: null | string; title: null | string } | null> => {
+ const rows = await ctx.db
+ .select({ avatar: agents.avatar, name: agents.name, title: agents.title })
+ .from(agents)
+ .where(and(eq(agents.id, id), ctx.ownership()))
+ .limit(1);
+
+ return rows[0] ?? null;
+};
+
+/**
+ * Returns the agent's visibility, scoped by the model's ownership filter, or
+ * `null` when the agent is missing or not visible to the current caller.
+ * Used by the task service to inherit a private agent's visibility onto
+ * tasks created against it.
+ */
+export const getAgentVisibility = async (
+ ctx: AgentModelContext,
+ id: string,
+): Promise<'private' | 'public' | null> => {
+ const rows = await ctx.db
+ .select({ visibility: agents.visibility })
+ .from(agents)
+ .where(and(eq(agents.id, id), ctx.ownership()))
+ .limit(1);
+ return (rows[0]?.visibility as 'private' | 'public' | undefined) ?? null;
+};
+
+export const existsById = async (ctx: AgentModelContext, id: string): Promise<boolean> => {
+ const rows = await ctx.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(and(eq(agents.id, id), ctx.ownership()))
+ .limit(1);
+
+ return rows.length > 0;
+};
+
+/**
+ * Stricter than {@link existsById}: the agent must be owned (created) by this
+ * user, regardless of workspace visibility. `existsById` uses the visibility
+ * -aware ownership predicate, so a *public* workspace agent created by another
+ * member also returns true β€” which is only "can see", not "can edit". Callers
+ * that bind credentials/config to an agent (e.g. agent-scoped connectors) must
+ * use this so a member can't attach an account to someone else's shared agent.
+ */
+export const existsOwnedById = async (ctx: AgentModelContext, id: string): Promise<boolean> => {
+ const rows = await ctx.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(and(eq(agents.id, id), eq(agents.userId, ctx.userId), notTrashed(agents.isDeleted)))
+ .limit(1);
+
+ return rows.length > 0;
+};
+
+/**
+ * Lightweight lookup of an agent's currently-configured model + provider,
+ * used to snapshot the model into a task config so later changes to the
+ * agent's default model don't silently affect already-created tasks.
+ * Returns null when the agent has no model/provider set, or the agent
+ * cannot be found for this user.
+ */
+export const getAgentModelConfig = async (
+ ctx: AgentModelContext,
+ idOrSlug: string,
+): Promise<{ model: string; provider: string } | null> => {
+ const rows = await ctx.db
+ .select({ model: agents.model, provider: agents.provider })
+ .from(agents)
+ .where(and(ctx.ownership(), or(eq(agents.id, idOrSlug), eq(agents.slug, idOrSlug))))
+ .limit(1);
+
+ const row = rows[0];
+ if (!row || !row.model || !row.provider) return null;
+ return { model: row.model, provider: row.provider };
+};
+
+/**
+ * Single-SELECT lookup of an agent's `agencyConfig`.
+ *
+ * The task runner needs the target the agent would use on its own β€” and
+ * whether a workspace author FIXED it β€” to tell a task-level pin the run will
+ * use from one the runtime replaces (see `resolveRunDeviceId`). The enriched
+ * `getAgentConfig` would drag knowledge/file queries into every run.
+ */
+export const getAgentAgencyConfig = async (
+ ctx: AgentModelContext,
+ idOrSlug: string,
+): Promise<LobeAgentAgencyConfig | null> => {
+ const rows = await ctx.db
+ .select({ agencyConfig: agents.agencyConfig })
+ .from(agents)
+ .where(and(ctx.ownership(), or(eq(agents.id, idOrSlug), eq(agents.slug, idOrSlug))))
+ .limit(1);
+
+ return rows[0]?.agencyConfig ?? null;
+};
+
+/**
+ * Single-SELECT lookup of the fields `TaskService.createTask` needs in one
+ * round-trip: the model/provider snapshot (for `task.config`) and the
+ * visibility (for inference + cross-table invariant assertion). Replaces
+ * the previous two-query path (`getAgentModelConfig` + `getAgentVisibility`).
+ *
+ * Returns `null` when the agent is not visible to the current caller. When
+ * found, `snapshot` is non-null only if both `model` and `provider` are set
+ * β€” same contract as `getAgentModelConfig`.
+ *
+ * Use when:
+ * - Creating a Task with inherited defaults or a native model-only override.
+ *
+ * Expects:
+ * - An Agent ID or slug within the caller's visibility scope.
+ *
+ * Returns:
+ * - The unchanged runtime snapshot and visibility, plus the model override provider
+ * for native or personal API Tasks. Null preserves missing/server-default API bindings.
+ */
+export const getAgentSnapshotForTaskCreate = async (
+ ctx: AgentModelContext,
+ idOrSlug: string,
+): Promise<{
+ /** Provider for model-only Tasks; null rejects inferred API bindings, absent for regular Agents. */
+ modelOverrideProvider?: string | null;
+ snapshot: { model: string; provider: string } | null;
+ visibility: 'private' | 'public';
+} | null> => {
+ const rows = await ctx.db
+ .select({
+ agencyConfig: agents.agencyConfig,
+ model: agents.model,
+ provider: agents.provider,
+ visibility: agents.visibility,
+ })
+ .from(agents)
+ .where(and(ctx.ownership(), or(eq(agents.id, idOrSlug), eq(agents.slug, idOrSlug))))
+ .limit(1);
+
+ const row = rows[0];
+ if (!row) return null;
+ const snapshot = row.model && row.provider ? { model: row.model, provider: row.provider } : null;
+ const modelOverrideProvider = getHeterogeneousTaskModelProvider(
+ row.agencyConfig?.heterogeneousProvider,
+ );
+ return {
+ ...(modelOverrideProvider !== undefined ? { modelOverrideProvider } : {}),
+ snapshot,
+ visibility: row.visibility as 'private' | 'public',
+ };
+};
+
+/**
+ * Lightweight lookup used to authorize visibility changes: the agent's
+ * creator, slug and current visibility, scoped by the ownership predicate
+ * (other members' private agents resolve to `null`).
+ */
+/**
+ * The topic-share policy and creator of one agent.
+ *
+ * Deliberately scoped by workspace rather than by {@link ownership}: this
+ * answers "what did the author decide for this agent", which must not depend
+ * on whether the *caller* can see the row. A visibility-scoped miss would
+ * return `null` and fail open, handing a restricted agent's topics back to
+ * every member.
+ */
+export const getTopicShareSubject = async (
+ ctx: AgentModelContext,
+ id: string,
+): Promise<AgentTopicShareSubject | null> => {
+ const rows = await ctx.db
+ .select({
+ agencyConfig: agents.agencyConfig,
+ userId: agents.userId,
+ workspaceId: agents.workspaceId,
+ })
+ .from(agents)
+ .where(
+ and(
+ eq(agents.id, id),
+ ctx.workspaceId ? eq(agents.workspaceId, ctx.workspaceId) : ctx.ownership(),
+ ),
+ )
+ .limit(1);
+
+ return rows[0] ?? null;
+};
+
+export const getAgentVisibilityMeta = async (
+ ctx: AgentModelContext,
+ id: string,
+): Promise<{ slug: string | null; userId: string; visibility: 'private' | 'public' } | null> => {
+ const rows = await ctx.db
+ .select({ slug: agents.slug, userId: agents.userId, visibility: agents.visibility })
+ .from(agents)
+ .where(and(eq(agents.id, id), ctx.ownership()))
+ .limit(1);
+ const row = rows[0];
+ if (!row) return null;
+ return {
+ slug: row.slug,
+ userId: row.userId,
+ visibility: (row.visibility as 'private' | 'public' | null) ?? 'public',
+ };
+};
+
+/**
+ * Check if an agent with the given marketIdentifier already exists
+ * @returns true if exists, false otherwise
+ */
+export const checkByMarketIdentifier = async (
+ ctx: AgentModelContext,
+ marketIdentifier: string,
+): Promise<boolean> => {
+ const result = await ctx.db.query.agents.findFirst({
+ where: and(eq(agents.marketIdentifier, marketIdentifier), ctx.ownership()),
+ });
+ return !!result;
+};
+
+/**
+ * Get an agent by marketIdentifier
+ * If multiple agents match, returns the most recently updated one
+ * @returns agent id if exists, null otherwise
+ */
+export const getAgentByMarketIdentifier = async (
+ ctx: AgentModelContext,
+ marketIdentifier: string,
+): Promise<string | null> => {
+ const result = await ctx.db.query.agents.findFirst({
+ columns: { id: true },
+ orderBy: (agents, { desc }) => [desc(agents.updatedAt)],
+ where: and(eq(agents.marketIdentifier, marketIdentifier), ctx.ownership()),
+ });
+ return result?.id ?? null;
+};
+
+/**
+ * Get an agent by the forkedFromIdentifier stored in params
+ * @param forkedFromIdentifier - The source agent's market identifier
+ * @returns agent id if exists, null otherwise
+ */
+export const getAgentByForkedFromIdentifier = async (
+ ctx: AgentModelContext,
+ forkedFromIdentifier: string,
+): Promise<string | null> => {
+ const result = await ctx.db.query.agents.findFirst({
+ columns: { id: true },
+ orderBy: (agents, { desc }) => [desc(agents.updatedAt)],
+ where: and(
+ ctx.ownership(),
+ sql`${agents.params}->>'forkedFromIdentifier' = ${forkedFromIdentifier}`,
+ ),
+ });
+ return result?.id ?? null;
+};
+
+/**
+ * Resolve a user-facing slug to its agent id, scoped by the caller's ownership
+ * predicate. Returns `null` when no visible agent owns that slug β€” callers must
+ * treat that as "not found" and must NOT distinguish it from "exists but not
+ * yours", or the endpoint becomes an existence oracle for other users' agents.
+ */
+export const resolveIdBySlug = async (
+ ctx: AgentModelContext,
+ slug: string,
+): Promise<string | null> => {
+ const trimmed = slug.trim();
+ if (!trimmed) return null;
+
+ const rows = await ctx.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(and(ctx.ownership(), eq(agents.slug, trimmed)))
+ .limit(1);
+
+ return rows[0]?.id ?? null;
+};
diff --git a/packages/database/src/models/agent/groupMembership.ts b/packages/database/src/models/agent/groupMembership.ts
new file mode 100644
index 00000000000..79d133dff40
--- /dev/null
+++ b/packages/database/src/models/agent/groupMembership.ts
@@ -0,0 +1,119 @@
+import { and, eq, inArray, sql } from 'drizzle-orm';
+
+import { agents, chatGroups, chatGroupsAgents } from '../../schemas';
+import type { LobeChatDatabase, Transaction } from '../../type';
+import { resolveGroupMembershipType } from '../../utils/groupMembership';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+import { type AgentModelContext } from './context';
+import { type AgentGroupMembershipRef } from './types';
+
+/**
+ * Chat-group memberships of the given agents, split by who owns the
+ * membership.
+ *
+ * Read from the RAW junction rows: whether an agent may move is a fact about
+ * the data, not about what the caller happens to see, and a group hidden
+ * from them would otherwise silently drop out of the guard. Only the TITLE is
+ * gated on visibility β€” a private group's name is its members' business β€”
+ * which is why `groupTitle` is nullable.
+ */
+export const queryGroupMemberships = async (
+ ctx: AgentModelContext,
+ executor: Transaction | LobeChatDatabase,
+ agentIds: string[],
+): Promise<{ blocked: AgentGroupMembershipRef[]; leaving: AgentGroupMembershipRef[] }> => {
+ if (agentIds.length === 0) return { blocked: [], leaving: [] };
+
+ const rows = await executor
+ .select({
+ agentId: chatGroupsAgents.agentId,
+ avatar: chatGroups.avatar,
+ backgroundColor: chatGroups.backgroundColor,
+ groupId: chatGroups.id,
+ role: chatGroupsAgents.role,
+ slug: agents.slug,
+ title: chatGroups.title,
+ virtual: agents.virtual,
+ visible: sql<boolean>`(${buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ isDeleted: chatGroups.isDeleted,
+ userId: chatGroups.userId,
+ visibility: chatGroups.visibility,
+ workspaceId: chatGroups.workspaceId,
+ },
+ )})`,
+ })
+ .from(chatGroupsAgents)
+ .innerJoin(chatGroups, eq(chatGroupsAgents.chatGroupId, chatGroups.id))
+ .innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
+ .where(inArray(chatGroupsAgents.agentId, agentIds));
+
+ const blocked: AgentGroupMembershipRef[] = [];
+ const leaving: AgentGroupMembershipRef[] = [];
+
+ for (const row of rows) {
+ // Identity is withheld as a unit: a hidden group leaks neither its name
+ // nor its avatar. The membership itself still counts toward the guard.
+ const ref: AgentGroupMembershipRef = {
+ agentId: row.agentId,
+ groupAvatar: row.visible ? row.avatar : null,
+ groupBackgroundColor: row.visible ? row.backgroundColor : null,
+ // Withheld as a unit β€” id included. This is the one place these refs
+ // are built, so the transfer error's `groups` payload is covered too.
+ groupId: row.visible ? row.groupId : null,
+ groupTitle: row.visible ? row.title : null,
+ groupVisible: !!row.visible,
+ };
+
+ if (resolveGroupMembershipType(row) === 'owned') blocked.push(ref);
+ else leaving.push(ref);
+ }
+
+ return { blocked, leaving };
+};
+
+export const findOwnedGroupMemberships = async (
+ ctx: AgentModelContext,
+ executor: Transaction | LobeChatDatabase,
+ agentIds: string[],
+): Promise<AgentGroupMembershipRef[]> =>
+ (await queryGroupMemberships(ctx, executor, agentIds)).blocked;
+
+/**
+ * What moving these agents would do to the chat groups they are in, asked
+ * BEFORE the move so the UI can block or confirm.
+ *
+ * `blocked` refuses the transfer outright (see the guard in
+ * {@link transferAgents}); `leaving` is the silent side effect the user is
+ * entitled to see first β€” a transfer drops every group link the agent holds,
+ * and until now did so without a word.
+ *
+ * Reports only on agents the caller can already see, so the endpoint cannot
+ * be used to probe which groups an arbitrary agent id sits in. The scoping
+ * lives HERE rather than in the router because {@link queryGroupMemberships}
+ * is deliberately unscoped β€” the transfer guard has to see a membership even
+ * in a group hidden from the caller β€” and that difference is too easy to
+ * lose track of one call site away.
+ */
+export const getGroupMembershipImpact = async (
+ ctx: AgentModelContext,
+ agentIds: string[],
+): Promise<{ blocked: AgentGroupMembershipRef[]; leaving: AgentGroupMembershipRef[] }> => {
+ const uniqueIds = [...new Set(agentIds)];
+ if (uniqueIds.length === 0) return { blocked: [], leaving: [] };
+
+ // One query for the whole batch: the endpoint accepts up to 100 ids, and a
+ // visibility probe per id is 100 round trips for a modal that opens on a
+ // click.
+ const visibleRows = await ctx.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(and(inArray(agents.id, uniqueIds), ctx.ownership()));
+
+ return queryGroupMemberships(
+ ctx,
+ ctx.db,
+ visibleRows.map((row) => row.id),
+ );
+};
diff --git a/packages/database/src/models/agent/index.ts b/packages/database/src/models/agent/index.ts
new file mode 100644
index 00000000000..5721f99507e
--- /dev/null
+++ b/packages/database/src/models/agent/index.ts
@@ -0,0 +1,378 @@
+import { and, asc, eq, inArray } from 'drizzle-orm';
+
+import { AgentDeletionRepository } from '../../repositories/agentDeletion';
+import { AgentTransferRepository } from '../../repositories/agentTransfer';
+import type { AgentItem } from '../../schemas';
+import { agents, agentsToSessions, documents } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { notFileBackedPlaceholder } from '../../utils/fileBackedPlaceholder';
+import { normalizeInboxAgentMeta } from '../../utils/inboxAgent';
+import { readOriginalCharCount } from '../../utils/parsedDocument';
+import { type AgentModelContext, createAgentModelContext } from './context';
+import * as create from './create';
+import * as remove from './delete';
+import * as find from './find';
+import * as groupMembership from './groupMembership';
+import * as knowledge from './knowledge';
+import * as list from './list';
+import * as transfer from './transfer';
+import * as transferOwnership from './transferOwnership';
+import * as trash from './trash';
+import { type AgentTransferOptions } from './types';
+import * as update from './update';
+
+export {
+ AGENT_OWNED_BY_GROUP,
+ AGENT_OWNERSHIP_STALE,
+ AGENT_SHARED_TRANSFER_BLOCKED,
+ AgentOwnedByGroupError,
+} from './errors';
+export type { AgentGroupMembershipRef, DeviceBindingCandidate } from './types';
+
+export class AgentModel {
+ private ctx: AgentModelContext;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.ctx = createAgentModelContext({ db, userId, workspaceId });
+ }
+
+ /**
+ * Binds an operation module function to this instance's context. The context
+ * is read at call time, so the bound methods can be class fields even though
+ * the context is assigned in the constructor body.
+ */
+ private withContext<A extends unknown[], R>(fn: (ctx: AgentModelContext, ...args: A) => R) {
+ return (...args: A): R => fn(this.ctx, ...args);
+ }
+
+ // **************** List *************** //
+
+ rank = this.withContext(list.rank);
+ queryBoundToDevice = this.withContext(list.queryBoundToDevice);
+ queryAgents = this.withContext(list.queryAgents);
+ countAgents = this.withContext(list.countAgents);
+ getAgentAvatarsByIds = this.withContext(list.getAgentAvatarsByIds);
+ listMessengerBindableAgents = this.withContext(list.listMessengerBindableAgents);
+
+ // **************** Read *************** //
+
+ getAgentDisplayFields = this.withContext(find.getAgentDisplayFields);
+ getAgentVisibility = this.withContext(find.getAgentVisibility);
+ existsById = this.withContext(find.existsById);
+ existsOwnedById = this.withContext(find.existsOwnedById);
+ getAgentModelConfig = this.withContext(find.getAgentModelConfig);
+ getAgentAgencyConfig = this.withContext(find.getAgentAgencyConfig);
+ getAgentSnapshotForTaskCreate = this.withContext(find.getAgentSnapshotForTaskCreate);
+ getTopicShareSubject = this.withContext(find.getTopicShareSubject);
+ getAgentVisibilityMeta = this.withContext(find.getAgentVisibilityMeta);
+ checkByMarketIdentifier = this.withContext(find.checkByMarketIdentifier);
+ getAgentByMarketIdentifier = this.withContext(find.getAgentByMarketIdentifier);
+ getAgentByForkedFromIdentifier = this.withContext(find.getAgentByForkedFromIdentifier);
+ resolveIdBySlug = this.withContext(find.resolveIdBySlug);
+
+ // **************** Knowledge & files *************** //
+
+ getAgentAssignedKnowledge = this.withContext(knowledge.getAgentAssignedKnowledge);
+ createAgentKnowledgeBase = this.withContext(knowledge.createAgentKnowledgeBase);
+ deleteAgentKnowledgeBase = this.withContext(knowledge.deleteAgentKnowledgeBase);
+ toggleKnowledgeBase = this.withContext(knowledge.toggleKnowledgeBase);
+ createAgentFiles = this.withContext(knowledge.createAgentFiles);
+ deleteAgentFile = this.withContext(knowledge.deleteAgentFile);
+ toggleFile = this.withContext(knowledge.toggleFile);
+
+ // **************** Create *************** //
+
+ create = this.withContext(create.create);
+ batchCreate = this.withContext(create.batchCreate);
+ duplicate = this.withContext(create.duplicate);
+ getBuiltinAgent = this.withContext(create.getBuiltinAgent);
+
+ // **************** Update *************** //
+
+ update = this.withContext(update.update);
+ setVisibility = this.withContext(update.setVisibility);
+ updateConfig = this.withContext(update.updateConfig);
+ getAssignableSessionGroupVisibility = this.withContext(
+ update.getAssignableSessionGroupVisibility,
+ );
+ updateSlug = this.withContext(update.updateSlug);
+
+ // **************** Delete *************** //
+
+ /**
+ * Delete an agent with its session links and legacy session shells. The
+ * unit of work spans the sessions aggregate, so it lives in
+ * {@link AgentDeletionRepository}; this forwards to it.
+ */
+ delete = (agentId: string) =>
+ new AgentDeletionRepository(this.ctx.db, this.ctx.userId, this.ctx.workspaceId).deleteAgent(
+ agentId,
+ );
+ assertDeletable = this.withContext(remove.assertDeletable);
+ findSessionIdsByAgentIds = this.withContext(remove.findSessionIdsByAgentIds);
+ findAgentIdsBySessionIds = this.withContext(remove.findAgentIdsBySessionIds);
+ batchDelete = this.withContext(remove.batchDelete);
+
+ // **************** Recycle bin *************** //
+
+ softDelete = this.withContext(trash.softDelete);
+ restore = this.withContext(trash.restore);
+ findTrashedByIds = this.withContext(trash.findTrashedByIds);
+ lockTrashedForPurge = this.withContext(trash.lockTrashedForPurge);
+ purge = this.withContext(trash.purge);
+
+ // **************** Group membership *************** //
+
+ getGroupMembershipImpact = this.withContext(groupMembership.getGroupMembershipImpact);
+
+ // **************** Transfer *************** //
+
+ transferHasForeignRows = this.withContext(transfer.transferHasForeignRows);
+ /**
+ * Cross-scope transfer of agents and everything they own. The unit of work
+ * spans many aggregates, so it lives in {@link AgentTransferRepository};
+ * this forwards to it.
+ */
+ transferAgents: AgentTransferRepository['transferAgents'] = (...args) =>
+ new AgentTransferRepository(this.ctx.db, this.ctx.userId, this.ctx.workspaceId).transferAgents(
+ ...args,
+ );
+
+ // **************** Ownership transfer *************** //
+
+ transferAgentOwnership = this.withContext(transferOwnership.transferAgentOwnership);
+
+ // **************** Methods that call other public methods *************** //
+
+ getAgentConfigById = async (id: string) => {
+ const agent = await this.ctx.db.query.agents.findFirst({
+ where: and(eq(agents.id, id), this.ctx.ownership()),
+ });
+
+ if (!agent) return null;
+
+ return this.enrichAgentWithKnowledge(agent);
+ };
+
+ /**
+ * Get agent config by ID or slug (single query with OR condition)
+ */
+ getAgentConfig = async (idOrSlug: string) => {
+ // Prefer an exact ID match over a slug match. The combined `or(id, slug)`
+ // query has no inherent ordering, so resolve ID first for determinism.
+ const agent =
+ (await this.ctx.db.query.agents.findFirst({
+ where: and(this.ctx.ownership(), eq(agents.id, idOrSlug)),
+ })) ??
+ (await this.ctx.db.query.agents.findFirst({
+ where: and(this.ctx.ownership(), eq(agents.slug, idOrSlug)),
+ }));
+
+ 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);
+ const normalizedAgent = normalizeInboxAgentMeta(agent, { slug: agent.slug });
+
+ // Fetch document content for enabled files
+ const enabledFileIds = knowledge.files
+ .filter((f) => f.enabled)
+ .map((f) => f.id)
+ .filter((id) => id !== undefined);
+ let files: Array<
+ (typeof knowledge.files)[number] & { content?: string | null; originalCharCount?: number }
+ > = knowledge.files;
+
+ if (enabledFileIds.length > 0) {
+ const documentsData = await this.ctx.db.query.documents.findMany({
+ // A file can own several documents; take the oldest, like `DocumentModel.findByFileId`
+ // (which `readAttachment` pages through), so the preview and its continuation agree.
+ orderBy: [asc(documents.createdAt), asc(documents.id)],
+ where: and(
+ this.ctx.documentsOwnership(),
+ inArray(documents.fileId, enabledFileIds),
+ notFileBackedPlaceholder(),
+ ),
+ });
+
+ const documentMap = new Map<string | null, (typeof documentsData)[number]>();
+ for (const doc of documentsData) {
+ if (!documentMap.has(doc.fileId)) documentMap.set(doc.fileId, doc);
+ }
+ files = knowledge.files.map((file) => {
+ const document = file.enabled && file.id ? documentMap.get(file.id) : undefined;
+ return {
+ ...file,
+ content: document?.content,
+ originalCharCount: readOriginalCharCount(document?.metadata),
+ };
+ });
+ }
+
+ return { ...normalizedAgent, ...knowledge, files };
+ };
+
+ /**
+ * Find agent by session id
+ */
+ findBySessionId = async (sessionId: string) => {
+ const item = await this.ctx.db.query.agentsToSessions.findFirst({
+ where: and(eq(agentsToSessions.sessionId, sessionId), this.ctx.agentsToSessionsOwnership()),
+ });
+
+ if (!item) return;
+
+ const agentId = item.agentId;
+
+ return this.getAgentConfigById(agentId);
+ };
+
+ /**
+ * Whether the agent that owns a row is sitting in the bin β€” reached either
+ * directly (`agent_id`) or, for legacy rows that only carry `session_id`,
+ * through the session shell's agent link. Restoring such a row first would
+ * bring it back under an invisible container.
+ */
+ hasTrashedOwner = async (owner: {
+ agentId?: string | null;
+ sessionId?: string | null;
+ }): Promise<boolean> => {
+ const agentIds = [
+ ...(owner.agentId ? [owner.agentId] : []),
+ ...(owner.sessionId ? await this.findAgentIdsBySessionIds([owner.sessionId]) : []),
+ ];
+ return (await this.findTrashedByIds([...new Set(agentIds)])).length > 0;
+ };
+
+ touchUpdatedAt = async (agentId: string) => {
+ return this.update(agentId, {});
+ };
+
+ /**
+ * Publish a private agent into the workspace. The `user_id = ?` +
+ * `visibility = 'private'` guards lock the operation to the creator's own
+ * still-private agent. The inverse transition (public β†’ private) goes
+ * through {@link setVisibility}, which the router gates to the creator or
+ * a workspace owner.
+ *
+ * Use the existing `update` to change other fields; visibility is the only
+ * one with these authorization rules.
+ */
+ publishToWorkspace = async (agentId: string) => {
+ const agent = await this.ctx.db.query.agents.findFirst({
+ columns: { agencyConfig: true, sessionGroupId: true, workspaceId: true },
+ where: and(
+ eq(agents.id, agentId),
+ this.ctx.ownership(),
+ eq(agents.userId, this.ctx.userId),
+ eq(agents.visibility, 'private'),
+ ),
+ });
+
+ if (!agent) {
+ throw new Error('Agent not found, already published, or access denied');
+ }
+
+ // Re-check at the publication boundary. A legacy/stale fixed target may
+ // predate the config-write guard; a concrete device must never be exposed
+ // when workspace members cannot resolve it.
+ await this.ctx.assertFixedExecutionTarget(agent.workspaceId, agent.agencyConfig);
+
+ // Rehome exactly as `setVisibility` does: a folder cannot mix
+ // visibilities, so publishing out of a private Category releases the
+ // folder. Left in place the agent would be public while its folder is not,
+ // and the sidebar would show it in Ungrouped rather than where it was
+ // published from.
+ const clearGroup = agent.sessionGroupId
+ ? await this.getAssignableSessionGroupVisibility(agent.sessionGroupId)
+ .then((visibility) => visibility !== 'public')
+ .catch(() => true)
+ : false;
+
+ const [result] = await this.ctx.db
+ .update(agents)
+ .set({
+ updatedAt: new Date(),
+ visibility: 'public',
+ ...(clearGroup ? { sessionGroupId: null } : {}),
+ })
+ .where(
+ and(
+ eq(agents.id, agentId),
+ this.ctx.ownership(),
+ eq(agents.userId, this.ctx.userId),
+ eq(agents.visibility, 'private'),
+ ),
+ )
+ .returning();
+
+ if (!result) {
+ throw new Error('Agent not found, already published, or access denied');
+ }
+
+ return result;
+ };
+
+ private assertSessionGroupAssignable = async (agentId: string, sessionGroupId: string) => {
+ const groupVisibility = await this.getAssignableSessionGroupVisibility(sessionGroupId);
+ const group = { visibility: groupVisibility };
+
+ if (!this.ctx.workspaceId) return;
+
+ const [agent] = await this.ctx.db
+ .select({ visibility: agents.visibility })
+ .from(agents)
+ .where(and(eq(agents.id, agentId), this.ctx.ownership()))
+ .limit(1);
+
+ // Buckets must match exactly, not merely "public agent needs a public
+ // folder". `processAgentList` resolves a private item's folder only against
+ // the private folder set and a public item's only against the public one,
+ // so a mismatch in either direction renders as Ungrouped rather than in
+ // the folder the user picked.
+ if (agent && agent.visibility !== group.visibility)
+ throw new Error(
+ `A ${agent.visibility} agent cannot be moved into a ${group.visibility} folder`,
+ );
+ };
+
+ updateSessionGroupId = async (agentId: string, sessionGroupId: string | null) => {
+ // The column is workspace-shared, so an unvalidated target corrupts the
+ // sidebar for everyone, not just the caller. The foreign key only proves
+ // the folder exists: another workspace's folder, or another member's
+ // private one, passes it happily and then renders as Ungrouped for every
+ // member who cannot see it.
+ if (sessionGroupId) await this.assertSessionGroupAssignable(agentId, sessionGroupId);
+
+ const result = await this.ctx.db
+ .update(agents)
+ .set({ sessionGroupId, updatedAt: new Date() })
+ .where(and(eq(agents.id, agentId), this.ctx.ownership()))
+ .returning();
+
+ return result[0];
+ };
+
+ transferAgent = async (
+ agentId: string,
+ targetWorkspaceId: string | null,
+ targetUserId: string,
+ targetVisibility?: 'private' | 'public',
+ options: AgentTransferOptions = {},
+ ): Promise<{ agentId: string; slug: string | null; transferJobId: string | null }> => {
+ const [result] = await this.transferAgents(
+ [agentId],
+ targetWorkspaceId,
+ targetUserId,
+ targetVisibility,
+ options,
+ );
+ return result;
+ };
+}
diff --git a/packages/database/src/models/agent/knowledge.ts b/packages/database/src/models/agent/knowledge.ts
new file mode 100644
index 00000000000..8f07f6e52d8
--- /dev/null
+++ b/packages/database/src/models/agent/knowledge.ts
@@ -0,0 +1,174 @@
+import { and, desc, eq, inArray } from 'drizzle-orm';
+
+import { agentsFiles, agentsKnowledgeBases, files, knowledgeBases } from '../../schemas';
+import { buildWorkspacePayload, buildWorkspaceWhere } from '../../utils/workspace';
+import { type AgentModelContext } from './context';
+
+export const getAgentAssignedKnowledge = async (ctx: AgentModelContext, id: string) => {
+ // The junction tables carry the mount (created by whoever wired the agent
+ // to the KB / file); the ownership() predicates below match the caller's
+ // own mount rows within the same workspace.
+ //
+ // The joined `knowledgeBases` / `files` rows also need a visibility guard
+ // in the `leftJoin` ON clause: without it, a KB or file that was later
+ // flipped back to `private` via `setVisibility` would keep
+ // leaking its name / description into every mounted-agent view across the
+ // workspace. Enforcing the guard on the ON clause (rather than WHERE)
+ // keeps the mount row in the result but nulls out the referenced entity β€”
+ // callers can then treat `id === null` as "unavailable" and render a
+ // placeholder in the editor list, while `resolveAgentKnowledgeBaseIds` in
+ // the runtime naturally skips such rows via its `k.id` filter.
+ const [knowledgeBaseResult, fileResult] = await Promise.all([
+ ctx.db
+ .select({ enabled: agentsKnowledgeBases.enabled, knowledgeBases })
+ .from(agentsKnowledgeBases)
+ .where(and(eq(agentsKnowledgeBases.agentId, id), ctx.agentsKnowledgeBasesOwnership()))
+ .orderBy(desc(agentsKnowledgeBases.createdAt))
+ .leftJoin(
+ knowledgeBases,
+ and(
+ eq(knowledgeBases.id, agentsKnowledgeBases.knowledgeBaseId),
+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, knowledgeBases),
+ ),
+ ),
+ ctx.db
+ .select({ enabled: agentsFiles.enabled, files })
+ .from(agentsFiles)
+ .where(and(eq(agentsFiles.agentId, id), ctx.agentsFilesOwnership()))
+ .orderBy(desc(agentsFiles.createdAt))
+ .leftJoin(
+ files,
+ and(
+ eq(files.id, agentsFiles.fileId),
+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, files),
+ ),
+ ),
+ ]);
+
+ return {
+ files: fileResult.map((item) => ({
+ ...item.files,
+ enabled: item.enabled,
+ })),
+ knowledgeBases: knowledgeBaseResult.map((item) => ({
+ ...item.knowledgeBases,
+ enabled: item.enabled,
+ })),
+ };
+};
+
+export const createAgentKnowledgeBase = async (
+ ctx: AgentModelContext,
+ agentId: string,
+ knowledgeBaseId: string,
+ enabled: boolean = true,
+) => {
+ return ctx.db
+ .insert(agentsKnowledgeBases)
+ .values(
+ buildWorkspacePayload(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ { agentId, enabled, knowledgeBaseId },
+ ),
+ );
+};
+
+export const deleteAgentKnowledgeBase = async (
+ ctx: AgentModelContext,
+ agentId: string,
+ knowledgeBaseId: string,
+) => {
+ return ctx.db
+ .delete(agentsKnowledgeBases)
+ .where(
+ and(
+ eq(agentsKnowledgeBases.agentId, agentId),
+ eq(agentsKnowledgeBases.knowledgeBaseId, knowledgeBaseId),
+ ctx.agentsKnowledgeBasesOwnership(),
+ ),
+ );
+};
+
+export const toggleKnowledgeBase = async (
+ ctx: AgentModelContext,
+ agentId: string,
+ knowledgeBaseId: string,
+ enabled?: boolean,
+) => {
+ return ctx.db
+ .update(agentsKnowledgeBases)
+ .set({ enabled })
+ .where(
+ and(
+ eq(agentsKnowledgeBases.agentId, agentId),
+ eq(agentsKnowledgeBases.knowledgeBaseId, knowledgeBaseId),
+ ctx.agentsKnowledgeBasesOwnership(),
+ ),
+ );
+};
+
+export const createAgentFiles = async (
+ ctx: AgentModelContext,
+ agentId: string,
+ fileIds: string[],
+ enabled: boolean = true,
+) => {
+ // Exclude the fileIds that already exist in agentsFiles, and then insert them
+ const existingFiles = await ctx.db
+ .select({ id: agentsFiles.fileId })
+ .from(agentsFiles)
+ .where(
+ and(
+ eq(agentsFiles.agentId, agentId),
+ ctx.agentsFilesOwnership(),
+ inArray(agentsFiles.fileId, fileIds),
+ ),
+ );
+
+ const existingFilesIds = new Set(existingFiles.map((item) => item.id));
+
+ const needToInsertFileIds = fileIds.filter((fileId) => !existingFilesIds.has(fileId));
+
+ if (needToInsertFileIds.length === 0) return;
+
+ return ctx.db
+ .insert(agentsFiles)
+ .values(
+ needToInsertFileIds.map((fileId) =>
+ buildWorkspacePayload(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ { agentId, enabled, fileId },
+ ),
+ ),
+ );
+};
+
+export const deleteAgentFile = async (ctx: AgentModelContext, agentId: string, fileId: string) => {
+ return ctx.db
+ .delete(agentsFiles)
+ .where(
+ and(
+ eq(agentsFiles.agentId, agentId),
+ eq(agentsFiles.fileId, fileId),
+ ctx.agentsFilesOwnership(),
+ ),
+ );
+};
+
+export const toggleFile = async (
+ ctx: AgentModelContext,
+ agentId: string,
+ fileId: string,
+ enabled?: boolean,
+) => {
+ return ctx.db
+ .update(agentsFiles)
+ .set({ enabled })
+ .where(
+ and(
+ eq(agentsFiles.agentId, agentId),
+ eq(agentsFiles.fileId, fileId),
+ ctx.agentsFilesOwnership(),
+ ),
+ );
+};
diff --git a/packages/database/src/models/agent/list.ts b/packages/database/src/models/agent/list.ts
new file mode 100644
index 00000000000..77495da966b
--- /dev/null
+++ b/packages/database/src/models/agent/list.ts
@@ -0,0 +1,355 @@
+import { DEFAULT_INBOX_TITLE, INBOX_SESSION_ID } from '@lobechat/const';
+import type { AgentRankItem } from '@lobechat/types';
+import { and, count, desc, eq, gt, ilike, inArray, isNull, ne, or, sql } from 'drizzle-orm';
+
+import { agents, topics } from '../../schemas';
+import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../../utils/genWhere';
+import { normalizeInboxAgentMeta } from '../../utils/inboxAgent';
+import { notShareVisitorTopic } from '../../utils/shareVisitor';
+import { notTrashed } from '../../utils/softDelete';
+import { type AgentModelContext } from './context';
+import { type DeviceBindingCandidate } from './types';
+
+/**
+ * Rank the user's agents by topic count (agent usage ranking). Counts topics
+ * directly via `topics.agentId`, so it is agent-native β€” no sessionId. Mirrors
+ * the recents filter: real agents plus the inbox, excluding other virtual agents.
+ *
+ * Share-visitor topics are excluded from the count: they carry the creator's
+ * `userId` (so the plain join would count them) but reflect visitor usage,
+ * not the creator's own β€” same rule as `TopicModel.rank` and every other
+ * creator-facing aggregate (see `notShareVisitorTopic`). Applied in the join
+ * condition rather than `where` so agents whose ONLY topics are visitor ones
+ * still drop out via the `count > 0` guard instead of being filtered away
+ * before grouping.
+ */
+export const rank = async (
+ ctx: AgentModelContext,
+ limit: number = 10,
+): Promise<AgentRankItem[]> => {
+ const rows = await ctx.db
+ .select({
+ avatar: agents.avatar,
+ backgroundColor: agents.backgroundColor,
+ count: count(topics.id).as('count'),
+ id: agents.id,
+ name: agents.name,
+ slug: agents.slug,
+ title: agents.title,
+ })
+ .from(agents)
+ .leftJoin(
+ topics,
+ and(eq(topics.agentId, agents.id), notShareVisitorTopic(), notTrashed(topics.isDeleted)),
+ )
+ .where(and(ctx.ownership(), or(eq(agents.slug, INBOX_SESSION_ID), ne(agents.virtual, true))))
+ .groupBy(agents.id)
+ .having(({ count }) => gt(count, 0))
+ .orderBy(desc(sql`count`))
+ .limit(limit);
+
+ return rows.map(({ slug, ...row }) => normalizeInboxAgentMeta(row, { slug }));
+};
+
+/**
+ * Candidate agents for a device's "bound agents" list: agents whose stored
+ * agency config routes execution there (`device`, or a desktop `local` pick,
+ * which also records its own `boundDeviceId`), plus `extraAgentIds` β€” agents
+ * a caller's per-agent device override may route there. Candidates pass the
+ * same visibility gate, so an id the caller cannot see is dropped rather
+ * than leaked.
+ *
+ * The routing fields ride along because the stored config is only a
+ * baseline: the caller merges their own override over it (see
+ * `resolveAgentAgencyConfig`) and keeps the agents whose EFFECTIVE target
+ * is still this device.
+ */
+export const queryBoundToDevice = async (
+ ctx: AgentModelContext,
+ deviceId: string,
+ extraAgentIds: string[] = [],
+): Promise<DeviceBindingCandidate[]> => {
+ const boundHere = and(
+ sql`${agents.agencyConfig} ->> 'boundDeviceId' = ${deviceId}`,
+ sql`${agents.agencyConfig} ->> 'executionTarget' IN ('device', 'local')`,
+ );
+
+ const rows = await ctx.db
+ .select({
+ agencyConfig: agents.agencyConfig,
+ avatar: agents.avatar,
+ backgroundColor: agents.backgroundColor,
+ id: agents.id,
+ name: agents.name,
+ slug: agents.slug,
+ title: agents.title,
+ userId: agents.userId,
+ visibility: agents.visibility,
+ workspaceId: agents.workspaceId,
+ })
+ .from(agents)
+ .where(
+ and(
+ ctx.ownership(),
+ or(eq(agents.slug, INBOX_SESSION_ID), ne(agents.virtual, true)),
+ extraAgentIds.length > 0 ? or(boundHere, inArray(agents.id, extraAgentIds)) : boundHere,
+ ),
+ )
+ .orderBy(desc(agents.updatedAt));
+
+ return rows.map(({ slug, ...row }) => normalizeInboxAgentMeta(row, { slug }));
+};
+
+/**
+ * Build the where condition shared by queryAgents / countAgents: the current
+ * user's agents, with optional keyword filter.
+ *
+ * Virtual rows are infrastructure (group-built members, supervisors) and stay
+ * excluded. That includes the inbox (Lobe AI): it is the product-owned
+ * assistant, so including it is a deliberate choice every caller makes with
+ * `includeInbox: true` β€” never something a generic agent lookup inherits. The
+ * default is therefore the long-standing behavior (real, user-created agents
+ * only), so callers that never asked for the inbox β€” older clients, the
+ * CRUD/management tool runtimes, group pickers β€” keep it out instead of
+ * discovering a row they cannot delete or add.
+ *
+ * When a caller does opt in, the inbox joins the page inside the where clause
+ * rather than being filtered afterwards, so `limit` is never spent on an inbox
+ * the caller would drop.
+ */
+export const buildQueryAgentsWhere = (
+ ctx: AgentModelContext,
+ keyword?: string,
+ includeInbox = false,
+) => {
+ // Include agents where virtual is false OR null (legacy data without virtual
+ // field), plus the inbox when the caller opts into it.
+ const baseConditions = and(
+ ctx.ownership(),
+ includeInbox
+ ? or(eq(agents.virtual, false), isNull(agents.virtual), eq(agents.slug, INBOX_SESSION_ID))
+ : or(eq(agents.virtual, false), isNull(agents.virtual)),
+ );
+
+ // `name` is the user-facing display name (see `agents.name`); resolving the
+ // label the UI shows is the primary way users and tools find an agent, so
+ // the keyword must match it alongside `title`/`description`.
+ if (!keyword) return baseConditions;
+
+ // An inbox with a blank title is shown as `DEFAULT_INBOX_TITLE` only after
+ // the query (see `normalizeInboxAgentMeta`), so the raw `title` column can't
+ // match it β€” match that default label here instead.
+ const matchesDefaultInboxTitle =
+ includeInbox && DEFAULT_INBOX_TITLE.toLowerCase().includes(keyword.toLowerCase());
+
+ return and(
+ baseConditions,
+ or(
+ ilike(agents.title, `%${keyword}%`),
+ ilike(agents.name, `%${keyword}%`),
+ ilike(agents.description, `%${keyword}%`),
+ matchesDefaultInboxTitle
+ ? and(
+ eq(agents.slug, INBOX_SESSION_ID),
+ or(isNull(agents.title), sql`trim(${agents.title}) = ''`),
+ )
+ : undefined,
+ ),
+ );
+};
+
+/**
+ * Query the user's agents with an optional keyword filter.
+ * Returns minimal agent info (id, title, name, description, avatar,
+ * backgroundColor), plus `userId`/`visibility` so callers can gate per-agent
+ * actions (e.g. transfer is creator/primary-owner only), a compact
+ * `heteroType` derived from `agencyConfig` so callers can tell which results
+ * are heterogeneous (external CLI/device) agents, and `isInbox` so callers can
+ * recognize the product-owned inbox (Lobe AI) without re-deriving it from a
+ * slug the row shape no longer carries.
+ * Excludes virtual agents (supervisors, group-built members) and, unless the
+ * caller opts in with `includeInbox: true`, the product-owned inbox (Lobe AI).
+ * See `buildQueryAgentsWhere`.
+ */
+export const queryAgents = async (
+ ctx: AgentModelContext,
+ params?: {
+ includeInbox?: boolean;
+ keyword?: string;
+ limit?: number;
+ offset?: number;
+ },
+) => {
+ const { includeInbox = false, keyword, limit = 9999, offset = 0 } = params ?? {};
+ const searchCondition = buildQueryAgentsWhere(ctx, keyword, includeInbox);
+
+ const rows = await ctx.db
+ .select({
+ agencyConfig: agents.agencyConfig,
+ avatar: agents.avatar,
+ backgroundColor: agents.backgroundColor,
+ description: agents.description,
+ id: agents.id,
+ name: agents.name,
+ slug: agents.slug,
+ title: agents.title,
+ userId: agents.userId,
+ visibility: agents.visibility,
+ })
+ .from(agents)
+ .where(searchCondition)
+ .orderBy(desc(agents.updatedAt))
+ .limit(limit)
+ .offset(offset);
+
+ // Surface only the hetero runtime type, not the full agencyConfig payload.
+ return rows.map(({ slug, agencyConfig, ...row }) => ({
+ ...normalizeInboxAgentMeta(
+ { ...row, heteroType: agencyConfig?.heterogeneousProvider?.type },
+ { slug },
+ ),
+ // When the caller opted in, the inbox is the only virtual row this query
+ // keeps, and `slug` is consumed above rather than returned β€” so the flag
+ // is what lets callers pin or annotate Lobe AI without re-deriving it.
+ isInbox: slug === INBOX_SESSION_ID,
+ }));
+};
+
+/**
+ * Count the agents matching the same conditions as queryAgents β€” the inbox is
+ * counted only when the caller opts in with `includeInbox: true`, other
+ * virtual rows always excluded β€” so the count stays a faithful total for
+ * paginated callers and for the assistants stats.
+ * Used to report real totals (and pagination) when queryAgents is limited.
+ * Accepts the same date filters as SessionModel.count so callers can compare
+ * current vs. prior-period totals without falling back to the legacy
+ * sessions table.
+ */
+export const countAgents = async (
+ ctx: AgentModelContext,
+ params?: {
+ endDate?: string;
+ includeInbox?: boolean;
+ keyword?: string;
+ range?: [string, string];
+ startDate?: string;
+ },
+): Promise<number> => {
+ const result = await ctx.db
+ .select({ count: count() })
+ .from(agents)
+ .where(
+ genWhere([
+ buildQueryAgentsWhere(ctx, params?.keyword, params?.includeInbox ?? false),
+ params?.range
+ ? genRangeWhere(params.range, agents.createdAt, (date) => date.toDate())
+ : undefined,
+ params?.endDate
+ ? genEndDateWhere(params.endDate, agents.createdAt, (date) => date.toDate())
+ : undefined,
+ params?.startDate
+ ? genStartDateWhere(params.startDate, agents.createdAt, (date) => date.toDate())
+ : undefined,
+ ]),
+ );
+
+ return result[0]?.count ?? 0;
+};
+
+/**
+ * Get minimal agent info (avatar, title, backgroundColor) by IDs.
+ * For inbox agent (slug='inbox'), falls back to LobeAI defaults when avatar/title are missing.
+ */
+export const getAgentAvatarsByIds = async (ctx: AgentModelContext, ids: string[]) => {
+ if (ids.length === 0) return [];
+
+ const rows = await ctx.db
+ .select({
+ avatar: agents.avatar,
+ backgroundColor: agents.backgroundColor,
+ id: agents.id,
+ name: agents.name,
+ slug: agents.slug,
+ title: agents.title,
+ })
+ .from(agents)
+ .where(and(ctx.ownership(), inArray(agents.id, ids)));
+
+ return rows.map(({ slug, ...row }) => normalizeInboxAgentMeta(row, { slug }));
+};
+
+/**
+ * List agents bindable by the System Bot messenger picker: real agents plus
+ * the inbox (other virtual agents excluded), ordered by `updatedAt DESC` with
+ * the inbox pinned to the top.
+ *
+ * Returns `name` and `title` separately β€” resolving them into one label is the
+ * caller's job (see `agentDisplayName`), since only the caller knows whether it
+ * can render an i18n fallback. `title` is still normalized here for the inbox
+ * (LobeAI default) and falls back to `options.fallbackTitle` when blank
+ * (default `null`, so a client caller can supply its own i18n default).
+ */
+export const listMessengerBindableAgents = async (
+ ctx: AgentModelContext,
+ options?: {
+ fallbackTitle?: string | null;
+ },
+): Promise<
+ Array<{
+ avatar: string | null;
+ backgroundColor: string | null;
+ id: string;
+ isInbox: boolean;
+ isPrivate: boolean;
+ name: string | null;
+ title: string | null;
+ }>
+> => {
+ const fallbackTitle = options?.fallbackTitle ?? null;
+
+ const rows = await ctx.db
+ .select({
+ avatar: agents.avatar,
+ backgroundColor: agents.backgroundColor,
+ id: agents.id,
+ name: agents.name,
+ slug: agents.slug,
+ title: agents.title,
+ visibility: agents.visibility,
+ })
+ .from(agents)
+ .where(and(ctx.ownership(), or(ne(agents.virtual, true), eq(agents.slug, INBOX_SESSION_ID))))
+ .orderBy(desc(agents.updatedAt));
+
+ const normalized = rows
+ .filter((row) => row.id)
+ .map(({ slug, visibility, ...row }) => {
+ const meta = normalizeInboxAgentMeta(row, { slug });
+ return {
+ avatar: meta.avatar,
+ backgroundColor: meta.backgroundColor,
+ id: meta.id,
+ isInbox: slug === INBOX_SESSION_ID,
+ // Only meaningful in workspace mode: the ownership predicate already
+ // scopes visible private rows to the caller, so `isPrivate` means
+ // "the caller's own private agent in this workspace". Personal-mode
+ // rows are all implicitly private, so the flag stays false there to
+ // signal "no grouping needed".
+ isPrivate: Boolean(ctx.workspaceId) && visibility === 'private',
+ name: meta.name ?? null,
+ // The inbox title is already resolved by normalizeInboxAgentMeta; any
+ // other blank title falls back to the caller-provided default.
+ title: meta.title?.trim() || fallbackTitle,
+ };
+ });
+
+ // Pin the inbox agent to the top regardless of updatedAt β€” it's the
+ // implicit "default" agent and should always be the first option.
+ const inboxIdx = normalized.findIndex((row) => row.isInbox);
+ if (inboxIdx > 0) {
+ const [inbox] = normalized.splice(inboxIdx, 1);
+ normalized.unshift(inbox);
+ }
+
+ return normalized;
+};
diff --git a/packages/database/src/models/agent/transfer.ts b/packages/database/src/models/agent/transfer.ts
new file mode 100644
index 00000000000..6d7fb6f042c
--- /dev/null
+++ b/packages/database/src/models/agent/transfer.ts
@@ -0,0 +1,91 @@
+import { and, inArray, ne, or } from 'drizzle-orm';
+
+import { agentsToSessions, messages, sessions, tasks, threads, topics } from '../../schemas';
+import { hasForeignTopicComments } from '../topicComment';
+import { type AgentModelContext } from './context';
+
+/**
+ * Transfer an agent and all its associated data to a different workspace or personal account.
+ * Runs in a single transaction to ensure atomicity.
+ *
+ * When moving into a workspace, `targetVisibility` picks the resulting scope
+ * within that workspace (`private` = only the target user sees it,
+ * `public` = every member does). Ignored when moving to a personal account.
+ */
+/**
+ * Whether the agent's transfer cascade (topics / messages / threads / tasks
+ * linked to it) contains rows created by someone else. Transfers rehome every
+ * cascaded row, so non-owner members must not move an agent that carries
+ * teammates' conversations.
+ */
+export const transferHasForeignRows = async (
+ ctx: AgentModelContext,
+ agentId: string | string[],
+): Promise<boolean> => {
+ const agentIds = Array.isArray(agentId) ? agentId : [agentId];
+ if (agentIds.length === 0) return false;
+
+ const links = await ctx.db
+ .select({ sessionId: agentsToSessions.sessionId })
+ .from(agentsToSessions)
+ .where(inArray(agentsToSessions.agentId, agentIds));
+ const sessionIds = [...new Set(links.map((link) => link.sessionId))];
+
+ // A member who merely opened the shared agent already owns a linked
+ // session, even with no topics/messages yet β€” the transfer would rewrite
+ // that session row too.
+ if (sessionIds.length > 0) {
+ const [foreignSession] = await ctx.db
+ .select({ id: sessions.id })
+ .from(sessions)
+ .where(and(inArray(sessions.id, sessionIds), ne(sessions.userId, ctx.userId)))
+ .limit(1);
+ if (foreignSession) return true;
+ }
+
+ const topicWhere =
+ sessionIds.length > 0
+ ? or(inArray(topics.sessionId, sessionIds), inArray(topics.agentId, agentIds))
+ : inArray(topics.agentId, agentIds);
+ const [foreignTopic] = await ctx.db
+ .select({ id: topics.id })
+ .from(topics)
+ .where(and(topicWhere, ne(topics.userId, ctx.userId)))
+ .limit(1);
+ if (foreignTopic) return true;
+
+ // Comments move (or die, when the target is personal scope) with their
+ // topics β€” a teammate's comment on the caller's own topic is still their
+ // work. NULL authors (deleted accounts) count as foreign too.
+ if (await hasForeignTopicComments(ctx.db, ctx.userId, topicWhere!)) return true;
+
+ const messageWhere =
+ sessionIds.length > 0
+ ? or(inArray(messages.sessionId, sessionIds), inArray(messages.agentId, agentIds))
+ : inArray(messages.agentId, agentIds);
+ const [foreignMessage] = await ctx.db
+ .select({ id: messages.id })
+ .from(messages)
+ .where(and(messageWhere, ne(messages.userId, ctx.userId)))
+ .limit(1);
+ if (foreignMessage) return true;
+
+ const [foreignThread] = await ctx.db
+ .select({ id: threads.id })
+ .from(threads)
+ .where(and(inArray(threads.agentId, agentIds), ne(threads.userId, ctx.userId)))
+ .limit(1);
+ if (foreignThread) return true;
+
+ const [foreignTask] = await ctx.db
+ .select({ id: tasks.id })
+ .from(tasks)
+ .where(
+ and(
+ or(inArray(tasks.assigneeAgentId, agentIds), inArray(tasks.createdByAgentId, agentIds)),
+ ne(tasks.createdByUserId, ctx.userId),
+ ),
+ )
+ .limit(1);
+ return !!foreignTask;
+};
diff --git a/packages/database/src/models/agent/transferOwnership.ts b/packages/database/src/models/agent/transferOwnership.ts
new file mode 100644
index 00000000000..6bba697fa2f
--- /dev/null
+++ b/packages/database/src/models/agent/transferOwnership.ts
@@ -0,0 +1,251 @@
+import { and, eq, inArray, ne } from 'drizzle-orm';
+
+import {
+ agentBotProviders,
+ agentCronJobs,
+ agents,
+ agentShares,
+ chatGroups,
+ chatGroupsAgents,
+ projectAgents,
+ projects,
+ tasks,
+} from '../../schemas';
+import type { Transaction } from '../../type';
+import { rehomeAgentConnectorsForRecipient } from '../../utils/agentConnectors';
+import { rehomeAgentDocumentsForRecipient } from '../../utils/agentDocumentsOwnership';
+import { rehomeAgentExpertiseForRecipient } from '../../utils/agentExpertise';
+import {
+ detachAgentKnowledgeMountsForRecipient,
+ rehomeRetainedAgentKnowledgeMounts,
+} from '../../utils/agentKnowledgeMounts';
+import { rehomeAgentLabelsForRecipient } from '../../utils/agentLabelsOwnership';
+import { rehomeAgentQuotaBindingsForRecipient } from '../../utils/agentQuotaBindings';
+import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from '../agentCopyJob';
+import { AGENT_TRANSFER_IN_PROGRESS, AgentTransferJobModel } from '../agentTransferJob';
+import { type AgentModelContext } from './context';
+import {
+ AGENT_OWNERSHIP_STALE,
+ AGENT_SHARED_TRANSFER_BLOCKED,
+ AgentOwnedByGroupError,
+} from './errors';
+import { findOwnedGroupMemberships } from './groupMembership';
+
+/**
+ * Same-workspace ownership handover: the recipient of an accepted transfer
+ * request becomes the agent's owner. Deliberately NOT {@link transferAgents}:
+ * the agent stays in its workspace, so nothing about scope changes β€” slug,
+ * visibility, permission rows, group links, labels and every member's
+ * conversations all stay put β€” conversation history never changes author on
+ * a member handover.
+ *
+ * Runs inside the caller's transaction: the caller flips the transfer
+ * request's status in the same `trx`, so a stale/raced accept rolls both
+ * back together.
+ */
+export const transferAgentOwnership = async (
+ ctx: AgentModelContext,
+ trx: Transaction,
+ params: {
+ agentId: string;
+ /** The owner recorded on the transfer request; a mismatch means the request is stale. */
+ fromUserId: string;
+ toUserId: string;
+ },
+): Promise<void> => {
+ const { agentId, fromUserId, toUserId } = params;
+ if (!ctx.workspaceId) throw new Error(AGENT_OWNERSHIP_STALE);
+
+ // FOR UPDATE: serialize against a concurrent cross-scope transfer or a
+ // second accept; the loser re-reads and fails the staleness check below.
+ const [agent] = await trx
+ .select()
+ .from(agents)
+ .where(and(eq(agents.id, agentId), eq(agents.workspaceId, ctx.workspaceId)))
+ .for('update');
+ if (!agent || agent.userId !== fromUserId) throw new Error(AGENT_OWNERSHIP_STALE);
+
+ // An unfinished backfill still rewrites rows toward the OLD owner's
+ // request; hand the agent over only once it has drained (same guards as
+ // the cross-scope transfer).
+ if (await AgentTransferJobModel.hasPendingJobForAgents(trx, [agentId])) {
+ throw new Error(AGENT_TRANSFER_IN_PROGRESS);
+ }
+ if (await AgentCopyJobModel.hasPendingCopyJobForSourceAgents(trx, [agentId])) {
+ throw new Error(AGENT_COPY_IN_PROGRESS);
+ }
+
+ // Mirror of cross-scope guard 1c: an agent with an OWNED group membership
+ // (virtual member, or a supervisor) has no life apart from its group β€”
+ // handing it to another member would leave the group broken or headless.
+ const ownedGroups = await findOwnedGroupMemberships(ctx, trx, [agentId]);
+ if (ownedGroups.length > 0) throw new AgentOwnedByGroupError(ownedGroups);
+
+ /** Reject before mutation so the transfer request and share remain unchanged. */
+ const [existingShare] = await trx
+ .select({ id: agentShares.id })
+ .from(agentShares)
+ .where(eq(agentShares.agentId, agentId))
+ .limit(1);
+ if (existingShare) throw new Error(AGENT_SHARED_TRANSFER_BLOCKED);
+
+ // A PRIVATE agent stops resolving for everyone but the recipient. Groups
+ // that reference it and are NOT the recipient's would render a silent hole
+ // in their roster; leave those groups explicitly instead (the manifest
+ // surfaces the count to both parties before commit).
+ if (agent.visibility === 'private') {
+ const groupLinks = await trx
+ .select({ groupId: chatGroupsAgents.chatGroupId, groupOwnerId: chatGroups.userId })
+ .from(chatGroupsAgents)
+ .innerJoin(chatGroups, eq(chatGroupsAgents.chatGroupId, chatGroups.id))
+ .where(eq(chatGroupsAgents.agentId, agentId));
+ const leavingGroupIds = groupLinks
+ .filter((link) => link.groupOwnerId !== toUserId)
+ .map((link) => link.groupId);
+ if (leavingGroupIds.length > 0) {
+ await trx
+ .delete(chatGroupsAgents)
+ .where(
+ and(
+ eq(chatGroupsAgents.agentId, agentId),
+ inArray(chatGroupsAgents.chatGroupId, leavingGroupIds),
+ ),
+ );
+ }
+
+ // Same policy for PROJECTS that attached this private agent: project
+ // agent listings apply member-agent visibility, so other members'
+ // projects would keep a silent hole. Leave them explicitly; the
+ // manifest surfaces the count to both parties.
+ const projectLinks = await trx
+ .select({ linkId: projectAgents.id, projectOwnerId: projects.userId })
+ .from(projectAgents)
+ .innerJoin(projects, eq(projectAgents.projectId, projects.id))
+ .where(eq(projectAgents.agentId, agentId));
+ const leavingProjectLinkIds = projectLinks
+ .filter((link) => link.projectOwnerId !== toUserId)
+ .map((link) => link.linkId);
+ if (leavingProjectLinkIds.length > 0) {
+ await trx.delete(projectAgents).where(inArray(projectAgents.id, leavingProjectLinkIds));
+ }
+ }
+
+ // Re-home device bindings: a boundDeviceId / workingDirByDevice entry (or
+ // a fixed device policy) pointing at the previous owner's personal device
+ // would leave the recipient's runs unroutable. Same sanitation as moving
+ // an agent into a workspace.
+ const [cleanedAgencyConfig] = await ctx.sanitizeAgencyConfigForWorkspace(
+ trx,
+ ctx.workspaceId,
+ [agent.agencyConfig],
+ // The recipient is the new author: bindings to another member's PRIVATE
+ // workspace device are as unreachable for them as a personal device.
+ { viewerUserId: toUserId },
+ );
+
+ // An ownership flip does not make the agent's content newer. `clientId`
+ // is cleared: it identifies the row to the CREATOR's client-side sync and
+ // is unique per (clientId, userId) β€” if the recipient already owns an
+ // agent with the same value, keeping it would abort every accept attempt.
+ await trx
+ .update(agents)
+ .set({
+ agencyConfig: cleanedAgencyConfig,
+ clientId: null,
+ updatedAt: agents.updatedAt,
+ userId: toUserId,
+ })
+ .where(eq(agents.id, agentId));
+
+ // Owner-attributed runtime rows travel with the agent: cron jobs and bot
+ // providers execute AS their `userId`, so rows the previous owner set up
+ // must re-home or the transferred bot keeps running as the former member
+ // (and dies with their account). They arrive DISABLED β€” nothing may run
+ // silently under the recipient's identity and budget; re-enabling in the
+ // agent's settings is their explicit consent. Only the previous owner's
+ // rows move β€” teammates' schedules stay theirs, untouched.
+ await trx
+ .update(agentCronJobs)
+ .set({ enabled: false, updatedAt: agentCronJobs.updatedAt, userId: toUserId })
+ .where(and(eq(agentCronJobs.agentId, agentId), eq(agentCronJobs.userId, fromUserId)));
+ await trx
+ .update(agentBotProviders)
+ .set({ enabled: false, updatedAt: agentBotProviders.updatedAt, userId: toUserId })
+ .where(and(eq(agentBotProviders.agentId, agentId), eq(agentBotProviders.userId, fromUserId)));
+ // Quota account bindings (and exclusively-consumed provider accounts)
+ // re-home: both cascade on user deletion. See the util.
+ await rehomeAgentQuotaBindingsForRecipient(trx, {
+ agentIds: [agentId],
+ fromUserId,
+ recipientId: toUserId,
+ });
+
+ // Label assignments (and exclusively-assigned backing labels) re-home:
+ // both cascade on user deletion. See the util.
+ await rehomeAgentLabelsForRecipient(trx, {
+ agentIds: [agentId],
+ fromUserId,
+ recipientId: toUserId,
+ });
+
+ // Tasks stay with their creators β€” moving `createdByUserId` would break
+ // in-flight run identity and split task subtrees across owners. What DOES
+ // change: a PRIVATE agent stops resolving for everyone but the recipient,
+ // so tasks other users had assigned to it would fail every scheduled run
+ // with NOT_FOUND. Detach those assignments instead β€” the schedule goes
+ // quiet (visible in the task list) rather than erroring; a public agent's
+ // tasks keep working and are left untouched.
+ if (agent.visibility === 'private') {
+ await trx
+ .update(tasks)
+ .set({ assigneeAgentId: null, updatedAt: tasks.updatedAt })
+ .where(and(eq(tasks.assigneeAgentId, agentId), ne(tasks.createdByUserId, toUserId)));
+ }
+
+ // Knowledge mounts whose KB / file the recipient cannot access (private to
+ // another member) would survive as dead links: the knowledge runtime
+ // silently filters them out and the agent stops using that knowledge with
+ // no visible cause. Detach them instead β€” the manifest surfaces the count
+ // to both parties before acceptance.
+ await detachAgentKnowledgeMountsForRecipient(trx, {
+ agentIds: [agentId],
+ recipientId: toUserId,
+ workspaceId: ctx.workspaceId,
+ });
+ // The retained mounts the previous owner created re-home to the recipient:
+ // the junction `user_id` cascades on user deletion, and knowledge wired to
+ // the agent must not die with the previous owner's account.
+ await rehomeRetainedAgentKnowledgeMounts(trx, {
+ agentIds: [agentId],
+ fromUserId,
+ recipientId: toUserId,
+ workspaceId: ctx.workspaceId,
+ });
+
+ // Connectors: OAuth credentials are personal identity and never travel.
+ // Agent-owned rows re-home as disconnected shells the recipient must
+ // reauthorize; other members' mounted rows unmount. See the util.
+ await rehomeAgentConnectorsForRecipient(trx, {
+ agentIds: [agentId],
+ recipientId: toUserId,
+ });
+
+ // Expertise: the agent's learned domains resolve through the viewer's
+ // visibility filter β€” agent-exclusive private domains re-home, shared
+ // ones unbind explicitly. See the util.
+ await rehomeAgentExpertiseForRecipient(trx, {
+ agentIds: [agentId],
+ recipientId: toUserId,
+ workspaceId: ctx.workspaceId,
+ });
+
+ // VFS documents / skills: dedicated files re-home with the agent (their
+ // user_id cascades on user deletion); ASSOCIATED personal documents never
+ // change owner β€” invisible-to-recipient bindings detach explicitly.
+ await rehomeAgentDocumentsForRecipient(trx, {
+ agentIds: [agentId],
+ fromUserId,
+ recipientId: toUserId,
+ workspaceId: ctx.workspaceId,
+ });
+};
diff --git a/packages/database/src/models/agent/trash.ts b/packages/database/src/models/agent/trash.ts
new file mode 100644
index 00000000000..1c7cc8f70d3
--- /dev/null
+++ b/packages/database/src/models/agent/trash.ts
@@ -0,0 +1,92 @@
+import { and, eq, inArray } from 'drizzle-orm';
+
+import type { AgentItem } from '../../schemas';
+import { agents, agentsToSessions } from '../../schemas';
+import {
+ isTrashed,
+ restoreStamp,
+ type SoftDeleteOptions,
+ trashStamp,
+} from '../../utils/softDelete';
+import { type AgentModelContext } from './context';
+
+/**
+ * Move agents to the recycle bin. Only the `agents` rows are stamped here β€”
+ * the server-side trash handler cascades to sessions / topics through their
+ * own models so the registry can record each child.
+ */
+export const softDelete = async (
+ ctx: AgentModelContext,
+ agentIds: string[],
+ options: SoftDeleteOptions,
+): Promise<AgentItem[]> => {
+ if (agentIds.length === 0) return [];
+ return ctx.db
+ .update(agents)
+ .set(trashStamp(options.deletedAt))
+ .where(
+ and(
+ inArray(agents.id, agentIds),
+ ctx.ownership(),
+ options.restrictToCreator ? eq(agents.userId, ctx.userId) : undefined,
+ ),
+ )
+ .returning();
+};
+
+export const restore = async (ctx: AgentModelContext, agentIds: string[]): Promise<AgentItem[]> => {
+ if (agentIds.length === 0) return [];
+ return ctx.db
+ .update(agents)
+ .set(restoreStamp())
+ .where(and(inArray(agents.id, agentIds), ctx.trashScope(), isTrashed(agents.isDeleted)))
+ .returning();
+};
+
+export const findTrashedByIds = async (
+ ctx: AgentModelContext,
+ agentIds: string[],
+): Promise<AgentItem[]> => {
+ if (agentIds.length === 0) return [];
+ return ctx.db
+ .select()
+ .from(agents)
+ .where(and(inArray(agents.id, agentIds), ctx.trashScope(), isTrashed(agents.isDeleted)));
+};
+
+/**
+ * Lock the given agents for a purge and return the ones still in the bin.
+ * Run inside the caller's transaction: the row lock holds until the purge
+ * commits, so a restore racing it waits and then finds nothing to restore,
+ * while a restore that already committed makes this return no ids.
+ */
+export const lockTrashedForPurge = async (
+ ctx: AgentModelContext,
+ agentIds: string[],
+): Promise<string[]> => {
+ if (agentIds.length === 0) return [];
+ const stamped = await ctx.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(and(inArray(agents.id, agentIds), ctx.trashScope(), isTrashed(agents.isDeleted)))
+ .for('update');
+ return stamped.map((row) => row.id);
+};
+
+/**
+ * Hard delete for the purge sweep: the agent rows and their session links,
+ * still-stamped rows only. FK cascades take topics / messages / threads.
+ * The legacy session shells are another aggregate β€” the trash handler
+ * drops them through `SessionModel` in the same transaction.
+ */
+export const purge = async (ctx: AgentModelContext, agentIds: string[]): Promise<string[]> => {
+ if (agentIds.length === 0) return [];
+ await ctx.db
+ .delete(agentsToSessions)
+ .where(and(inArray(agentsToSessions.agentId, agentIds), ctx.agentsToSessionsOwnership()));
+ const rows = await ctx.db
+ .delete(agents)
+ .where(and(inArray(agents.id, agentIds), ctx.trashScope(), isTrashed(agents.isDeleted)))
+ .returning({ id: agents.id });
+ return rows.map((row) => row.id);
+};
diff --git a/packages/database/src/models/agent/types.ts b/packages/database/src/models/agent/types.ts
new file mode 100644
index 00000000000..a54fc303f3f
--- /dev/null
+++ b/packages/database/src/models/agent/types.ts
@@ -0,0 +1,39 @@
+import type { DeviceBoundAgentItem, LobeAgentAgencyConfig } from '@lobechat/types';
+
+/** One chat group an agent belongs to, as surfaced by the transfer guards. */
+/**
+ * A row of {@link AgentModel.queryBoundToDevice}: display fields plus the
+ * stored routing config and ownership needed to resolve the caller's
+ * effective target.
+ */
+export interface DeviceBindingCandidate extends DeviceBoundAgentItem {
+ agencyConfig: LobeAgentAgencyConfig | null;
+ userId: string;
+ workspaceId: string | null;
+}
+
+export interface AgentGroupMembershipRef {
+ agentId: string;
+ /** `null` when the group is not visible to the caller (see the read below). */
+ groupAvatar: string | null;
+ groupBackgroundColor: string | null;
+ /**
+ * `null` when the group is not visible to the caller. The id is identity
+ * too: the membership still counts toward the guard, but a private group's
+ * identifier is no more the caller's to read than its name.
+ */
+ groupId: string | null;
+ /** `null` when the group is not visible to the caller (see the read below). */
+ groupTitle: string | null;
+ /**
+ * Whether the caller may see this group at all. Carried explicitly because a
+ * `null` title is otherwise ambiguous β€” a group can simply be untitled β€” and
+ * telling someone a group of theirs is "one you cannot see" is worse than
+ * saying nothing.
+ */
+ groupVisible: boolean;
+}
+
+export interface AgentTransferOptions {
+ rejectForeignTopicCommentAuthors?: boolean;
+}
diff --git a/packages/database/src/models/agent/update.ts b/packages/database/src/models/agent/update.ts
new file mode 100644
index 00000000000..0a058d99c60
--- /dev/null
+++ b/packages/database/src/models/agent/update.ts
@@ -0,0 +1,494 @@
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { INBOX_SESSION_ID, isHeterogeneousAgentModelId } from '@lobechat/const';
+import { applyWorkingDirByDevicePatch } from '@lobechat/types';
+import { toRecord } from '@lobechat/utils/object';
+import { TRPCError } from '@trpc/server';
+import { and, eq } from 'drizzle-orm';
+import type { PartialDeep } from 'type-fest';
+
+import { merge } from '@/utils/merge';
+
+import type { AgentItem } from '../../schemas';
+import { agents, sessionGroups } from '../../schemas';
+import { sanitizeAgentApiConfig } from '../../utils/sanitizeAgentApiConfig';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+import { RESERVED_AGENT_SLUGS } from './constants';
+import { type AgentModelContext } from './context';
+
+/**
+ * Fields the Agent Builder's own row (`slug = BUILTIN_AGENT_SLUGS.agentBuilder`) must never
+ * carry. Its `persist` config only stores `model`/`provider`/`chatConfig` β€” title, avatar,
+ * systemRole, etc. are rendered from i18n / the static systemRoleTemplate at runtime, never
+ * from this row.
+ *
+ * Before PR #16420, `lobe-agent-management`'s self-management prompt could make the builder
+ * mistake an ambiguous "update this" request for editing itself instead of the target agent.
+ * Depending on caller (browser client tool executor vs. gateway server runtime in
+ * `apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts`), these fields can
+ * arrive through *either* `AgentModel.update()` or `updateConfig()` β€” e.g. the gateway's
+ * `updatePrompt` writes `systemRole` via `update()`, while the browser client's meta editor
+ * writes `title`/`avatar`/etc. via `updateConfig()`. So both methods must strip the full list,
+ * not just the fields each historically happened to receive. Clients on builds older than
+ * PR #16420 can still hit this path, so enforce it here (the single write chokepoint)
+ * regardless of caller.
+ *
+ * Such a write is rejected, not silently trimmed: the writer is almost always aiming at a
+ * different agent (the one the builder is editing), and a trimmed write still reports
+ * success β€” the caller would believe the prompt/name landed when nothing changed.
+ */
+const AGENT_BUILDER_PROTECTED_FIELDS = [
+ 'title',
+ 'name',
+ 'description',
+ 'avatar',
+ 'backgroundColor',
+ 'tags',
+ 'marketIdentifier',
+ 'systemRole',
+] as const;
+
+const assertNoAgentBuilderProtectedFields = (data: Record<string, unknown>) => {
+ const fields = AGENT_BUILDER_PROTECTED_FIELDS.filter((field) => data[field] !== undefined);
+ if (fields.length === 0) return;
+
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message:
+ `The Agent Builder's own ${fields.join(', ')} cannot be changed, so nothing was updated. ` +
+ 'Target the agent being edited instead.',
+ });
+};
+
+/**
+ * Fields that define a row's identity, scope and provisioning status. Every one of
+ * them feeds authorization β€” `slug` + `virtual` classify collaborative builtins,
+ * `userId` is authorship, `workspaceId` is the tenancy boundary, and `visibility`
+ * has dedicated creator/owner-gated endpoints β€” so an update must never carry them. `updateConfig` merges whatever the passthrough config endpoint
+ * receives, which would otherwise let a member with edit access declassify, orphan
+ * or rehome a shared builtin through the very path that was opened for editing it.
+ *
+ * Creation is different: it legitimately assigns `slug` (random by default) and
+ * takes `userId` / `workspaceId` from the trusted context via
+ * `buildWorkspacePayload`, so only reserved slugs are filtered there.
+ */
+const IMMUTABLE_AGENT_FIELDS = [
+ 'createdAt',
+ 'id',
+ // Folder placement is shared state and has its own validated path
+ // (`updateSessionGroupId`), which checks the target is visible in scope and
+ // matches the agent's visibility bucket. Riding along in a config patch
+ // would skip both, leaving the shared row in a folder the sidebar cannot
+ // resolve β€” it then renders in Ungrouped for every member.
+ 'sessionGroupId',
+ 'slug',
+ 'userId',
+ 'virtual',
+ // `visibility` has its own authorization rules (`setVisibility` is creator /
+ // workspace-owner gated, `publishToWorkspace` is creator-only), so it must not
+ // ride along in a config patch: a member with edit access on a collaborative
+ // builtin could otherwise flip it to `private`, hiding the shared row from
+ // everyone else while its workspace slug stays occupied β€” nothing can
+ // reprovision it.
+ 'visibility',
+ 'workspaceId',
+] as const;
+
+/**
+ * Accepted shape for a user-chosen slug: lowercase words joined by single
+ * hyphens, matching what `randomSlug` generates. No underscores β€” the agent
+ * route tells an id from a slug by the underscore in every generated id.
+ */
+const AGENT_SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
+
+/**
+ * Builtin slugs are not decoration: `getBuiltinAgent` resolves infrastructure
+ * agents BY slug, and authorization treats the collaborative ones as workspace
+ * resources (`canPerformResourceAction`). A user-created row must therefore
+ * never claim one β€” otherwise a member could squat `inbox` / `agent-builder`
+ * before the real row is provisioned and have their own agent adopted as the
+ * workspace's, with the shared-resource permissions that come with it.
+ *
+ * Every user-controlled write funnels through `create` / `batchCreate` (group
+ * member batch-create takes a caller-supplied `slug`, as do imports and market
+ * installs) or through `update` / `updateConfig` (the passthrough config
+ * endpoint accepts one too β€” renaming an existing row is the same squat).
+ * Builtin provisioning bypasses all four by inserting/updating directly inside
+ * `getBuiltinAgent`, so dropping the field here closes every caller path at
+ * once; on create the column's own default then assigns a random slug.
+ */
+export const stripImmutableFields = <T extends Record<string, any>>(data: T): T => {
+ const carried = IMMUTABLE_AGENT_FIELDS.filter((field) => field in data);
+ if (carried.length === 0) return data;
+
+ const next = { ...data };
+ for (const field of carried) delete next[field];
+ return next;
+};
+
+export const update = async (ctx: AgentModelContext, agentId: string, data: Partial<AgentItem>) => {
+ const apiSafeData = Object.hasOwn(data, 'agencyConfig')
+ ? { ...data, agencyConfig: sanitizeAgentApiConfig(data.agencyConfig) }
+ : data;
+ const sanitizedData = stripImmutableFields(apiSafeData);
+ await assertNotAgentBuilderProtectedWrite(ctx, agentId, sanitizedData);
+
+ return ctx.db
+ .update(agents)
+ .set({ ...sanitizedData, updatedAt: new Date() })
+ .where(and(eq(agents.id, agentId), ctx.ownership()));
+};
+
+/**
+ * Reject a write of fields the Agent Builder's own row must never carry (see
+ * {@link AGENT_BUILDER_PROTECTED_FIELDS}). Only looks up the target row's `slug` when the
+ * incoming patch actually touches a protected field, so normal updates pay no extra query.
+ */
+export const assertNotAgentBuilderProtectedWrite = async (
+ ctx: AgentModelContext,
+ agentId: string,
+ data: Record<string, unknown>,
+) => {
+ if (!AGENT_BUILDER_PROTECTED_FIELDS.some((field) => data[field] !== undefined)) return;
+
+ const agent = await ctx.db.query.agents.findFirst({
+ columns: { slug: true },
+ where: and(eq(agents.id, agentId), ctx.ownership()),
+ });
+
+ if (agent?.slug === BUILTIN_AGENT_SLUGS.agentBuilder) assertNoAgentBuilderProtectedFields(data);
+};
+
+/**
+ * Bidirectional visibility switch. Authorization (creator OR
+ * workspace owner, builtin agents excluded) is the router's responsibility β€”
+ * this method only applies the ownership-scoped write.
+ *
+ * Uses UPDATE … RETURNING instead of a follow-up SELECT: when a workspace
+ * owner demotes another member's agent to private, the post-update row no
+ * longer matches the visibility-aware ownership predicate, so a read-back
+ * would return 0 rows even though the write succeeded (same pattern as
+ * TaskModel.updateVisibility).
+ */
+export const setVisibility = async (
+ ctx: AgentModelContext,
+ agentId: string,
+ visibility: 'private' | 'public',
+) => {
+ // A sidebar folder cannot mix visibilities (HomeRepository.processAgentList
+ // buckets grouped items by item visibility under same-visibility groups),
+ // so an agent crossing scopes while keyed to a group of the OLD scope
+ // would be emitted nowhere and vanish from the sidebar. Rehome it to the
+ // ungrouped section of its new scope when the group no longer matches.
+ const [current] = await ctx.db
+ .select({
+ agencyConfig: agents.agencyConfig,
+ groupVisibility: sessionGroups.visibility,
+ workspaceId: agents.workspaceId,
+ })
+ .from(agents)
+ .leftJoin(sessionGroups, eq(agents.sessionGroupId, sessionGroups.id))
+ .where(and(eq(agents.id, agentId), ctx.ownership()))
+ .limit(1);
+
+ // `publishAgentToWorkspace` is the normal client path, but keep the
+ // bidirectional visibility mutation equally safe for direct API callers.
+ if (visibility === 'public' && current) {
+ await ctx.assertFixedExecutionTarget(current.workspaceId, current.agencyConfig);
+ }
+
+ const groupVisibility = current?.groupVisibility as 'private' | 'public' | null | undefined;
+ const clearGroup = groupVisibility != null && groupVisibility !== visibility;
+
+ const [updated] = await ctx.db
+ .update(agents)
+ .set({
+ updatedAt: new Date(),
+ visibility,
+ ...(clearGroup ? { sessionGroupId: null } : {}),
+ })
+ .where(and(eq(agents.id, agentId), ctx.ownership()))
+ .returning();
+ return updated ?? null;
+};
+
+export const updateConfig = async (
+ ctx: AgentModelContext,
+ agentId: string,
+ input: PartialDeep<AgentItem> | undefined | null,
+ replaceWorkingDirDeviceIds?: string[],
+) => {
+ if (!input || Object.keys(input).length === 0) return;
+
+ const data = stripImmutableFields(input);
+
+ const agent = await ctx.db.query.agents.findFirst({
+ where: and(eq(agents.id, agentId), ctx.ownership()),
+ });
+
+ if (!agent) return;
+
+ await ctx.assertWorkspaceDeviceBinding(agent.workspaceId, data.agencyConfig, agent.agencyConfig);
+
+ // 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)
+
+ const { params: _params, ...restData } = data;
+
+ // See AGENT_BUILDER_PROTECTED_FIELDS: some callers (e.g. the browser client's meta
+ // editor) route title/avatar/etc. through updateConfig() rather than update().
+ if (agent.slug === BUILTIN_AGENT_SLUGS.agentBuilder) {
+ assertNoAgentBuilderProtectedFields(restData as Record<string, unknown>);
+ }
+
+ // Only the columns this patch touches are written back. The row was read
+ // before the awaits above, so writing the whole merged row would restore
+ // any column another writer committed in between β€” e.g. a parallel
+ // `updatePrompt` losing its new systemRole to a concurrent config write.
+ const touchedColumns = new Set<string>(Object.keys(restData));
+ if (data.params) touchedColumns.add('params');
+
+ const mergedValue = merge(agent, restData);
+
+ // API bindings follow updateConfig's partial deep-merge contract. A user-provider patch must
+ // only clear the deployment discriminator retained from a previous server-default binding.
+ const apiConfigPatch = toRecord(data.agencyConfig?.heterogeneousProvider?.apiConfig);
+ const mergedApiConfig = toRecord(mergedValue.agencyConfig?.heterogeneousProvider?.apiConfig);
+ if (
+ apiConfigPatch &&
+ apiConfigPatch.source !== 'server-default' &&
+ typeof apiConfigPatch.providerId === 'string' &&
+ mergedApiConfig
+ ) {
+ delete mergedApiConfig.source;
+ }
+
+ mergedValue.agencyConfig = sanitizeAgentApiConfig(mergedValue.agencyConfig) ?? null;
+
+ // The inbox is LobeHub's built-in default cloud agent; it must never be
+ // turned into a heterogeneous (external-CLI) agent. Two independent inputs can
+ // flip it β€” a stray `agencyConfig.heterogeneousProvider`, and a legacy hetero
+ // `model` id, which AiAgentService still treats as heterogeneous on its own even
+ // without a provider config. Either one
+ // reroutes the whole chat surface through the device gateway and breaks it with
+ // GATEWAY_NOT_CONFIGURED, so sanitize both at this write chokepoint regardless
+ // of caller (mirrors AGENT_BUILDER_PROTECTED_FIELDS).
+ if (agent.slug === INBOX_SESSION_ID) {
+ if (mergedValue.agencyConfig?.heterogeneousProvider) {
+ delete mergedValue.agencyConfig.heterogeneousProvider;
+ touchedColumns.add('agencyConfig');
+ }
+ if (isHeterogeneousAgentModelId(mergedValue.model)) {
+ mergedValue.model = null;
+ touchedColumns.add('model');
+ }
+ }
+
+ // A character sheet is authored as a whole: the studio reads the current
+ // profile and writes the version it wants. Deep-merging it would make a
+ // cleared trait or a removed artwork impossible to express, since a missing
+ // key reads as "leave it alone". Same reasoning as the graph below.
+ if (Object.hasOwn(data, 'profile')) {
+ mergedValue.profile = data.profile as AgentItem['profile'];
+ }
+
+ // A AgentGraph is a complete executable document, not a partial config
+ // patch β€” replace it wholesale instead of deep-merging. The Graph Agent
+ // (agencyConfig.graph) is the agent's behavior body; legacy clients may
+ // still send `chatConfig.graph`, so write it through to `agencyConfig.graph`
+ // (and forward the switch) to migrate the row on the next write.
+ if (data.agencyConfig && Object.hasOwn(data.agencyConfig, 'graph')) {
+ mergedValue.agencyConfig = {
+ ...mergedValue.agencyConfig,
+ graph: data.agencyConfig.graph,
+ } as AgentItem['agencyConfig'];
+ // An explicit agency-level graph β€” including `null` to clear it β€” takes
+ // ownership of the graph: drop the legacy chatConfig fields so the
+ // runtime's `??` fallback cannot resurrect an old snapshot.
+ if (mergedValue.chatConfig) {
+ touchedColumns.add('chatConfig');
+ const {
+ graph: _legacyGraph,
+ enableGraphMode: _legacyEnableGraphMode,
+ ...restChatConfig
+ } = mergedValue.chatConfig as Record<string, unknown>;
+ mergedValue.chatConfig = restChatConfig as AgentItem['chatConfig'];
+ }
+ } else if (data.chatConfig && Object.hasOwn(data.chatConfig, 'graph')) {
+ touchedColumns.add('agencyConfig');
+ const legacyChatConfig = data.chatConfig as Record<string, unknown>;
+ mergedValue.agencyConfig = {
+ ...mergedValue.agencyConfig,
+ graph: legacyChatConfig.graph,
+ ...(Object.hasOwn(legacyChatConfig, 'enableGraphMode') && {
+ enableGraphMode: legacyChatConfig.enableGraphMode,
+ }),
+ } as AgentItem['agencyConfig'];
+ const {
+ graph: _legacyGraph,
+ enableGraphMode: _legacyEnableGraphMode,
+ ...restChatConfig
+ } = (mergedValue.chatConfig ?? {}) as Record<string, unknown>;
+ mergedValue.chatConfig = restChatConfig as AgentItem['chatConfig'];
+ }
+
+ // Apply the processed parameters
+ mergedValue.params = Object.keys(updatedParams).length > 0 ? updatedParams : undefined;
+
+ // Opt-in replacement prevents old clients' complete cached maps from
+ // deleting Git metadata on devices they did not actually edit.
+ applyWorkingDirByDevicePatch(
+ mergedValue.agencyConfig,
+ data.agencyConfig,
+ replaceWorkingDirDeviceIds,
+ );
+
+ await ctx.assertFixedExecutionTarget(agent.workspaceId, mergedValue.agencyConfig);
+
+ // 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;
+ }
+ }
+
+ // Timestamp fields are left to Drizzle's $onUpdate.
+ touchedColumns.delete('updatedAt');
+ touchedColumns.delete('accessedAt');
+ touchedColumns.delete('createdAt');
+
+ const updateData = Object.fromEntries(
+ Object.entries(mergedValue).filter(([column]) => touchedColumns.has(column)),
+ ) as Partial<typeof mergedValue>;
+ if (!Object.values(updateData).some((value) => value !== undefined)) return;
+
+ return ctx.db
+ .update(agents)
+ .set(updateData)
+ .where(and(eq(agents.id, agentId), ctx.ownership()));
+};
+
+/**
+ * Update the sessionGroupId for an agent
+ */
+/**
+ * A move target must be a folder the caller can actually see, and a *public*
+ * agent may only sit in a *public* folder β€” otherwise the agent stays
+ * visible to the workspace while its folder does not, and everyone else
+ * silently finds it in Ungrouped. Private agents are only visible to their
+ * owner, so any folder that owner can see is fine.
+ */
+/**
+ * Resolve a folder the caller may put an item in, returning its visibility.
+ * Shared by the move guard and the create path β€” both need the same
+ * "visible in scope" check, and create additionally derives the new agent's
+ * visibility from the result.
+ */
+export const getAssignableSessionGroupVisibility = async (
+ ctx: AgentModelContext,
+ sessionGroupId: string,
+): Promise<'private' | 'public'> => {
+ const [group] = await ctx.db
+ .select({ visibility: sessionGroups.visibility })
+ .from(sessionGroups)
+ .where(
+ and(
+ eq(sessionGroups.id, sessionGroupId),
+ buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ isDeleted: sessionGroups.isDeleted,
+ userId: sessionGroups.userId,
+ visibility: sessionGroups.visibility,
+ workspaceId: sessionGroups.workspaceId,
+ },
+ ),
+ ),
+ )
+ .limit(1);
+
+ if (!group) throw new Error(`Session group ${sessionGroupId} not found in current scope`);
+
+ return group.visibility as 'private' | 'public';
+};
+
+/**
+ * Rename an agent's url slug.
+ *
+ * Deliberately its own method rather than a field on `updateConfig`: `slug`
+ * stays in {@link IMMUTABLE_AGENT_FIELDS} so it can never ride along in a
+ * passthrough config patch. Renaming needs validation the config path has no
+ * place for β€” shape, reserved builtin slugs, and a uniqueness scope that
+ * differs between personal and workspace rows.
+ *
+ * Returns a discriminated result instead of throwing so the caller can render
+ * a field-level message; only a genuinely missing agent throws.
+ */
+export const updateSlug = async (
+ ctx: AgentModelContext,
+ agentId: string,
+ slug: string,
+): Promise<{ reason?: 'builtin' | 'invalid' | 'reserved' | 'taken'; success: boolean }> => {
+ const next = slug.trim().toLowerCase();
+
+ if (!AGENT_SLUG_PATTERN.test(next)) return { reason: 'invalid', success: false };
+
+ const current = await ctx.db.query.agents.findFirst({
+ columns: { slug: true },
+ where: and(eq(agents.id, agentId), ctx.ownership()),
+ });
+ if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
+ if (current.slug === next) return { success: true };
+
+ // A builtin agent IS its slug: `getBuiltinAgent` resolves it by that string,
+ // so renaming one away would silently mint a second, empty inbox / page
+ // agent and strand the original's history on an ordinary agent.
+ if (current.slug && RESERVED_AGENT_SLUGS.has(current.slug))
+ return { reason: 'builtin', success: false };
+ if (RESERVED_AGENT_SLUGS.has(next)) return { reason: 'reserved', success: false };
+
+ // Check within the same scope the unique indexes use, so the pre-check and
+ // the constraint agree. The insert can still lose a race, hence the catch.
+ const clash = await ctx.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(and(ctx.ownership(), eq(agents.slug, next)))
+ .limit(1);
+ if (clash.length > 0) return { reason: 'taken', success: false };
+
+ try {
+ await ctx.db
+ .update(agents)
+ .set({ slug: next, updatedAt: new Date() })
+ .where(and(eq(agents.id, agentId), ctx.ownership()));
+ } catch {
+ // Unique violation from a concurrent rename β€” same user-facing outcome.
+ return { reason: 'taken', success: false };
+ }
+
+ return { success: true };
+};
diff --git a/packages/database/src/repositories/agentDeletion/index.ts b/packages/database/src/repositories/agentDeletion/index.ts
new file mode 100644
index 00000000000..470d6684ef8
--- /dev/null
+++ b/packages/database/src/repositories/agentDeletion/index.ts
@@ -0,0 +1,110 @@
+import { TRPCError } from '@trpc/server';
+import { and, eq, inArray } from 'drizzle-orm';
+
+import { RESERVED_AGENT_SLUGS } from '../../models/agent/constants';
+import { type AgentModelContext, createAgentModelContext } from '../../models/agent/context';
+import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from '../../models/agentCopyJob';
+import { AGENT_TRANSFER_IN_PROGRESS, AgentTransferJobModel } from '../../models/agentTransferJob';
+import { agents, agentsToSessions, sessions } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+
+/**
+ * Delete an agent and its associated session.
+ * This will cascade delete messages, topics, etc. through the session deletion.
+ */
+const deleteAgent = async (ctx: AgentModelContext, agentId: string) => {
+ return ctx.db.transaction(async (trx) => {
+ // Lock the agent row BEFORE consulting the pending-copy guard β€” same
+ // lock-then-guard order as transferAgents. A concurrent copy enqueue
+ // locks the same source rows, so the guard here cannot run in the window
+ // where the enqueue's job row exists but is not yet committed.
+ const [locked] = await trx
+ .select({ id: agents.id, slug: agents.slug })
+ .from(agents)
+ .where(and(eq(agents.id, agentId), ctx.ownership()))
+ .for('update');
+
+ // Builtins (the inbox, the agent builders) are provisioned per user and
+ // carry `virtual` exactly like a group's own members. Deleting one takes
+ // its linked session and every conversation with it, and nothing can
+ // recreate them β€” refuse here, the same way `addAgentsToGroup` refuses to
+ // seat one. This only guards callers of `AgentModel.delete` /
+ // `AgentDeletionRepository.deleteAgent`; paths that
+ // delete `agents` rows directly (e.g. the OpenAPI `migrateSessionTo`
+ // delete) bypass it.
+ if (locked?.slug && RESERVED_AGENT_SLUGS.has(locked.slug)) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'A builtin agent cannot be deleted',
+ });
+ }
+
+ // The junction records every agent an unfinished job still maps, a
+ // copy's TARGET included β€” and a group copy's drain writes those ids into
+ // `messages.agent_id`. Deleting one leaves the queue rows behind, so the
+ // drain hits a missing-agent FK and retries forever, stranding the copied
+ // conversations as pending. Distinct from the source guard below: a copy
+ // registers only its target here.
+ if (await AgentTransferJobModel.hasPendingJobForAgents(trx, [agentId])) {
+ throw new Error(AGENT_TRANSFER_IN_PROGRESS);
+ }
+
+ // Not covered above: a group transfer that left this agent behind and
+ // took a clone does NOT register it as a covered agent (it never moved).
+ // But its id is still the live value of `messages.agent_id` on every
+ // topic the drain has not reached yet, and that column cascades β€” so
+ // deleting it now would destroy the moved group history the remap is
+ // partway through rescuing.
+ if (await AgentTransferJobModel.hasPendingRemapForSourceAgents(trx, [agentId])) {
+ throw new Error(AGENT_TRANSFER_IN_PROGRESS);
+ }
+
+ // A pending copy job still reads this agent's topics β€” deleting it would
+ // cascade them away and the copy would silently complete with empty
+ // conversations. Surface the in-progress state instead.
+ if (await AgentCopyJobModel.hasPendingCopyJobForSourceAgents(trx, [agentId])) {
+ throw new Error(AGENT_COPY_IN_PROGRESS);
+ }
+
+ // 1. Get associated session IDs
+ const links = await trx
+ .select({ sessionId: agentsToSessions.sessionId })
+ .from(agentsToSessions)
+ .where(and(eq(agentsToSessions.agentId, agentId), ctx.agentsToSessionsOwnership()));
+
+ const sessionIds = links.map((link) => link.sessionId);
+
+ // 2. Delete links in agentsToSessions
+ await trx
+ .delete(agentsToSessions)
+ .where(and(eq(agentsToSessions.agentId, agentId), ctx.agentsToSessionsOwnership()));
+
+ // 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), ctx.sessionsOwnership()));
+ }
+
+ // 4. Delete the agent itself
+ return trx.delete(agents).where(and(eq(agents.id, agentId), ctx.ownership()));
+ });
+};
+
+/**
+ * Agent deletion as one unit of work: the agent row, its session links and
+ * the legacy session shells (which cascade their messages and topics) go in
+ * one transaction, under the agent row lock and the pending-job guards.
+ * Sessions are their own aggregate, so the flow lives here rather than in
+ * `AgentModel`; `AgentModel.delete` forwards to it.
+ */
+export class AgentDeletionRepository {
+ private readonly ctx: AgentModelContext;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.ctx = createAgentModelContext({ db, userId, workspaceId });
+ }
+
+ /** See {@link deleteAgent}. */
+ deleteAgent = (agentId: string) => deleteAgent(this.ctx, agentId);
+}
diff --git a/packages/database/src/repositories/agentTransfer/index.ts b/packages/database/src/repositories/agentTransfer/index.ts
new file mode 100644
index 00000000000..19fb2fe09fc
--- /dev/null
+++ b/packages/database/src/repositories/agentTransfer/index.ts
@@ -0,0 +1,573 @@
+import type { LobeAgentAgencyConfig } from '@lobechat/types';
+import { and, asc, count, eq, inArray, isNull, like, notInArray, or } from 'drizzle-orm';
+
+import { type AgentModelContext, createAgentModelContext } from '../../models/agent/context';
+import { AGENT_SHARED_TRANSFER_BLOCKED, AgentOwnedByGroupError } from '../../models/agent/errors';
+import { findOwnedGroupMemberships } from '../../models/agent/groupMembership';
+import { type AgentTransferOptions } from '../../models/agent/types';
+import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from '../../models/agentCopyJob';
+import {
+ AGENT_TRANSFER_IN_PROGRESS,
+ AgentTransferJobModel,
+ getAgentTransferSyncMessageThreshold,
+ rewriteMessageScopeForTopics,
+ rewriteResidualMessageScope,
+} from '../../models/agentTransferJob';
+import {
+ hasForeignTopicComments,
+ syncTopicCommentsOnTopicTransfer,
+ TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS,
+} from '../../models/topicComment';
+import {
+ agentBotProviders,
+ agentCronJobs,
+ agentLabelAssignments,
+ agents,
+ agentsFiles,
+ agentShares,
+ agentsKnowledgeBases,
+ agentsToSessions,
+ briefs,
+ chatGroupsAgents,
+ expertiseBindings,
+ expertiseDomains,
+ expertiseInsights,
+ expertiseRuns,
+ messages,
+ sessions,
+ taskComments,
+ taskDependencies,
+ taskDocuments,
+ tasks,
+ taskTopics,
+ threads,
+ topicDocuments,
+ topics,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { rehomeAgentConnectorsForScopeTransfer } from '../../utils/agentConnectors';
+import { moveAgentDocumentsForScopeTransfer } from '../../utils/agentDocumentsOwnership';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+
+/**
+ * Batch variant of {@link transferAgent}: moves several agents (and their
+ * cascaded topics / messages / threads / tasks / …) in ONE transaction, with
+ * every large-table UPDATE issued once via `inArray` instead of once per
+ * agent. All-or-nothing: a failure on any agent rolls back the whole batch.
+ */
+const transferAgents = async (
+ ctx: AgentModelContext,
+ agentIds: string[],
+ targetWorkspaceId: string | null,
+ targetUserId: string,
+ targetVisibility?: 'private' | 'public',
+ options: AgentTransferOptions = {},
+): Promise<{ agentId: string; slug: string | null; transferJobId: string | null }[]> => {
+ if (agentIds.length === 0) return [];
+
+ return ctx.db.transaction(async (trx) => {
+ // 1. Verify all agents exist and belong to current scope. FOR UPDATE so
+ // two concurrent transfers of the same agent serialize HERE, before the
+ // pending-job guard below: the loser re-reads after the winner commits
+ // and either no longer finds the agent in its scope, or sees the
+ // winner's freshly inserted job. Without the lock both would pass the
+ // guard first (check-then-act) and enqueue duplicate jobs.
+ const foundAgents = await trx
+ .select()
+ .from(agents)
+ .where(and(inArray(agents.id, agentIds), ctx.ownership()))
+ .for('update');
+ if (foundAgents.length !== new Set(agentIds).size) throw new Error('Agent not found');
+ const agentById = new Map(foundAgents.map((agent) => [agent.id, agent]));
+
+ // 1a. An unfinished backfill still owns these agents' message rewrite β€”
+ // a second transfer would race it (and re-enqueue topics the first job
+ // is still draining). Runs under the row locks above, so the check is
+ // race-free against a concurrent transfer's own job insert.
+ if (await AgentTransferJobModel.hasPendingJobForAgents(trx, agentIds)) {
+ throw new Error(AGENT_TRANSFER_IN_PROGRESS);
+ }
+
+ // 1b. A pending copy job reads from these agents' topics by id β€” moving
+ // them to another scope would make it drain empty topics. Copy jobs
+ // register only their TARGET agents in the junction, so the source side
+ // needs its own payload-based guard.
+ if (await AgentCopyJobModel.hasPendingCopyJobForSourceAgents(trx, agentIds)) {
+ throw new Error(AGENT_COPY_IN_PROGRESS);
+ }
+
+ // 1c. A group-owned agent has no existence apart from its group: the
+ // synthetic supervisor, and members built through the group builder.
+ // Step 14 below drops every chat-group link the moved agents hold, which
+ // for an owned member means the group silently loses it β€” and for a
+ // supervisor means the group is left headless, at which point
+ // `findByIdWithAgents` quietly mints a blank replacement and the
+ // configured systemRole/model are gone for good.
+ //
+ // Refuse instead, naming the groups so the caller can act. Nothing in the
+ // product can reach this: owned implies `virtual`, and `queryAgents`
+ // filters virtual agents out of every transfer surface. It is a guard
+ // against a caller that reaches the model directly.
+ const ownedGroups = await findOwnedGroupMemberships(ctx, trx, agentIds);
+ if (ownedGroups.length > 0) throw new AgentOwnedByGroupError(ownedGroups);
+
+ // 1d. Keep the share owner and tenancy stable. Check paused shares too:
+ // disabling a link retains its grants and visitor history. The Agent row
+ // lock also serializes this guard with AgentShareModel.create.
+ const [existingShare] = await trx
+ .select({ id: agentShares.id })
+ .from(agentShares)
+ .where(inArray(agentShares.agentId, agentIds))
+ .limit(1);
+ if (existingShare) throw new Error(AGENT_SHARED_TRANSFER_BLOCKED);
+
+ // 2. Resolve slug conflicts in the target scope with a single query:
+ // fetch every existing slug that could collide (exact match or
+ // `<slug>-<n>` suffix), then pick free suffixes in memory. Agents
+ // inside the batch also compete with each other for the same slug.
+ const targetScopeWhere = targetWorkspaceId
+ ? eq(agents.workspaceId, targetWorkspaceId)
+ : and(eq(agents.userId, targetUserId), isNull(agents.workspaceId));
+ const sluggedAgents = foundAgents.filter((agent) => agent.slug);
+ const resolvedSlugs = new Map<string, string | null>();
+ if (sluggedAgents.length > 0) {
+ const conflictRows = await trx
+ .select({ slug: agents.slug })
+ .from(agents)
+ .where(
+ and(
+ targetScopeWhere,
+ notInArray(agents.id, agentIds),
+ or(
+ ...sluggedAgents.map((agent) =>
+ or(eq(agents.slug, agent.slug!), like(agents.slug, `${agent.slug}-%`)),
+ ),
+ ),
+ ),
+ );
+ const taken = new Set(conflictRows.map((row) => row.slug));
+ for (const agent of sluggedAgents) {
+ let slug = agent.slug!;
+ if (taken.has(slug)) {
+ let suffix = 1;
+ while (suffix < 100) {
+ const candidate = `${slug}-${suffix}`;
+ if (!taken.has(candidate)) {
+ slug = candidate;
+ break;
+ }
+ suffix++;
+ }
+ }
+ taken.add(slug);
+ resolvedSlugs.set(agent.id, slug);
+ }
+ }
+
+ // 3. Build ownership update payload
+ const ownershipUpdate = {
+ userId: targetUserId,
+ workspaceId: targetWorkspaceId,
+ };
+
+ // 3a. Strip stale device bindings when moving INTO a workspace: any
+ // boundDeviceId / workingDirByDevice entry that isn't enrolled in the
+ // target workspace is silently dropped. Otherwise the moved agent would
+ // reference a device only the previous owner can reach. Moving to a
+ // personal scope (`targetWorkspaceId === null`) keeps existing bindings.
+ // Device rows for the whole batch are fetched with one query.
+ const resolvedAgencyConfigs = new Map<string, LobeAgentAgencyConfig | null>();
+ if (targetWorkspaceId) {
+ const cleanedConfigs = await ctx.sanitizeAgencyConfigForWorkspace(
+ trx,
+ targetWorkspaceId,
+ foundAgents.map((agent) => agent.agencyConfig),
+ );
+ foundAgents.forEach((agent, index) =>
+ resolvedAgencyConfigs.set(agent.id, cleanedConfigs[index]),
+ );
+ }
+
+ // 4. Update the agent records. slug / agencyConfig differ per agent, so
+ // these are per-row PK updates (cheap); the large cascaded tables
+ // below are still one bulk UPDATE each.
+ // Only apply visibility when moving into a workspace β€” visibility is
+ // a no-op in personal scope where every row is implicitly private.
+ // `sessionGroupId` is cleared because sidebar folders belong to the
+ // source scope (same rationale as dropping chatGroupsAgents below);
+ // a stale reference would orphan the agent out of the target sidebar.
+ const visibilityUpdate =
+ targetWorkspaceId && targetVisibility ? { visibility: targetVisibility } : {};
+ for (const agent of foundAgents) {
+ await trx
+ .update(agents)
+ .set({
+ ...ownershipUpdate,
+ ...visibilityUpdate,
+ agencyConfig: targetWorkspaceId
+ ? (resolvedAgencyConfigs.get(agent.id) ?? null)
+ : (agent.agencyConfig ?? null),
+ // Pins are shared state now, exactly like the folder above: a pin
+ // the previous owner set for themselves would arrive as a pin for
+ // every member of the target workspace. Both belong to the source
+ // scope and are dropped with it.
+ pinned: false,
+ sessionGroupId: null,
+ slug: resolvedSlugs.get(agent.id) ?? agent.slug,
+ // A scope transfer does not make the agent's content newer. Keep the
+ // original recency so home/search ordering is not reshuffled.
+ updatedAt: agents.updatedAt,
+ })
+ .where(eq(agents.id, agent.id));
+ }
+
+ // 5. Update sessions linked via agentsToSessions
+ const links = await trx
+ .select({ sessionId: agentsToSessions.sessionId })
+ .from(agentsToSessions)
+ .where(inArray(agentsToSessions.agentId, agentIds));
+
+ const sessionIds = [...new Set(links.map((l) => l.sessionId))];
+
+ if (sessionIds.length > 0) {
+ // `groupId` is cleared for the same reason as the agent's
+ // `sessionGroupId`: folders stay in the source scope.
+ await trx
+ .update(sessions)
+ .set({ ...ownershipUpdate, groupId: null, updatedAt: sessions.updatedAt })
+ .where(inArray(sessions.id, sessionIds));
+ }
+
+ await trx
+ .update(agentsToSessions)
+ .set(ownershipUpdate)
+ .where(inArray(agentsToSessions.agentId, agentIds));
+
+ // 5b. Drop label assignments. Unlike sessions, these cannot travel: a
+ // label belongs to the source registry, and the target scope has its own
+ // (or none). Re-homing them would need a name-matched label in the
+ // target, which is a merge decision, not a transfer one. Leaving them
+ // instead would keep inflating the source label's usage count and make
+ // the labels reappear if the agent ever moves back β€” same reasoning as
+ // the device bindings stripped above.
+ await trx.delete(agentLabelAssignments).where(inArray(agentLabelAssignments.agentId, agentIds));
+
+ // 6. Update topics (linked via sessionId or agentId)
+ const topicCondition =
+ sessionIds.length > 0
+ ? or(inArray(topics.sessionId, sessionIds), inArray(topics.agentId, agentIds))
+ : inArray(topics.agentId, agentIds);
+
+ // Create locks the topic before inserting a comment. Lock every topic in
+ // the same order before the authoritative transfer authorization check,
+ // so either the create becomes visible here or it observes the moved
+ // scope and fails after this transaction commits.
+ await trx
+ .select({ id: topics.id })
+ .from(topics)
+ .where(topicCondition!)
+ .orderBy(asc(topics.id))
+ .for('update');
+
+ if (
+ options.rejectForeignTopicCommentAuthors &&
+ (await hasForeignTopicComments(trx, ctx.userId, topicCondition!))
+ ) {
+ throw new Error(TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS);
+ }
+ const movedTopics = await trx
+ .update(topics)
+ .set({ ...ownershipUpdate, updatedAt: topics.updatedAt })
+ .where(topicCondition!)
+ .returning({ id: topics.id, updatedAt: topics.updatedAt });
+ const movedTopicIds = movedTopics.map((topic) => topic.id);
+
+ // 6a. Topic comments denormalize the topic's workspaceId β€” move them
+ // with the topic (or drop them when leaving workspace scope entirely),
+ // otherwise workspace-filtered comment reads go stale. See the helper doc.
+ await syncTopicCommentsOnTopicTransfer(trx, movedTopicIds, targetWorkspaceId);
+
+ // 7. Message scope rewrite β€” fast/slow split. Rewriting a message row
+ // maintains every message index (incl. the multi-GB BM25 index), so a
+ // heavy agent's history cannot be rewritten inside this transaction:
+ // above the threshold the rewrite is recorded as an async backfill job
+ // (drained topic-by-topic; see AgentTransferJobModel) and the rows keep
+ // their source-scope snapshot until the job reaches them.
+ //
+ // Both paths anchor on the moved topics (plus a topicless residual by
+ // session/agent linkage) rather than the legacy session/agent-only
+ // condition, so topic-only rows (OpenAPI create shape) and the message
+ // child tables move too instead of stranding in the source scope.
+ const messageCondition =
+ sessionIds.length > 0
+ ? or(inArray(messages.sessionId, sessionIds), inArray(messages.agentId, agentIds))
+ : inArray(messages.agentId, agentIds);
+ const [{ affectedMessages }] = await trx
+ .select({ affectedMessages: count() })
+ .from(messages)
+ .where(
+ movedTopicIds.length > 0
+ ? or(inArray(messages.topicId, movedTopicIds), messageCondition!)
+ : messageCondition!,
+ );
+
+ const targetScope = { userId: targetUserId, workspaceId: targetWorkspaceId };
+ let transferJobId: string | null = null;
+ if (affectedMessages <= getAgentTransferSyncMessageThreshold()) {
+ await rewriteMessageScopeForTopics(trx, movedTopicIds, targetScope);
+ await rewriteResidualMessageScope(trx, { agentIds, sessionIds }, targetScope);
+ } else {
+ transferJobId = await AgentTransferJobModel.createJob(trx, {
+ agentIds,
+ sessionIds,
+ source: { userId: ctx.userId, workspaceId: ctx.workspaceId ?? null },
+ target: targetScope,
+ topics: movedTopics.map((topic) => ({ activityAt: topic.updatedAt, id: topic.id })),
+ });
+ }
+
+ // 8. Update threads (linked via agentId)
+ await trx
+ .update(threads)
+ .set({ ...ownershipUpdate, updatedAt: threads.updatedAt })
+ .where(inArray(threads.agentId, agentIds));
+
+ // 9. Update agent files associations
+ await trx
+ .update(agentsFiles)
+ .set({ ...ownershipUpdate, updatedAt: agentsFiles.updatedAt })
+ .where(inArray(agentsFiles.agentId, agentIds));
+
+ // 10. Update agent knowledge base associations
+ await trx
+ .update(agentsKnowledgeBases)
+ .set({ ...ownershipUpdate, updatedAt: agentsKnowledgeBases.updatedAt })
+ .where(inArray(agentsKnowledgeBases.agentId, agentIds));
+
+ // 11. Update agent cron jobs
+ await trx
+ .update(agentCronJobs)
+ .set({ ...ownershipUpdate, updatedAt: agentCronJobs.updatedAt })
+ .where(inArray(agentCronJobs.agentId, agentIds));
+
+ // 12. Update tasks assigned to or created by these agents. The scheduled
+ // task dispatcher uses `createdByUserId` as the execution owner, so tasks
+ // must move with the agent instead of staying under the old owner.
+ // Visibility is cascaded to tasks and child rows so a `private` transfer
+ // does not leak previously-personal task data to every workspace member:
+ // personal rows keep the schema default (`visibility='public'`) but ignore
+ // it, whereas workspace rows honor it β€” without this cascade a `private`
+ // transfer would silently downgrade to workspace-public.
+ const movedTasks = await trx
+ .update(tasks)
+ .set({
+ createdByUserId: targetUserId,
+ updatedAt: tasks.updatedAt,
+ workspaceId: targetWorkspaceId,
+ ...visibilityUpdate,
+ })
+ .where(
+ or(inArray(tasks.assigneeAgentId, agentIds), inArray(tasks.createdByAgentId, agentIds)),
+ )
+ .returning({ id: tasks.id });
+ const movedTaskIds = movedTasks.map((task) => task.id);
+
+ if (movedTaskIds.length > 0) {
+ await trx
+ .update(taskDependencies)
+ .set({ ...ownershipUpdate, ...visibilityUpdate })
+ .where(inArray(taskDependencies.taskId, movedTaskIds));
+ await trx
+ .update(taskTopics)
+ .set({ ...ownershipUpdate, ...visibilityUpdate, updatedAt: taskTopics.updatedAt })
+ .where(inArray(taskTopics.taskId, movedTaskIds));
+ await trx
+ .update(taskComments)
+ .set({ ...ownershipUpdate, ...visibilityUpdate, updatedAt: taskComments.updatedAt })
+ .where(inArray(taskComments.taskId, movedTaskIds));
+ await trx.update(briefs).set(ownershipUpdate).where(inArray(briefs.taskId, movedTaskIds));
+ }
+
+ await trx.update(briefs).set(ownershipUpdate).where(inArray(briefs.agentId, agentIds));
+
+ // 13. Move expertise owned exclusively by these agents. The domain is
+ // the ownership root for lessons, hits and snapshots, so those rows keep
+ // their IDs and follow it without per-table rewrites. Runs additionally
+ // carry their own scope for attribution and must be re-scoped explicitly.
+ // A domain
+ // that is also bound to a carrier outside this transfer is shared state
+ // and must stay in the source scope; only the moved agent's binding is
+ // re-scoped in that case.
+ const boundExpertiseDomains = await trx
+ .select({ domainId: expertiseBindings.domainId })
+ .from(expertiseBindings)
+ .innerJoin(expertiseDomains, eq(expertiseDomains.id, expertiseBindings.domainId))
+ .where(
+ and(
+ inArray(expertiseBindings.agentId, agentIds),
+ buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ expertiseDomains,
+ ),
+ ),
+ );
+ const candidateDomainIds = [...new Set(boundExpertiseDomains.map((row) => row.domainId))];
+
+ await trx
+ .update(expertiseBindings)
+ .set({ workspaceId: targetWorkspaceId, updatedAt: expertiseBindings.updatedAt })
+ .where(inArray(expertiseBindings.agentId, agentIds));
+
+ if (candidateDomainIds.length > 0) {
+ const bindings = await trx
+ .select({
+ agentId: expertiseBindings.agentId,
+ boundUserId: expertiseBindings.boundUserId,
+ boundWorkspaceId: expertiseBindings.boundWorkspaceId,
+ domainId: expertiseBindings.domainId,
+ projectId: expertiseBindings.projectId,
+ })
+ .from(expertiseBindings)
+ .where(inArray(expertiseBindings.domainId, candidateDomainIds));
+ const movedAgentIds = new Set(agentIds);
+ const transferableDomainIds = candidateDomainIds.filter((domainId) =>
+ bindings
+ .filter((binding) => binding.domainId === domainId)
+ .every(
+ (binding) =>
+ binding.agentId !== null &&
+ movedAgentIds.has(binding.agentId) &&
+ binding.projectId === null &&
+ binding.boundWorkspaceId === null &&
+ binding.boundUserId === null,
+ ),
+ );
+
+ if (transferableDomainIds.length > 0) {
+ await trx
+ .update(expertiseDomains)
+ .set({ ...ownershipUpdate, updatedAt: expertiseDomains.updatedAt })
+ .where(inArray(expertiseDomains.id, transferableDomainIds));
+ await trx
+ .update(expertiseInsights)
+ .set({ ...ownershipUpdate, updatedAt: expertiseInsights.updatedAt })
+ .where(inArray(expertiseInsights.domainId, transferableDomainIds));
+ await trx
+ .update(expertiseRuns)
+ .set({ ...ownershipUpdate, updatedAt: expertiseRuns.updatedAt })
+ .where(inArray(expertiseRuns.domainId, transferableDomainIds));
+ }
+ }
+
+ // 14. Update agent bot providers (transfer, not delete)
+ await trx
+ .update(agentBotProviders)
+ .set({ ...ownershipUpdate, updatedAt: agentBotProviders.updatedAt })
+ .where(inArray(agentBotProviders.agentId, agentIds));
+
+ // 14a. Agent-scoped connectors (custom plugins) ride along, or every
+ // custom tool the agent carries stops resolving in the target scope.
+ // Same-owner rows keep their credentials; a target owner change strips
+ // them to reauthorization shells (member-handover policy).
+ await rehomeAgentConnectorsForScopeTransfer(trx, {
+ agentIds,
+ targetUserId,
+ targetWorkspaceId,
+ });
+
+ // 14b. Agent documents (Skills / VFS files) ride along: dedicated
+ // agent-created documents move with binding + history, associated
+ // personal documents stay behind with their binding detached. Without
+ // this the agent's Documents list arrives empty and the files strand in
+ // the source scope's Resource list.
+ const movedDocumentIds = await moveAgentDocumentsForScopeTransfer(trx, {
+ agentIds,
+ movedTaskIds,
+ movedTopicIds,
+ targetUserId,
+ targetVisibility,
+ targetWorkspaceId,
+ });
+
+ // 14c. Topic- and task-document junction rows denormalize the owner
+ // scope, but a junction only resolves when BOTH it and its document pass
+ // the target predicate β€” `TopicDocumentModel.findByTopicId` and
+ // `TaskModel.getDocumentsPinnedSince` join the two. So the split can only
+ // be decided once 14b has said which documents actually moved: links
+ // whose document rode along follow their topic/task, and the rest are
+ // detached. Kept, they would be rows no scope can resolve β€” invisible in
+ // the target, orphaned in the source once their topic/task left it.
+ if (movedTopicIds.length > 0) {
+ const onMovedTopics = inArray(topicDocuments.topicId, movedTopicIds);
+ if (movedDocumentIds.length > 0) {
+ await trx
+ .update(topicDocuments)
+ .set(ownershipUpdate)
+ .where(and(onMovedTopics, inArray(topicDocuments.documentId, movedDocumentIds)));
+ }
+ await trx
+ .delete(topicDocuments)
+ .where(
+ movedDocumentIds.length > 0
+ ? and(onMovedTopics, notInArray(topicDocuments.documentId, movedDocumentIds))
+ : onMovedTopics,
+ );
+ }
+
+ if (movedTaskIds.length > 0) {
+ const onMovedTasks = inArray(taskDocuments.taskId, movedTaskIds);
+ if (movedDocumentIds.length > 0) {
+ await trx
+ .update(taskDocuments)
+ .set({ ...ownershipUpdate, ...visibilityUpdate })
+ .where(and(onMovedTasks, inArray(taskDocuments.documentId, movedDocumentIds)));
+ }
+ await trx
+ .delete(taskDocuments)
+ .where(
+ movedDocumentIds.length > 0
+ ? and(onMovedTasks, notInArray(taskDocuments.documentId, movedDocumentIds))
+ : onMovedTasks,
+ );
+ }
+
+ // 15. Leave every chat group: a group belongs to the source scope, and a
+ // roster row pointing at an agent that now lives elsewhere would render
+ // as a member nobody in either scope can use. Guard 1c above has already
+ // rejected the memberships where leaving would damage the GROUP, so
+ // everything reaching here is a `referenced` link the caller confirmed.
+ await trx.delete(chatGroupsAgents).where(inArray(chatGroupsAgents.agentId, agentIds));
+
+ return agentIds.map((id) => ({
+ agentId: id,
+ slug: resolvedSlugs.get(id) ?? agentById.get(id)?.slug ?? null,
+ transferJobId,
+ }));
+ });
+};
+
+/**
+ * Cross-scope agent transfer as one unit of work. Moving an agent rehomes its
+ * sessions, topics, messages, threads, tasks (and their child rows),
+ * expertise, documents and connectors in a single transaction, so the flow
+ * lives here rather than in `AgentModel`; the read-only guards
+ * (`AgentModel.transferHasForeignRows`, the pending-job checks) stay with
+ * their models.
+ */
+export class AgentTransferRepository {
+ private readonly ctx: AgentModelContext;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.ctx = createAgentModelContext({ db, userId, workspaceId });
+ }
+
+ /** See {@link transferAgents}. */
+ transferAgents = (
+ agentIds: string[],
+ targetWorkspaceId: string | null,
+ targetUserId: string,
+ targetVisibility?: 'private' | 'public',
+ options: AgentTransferOptions = {},
+ ): Promise<{ agentId: string; slug: string | null; transferJobId: string | null }[]> =>
+ transferAgents(this.ctx, agentIds, targetWorkspaceId, targetUserId, targetVisibility, options);
+}