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(server): split the 1,601-line agent router into sub-domain modules (#21087)

Arvin Xu758b7e82dbad
diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.ts
deleted file mode 100644
index feddcf04a35..00000000000
--- a/apps/server/src/routers/lambda/agent.ts
+++ /dev/null
@@ -1,1601 +0,0 @@
-import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
-import { DEFAULT_AGENT_CONFIG, INBOX_SESSION_ID } from '@lobechat/const';
-import type { KnowledgeItem } from '@lobechat/types';
-import { AGENT_PERMISSION_POLICY_KEYS, CreateAgentSchema, KnowledgeType } from '@lobechat/types';
-import { isRecord } from '@lobechat/utils/object';
-import { TRPCError } from '@trpc/server';
-import { z } from 'zod';
-
-import {
- prioritizeAgentTransferTopic,
- startAgentTransferJob,
-} from '@/business/server/agent-transfer/jobRunner';
-import { notifyResourceTransfer } from '@/business/server/resource-transfer/notify';
-import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
-import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
-import {
- AGENT_SHARED_TRANSFER_BLOCKED,
- AgentModel,
- AgentOwnedByGroupError,
-} from '@/database/models/agent';
-import { AGENT_COPY_IN_PROGRESS } from '@/database/models/agentCopyJob';
-import {
- AGENT_TRANSFER_IN_PROGRESS,
- AgentTransferJobModel,
-} from '@/database/models/agentTransferJob';
-import { ChatGroupModel } from '@/database/models/chatGroup';
-import { FileModel } from '@/database/models/file';
-import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
-import { ResourcePermissionModel } from '@/database/models/resourcePermission';
-import {
- ResourceTransferRequestModel,
- TRANSFER_REQUEST_ALREADY_PENDING,
-} from '@/database/models/resourceTransferRequest';
-import { SessionModel } from '@/database/models/session';
-import { TaskModel } from '@/database/models/task';
-import { TopicModel } from '@/database/models/topic';
-import { TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS } from '@/database/models/topicComment';
-import { UserModel } from '@/database/models/user';
-import type { ResourceAccessLevel } from '@/database/schemas';
-import {
- DEFAULT_RESOURCE_ACCESS_LEVELS,
- LEGACY_VIEWER_ACCESS_LEVELS,
- RESOURCE_ACCESS_LEVELS_BY_TYPE,
-} from '@/database/schemas';
-import { router } from '@/libs/trpc/lambda';
-import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { AgentService } from '@/server/services/agent';
-import { EditLockService } from '@/server/services/editLock';
-import { publishResourceEvent } from '@/server/services/resourceEvents';
-import {
- assertCanEditResource,
- assertCanPerformResourceAction,
- buildResourcePermissionState,
-} from '@/server/services/resourcePermission';
-import { assertTransferRecipientValid } from '@/server/services/resourceTransferRequest';
-import { TrashService } from '@/server/services/trash';
-import {
- hasWorkspaceScopedPermission,
- isWorkspacePrimaryOwner,
-} from '@/server/services/workspacePermission';
-import { after } from '@/server/utils/scheduleAfterResponse';
-import { TransferErrorCode } from '@/types/transferError';
-
-import { isWorkspaceNonOwner } from './_helpers/assertWorkspaceRowManageable';
-import {
- getRestrictedKnowledgeBaseIds,
- getUseLevelKnowledgeBaseIds,
-} from './_helpers/knowledgeBaseAccess';
-import { getResourceConfigAccess, redactAgentConfig } from './_helpers/resourceConfigGuard';
-
-const getAgentPermissionPolicyPatch = (value: Record<string, unknown>) => {
- const agencyConfig = value.agencyConfig;
-
- return isRecord(agencyConfig) && AGENT_PERMISSION_POLICY_KEYS.some((key) => key in agencyConfig)
- ? agencyConfig
- : null;
-};
-
-const stripAgentPermissionPolicies = (value: Record<string, unknown>) => {
- const policyPatch = getAgentPermissionPolicyPatch(value);
- if (!policyPatch) return value;
-
- const {
- executionTargetSelectionPolicy: _executionTargetSelectionPolicy,
- modelSelectionPolicy: _modelSelectionPolicy,
- topicSharePolicy: _topicSharePolicy,
- ...safeAgencyConfig
- } = policyPatch;
-
- return { ...value, agencyConfig: safeAgencyConfig };
-};
-
-const protectAgentConfig = async <T extends Record<string, any>>(
- ctx: {
- serverDB: Parameters<typeof getResourceConfigAccess>[0]['db'];
- userId: string;
- workspaceId?: string | null;
- workspacePermissionCodes?: string[];
- },
- agentId: string,
- config: T | null | undefined,
-): Promise<T | null> => {
- if (!config) return null;
-
- const access = await getResourceConfigAccess(
- {
- db: ctx.serverDB,
- grantedPermissions: ctx.workspacePermissionCodes,
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- },
- 'agent',
- agentId,
- );
-
- if (access === 'none') return null;
- return access === 'profile' ? redactAgentConfig(config) : config;
-};
-
-/** What a `/agent/:slugOrId` param resolves to β€” see `resolveAgentRoute`. */
-export interface AgentRouteResolution {
- /** The resolved agent id. Present for `own` routes. */
- agentId?: string;
- /**
- * `own`: one of the caller's agents (by id or by agent slug).
- * `notFound`: no agent of the caller's claims the param β€” the caller sees
- * the agent not-found surface.
- */
- kind: 'own' | 'notFound';
-}
-
-const agentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
- const { ctx } = opts;
- const wsId = ctx.workspaceId ?? undefined;
-
- return opts.next({
- ctx: {
- agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),
- agentService: new AgentService(ctx.serverDB, ctx.userId, wsId),
- chatGroupModel: new ChatGroupModel(ctx.serverDB, ctx.userId, wsId),
- editLockService: new EditLockService(ctx.userId),
- fileModel: new FileModel(ctx.serverDB, ctx.userId, wsId),
- knowledgeBaseModel: new KnowledgeBaseModel(ctx.serverDB, ctx.userId, wsId),
- sessionModel: new SessionModel(ctx.serverDB, ctx.userId, wsId),
- },
- });
-});
-
-export const agentRouter = router({
- /**
- * Check if an agent with the given marketIdentifier already exists
- */
- checkByMarketIdentifier: agentProcedure
- .input(
- z.object({
- marketIdentifier: z.string(),
- }),
- )
- .query(async ({ input, ctx }) => {
- return ctx.agentModel.checkByMarketIdentifier(input.marketIdentifier);
- }),
-
- /**
- * Count the agents matching the conditions of queryAgents β€” other virtual
- * rows excluded, and the inbox (Lobe AI) counted only when the caller passes
- * `includeInbox: true`. Lets paginated callers report real totals.
- */
- countAgents: agentProcedure
- .input(
- z
- .object({
- endDate: z.string().optional(),
- includeInbox: z.boolean().optional(),
- keyword: z.string().optional(),
- range: z.tuple([z.string(), z.string()]).optional(),
- startDate: z.string().optional(),
- })
- .optional(),
- )
- .query(async ({ input, ctx }) => {
- return ctx.agentModel.countAgents(input);
- }),
-
- /**
- * Create a new agent with session
- * Returns the created agent ID and session ID
- */
- createAgent: agentProcedure
- .use(withScopedPermission('agent:create'))
- .input(
- z.object({
- config: CreateAgentSchema.optional(),
- groupId: z.string().optional(),
- visibility: z.enum(['private', 'public']).optional(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- // Creating inside a Category has to land in that Category. The folder's
- // visibility decides the new agent's, rather than the other way round:
- // the sidebar resolves a public agent's folder only against public
- // folders (and a private agent's only against private ones), so a
- // default-public agent created from a private Category would render in
- // Ungrouped β€” for its creator too. The "New Agent" action inside a
- // private Category sends only `{ groupId }`, so this is the normal path,
- // not a crafted one. An explicit conflicting `visibility` is refused
- // rather than silently overridden.
- const folderVisibility = input.groupId
- ? await ctx.agentModel.getAssignableSessionGroupVisibility(input.groupId)
- : undefined;
-
- if (folderVisibility && input.visibility && input.visibility !== folderVisibility)
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: `A ${input.visibility} agent cannot be created in a ${folderVisibility} folder`,
- });
-
- const agent = await ctx.agentModel.create({
- ...input.config,
- // The DB-layer AgentItem (packages/database/src/schemas/agent.ts) is
- // intentionally still typed `plugins?: string[]` β€” the JSONB column
- // itself isn't widened, only the domain-level `@lobechat/types`
- // shapes. Bridges the tri-state object shape through.
- plugins: input.config?.plugins as unknown as string[] | undefined,
- sessionGroupId: input.groupId,
- // Router-level `visibility` wins over any nested config value so the
- // sidebar's "Create in Private" entry can't be overridden by a stale
- // default config.
- ...(input.visibility || folderVisibility
- ? { visibility: input.visibility ?? folderVisibility }
- : {}),
- });
-
- if (ctx.workspaceId && agent.visibility !== 'private') {
- await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
- 'agent',
- agent.id,
- DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
- ctx.userId,
- );
- }
-
- return { agentId: agent.id };
- }),
-
- /**
- * Publish a private agent into the workspace. Only the creator of a
- * still-private agent can run this; the underlying SQL enforces both rules.
- * The inverse transition (public β†’ private) goes through
- * `setAgentVisibility`, which is gated to the creator only.
- */
- publishAgentToWorkspace: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(
- z.object({
- accessLevel: z.enum(RESOURCE_ACCESS_LEVELS_BY_TYPE.agent).optional(),
- id: z.string(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const result = await ctx.agentModel.publishToWorkspace(input.id);
- if (ctx.workspaceId) {
- const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
- // An explicit request wins; otherwise keep whatever the creator already
- // chose on the Permission page while the agent was still private β€”
- // rewriting the default here would silently discard that decision.
- const accessLevel =
- input.accessLevel ??
- (await permissionModel.getAccessLevel('agent', input.id)) ??
- DEFAULT_RESOURCE_ACCESS_LEVELS.agent;
- await permissionModel.setAccessLevel('agent', input.id, accessLevel, ctx.userId);
- }
- return result;
- }),
-
- /**
- * Bidirectional visibility switch. Rules:
- * - builtin agents (LobeAI etc., identified by slug) can never change
- * visibility β€” the workspace copy must stay shared;
- * - only the agent's creator may pull a published agent back to private
- *: a workspace owner demoting another member's agent would
- * effectively appropriate it, so everyone else gets FORBIDDEN. The UI
- * hides the entry for them, this is the server-side backstop.
- */
- setAgentVisibility: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(
- z.object({
- accessLevel: z.enum(RESOURCE_ACCESS_LEVELS_BY_TYPE.agent).optional(),
- id: z.string(),
- visibility: z.enum(['private', 'public']),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const meta = await ctx.agentModel.getAgentVisibilityMeta(input.id);
- if (!meta) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
-
- if (meta.slug && Object.values(BUILTIN_AGENT_SLUGS).includes(meta.slug as any)) {
- throw new TRPCError({
- code: 'FORBIDDEN',
- message: 'Builtin agents cannot change visibility',
- });
- }
-
- if (!ctx.workspaceId) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'Agent visibility only applies inside a workspace',
- });
- }
- const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
- const permissionMeta = { ...meta, workspaceId: ctx.workspaceId };
- const blockingTasksPromise =
- input.visibility === 'private' && meta.visibility !== input.visibility
- ? new TaskModel(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId,
- ).countTasksBlockingAgentDemotion(input.id, meta.userId)
- : Promise.resolve(0);
- const [, blockingTasks] = await Promise.all([
- assertCanPerformResourceAction({
- action: 'changeVisibility',
- db: ctx.serverDB,
- grantedPermissions: (ctx as { workspacePermissionCodes?: string[] })
- .workspacePermissionCodes,
- meta: permissionMeta,
- resourceId: input.id,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- }),
- blockingTasksPromise,
- ]);
-
- if (meta.visibility === input.visibility) {
- const accessLevel =
- input.visibility === 'public'
- ? (input.accessLevel ??
- (await permissionModel.getEffectiveAccessLevel('agent', input.id)))
- : 'edit';
- if (input.visibility === 'public' && input.accessLevel) {
- await permissionModel.setAccessLevel('agent', input.id, input.accessLevel, ctx.userId);
- }
- return buildResourcePermissionState({
- accessLevel,
- canManage: true,
- creatorId: meta.userId,
- visibility: input.visibility,
- });
- }
-
- // Demoting an agent must not strand tasks that depend on it: public
- // tasks would violate the `assertAgentVisibilityCompat` invariant
- // (members keep seeing the task but can no longer see or run the
- // assignee), and other members' tasks β€” private ones included β€” would
- // fail future runs/updates because their creators can no longer
- // resolve the agent. Reject early β€” reassign or demote those tasks
- // first.
- if (blockingTasks > 0) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message:
- 'Cannot make this agent private while workspace tasks still depend on it. Reassign those tasks or make them private first.',
- });
- }
-
- // Same source-level guard for group chats, but only for the supervisor
- // role: a private supervisor is unresolvable for every other viewer and
- // bricks the whole group. Regular members are not blocked β€” roster
- // reads drop a non-visible member per viewer instead.
- if (input.visibility === 'private') {
- const chatGroupModel = new ChatGroupModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
- const blockingGroups = await chatGroupModel.countGroupsBlockingAgentDemotion(
- input.id,
- meta.userId,
- );
- if (blockingGroups > 0) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message:
- 'Cannot make this agent private while it supervises workspace group chats. Remove it as supervisor first.',
- });
- }
- }
-
- const updated = await ctx.agentModel.setVisibility(input.id, input.visibility);
- if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
-
- let accessLevel: ResourceAccessLevel;
- if (input.visibility === 'private') {
- accessLevel = 'edit';
- await permissionModel.removeAll('agent', input.id);
- } else {
- // Same rule as `publishAgentToWorkspace`: promotion keeps a level the
- // creator already set while private instead of resetting to the default.
- accessLevel =
- input.accessLevel ??
- (await permissionModel.getAccessLevel('agent', input.id)) ??
- DEFAULT_RESOURCE_ACCESS_LEVELS.agent;
- await permissionModel.setAccessLevel('agent', input.id, accessLevel, ctx.userId);
- }
-
- return buildResourcePermissionState({
- accessLevel,
- canManage: true,
- creatorId: meta.userId,
- visibility: input.visibility,
- });
- }),
-
- createAgentFiles: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(
- z.object({
- agentId: z.string(),
- enabled: z.boolean().optional(),
- fileIds: z.array(z.string()),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- if (ctx.workspaceId) {
- await assertCanPerformResourceAction({
- action: 'edit',
- db: ctx.serverDB,
- resourceId: input.agentId,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
- }
- return ctx.agentModel.createAgentFiles(input.agentId, input.fileIds, input.enabled);
- }),
-
- createAgentKnowledgeBase: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(
- z.object({
- agentId: z.string(),
- enabled: z.boolean().optional(),
- knowledgeBaseId: z.string(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- if (ctx.workspaceId) {
- await assertCanPerformResourceAction({
- action: 'edit',
- db: ctx.serverDB,
- resourceId: input.agentId,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
- }
- return ctx.agentModel.createAgentKnowledgeBase(
- input.agentId,
- input.knowledgeBaseId,
- input.enabled,
- );
- }),
-
- /**
- * Create an agent without session.
- * Used for Group Agent Builder to create agents for groups.
- * Returns only the agent ID.
- */
- createAgentOnly: agentProcedure
- .use(withScopedPermission('agent:create'))
- .input(
- z.object({
- config: z.object({}).passthrough().optional(),
- groupId: z.string(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- // Mutating the group's roster is a group edit β€” same ACL as
- // `agentGroup.addAgentsToGroup`. Check before creating the agent so a
- // denied call doesn't leave an orphan agent behind.
- if (ctx.workspaceId) {
- await assertCanPerformResourceAction({
- action: 'edit',
- db: ctx.serverDB,
- resourceId: input.groupId,
- resourceType: 'agentGroup',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
- }
-
- // Create the agent entity only (no session)
- const agent = await ctx.agentModel.create(input.config ?? {});
-
- // Add the agent to the group
- await ctx.chatGroupModel.addAgentToGroup(input.groupId, agent.id);
-
- if (ctx.workspaceId && agent.visibility !== 'private') {
- await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
- 'agent',
- agent.id,
- DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
- ctx.userId,
- );
- }
-
- return { agentId: agent.id };
- }),
-
- deleteAgentFile: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(
- z.object({
- agentId: z.string(),
- fileId: z.string(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- if (ctx.workspaceId) {
- await assertCanPerformResourceAction({
- action: 'edit',
- db: ctx.serverDB,
- resourceId: input.agentId,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
- }
- return ctx.agentModel.deleteAgentFile(input.agentId, input.fileId);
- }),
-
- deleteAgentKnowledgeBase: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(
- z.object({
- agentId: z.string(),
- knowledgeBaseId: z.string(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- if (ctx.workspaceId) {
- await assertCanPerformResourceAction({
- action: 'edit',
- db: ctx.serverDB,
- resourceId: input.agentId,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
- }
- return ctx.agentModel.deleteAgentKnowledgeBase(input.agentId, input.knowledgeBaseId);
- }),
-
- /**
- * Duplicate an agent and its associated session.
- * Returns the new agent ID and session ID.
- */
- duplicateAgent: agentProcedure
- .use(withScopedPermission('agent:fork'))
- .input(
- z.object({
- agentId: z.string(),
- newTitle: z.string().optional(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- // Forking creates a caller-owned Agent and is governed by `agent:fork`,
- // independently of the source Agent's collaborative-edit permission.
- const result = await ctx.agentModel.duplicate(input.agentId, input.newTitle);
- if (ctx.workspaceId && result) {
- await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
- 'agent',
- result.agentId,
- DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
- ctx.userId,
- );
- }
- return result;
- }),
-
- /**
- * Get an agent by forkedFromIdentifier stored in params
- * @returns agent id if exists, null otherwise
- */
- getAgentByForkedFromIdentifier: agentProcedure
- .input(
- z.object({
- forkedFromIdentifier: z.string(),
- }),
- )
- .query(async ({ input, ctx }) => {
- return ctx.agentModel.getAgentByForkedFromIdentifier(input.forkedFromIdentifier);
- }),
-
- /**
- * Get an agent by marketIdentifier
- * @returns agent id if exists, null otherwise
- */
- getAgentByMarketIdentifier: agentProcedure
- .input(
- z.object({
- marketIdentifier: z.string(),
- }),
- )
- .query(async ({ input, ctx }) => {
- return ctx.agentModel.getAgentByMarketIdentifier(input.marketIdentifier);
- }),
-
- getAgentConfig: agentProcedure
- .input(
- z.object({
- sessionId: z.string(),
- }),
- )
- .query(async ({ input, ctx }) => {
- if (input.sessionId === INBOX_SESSION_ID) {
- const item = await ctx.sessionModel.findByIdOrSlug(INBOX_SESSION_ID);
- // if there is no session for user, create one
- if (!item) {
- // if there is no user, return default config
- const user = await UserModel.findById(ctx.serverDB, ctx.userId);
- if (!user) return DEFAULT_AGENT_CONFIG;
-
- const res = await ctx.agentService.createInbox();
- console.info('create inbox session', res);
- }
- }
-
- const session = await ctx.sessionModel.findByIdOrSlug(input.sessionId);
-
- if (!session) throw new Error(`Session [${input.sessionId}] not found`);
- const sessionId = session.id;
-
- const config = await ctx.agentModel.findBySessionId(sessionId);
- return config?.id ? protectAgentConfig(ctx, config.id, config) : config;
- }),
-
- getAgentConfigById: agentProcedure
- .input(
- z.object({
- agentId: z.string(),
- }),
- )
- .query(async ({ input, ctx }) => {
- const config = await ctx.agentService.getAgentConfigById(input.agentId);
- return protectAgentConfig(ctx, input.agentId, config);
- }),
-
- /**
- * Get a builtin agent by slug, creating it if it doesn't exist.
- * This is a generic interface for all builtin agents (page-copilot, inbox, etc.)
- */
- getBuiltinAgent: agentProcedure
- .input(
- z.object({
- slug: z.string(),
- }),
- )
- .query(async ({ input, ctx }) => {
- const config = await ctx.agentService.getBuiltinAgent(input.slug);
- return config?.id ? protectAgentConfig(ctx, config.id, config) : config;
- }),
-
- getKnowledgeBasesAndFiles: agentProcedure
- .input(
- z.object({
- agentId: z.string(),
- visibility: z.enum(['private', 'public']).optional(),
- }),
- )
- .query(async ({ ctx, input }): Promise<KnowledgeItem[]> => {
- await assertCanEditResource({
- db: ctx.serverDB,
- resourceId: input.agentId,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId ?? undefined,
- });
-
- // Look up the target agent's visibility so we can (a) apply the
- // "public agent cannot reach caller's private rows" defensive filter
- // in the model layer, and (b) hard-force `visibility='public'` when
- // the agent is public β€” the client tab is a UX aid, not a gate.
- const agentVisibility = await ctx.agentModel.getAgentVisibility(input.agentId);
-
- // `visibility` is workspace-scoped. In personal mode buildWorkspaceWhere
- // ignores the column entirely (every row is implicitly private to its
- // owner) while the column still defaults to 'public', so forcing a scope
- // here would filter personal rows by a value that carries no meaning.
- // Only workspace agents get a visibility scope.
- const effectiveVisibility = ctx.workspaceId
- ? agentVisibility === 'public'
- ? ('public' as const)
- : input.visibility
- : undefined;
-
- const knowledgeBases = await ctx.knowledgeBaseModel.query({
- callerAgentVisibility: agentVisibility,
- visibility: effectiveVisibility,
- });
-
- const files = await ctx.fileModel.query({
- callerAgentVisibility: agentVisibility,
- showFilesInKnowledgeBase: false,
- visibility: effectiveVisibility,
- });
-
- const knowledge = await ctx.agentModel.getAgentAssignedKnowledge(input.agentId);
-
- // Member-restricted (No-access) KBs disappear from the picker for
- // non-privileged members, except ones already attached to this agent β€”
- // an invisible-but-attached row would be impossible to unmount. Managers
- // keep seeing them, with a flag so the client can badge the icon.
- const [restrictedForCaller, useLevelIds] = ctx.workspaceId
- ? await Promise.all([
- getRestrictedKnowledgeBaseIds(ctx),
- getUseLevelKnowledgeBaseIds(ctx.serverDB, ctx.workspaceId),
- ])
- : [[], []];
- const restrictedSet = new Set(restrictedForCaller);
- const memberRestrictedSet = new Set(useLevelIds);
- const visibleKnowledgeBases = knowledgeBases.filter(
- (kb) =>
- !restrictedSet.has(kb.id) || knowledge.knowledgeBases.some((item) => item.id === kb.id),
- );
-
- return [
- ...files
- // Filter out all images
- .filter((file) => !file.fileType.startsWith('image'))
- .map((file) => ({
- enabled: knowledge.files.some((item) => item.id === file.id),
- fileType: file.fileType,
- id: file.id,
- name: file.name,
- ownerUserId: file.userId,
- type: KnowledgeType.File,
- visibility: file.visibility as 'private' | 'public',
- })),
- ...visibleKnowledgeBases.map((knowledgeBase) => ({
- avatar: knowledgeBase.avatar,
- description: knowledgeBase.description,
- enabled: knowledge.knowledgeBases.some((item) => item.id === knowledgeBase.id),
- id: knowledgeBase.id,
- memberRestricted: memberRestrictedSet.has(knowledgeBase.id),
- name: knowledgeBase.name,
- ownerUserId: knowledgeBase.userId,
- type: KnowledgeType.KnowledgeBase,
- visibility: knowledgeBase.visibility,
- })),
- ];
- }),
-
- /**
- * Query the user's agents with optional keyword filter β€” other virtual rows
- * excluded, and the inbox (Lobe AI) included and flagged with `isInbox` only
- * when the caller passes `includeInbox: true`.
- * Returns agents with minimal info (id, name, title, description, avatar,
- * backgroundColor).
- * Used by AddGroupMemberModal and group-management tool to search/select agents.
- */
- queryAgents: agentProcedure
- .input(
- z
- .object({
- includeInbox: z.boolean().optional(),
- keyword: z.string().optional(),
- limit: z.number().max(100).optional(),
- offset: z.number().optional(),
- })
- .optional(),
- )
- .query(async ({ input, ctx }) => {
- return ctx.agentModel.queryAgents(input);
- }),
-
- rankAgents: agentProcedure.input(z.number().max(50).optional()).query(async ({ ctx, input }) => {
- return ctx.agentModel.rank(input);
- }),
-
- /**
- * Remove an agent and its associated session
- */
- removeAgent: agentProcedure
- .use(withScopedPermission('agent:delete'))
- .input(z.object({ agentId: z.string() }))
- .mutation(async ({ input, ctx }) => {
- if (ctx.workspaceId) {
- await assertCanPerformResourceAction({
- action: 'delete',
- db: ctx.serverDB,
- resourceId: input.agentId,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
- // Same rule as transfer: the delete cascade erases every linked
- // session/topic/message, so a non-owner member must not take teammates'
- // conversations down with their own agent.
- if (
- isWorkspaceNonOwner(ctx) &&
- (await ctx.agentModel.transferHasForeignRows(input.agentId))
- ) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.OwnerOnly } },
- code: 'FORBIDDEN',
- message: "Only workspace owners can delete an agent carrying others' conversations",
- });
- }
- }
- let result;
- try {
- // Recycle bin: the agent, its session shells and every topic under it
- // are stamped, not dropped β€” the FK cascade only runs at purge time.
- result = await new TrashService(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- ).trashAgent(input.agentId);
- } catch (error) {
- if (error instanceof Error && error.message === AGENT_COPY_IN_PROGRESS) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.CopyInProgress } },
- code: 'CONFLICT',
- message: 'A previous copy of this agent is still duplicating its history',
- });
- }
- // A backfill still maps this agent's message rows β€” deleting it now
- // would strand the job on a dangling `messages.agent_id`.
- if (error instanceof Error && error.message === AGENT_TRANSFER_IN_PROGRESS) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.TransferInProgress } },
- code: 'CONFLICT',
- message: "A previous transfer of this agent's history is still migrating",
- });
- }
- throw error;
- }
- // Sharing grants are left in place while the agent sits in the bin (the
- // row is invisible anyway) so a restore brings them back; the purge
- // handler removes them for good. A pending handover is different: the
- // agent is invisible to the recipient too, so an acceptance would move
- // ownership of trashed content β€” void it now, as the hard delete did.
- if (ctx.workspaceId) {
- await new ResourceTransferRequestModel(
- ctx.serverDB,
- ctx.workspaceId,
- ).invalidateForResources('agent', [input.agentId]);
- }
- return result;
- }),
-
- toggleFile: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(
- z.object({
- agentId: z.string(),
- enabled: z.boolean().optional(),
- fileId: z.string(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- if (ctx.workspaceId) {
- await assertCanPerformResourceAction({
- action: 'edit',
- db: ctx.serverDB,
- resourceId: input.agentId,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
- }
- return ctx.agentModel.toggleFile(input.agentId, input.fileId, input.enabled);
- }),
-
- toggleKnowledgeBase: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(
- z.object({
- agentId: z.string(),
- enabled: z.boolean().optional(),
- knowledgeBaseId: z.string(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- if (ctx.workspaceId) {
- await assertCanPerformResourceAction({
- action: 'edit',
- db: ctx.serverDB,
- resourceId: input.agentId,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
- }
- return ctx.agentModel.toggleKnowledgeBase(
- input.agentId,
- input.knowledgeBaseId,
- input.enabled,
- );
- }),
-
- /**
- * Progress of the async history backfill after a heavy transfer, plus the
- * topic ids still awaiting their scope rewrite (the UI's gray-out set).
- * Returns null when no backfill is running for the agent.
- */
- getTransferJobStatus: agentProcedure
- .input(
- z.object({
- agentId: z.string(),
- /**
- * Topics the client currently shows (sidebar rows + active topic).
- * `pendingTopicIds` is the intersection with the job's queue, keeping
- * the 3s poll payload bounded however large the backfill is. Required
- * so no caller can pull the whole queue (this endpoint ships with the
- * clients that send it β€” there is no released-client compat to keep).
- */
- topicIds: z.array(z.string()).max(1000),
- }),
- )
- .query(async ({ input, ctx }) => {
- // Scope check: only report migration state for agents visible to the
- // caller's current personal/workspace scope (agent ids are guessable).
- const visibility = await ctx.agentModel.getAgentVisibility(input.agentId);
- if (!visibility) return null;
-
- const job = await AgentTransferJobModel.findPendingJobForAgent(ctx.serverDB, input.agentId);
- if (!job) return null;
- const pendingTopicIds = await AgentTransferJobModel.getPendingTopicIds(
- ctx.serverDB,
- job.id,
- input.topicIds,
- );
- return {
- completedTopics: job.completedTopics,
- jobId: job.id,
- pendingTopicIds,
- totalTopics: job.totalTopics,
- // `transfer` vs `copy` β€” the client words its progress hints by it.
- type: job.type,
- };
- }),
-
- /**
- * What moving these agents would do to the chat groups they are in.
- *
- * Asked before the move, because both outcomes are invisible otherwise: a
- * transfer drops every group link the agent holds β€” historically without a
- * word β€” and a group-owned agent cannot be moved at all. The mutation
- * enforces the second case regardless; this endpoint exists so the user
- * learns about it while they can still choose differently.
- */
- getGroupMembershipImpact: agentProcedure
- .input(z.object({ agentIds: z.array(z.string()).min(1).max(100) }))
- .query(async ({ input, ctx }) =>
- // Reports only on agents the caller can see β€” the model does that scoping
- // itself, because the guard path deliberately does not.
- ctx.agentModel.getGroupMembershipImpact(input.agentIds),
- ),
-
- /**
- * The user opened a topic whose history is still migrating β€” jump it to the
- * front of the backfill queue. Returns whether the topic was still pending
- * (false β†’ already migrated, the client can refetch messages immediately).
- */
- prioritizeTransferTopic: agentProcedure
- .input(z.object({ topicId: z.string() }))
- .mutation(async ({ input, ctx }) => {
- // Scope check: reordering the backfill queue is only allowed for topics
- // the caller can see (the transfer moves topics to the target scope
- // synchronously, so a pending topic is visible to its new owner).
- const topic = await new TopicModel(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- ).findById(input.topicId);
- if (!topic) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });
- }
-
- const flagged = await prioritizeAgentTransferTopic(ctx.serverDB, input.topicId);
- return { pending: flagged };
- }),
-
- transferAgent: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(
- z.object({
- agentId: z.string(),
- /**
- * Cross-workspace move only: the General Access level the agent gets
- * in the target workspace. Ignored on a member transfer (`targetMemberId`),
- * which keeps the agent's existing ACL in place.
- */
- targetAccessLevel: z.enum(RESOURCE_ACCESS_LEVELS_BY_TYPE.agent).optional(),
- /** @deprecated Compatibility for released clients. */
- targetGeneralAccess: z.enum(['editor', 'viewer']).optional(),
- /**
- * Hand ownership to another member of the CURRENT workspace. Mutually
- * exclusive with `targetWorkspaceId`; creates a pending transfer
- * request the recipient must accept instead of moving anything now.
- */
- targetMemberId: z.string().min(1).optional(),
- targetVisibility: z.enum(['private', 'public']).optional(),
- targetWorkspaceId: z.string().nullable(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- // 1. Fetch the agent to check ownership
- const agent = await ctx.agentModel.getAgentConfigById(input.agentId);
- if (!agent) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.ResourceNotFound } },
- code: 'NOT_FOUND',
- message: 'Agent not found',
- });
- }
-
- // 2. Transferring ownership/scope is always creator-only.
- if (ctx.workspaceId) {
- await assertCanPerformResourceAction({
- action: 'transfer',
- db: ctx.serverDB,
- resourceId: input.agentId,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
- }
-
- // 2a. Member transfer: initiate a pending request instead of moving the
- // agent. Nothing changes until the recipient accepts.
- if (input.targetMemberId) {
- if (!ctx.workspaceId || input.targetWorkspaceId) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.TransferNotSupported } },
- code: 'BAD_REQUEST',
- message: 'Member transfer happens inside the current workspace',
- });
- }
- // Group-built/virtual rows are workspace infrastructure, not content
- // someone can personally hand over.
- if (agent.virtual) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.TransferNotSupported } },
- code: 'BAD_REQUEST',
- message: 'This agent cannot be transferred',
- });
- }
- await assertTransferRecipientValid({
- currentOwnerId: agent.userId,
- db: ctx.serverDB,
- initiatorId: ctx.userId,
- recipientId: input.targetMemberId,
- workspaceId: ctx.workspaceId,
- });
-
- try {
- const request = await new ResourceTransferRequestModel(
- ctx.serverDB,
- ctx.workspaceId,
- ).create({
- initiatorId: ctx.userId,
- previousOwnerId: agent.userId,
- recipientId: input.targetMemberId,
- resourceId: input.agentId,
- resourceType: 'agent',
- });
- // Best-effort: a notification failure must not fail the request.
- // Scheduled with after() so serverless runtimes keep it alive past
- // the response.
- const notifyParams = {
- event: 'requested' as const,
- initiatorId: ctx.userId,
- previousOwnerId: agent.userId,
- recipientId: input.targetMemberId,
- requestId: request.id,
- resourceId: input.agentId,
- resourceType: 'agent' as const,
- workspaceId: ctx.workspaceId,
- };
- after(() =>
- notifyResourceTransfer(notifyParams).catch((error) =>
- console.error('[agent:transferAgent] notify failed', error),
- ),
- );
- return { requestId: request.id, status: 'pending' as const };
- } catch (error) {
- if (error instanceof Error && error.message === TRANSFER_REQUEST_ALREADY_PENDING) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.TransferRequestPending } },
- code: 'CONFLICT',
- message: 'This agent already has a pending transfer request',
- });
- }
- throw error;
- }
- }
-
- // 3. Validate target workspace access (user must be member+)
- if (input.targetWorkspaceId) {
- const canWriteTarget = await hasWorkspaceScopedPermission({
- action: 'AGENT_CREATE',
- db: ctx.serverDB,
- userId: ctx.userId,
- workspaceId: input.targetWorkspaceId,
- });
-
- if (!canWriteTarget) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.TargetNoWriteAccess } },
- code: 'FORBIDDEN',
- message: 'No write access to target workspace',
- });
- }
- }
-
- // 4. Cannot transfer to the same workspace
- if (input.targetWorkspaceId === ctx.workspaceId) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.SameWorkspace } },
- code: 'BAD_REQUEST',
- message: 'Cannot transfer agent to the same workspace',
- });
- }
-
- // 5. The transfer rehomes every linked topic/message/thread/task β€” only
- // the primary owner may move teammates' conversations along with an
- // agent; co-admins and members may not.
- if (
- ctx.workspaceId &&
- !(await isWorkspacePrimaryOwner({
- db: ctx.serverDB,
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- })) &&
- (await ctx.agentModel.transferHasForeignRows(input.agentId))
- ) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.OwnerOnly } },
- code: 'FORBIDDEN',
- message: "Only the workspace owner can transfer an agent carrying others' conversations",
- });
- }
-
- let result;
- try {
- result = await ctx.agentModel.transferAgent(
- input.agentId,
- input.targetWorkspaceId,
- ctx.userId,
- input.targetVisibility,
- {
- rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx),
- },
- );
- } catch (error) {
- if (
- error instanceof Error &&
- error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS
- ) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.OwnerOnly } },
- code: 'FORBIDDEN',
- message: "Only workspace owners can transfer an agent carrying others' conversations",
- });
- }
- if (error instanceof AgentOwnedByGroupError) {
- throw new TRPCError({
- // The group list travels with the code: "this agent belongs to a
- // group" is only actionable once the user knows which group.
- cause: { data: { code: TransferErrorCode.AgentOwnedByGroup, groups: error.groups } },
- code: 'CONFLICT',
- message: 'This agent belongs to a chat group and cannot be moved on its own',
- });
- }
- if (error instanceof Error && error.message === AGENT_COPY_IN_PROGRESS) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.CopyInProgress } },
- code: 'CONFLICT',
- message: 'A previous copy of this agent is still duplicating its history',
- });
- }
- if (error instanceof Error && error.message === AGENT_TRANSFER_IN_PROGRESS) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.TransferInProgress } },
- code: 'CONFLICT',
- message: 'A previous transfer of this agent is still migrating its history',
- });
- }
- if (error instanceof Error && error.message === AGENT_SHARED_TRANSFER_BLOCKED) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.SharedTransferBlocked } },
- code: 'PRECONDITION_FAILED',
- message:
- 'This agent cannot be transferred while a share link exists, including paused links.',
- });
- }
- throw error;
- }
-
- // Heavy history goes through an async backfill β€” kick the driver now
- // that the transfer transaction has committed.
- if (result.transferJobId) startAgentTransferJob(ctx.serverDB, result.transferJobId);
-
- if (ctx.workspaceId) {
- await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).removeAll(
- 'agent',
- input.agentId,
- );
- // The agent left this workspace β€” a live member-transfer request can
- // no longer be accepted, so void it.
- await new ResourceTransferRequestModel(
- ctx.serverDB,
- ctx.workspaceId,
- ).invalidateForResources('agent', [input.agentId]);
- }
- if (input.targetWorkspaceId && input.targetVisibility === 'public') {
- // A released client's two-valued `viewer` is an explicit "less than
- // editor" choice, so it resolves through the legacy map rather than the
- // default (which is `edit`); saying nothing at all still means "what a
- // newly created agent would get".
- const targetAccessLevel =
- input.targetAccessLevel ??
- (input.targetGeneralAccess
- ? input.targetGeneralAccess === 'editor'
- ? 'edit'
- : LEGACY_VIEWER_ACCESS_LEVELS.agent
- : DEFAULT_RESOURCE_ACCESS_LEVELS.agent);
- await new ResourcePermissionModel(ctx.serverDB, input.targetWorkspaceId).setAccessLevel(
- 'agent',
- input.agentId,
- targetAccessLevel,
- ctx.userId,
- );
- }
-
- return result;
- }),
-
- /**
- * Batch variant of `transferAgent`: one request + one DB transaction for all
- * selected agents, so a multi-select "Move Agent" is no longer N serial
- * round-trips (each with its own permission checks and large-table updates).
- */
- transferAgents: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(
- z.object({
- agentIds: z.array(z.string()).min(1).max(100),
- targetAccessLevel: z.enum(RESOURCE_ACCESS_LEVELS_BY_TYPE.agent).optional(),
- targetVisibility: z.enum(['private', 'public']).optional(),
- targetWorkspaceId: z.string().nullable(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const agentIds = [...new Set(input.agentIds)];
-
- // 1. All agents must exist in the current scope
- const existences = await Promise.all(
- agentIds.map((agentId) => ctx.agentModel.existsById(agentId)),
- );
- if (existences.some((exists) => !exists)) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.ResourceNotFound } },
- code: 'NOT_FOUND',
- message: 'Agent not found',
- });
- }
-
- // 2. Transferring ownership/scope is always creator-only.
- if (ctx.workspaceId) {
- await Promise.all(
- agentIds.map((agentId) =>
- assertCanPerformResourceAction({
- action: 'transfer',
- db: ctx.serverDB,
- resourceId: agentId,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId!,
- }),
- ),
- );
- }
-
- // 3. Validate target workspace access once (user must be member+)
- if (input.targetWorkspaceId) {
- const canWriteTarget = await hasWorkspaceScopedPermission({
- action: 'AGENT_CREATE',
- db: ctx.serverDB,
- userId: ctx.userId,
- workspaceId: input.targetWorkspaceId,
- });
-
- if (!canWriteTarget) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.TargetNoWriteAccess } },
- code: 'FORBIDDEN',
- message: 'No write access to target workspace',
- });
- }
- }
-
- // 4. Cannot transfer to the same workspace
- if (input.targetWorkspaceId === ctx.workspaceId) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.SameWorkspace } },
- code: 'BAD_REQUEST',
- message: 'Cannot transfer agent to the same workspace',
- });
- }
-
- // 5. The transfer rehomes every linked topic/message/thread/task β€” only
- // the primary owner may move teammates' conversations along with
- // agents. One batched check for the whole selection.
- if (
- ctx.workspaceId &&
- !(await isWorkspacePrimaryOwner({
- db: ctx.serverDB,
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- })) &&
- (await ctx.agentModel.transferHasForeignRows(agentIds))
- ) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.OwnerOnly } },
- code: 'FORBIDDEN',
- message: "Only the workspace owner can transfer an agent carrying others' conversations",
- });
- }
-
- let results;
- try {
- results = await ctx.agentModel.transferAgents(
- agentIds,
- input.targetWorkspaceId,
- ctx.userId,
- input.targetVisibility,
- {
- rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx),
- },
- );
- } catch (error) {
- if (
- error instanceof Error &&
- error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS
- ) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.OwnerOnly } },
- code: 'FORBIDDEN',
- message: "Only workspace owners can transfer agents carrying others' conversations",
- });
- }
- if (error instanceof AgentOwnedByGroupError) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.AgentOwnedByGroup, groups: error.groups } },
- code: 'CONFLICT',
- message: 'One of these agents belongs to a chat group and cannot be moved on its own',
- });
- }
- if (error instanceof Error && error.message === AGENT_COPY_IN_PROGRESS) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.CopyInProgress } },
- code: 'CONFLICT',
- message: 'A previous copy of this agent is still duplicating its history',
- });
- }
- if (error instanceof Error && error.message === AGENT_TRANSFER_IN_PROGRESS) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.TransferInProgress } },
- code: 'CONFLICT',
- message: 'A previous transfer of these agents is still migrating their history',
- });
- }
- if (error instanceof Error && error.message === AGENT_SHARED_TRANSFER_BLOCKED) {
- throw new TRPCError({
- cause: { data: { code: TransferErrorCode.SharedTransferBlocked } },
- code: 'PRECONDITION_FAILED',
- message:
- 'These agents cannot be transferred while a share link exists, including paused links.',
- });
- }
- throw error;
- }
-
- // The whole batch shares one backfill job; kick it post-commit.
- const batchTransferJobId = results[0]?.transferJobId;
- if (batchTransferJobId) startAgentTransferJob(ctx.serverDB, batchTransferJobId);
-
- if (ctx.workspaceId) {
- const sourcePermissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
- await Promise.all(
- agentIds.map((agentId) => sourcePermissionModel.removeAll('agent', agentId)),
- );
- // The agents left this workspace β€” void any live member-transfer requests.
- await new ResourceTransferRequestModel(
- ctx.serverDB,
- ctx.workspaceId,
- ).invalidateForResources('agent', agentIds);
- }
- if (input.targetWorkspaceId && input.targetVisibility === 'public') {
- const targetAccessLevel = input.targetAccessLevel ?? DEFAULT_RESOURCE_ACCESS_LEVELS.agent;
- const targetPermissionModel = new ResourcePermissionModel(
- ctx.serverDB,
- input.targetWorkspaceId,
- );
- await Promise.all(
- agentIds.map((agentId) =>
- targetPermissionModel.setAccessLevel('agent', agentId, targetAccessLevel, ctx.userId),
- ),
- );
- }
-
- return results;
- }),
-
- updateAgentConfig: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(
- z.object({
- agentId: z.string(),
- // Transport-only opt-in; old clients send cached complete device maps.
- replaceWorkingDirDeviceIds: z.array(z.string()).optional(),
- value: z.object({}).passthrough().partial(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- // General-access write guard: only `edit` permits collaborative updates.
- await assertCanEditResource({
- db: ctx.serverDB,
- resourceId: input.agentId,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId ?? undefined,
- });
-
- let safeValue = input.value;
-
- // Model / execution-environment / topic-share policies govern every member.
- // Only the creator or workspace primary owner may write them; other
- // collaborators send a fully merged agencyConfig, so strip the protected
- // keys instead of comparing and later merging stale values over a newer
- // owner update.
- if (ctx.workspaceId) {
- const policyPatch = getAgentPermissionPolicyPatch(input.value);
-
- if (policyPatch) {
- const canUpdatePolicies =
- (await ctx.agentModel.existsOwnedById(input.agentId)) ||
- (await isWorkspacePrimaryOwner({
- db: ctx.serverDB,
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- }));
-
- if (!canUpdatePolicies) safeValue = stripAgentPermissionPolicies(input.value);
- }
- }
-
- // Collaborative edit lock: reject writes to a workspace agent another
- // member is actively editing. Inert until a client acquires the lock.
- if (ctx.workspaceId) {
- const blockedBy = await ctx.editLockService.getBlockingHolder('agent', input.agentId);
- if (blockedBy) {
- throw new TRPCError({
- cause: { data: { code: 'DocumentLocked' } },
- code: 'CONFLICT',
- message: 'Agent is being edited by another user',
- });
- }
- }
-
- // Use AgentService to update and return the updated agent data
- return ctx.agentService.updateAgentConfig(
- input.agentId,
- safeValue,
- input.replaceWorkingDirDeviceIds,
- );
- }),
-
- /**
- * Resolve a slug to its agent id so `/agent/:slug` can open the agent.
- *
- * Read-only and ownership-scoped: an unknown slug and someone else's slug both
- * return `null`, so this cannot be used to probe which slugs exist.
- */
- resolveAgentIdBySlug: agentProcedure
- .input(z.object({ slug: z.string() }))
- .query(async ({ input, ctx }) => {
- const agentId = await ctx.agentModel.resolveIdBySlug(input.slug);
- return { agentId };
- }),
-
- /**
- * Compatibility endpoint for released clients that still resolve their
- * agent routes here. Keep ownership-scoped lookup behavior so those clients
- * can open their own agents without restoring share-link routing.
- *
- * @deprecated New clients resolve slugs with `resolveAgentIdBySlug`.
- *
- * Resolution order, cheapest first:
- * 1. an id-shaped param is always an own-agent route (no query at all);
- * 2. an ownership-scoped agent-slug lookup;
- * 3. otherwise `notFound`.
- *
- * The slug lookup is ownership-scoped on purpose: a stranger's slug reads as
- * `notFound`, so this resolver cannot be used to probe which slugs exist.
- */
- resolveAgentRoute: agentProcedure
- .input(z.object({ slugOrId: z.string().trim().min(1) }))
- .query(async ({ input, ctx }): Promise<AgentRouteResolution> => {
- const { slugOrId } = input;
-
- // Every generated agent id carries an underscore (`agt_…`) and no
- // generated slug does, so the shape alone settles this case. A bogus
- // id still routes to the own-agent shell, which owns the not-found UI.
- if (slugOrId.includes('_')) return { agentId: slugOrId, kind: 'own' };
-
- const agentId = await ctx.agentModel.resolveIdBySlug(slugOrId);
- if (agentId) return { agentId, kind: 'own' };
-
- return { kind: 'notFound' };
- }),
-
- /**
- * Rename an agent's url slug. Separate from `updateAgentConfig` because `slug`
- * is immutable there by design β€” see `IMMUTABLE_AGENT_FIELDS`.
- */
- updateAgentSlug: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(z.object({ agentId: z.string(), slug: z.string() }))
- .mutation(async ({ input, ctx }) => {
- await assertCanEditResource({
- db: ctx.serverDB,
- resourceId: input.agentId,
- resourceType: 'agent',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId ?? undefined,
- });
-
- return ctx.agentModel.updateSlug(input.agentId, input.slug);
- }),
-
- /**
- * Pin or unpin an agent
- */
- updateAgentPinned: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(
- z.object({
- id: z.string(),
- pinned: z.boolean(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- return ctx.agentModel.update(input.id, { pinned: input.pinned });
- }),
-
- acquireAgentLock: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(z.object({ agentId: z.string() }))
- .mutation(async ({ ctx, input }) => {
- if (!ctx.workspaceId) return { expiresAt: null, holderId: null, lockedByOther: false };
- const prev = await ctx.editLockService.getActiveHolder('agent', input.agentId);
- const result = await ctx.editLockService.acquire('agent', input.agentId);
- if ((result.holderId ?? null) !== (prev ?? null)) {
- void publishResourceEvent(
- { id: input.agentId, type: 'agent' },
- { actorId: ctx.userId, data: { holderId: result.holderId }, type: 'lock.changed' },
- );
- }
- return result;
- }),
-
- getAgentLock: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(z.object({ agentId: z.string() }))
- .query(async ({ ctx, input }) => {
- if (!ctx.workspaceId) return { expiresAt: null, holderId: null, lockedByOther: false };
- const holder = await ctx.editLockService.getActiveHolder('agent', input.agentId);
- return {
- expiresAt: null,
- holderId: holder ?? null,
- lockedByOther: Boolean(holder) && holder !== ctx.userId,
- };
- }),
-
- releaseAgentLock: agentProcedure
- .use(withScopedPermission('agent:update'))
- .input(z.object({ agentId: z.string() }))
- .mutation(async ({ ctx, input }) => {
- if (!ctx.workspaceId) return;
- // Only broadcast "unlocked" when we actually released our own lock β€” if the
- // lease expired and another member took over, the lock is still held.
- const released = await ctx.editLockService.release('agent', input.agentId);
- if (!released) return;
- void publishResourceEvent(
- { id: input.agentId, type: 'agent' },
- { actorId: ctx.userId, data: { holderId: null }, type: 'lock.changed' },
- );
- }),
-});
diff --git a/apps/server/src/routers/lambda/agent/config.ts b/apps/server/src/routers/lambda/agent/config.ts
new file mode 100644
index 00000000000..f7348f59502
--- /dev/null
+++ b/apps/server/src/routers/lambda/agent/config.ts
@@ -0,0 +1,181 @@
+import { DEFAULT_AGENT_CONFIG, INBOX_SESSION_ID } from '@lobechat/const';
+import { AGENT_PERMISSION_POLICY_KEYS } from '@lobechat/types';
+import { isRecord } from '@lobechat/utils/object';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { UserModel } from '@/database/models/user';
+import { router } from '@/libs/trpc/lambda';
+import { assertCanEditResource } from '@/server/services/resourcePermission';
+import { isWorkspacePrimaryOwner } from '@/server/services/workspacePermission';
+
+import { getResourceConfigAccess, redactAgentConfig } from '../_helpers/resourceConfigGuard';
+import { agentProcedure } from './procedures';
+
+const getAgentPermissionPolicyPatch = (value: Record<string, unknown>) => {
+ const agencyConfig = value.agencyConfig;
+
+ return isRecord(agencyConfig) && AGENT_PERMISSION_POLICY_KEYS.some((key) => key in agencyConfig)
+ ? agencyConfig
+ : null;
+};
+
+const stripAgentPermissionPolicies = (value: Record<string, unknown>) => {
+ const policyPatch = getAgentPermissionPolicyPatch(value);
+ if (!policyPatch) return value;
+
+ const {
+ executionTargetSelectionPolicy: _executionTargetSelectionPolicy,
+ modelSelectionPolicy: _modelSelectionPolicy,
+ topicSharePolicy: _topicSharePolicy,
+ ...safeAgencyConfig
+ } = policyPatch;
+
+ return { ...value, agencyConfig: safeAgencyConfig };
+};
+
+const protectAgentConfig = async <T extends Record<string, any>>(
+ ctx: {
+ serverDB: Parameters<typeof getResourceConfigAccess>[0]['db'];
+ userId: string;
+ workspaceId?: string | null;
+ workspacePermissionCodes?: string[];
+ },
+ agentId: string,
+ config: T | null | undefined,
+): Promise<T | null> => {
+ if (!config) return null;
+
+ const access = await getResourceConfigAccess(
+ {
+ db: ctx.serverDB,
+ grantedPermissions: ctx.workspacePermissionCodes,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ },
+ 'agent',
+ agentId,
+ );
+
+ if (access === 'none') return null;
+ return access === 'profile' ? redactAgentConfig(config) : config;
+};
+
+export const configRouter = router({
+ getAgentConfig: agentProcedure
+ .input(
+ z.object({
+ sessionId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ if (input.sessionId === INBOX_SESSION_ID) {
+ const item = await ctx.sessionModel.findByIdOrSlug(INBOX_SESSION_ID);
+ // if there is no session for user, create one
+ if (!item) {
+ // if there is no user, return default config
+ const user = await UserModel.findById(ctx.serverDB, ctx.userId);
+ if (!user) return DEFAULT_AGENT_CONFIG;
+
+ const res = await ctx.agentService.createInbox();
+ console.info('create inbox session', res);
+ }
+ }
+
+ const session = await ctx.sessionModel.findByIdOrSlug(input.sessionId);
+
+ if (!session) throw new Error(`Session [${input.sessionId}] not found`);
+ const sessionId = session.id;
+
+ const config = await ctx.agentModel.findBySessionId(sessionId);
+ return config?.id ? protectAgentConfig(ctx, config.id, config) : config;
+ }),
+ getAgentConfigById: agentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ const config = await ctx.agentService.getAgentConfigById(input.agentId);
+ return protectAgentConfig(ctx, input.agentId, config);
+ }),
+ /**
+ * Get a builtin agent by slug, creating it if it doesn't exist.
+ * This is a generic interface for all builtin agents (page-copilot, inbox, etc.)
+ */
+ getBuiltinAgent: agentProcedure
+ .input(
+ z.object({
+ slug: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ const config = await ctx.agentService.getBuiltinAgent(input.slug);
+ return config?.id ? protectAgentConfig(ctx, config.id, config) : config;
+ }),
+ updateAgentConfig: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(
+ z.object({
+ agentId: z.string(),
+ // Transport-only opt-in; old clients send cached complete device maps.
+ replaceWorkingDirDeviceIds: z.array(z.string()).optional(),
+ value: z.object({}).passthrough().partial(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ // General-access write guard: only `edit` permits collaborative updates.
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
+ let safeValue = input.value;
+
+ // Model / execution-environment / topic-share policies govern every member.
+ // Only the creator or workspace primary owner may write them; other
+ // collaborators send a fully merged agencyConfig, so strip the protected
+ // keys instead of comparing and later merging stale values over a newer
+ // owner update.
+ if (ctx.workspaceId) {
+ const policyPatch = getAgentPermissionPolicyPatch(input.value);
+
+ if (policyPatch) {
+ const canUpdatePolicies =
+ (await ctx.agentModel.existsOwnedById(input.agentId)) ||
+ (await isWorkspacePrimaryOwner({
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ }));
+
+ if (!canUpdatePolicies) safeValue = stripAgentPermissionPolicies(input.value);
+ }
+ }
+
+ // Collaborative edit lock: reject writes to a workspace agent another
+ // member is actively editing. Inert until a client acquires the lock.
+ if (ctx.workspaceId) {
+ const blockedBy = await ctx.editLockService.getBlockingHolder('agent', input.agentId);
+ if (blockedBy) {
+ throw new TRPCError({
+ cause: { data: { code: 'DocumentLocked' } },
+ code: 'CONFLICT',
+ message: 'Agent is being edited by another user',
+ });
+ }
+ }
+
+ // Use AgentService to update and return the updated agent data
+ return ctx.agentService.updateAgentConfig(
+ input.agentId,
+ safeValue,
+ input.replaceWorkingDirDeviceIds,
+ );
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agent/editLock.ts b/apps/server/src/routers/lambda/agent/editLock.ts
new file mode 100644
index 00000000000..5425ec57b76
--- /dev/null
+++ b/apps/server/src/routers/lambda/agent/editLock.ts
@@ -0,0 +1,51 @@
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { router } from '@/libs/trpc/lambda';
+import { publishResourceEvent } from '@/server/services/resourceEvents';
+
+import { agentProcedure } from './procedures';
+
+export const editLockRouter = router({
+ acquireAgentLock: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(z.object({ agentId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ if (!ctx.workspaceId) return { expiresAt: null, holderId: null, lockedByOther: false };
+ const prev = await ctx.editLockService.getActiveHolder('agent', input.agentId);
+ const result = await ctx.editLockService.acquire('agent', input.agentId);
+ if ((result.holderId ?? null) !== (prev ?? null)) {
+ void publishResourceEvent(
+ { id: input.agentId, type: 'agent' },
+ { actorId: ctx.userId, data: { holderId: result.holderId }, type: 'lock.changed' },
+ );
+ }
+ return result;
+ }),
+ getAgentLock: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(z.object({ agentId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ if (!ctx.workspaceId) return { expiresAt: null, holderId: null, lockedByOther: false };
+ const holder = await ctx.editLockService.getActiveHolder('agent', input.agentId);
+ return {
+ expiresAt: null,
+ holderId: holder ?? null,
+ lockedByOther: Boolean(holder) && holder !== ctx.userId,
+ };
+ }),
+ releaseAgentLock: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(z.object({ agentId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ if (!ctx.workspaceId) return;
+ // Only broadcast "unlocked" when we actually released our own lock β€” if the
+ // lease expired and another member took over, the lock is still held.
+ const released = await ctx.editLockService.release('agent', input.agentId);
+ if (!released) return;
+ void publishResourceEvent(
+ { id: input.agentId, type: 'agent' },
+ { actorId: ctx.userId, data: { holderId: null }, type: 'lock.changed' },
+ );
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agent/index.procedures.test.ts b/apps/server/src/routers/lambda/agent/index.procedures.test.ts
new file mode 100644
index 00000000000..067f2a43380
--- /dev/null
+++ b/apps/server/src/routers/lambda/agent/index.procedures.test.ts
@@ -0,0 +1,64 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { agentRouter } from '.';
+
+/**
+ * Pins the router's public surface: every procedure path, its kind, and its
+ * middleware chain length (which encodes the procedure builder and its input
+ * parsers). Splitting the router across files must keep all three.
+ */
+describe('agentRouter procedures', () => {
+ const procedures = (agentRouter as any)._def.procedures as Record<string, any>;
+
+ it('exposes exactly the expected procedure paths', () => {
+ expect(Object.keys(procedures).sort()).toEqual(expected().map(([name]) => name));
+ });
+
+ it.each(expected())('%s is a %s with %i middlewares', (name, type, middlewares) => {
+ expect(procedures[name]._def.type).toBe(type);
+ expect(procedures[name]._def.middlewares).toHaveLength(middlewares);
+ });
+});
+
+function expected(): Array<
+ [name: string, type: 'mutation' | 'query' | 'subscription', middlewares: number]
+> {
+ return [
+ ['acquireAgentLock', 'mutation', 13],
+ ['checkByMarketIdentifier', 'query', 12],
+ ['countAgents', 'query', 12],
+ ['createAgent', 'mutation', 13],
+ ['createAgentFiles', 'mutation', 13],
+ ['createAgentKnowledgeBase', 'mutation', 13],
+ ['createAgentOnly', 'mutation', 13],
+ ['deleteAgentFile', 'mutation', 13],
+ ['deleteAgentKnowledgeBase', 'mutation', 13],
+ ['duplicateAgent', 'mutation', 13],
+ ['getAgentByForkedFromIdentifier', 'query', 12],
+ ['getAgentByMarketIdentifier', 'query', 12],
+ ['getAgentConfig', 'query', 12],
+ ['getAgentConfigById', 'query', 12],
+ ['getAgentLock', 'query', 13],
+ ['getBuiltinAgent', 'query', 12],
+ ['getGroupMembershipImpact', 'query', 12],
+ ['getKnowledgeBasesAndFiles', 'query', 12],
+ ['getTransferJobStatus', 'query', 12],
+ ['prioritizeTransferTopic', 'mutation', 12],
+ ['publishAgentToWorkspace', 'mutation', 13],
+ ['queryAgents', 'query', 12],
+ ['rankAgents', 'query', 12],
+ ['releaseAgentLock', 'mutation', 13],
+ ['removeAgent', 'mutation', 13],
+ ['resolveAgentIdBySlug', 'query', 12],
+ ['resolveAgentRoute', 'query', 12],
+ ['setAgentVisibility', 'mutation', 13],
+ ['toggleFile', 'mutation', 13],
+ ['toggleKnowledgeBase', 'mutation', 13],
+ ['transferAgent', 'mutation', 13],
+ ['transferAgents', 'mutation', 13],
+ ['updateAgentConfig', 'mutation', 13],
+ ['updateAgentPinned', 'mutation', 13],
+ ['updateAgentSlug', 'mutation', 13],
+ ];
+}
diff --git a/apps/server/src/routers/lambda/agent/index.ts b/apps/server/src/routers/lambda/agent/index.ts
new file mode 100644
index 00000000000..459439029d4
--- /dev/null
+++ b/apps/server/src/routers/lambda/agent/index.ts
@@ -0,0 +1,21 @@
+import { mergeRouters } from '@/libs/trpc/lambda';
+
+import { configRouter } from './config';
+import { editLockRouter } from './editLock';
+import { knowledgeRouter } from './knowledge';
+import { lifecycleRouter } from './lifecycle';
+import { routingRouter } from './routing';
+import { transferRouter } from './transfer';
+import { visibilityRouter } from './visibility';
+
+export type { AgentRouteResolution } from './routing';
+
+export const agentRouter = mergeRouters(
+ lifecycleRouter,
+ visibilityRouter,
+ knowledgeRouter,
+ configRouter,
+ transferRouter,
+ routingRouter,
+ editLockRouter,
+);
diff --git a/apps/server/src/routers/lambda/agent/knowledge.ts b/apps/server/src/routers/lambda/agent/knowledge.ts
new file mode 100644
index 00000000000..fad5f05bf1d
--- /dev/null
+++ b/apps/server/src/routers/lambda/agent/knowledge.ts
@@ -0,0 +1,246 @@
+import type { KnowledgeItem } from '@lobechat/types';
+import { KnowledgeType } from '@lobechat/types';
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { router } from '@/libs/trpc/lambda';
+import {
+ assertCanEditResource,
+ assertCanPerformResourceAction,
+} from '@/server/services/resourcePermission';
+
+import {
+ getRestrictedKnowledgeBaseIds,
+ getUseLevelKnowledgeBaseIds,
+} from '../_helpers/knowledgeBaseAccess';
+import { agentProcedure } from './procedures';
+
+export const knowledgeRouter = router({
+ createAgentFiles: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(
+ z.object({
+ agentId: z.string(),
+ enabled: z.boolean().optional(),
+ fileIds: z.array(z.string()),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+ return ctx.agentModel.createAgentFiles(input.agentId, input.fileIds, input.enabled);
+ }),
+ createAgentKnowledgeBase: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(
+ z.object({
+ agentId: z.string(),
+ enabled: z.boolean().optional(),
+ knowledgeBaseId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+ return ctx.agentModel.createAgentKnowledgeBase(
+ input.agentId,
+ input.knowledgeBaseId,
+ input.enabled,
+ );
+ }),
+ deleteAgentFile: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(
+ z.object({
+ agentId: z.string(),
+ fileId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+ return ctx.agentModel.deleteAgentFile(input.agentId, input.fileId);
+ }),
+ deleteAgentKnowledgeBase: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(
+ z.object({
+ agentId: z.string(),
+ knowledgeBaseId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+ return ctx.agentModel.deleteAgentKnowledgeBase(input.agentId, input.knowledgeBaseId);
+ }),
+ getKnowledgeBasesAndFiles: agentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ visibility: z.enum(['private', 'public']).optional(),
+ }),
+ )
+ .query(async ({ ctx, input }): Promise<KnowledgeItem[]> => {
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
+ // Look up the target agent's visibility so we can (a) apply the
+ // "public agent cannot reach caller's private rows" defensive filter
+ // in the model layer, and (b) hard-force `visibility='public'` when
+ // the agent is public β€” the client tab is a UX aid, not a gate.
+ const agentVisibility = await ctx.agentModel.getAgentVisibility(input.agentId);
+
+ // `visibility` is workspace-scoped. In personal mode buildWorkspaceWhere
+ // ignores the column entirely (every row is implicitly private to its
+ // owner) while the column still defaults to 'public', so forcing a scope
+ // here would filter personal rows by a value that carries no meaning.
+ // Only workspace agents get a visibility scope.
+ const effectiveVisibility = ctx.workspaceId
+ ? agentVisibility === 'public'
+ ? ('public' as const)
+ : input.visibility
+ : undefined;
+
+ const knowledgeBases = await ctx.knowledgeBaseModel.query({
+ callerAgentVisibility: agentVisibility,
+ visibility: effectiveVisibility,
+ });
+
+ const files = await ctx.fileModel.query({
+ callerAgentVisibility: agentVisibility,
+ showFilesInKnowledgeBase: false,
+ visibility: effectiveVisibility,
+ });
+
+ const knowledge = await ctx.agentModel.getAgentAssignedKnowledge(input.agentId);
+
+ // Member-restricted (No-access) KBs disappear from the picker for
+ // non-privileged members, except ones already attached to this agent β€”
+ // an invisible-but-attached row would be impossible to unmount. Managers
+ // keep seeing them, with a flag so the client can badge the icon.
+ const [restrictedForCaller, useLevelIds] = ctx.workspaceId
+ ? await Promise.all([
+ getRestrictedKnowledgeBaseIds(ctx),
+ getUseLevelKnowledgeBaseIds(ctx.serverDB, ctx.workspaceId),
+ ])
+ : [[], []];
+ const restrictedSet = new Set(restrictedForCaller);
+ const memberRestrictedSet = new Set(useLevelIds);
+ const visibleKnowledgeBases = knowledgeBases.filter(
+ (kb) =>
+ !restrictedSet.has(kb.id) || knowledge.knowledgeBases.some((item) => item.id === kb.id),
+ );
+
+ return [
+ ...files
+ // Filter out all images
+ .filter((file) => !file.fileType.startsWith('image'))
+ .map((file) => ({
+ enabled: knowledge.files.some((item) => item.id === file.id),
+ fileType: file.fileType,
+ id: file.id,
+ name: file.name,
+ ownerUserId: file.userId,
+ type: KnowledgeType.File,
+ visibility: file.visibility as 'private' | 'public',
+ })),
+ ...visibleKnowledgeBases.map((knowledgeBase) => ({
+ avatar: knowledgeBase.avatar,
+ description: knowledgeBase.description,
+ enabled: knowledge.knowledgeBases.some((item) => item.id === knowledgeBase.id),
+ id: knowledgeBase.id,
+ memberRestricted: memberRestrictedSet.has(knowledgeBase.id),
+ name: knowledgeBase.name,
+ ownerUserId: knowledgeBase.userId,
+ type: KnowledgeType.KnowledgeBase,
+ visibility: knowledgeBase.visibility,
+ })),
+ ];
+ }),
+ toggleFile: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(
+ z.object({
+ agentId: z.string(),
+ enabled: z.boolean().optional(),
+ fileId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+ return ctx.agentModel.toggleFile(input.agentId, input.fileId, input.enabled);
+ }),
+ toggleKnowledgeBase: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(
+ z.object({
+ agentId: z.string(),
+ enabled: z.boolean().optional(),
+ knowledgeBaseId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+ return ctx.agentModel.toggleKnowledgeBase(
+ input.agentId,
+ input.knowledgeBaseId,
+ input.enabled,
+ );
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agent/lifecycle.ts b/apps/server/src/routers/lambda/agent/lifecycle.ts
new file mode 100644
index 00000000000..e64e5240b5b
--- /dev/null
+++ b/apps/server/src/routers/lambda/agent/lifecycle.ts
@@ -0,0 +1,319 @@
+import { CreateAgentSchema } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { AGENT_COPY_IN_PROGRESS } from '@/database/models/agentCopyJob';
+import { AGENT_TRANSFER_IN_PROGRESS } from '@/database/models/agentTransferJob';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import { ResourceTransferRequestModel } from '@/database/models/resourceTransferRequest';
+import { DEFAULT_RESOURCE_ACCESS_LEVELS } from '@/database/schemas';
+import { router } from '@/libs/trpc/lambda';
+import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
+import { TrashService } from '@/server/services/trash';
+import { TransferErrorCode } from '@/types/transferError';
+
+import { isWorkspaceNonOwner } from '../_helpers/assertWorkspaceRowManageable';
+import { agentProcedure } from './procedures';
+
+export const lifecycleRouter = router({
+ /**
+ * Check if an agent with the given marketIdentifier already exists
+ */
+ checkByMarketIdentifier: agentProcedure
+ .input(
+ z.object({
+ marketIdentifier: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.agentModel.checkByMarketIdentifier(input.marketIdentifier);
+ }),
+ /**
+ * Count the agents matching the conditions of queryAgents β€” other virtual
+ * rows excluded, and the inbox (Lobe AI) counted only when the caller passes
+ * `includeInbox: true`. Lets paginated callers report real totals.
+ */
+ countAgents: agentProcedure
+ .input(
+ z
+ .object({
+ endDate: z.string().optional(),
+ includeInbox: z.boolean().optional(),
+ keyword: z.string().optional(),
+ range: z.tuple([z.string(), z.string()]).optional(),
+ startDate: z.string().optional(),
+ })
+ .optional(),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.agentModel.countAgents(input);
+ }),
+ /**
+ * Create a new agent with session
+ * Returns the created agent ID and session ID
+ */
+ createAgent: agentProcedure
+ .use(withScopedPermission('agent:create'))
+ .input(
+ z.object({
+ config: CreateAgentSchema.optional(),
+ groupId: z.string().optional(),
+ visibility: z.enum(['private', 'public']).optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ // Creating inside a Category has to land in that Category. The folder's
+ // visibility decides the new agent's, rather than the other way round:
+ // the sidebar resolves a public agent's folder only against public
+ // folders (and a private agent's only against private ones), so a
+ // default-public agent created from a private Category would render in
+ // Ungrouped β€” for its creator too. The "New Agent" action inside a
+ // private Category sends only `{ groupId }`, so this is the normal path,
+ // not a crafted one. An explicit conflicting `visibility` is refused
+ // rather than silently overridden.
+ const folderVisibility = input.groupId
+ ? await ctx.agentModel.getAssignableSessionGroupVisibility(input.groupId)
+ : undefined;
+
+ if (folderVisibility && input.visibility && input.visibility !== folderVisibility)
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `A ${input.visibility} agent cannot be created in a ${folderVisibility} folder`,
+ });
+
+ const agent = await ctx.agentModel.create({
+ ...input.config,
+ // The DB-layer AgentItem (packages/database/src/schemas/agent.ts) is
+ // intentionally still typed `plugins?: string[]` β€” the JSONB column
+ // itself isn't widened, only the domain-level `@lobechat/types`
+ // shapes. Bridges the tri-state object shape through.
+ plugins: input.config?.plugins as unknown as string[] | undefined,
+ sessionGroupId: input.groupId,
+ // Router-level `visibility` wins over any nested config value so the
+ // sidebar's "Create in Private" entry can't be overridden by a stale
+ // default config.
+ ...(input.visibility || folderVisibility
+ ? { visibility: input.visibility ?? folderVisibility }
+ : {}),
+ });
+
+ if (ctx.workspaceId && agent.visibility !== 'private') {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
+ 'agent',
+ agent.id,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ ctx.userId,
+ );
+ }
+
+ return { agentId: agent.id };
+ }),
+ /**
+ * Create an agent without session.
+ * Used for Group Agent Builder to create agents for groups.
+ * Returns only the agent ID.
+ */
+ createAgentOnly: agentProcedure
+ .use(withScopedPermission('agent:create'))
+ .input(
+ z.object({
+ config: z.object({}).passthrough().optional(),
+ groupId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ // Mutating the group's roster is a group edit β€” same ACL as
+ // `agentGroup.addAgentsToGroup`. Check before creating the agent so a
+ // denied call doesn't leave an orphan agent behind.
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'edit',
+ db: ctx.serverDB,
+ resourceId: input.groupId,
+ resourceType: 'agentGroup',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+
+ // Create the agent entity only (no session)
+ const agent = await ctx.agentModel.create(input.config ?? {});
+
+ // Add the agent to the group
+ await ctx.chatGroupModel.addAgentToGroup(input.groupId, agent.id);
+
+ if (ctx.workspaceId && agent.visibility !== 'private') {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
+ 'agent',
+ agent.id,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ ctx.userId,
+ );
+ }
+
+ return { agentId: agent.id };
+ }),
+ /**
+ * Duplicate an agent and its associated session.
+ * Returns the new agent ID and session ID.
+ */
+ duplicateAgent: agentProcedure
+ .use(withScopedPermission('agent:fork'))
+ .input(
+ z.object({
+ agentId: z.string(),
+ newTitle: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ // Forking creates a caller-owned Agent and is governed by `agent:fork`,
+ // independently of the source Agent's collaborative-edit permission.
+ const result = await ctx.agentModel.duplicate(input.agentId, input.newTitle);
+ if (ctx.workspaceId && result) {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).setAccessLevel(
+ 'agent',
+ result.agentId,
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent,
+ ctx.userId,
+ );
+ }
+ return result;
+ }),
+ /**
+ * Get an agent by forkedFromIdentifier stored in params
+ * @returns agent id if exists, null otherwise
+ */
+ getAgentByForkedFromIdentifier: agentProcedure
+ .input(
+ z.object({
+ forkedFromIdentifier: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.agentModel.getAgentByForkedFromIdentifier(input.forkedFromIdentifier);
+ }),
+ /**
+ * Get an agent by marketIdentifier
+ * @returns agent id if exists, null otherwise
+ */
+ getAgentByMarketIdentifier: agentProcedure
+ .input(
+ z.object({
+ marketIdentifier: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.agentModel.getAgentByMarketIdentifier(input.marketIdentifier);
+ }),
+ /**
+ * Query the user's agents with optional keyword filter β€” other virtual rows
+ * excluded, and the inbox (Lobe AI) included and flagged with `isInbox` only
+ * when the caller passes `includeInbox: true`.
+ * Returns agents with minimal info (id, name, title, description, avatar,
+ * backgroundColor).
+ * Used by AddGroupMemberModal and group-management tool to search/select agents.
+ */
+ queryAgents: agentProcedure
+ .input(
+ z
+ .object({
+ includeInbox: z.boolean().optional(),
+ keyword: z.string().optional(),
+ limit: z.number().max(100).optional(),
+ offset: z.number().optional(),
+ })
+ .optional(),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.agentModel.queryAgents(input);
+ }),
+ rankAgents: agentProcedure.input(z.number().max(50).optional()).query(async ({ ctx, input }) => {
+ return ctx.agentModel.rank(input);
+ }),
+ /**
+ * Remove an agent and its associated session
+ */
+ removeAgent: agentProcedure
+ .use(withScopedPermission('agent:delete'))
+ .input(z.object({ agentId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'delete',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ // Same rule as transfer: the delete cascade erases every linked
+ // session/topic/message, so a non-owner member must not take teammates'
+ // conversations down with their own agent.
+ if (
+ isWorkspaceNonOwner(ctx) &&
+ (await ctx.agentModel.transferHasForeignRows(input.agentId))
+ ) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.OwnerOnly } },
+ code: 'FORBIDDEN',
+ message: "Only workspace owners can delete an agent carrying others' conversations",
+ });
+ }
+ }
+ let result;
+ try {
+ // Recycle bin: the agent, its session shells and every topic under it
+ // are stamped, not dropped β€” the FK cascade only runs at purge time.
+ result = await new TrashService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).trashAgent(input.agentId);
+ } catch (error) {
+ if (error instanceof Error && error.message === AGENT_COPY_IN_PROGRESS) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.CopyInProgress } },
+ code: 'CONFLICT',
+ message: 'A previous copy of this agent is still duplicating its history',
+ });
+ }
+ // A backfill still maps this agent's message rows β€” deleting it now
+ // would strand the job on a dangling `messages.agent_id`.
+ if (error instanceof Error && error.message === AGENT_TRANSFER_IN_PROGRESS) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.TransferInProgress } },
+ code: 'CONFLICT',
+ message: "A previous transfer of this agent's history is still migrating",
+ });
+ }
+ throw error;
+ }
+ // Sharing grants are left in place while the agent sits in the bin (the
+ // row is invisible anyway) so a restore brings them back; the purge
+ // handler removes them for good. A pending handover is different: the
+ // agent is invisible to the recipient too, so an acceptance would move
+ // ownership of trashed content β€” void it now, as the hard delete did.
+ if (ctx.workspaceId) {
+ await new ResourceTransferRequestModel(
+ ctx.serverDB,
+ ctx.workspaceId,
+ ).invalidateForResources('agent', [input.agentId]);
+ }
+ return result;
+ }),
+ /**
+ * Pin or unpin an agent
+ */
+ updateAgentPinned: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(
+ z.object({
+ id: z.string(),
+ pinned: z.boolean(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ return ctx.agentModel.update(input.id, { pinned: input.pinned });
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agent/procedures.ts b/apps/server/src/routers/lambda/agent/procedures.ts
new file mode 100644
index 00000000000..0e0ac9b3325
--- /dev/null
+++ b/apps/server/src/routers/lambda/agent/procedures.ts
@@ -0,0 +1,26 @@
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { AgentModel } from '@/database/models/agent';
+import { ChatGroupModel } from '@/database/models/chatGroup';
+import { FileModel } from '@/database/models/file';
+import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
+import { SessionModel } from '@/database/models/session';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { AgentService } from '@/server/services/agent';
+import { EditLockService } from '@/server/services/editLock';
+
+export const agentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ const wsId = ctx.workspaceId ?? undefined;
+
+ return opts.next({
+ ctx: {
+ agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),
+ agentService: new AgentService(ctx.serverDB, ctx.userId, wsId),
+ chatGroupModel: new ChatGroupModel(ctx.serverDB, ctx.userId, wsId),
+ editLockService: new EditLockService(ctx.userId),
+ fileModel: new FileModel(ctx.serverDB, ctx.userId, wsId),
+ knowledgeBaseModel: new KnowledgeBaseModel(ctx.serverDB, ctx.userId, wsId),
+ sessionModel: new SessionModel(ctx.serverDB, ctx.userId, wsId),
+ },
+ });
+});
diff --git a/apps/server/src/routers/lambda/agent/routing.ts b/apps/server/src/routers/lambda/agent/routing.ts
new file mode 100644
index 00000000000..496f28b2002
--- /dev/null
+++ b/apps/server/src/routers/lambda/agent/routing.ts
@@ -0,0 +1,82 @@
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { router } from '@/libs/trpc/lambda';
+import { assertCanEditResource } from '@/server/services/resourcePermission';
+
+import { agentProcedure } from './procedures';
+
+/** What a `/agent/:slugOrId` param resolves to β€” see `resolveAgentRoute`. */
+export interface AgentRouteResolution {
+ /** The resolved agent id. Present for `own` routes. */
+ agentId?: string;
+ /**
+ * `own`: one of the caller's agents (by id or by agent slug).
+ * `notFound`: no agent of the caller's claims the param β€” the caller sees
+ * the agent not-found surface.
+ */
+ kind: 'own' | 'notFound';
+}
+
+export const routingRouter = router({
+ /**
+ * Resolve a slug to its agent id so `/agent/:slug` can open the agent.
+ *
+ * Read-only and ownership-scoped: an unknown slug and someone else's slug both
+ * return `null`, so this cannot be used to probe which slugs exist.
+ */
+ resolveAgentIdBySlug: agentProcedure
+ .input(z.object({ slug: z.string() }))
+ .query(async ({ input, ctx }) => {
+ const agentId = await ctx.agentModel.resolveIdBySlug(input.slug);
+ return { agentId };
+ }),
+ /**
+ * Compatibility endpoint for released clients that still resolve their
+ * agent routes here. Keep ownership-scoped lookup behavior so those clients
+ * can open their own agents without restoring share-link routing.
+ *
+ * @deprecated New clients resolve slugs with `resolveAgentIdBySlug`.
+ *
+ * Resolution order, cheapest first:
+ * 1. an id-shaped param is always an own-agent route (no query at all);
+ * 2. an ownership-scoped agent-slug lookup;
+ * 3. otherwise `notFound`.
+ *
+ * The slug lookup is ownership-scoped on purpose: a stranger's slug reads as
+ * `notFound`, so this resolver cannot be used to probe which slugs exist.
+ */
+ resolveAgentRoute: agentProcedure
+ .input(z.object({ slugOrId: z.string().trim().min(1) }))
+ .query(async ({ input, ctx }): Promise<AgentRouteResolution> => {
+ const { slugOrId } = input;
+
+ // Every generated agent id carries an underscore (`agt_…`) and no
+ // generated slug does, so the shape alone settles this case. A bogus
+ // id still routes to the own-agent shell, which owns the not-found UI.
+ if (slugOrId.includes('_')) return { agentId: slugOrId, kind: 'own' };
+
+ const agentId = await ctx.agentModel.resolveIdBySlug(slugOrId);
+ if (agentId) return { agentId, kind: 'own' };
+
+ return { kind: 'notFound' };
+ }),
+ /**
+ * Rename an agent's url slug. Separate from `updateAgentConfig` because `slug`
+ * is immutable there by design β€” see `IMMUTABLE_AGENT_FIELDS`.
+ */
+ updateAgentSlug: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(z.object({ agentId: z.string(), slug: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ await assertCanEditResource({
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+
+ return ctx.agentModel.updateSlug(input.agentId, input.slug);
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agent/transfer.test.ts b/apps/server/src/routers/lambda/agent/transfer.test.ts
new file mode 100644
index 00000000000..71d12ca01c7
--- /dev/null
+++ b/apps/server/src/routers/lambda/agent/transfer.test.ts
@@ -0,0 +1,147 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentModel } from '@/database/models/agent';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import { ResourceTransferRequestModel } from '@/database/models/resourceTransferRequest';
+import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
+import {
+ hasWorkspaceScopedPermission,
+ isWorkspacePrimaryOwner,
+} from '@/server/services/workspacePermission';
+
+import { transferRouter } from './transfer';
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => ({})) }));
+vi.mock('@/database/models/agent', async (importOriginal) => ({
+ ...((await importOriginal()) as object),
+ AgentModel: vi.fn(),
+}));
+vi.mock('@/database/models/chatGroup', () => ({ ChatGroupModel: vi.fn() }));
+vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));
+vi.mock('@/database/models/knowledgeBase', () => ({ KnowledgeBaseModel: vi.fn() }));
+vi.mock('@/database/models/session', () => ({ SessionModel: vi.fn() }));
+vi.mock('@/server/services/agent', () => ({ AgentService: vi.fn() }));
+vi.mock('@/database/models/resourcePermission', () => ({ ResourcePermissionModel: vi.fn() }));
+vi.mock('@/database/models/resourceTransferRequest', async (importOriginal) => ({
+ ...((await importOriginal()) as object),
+ ResourceTransferRequestModel: vi.fn(),
+}));
+vi.mock('@/business/server/agent-transfer/jobRunner', () => ({
+ prioritizeAgentTransferTopic: vi.fn(),
+ startAgentTransferJob: vi.fn(),
+}));
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanPerformResourceAction: vi.fn(),
+}));
+vi.mock('@/server/services/workspacePermission', () => ({
+ hasWorkspaceScopedPermission: vi.fn(),
+ isWorkspacePrimaryOwner: vi.fn(),
+}));
+
+/** Wraps a mock so it records the peak number of concurrent in-flight calls. */
+const trackInFlight = <T>(result: (id: string) => T) => {
+ const state = { inFlight: 0, peak: 0 };
+ const fn = vi.fn(async (...args: any[]) => {
+ state.inFlight += 1;
+ state.peak = Math.max(state.peak, state.inFlight);
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ state.inFlight -= 1;
+ return result(args.find((arg) => typeof arg === 'string' && arg.startsWith('agent-')));
+ });
+ return { fn, state };
+};
+
+describe('transferRouter.transferAgents', () => {
+ const userId = 'user-1';
+ const agentIds = Array.from({ length: 12 }, (_, i) => `agent-${i}`);
+
+ let existsById: ReturnType<typeof trackInFlight<boolean>>;
+ let assertTransfer: ReturnType<typeof trackInFlight<void>>;
+ let removeAll: ReturnType<typeof trackInFlight<void>>;
+ let setAccessLevel: ReturnType<typeof trackInFlight<void>>;
+ let transferAgents: ReturnType<typeof vi.fn>;
+ let invalidateForResources: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ existsById = trackInFlight(() => true);
+ assertTransfer = trackInFlight(() => undefined);
+ removeAll = trackInFlight(() => undefined);
+ setAccessLevel = trackInFlight(() => undefined);
+ transferAgents = vi.fn(async (ids: string[]) => ids.map((id) => ({ id })));
+ invalidateForResources = vi.fn();
+
+ vi.mocked(AgentModel).mockImplementation(function () {
+ return { existsById: existsById.fn, transferAgents } as any;
+ });
+ vi.mocked(ResourcePermissionModel).mockImplementation(function (_db: any, workspaceId: any) {
+ return workspaceId === 'ws-source'
+ ? ({ removeAll: removeAll.fn } as any)
+ : ({ setAccessLevel: setAccessLevel.fn } as any);
+ });
+ vi.mocked(ResourceTransferRequestModel).mockImplementation(function () {
+ return { invalidateForResources } as any;
+ });
+ vi.mocked(assertCanPerformResourceAction).mockImplementation(assertTransfer.fn as any);
+ vi.mocked(hasWorkspaceScopedPermission).mockResolvedValue(true);
+ vi.mocked(isWorkspacePrimaryOwner).mockResolvedValue(true);
+ });
+
+ const callTransfer = () =>
+ transferRouter.createCaller({ userId, workspaceId: 'ws-source' } as any).transferAgents({
+ agentIds,
+ targetVisibility: 'public',
+ targetWorkspaceId: 'ws-target',
+ });
+
+ it('checks and rehomes every agent with a bounded per-agent fan-out', async () => {
+ const result = await callTransfer();
+
+ expect(result).toEqual(agentIds.map((id) => ({ id })));
+ expect(transferAgents).toHaveBeenCalledWith(
+ agentIds,
+ 'ws-target',
+ userId,
+ 'public',
+ expect.any(Object),
+ );
+ expect(invalidateForResources).toHaveBeenCalledWith('agent', agentIds);
+
+ for (const tracked of [existsById, assertTransfer, removeAll, setAccessLevel]) {
+ expect(tracked.fn).toHaveBeenCalledTimes(agentIds.length);
+ expect(tracked.state.peak).toBeGreaterThan(1);
+ expect(tracked.state.peak).toBeLessThanOrEqual(5);
+ }
+ expect(existsById.fn.mock.calls.map(([id]) => id)).toEqual(agentIds);
+ expect(setAccessLevel.fn).toHaveBeenCalledWith('agent', 'agent-0', 'edit', userId);
+ });
+
+ it('still attempts every target ACL write after the commit when one fails', async () => {
+ const failure = new Error('acl write failed');
+ setAccessLevel.fn.mockImplementation(async (_type: string, agentId: string) => {
+ if (agentId === 'agent-0') throw failure;
+ });
+
+ await expect(callTransfer()).rejects.toThrow('acl write failed');
+ expect(transferAgents).toHaveBeenCalledTimes(1);
+ expect(setAccessLevel.fn).toHaveBeenCalledTimes(agentIds.length);
+ });
+
+ it('still attempts every source ACL cleanup after the commit when one fails', async () => {
+ removeAll.fn.mockImplementation(async (_type: string, agentId: string) => {
+ if (agentId === 'agent-0') throw new Error('cleanup failed');
+ });
+
+ await expect(callTransfer()).rejects.toThrow('cleanup failed');
+ expect(removeAll.fn).toHaveBeenCalledTimes(agentIds.length);
+ });
+
+ it('rejects with NOT_FOUND when any agent is missing, before transferring', async () => {
+ existsById.fn.mockImplementation(async (id: string) => id !== 'agent-7');
+
+ await expect(callTransfer()).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(transferAgents).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/agent/transfer.ts b/apps/server/src/routers/lambda/agent/transfer.ts
new file mode 100644
index 00000000000..2c484694e1c
--- /dev/null
+++ b/apps/server/src/routers/lambda/agent/transfer.ts
@@ -0,0 +1,582 @@
+import { TRPCError } from '@trpc/server';
+import pMap from 'p-map';
+import { z } from 'zod';
+
+import {
+ prioritizeAgentTransferTopic,
+ startAgentTransferJob,
+} from '@/business/server/agent-transfer/jobRunner';
+import { notifyResourceTransfer } from '@/business/server/resource-transfer/notify';
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { AGENT_SHARED_TRANSFER_BLOCKED, AgentOwnedByGroupError } from '@/database/models/agent';
+import { AGENT_COPY_IN_PROGRESS } from '@/database/models/agentCopyJob';
+import {
+ AGENT_TRANSFER_IN_PROGRESS,
+ AgentTransferJobModel,
+} from '@/database/models/agentTransferJob';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import {
+ ResourceTransferRequestModel,
+ TRANSFER_REQUEST_ALREADY_PENDING,
+} from '@/database/models/resourceTransferRequest';
+import { TopicModel } from '@/database/models/topic';
+import { TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS } from '@/database/models/topicComment';
+import {
+ DEFAULT_RESOURCE_ACCESS_LEVELS,
+ LEGACY_VIEWER_ACCESS_LEVELS,
+ RESOURCE_ACCESS_LEVELS_BY_TYPE,
+} from '@/database/schemas';
+import { router } from '@/libs/trpc/lambda';
+import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
+import { assertTransferRecipientValid } from '@/server/services/resourceTransferRequest';
+import {
+ hasWorkspaceScopedPermission,
+ isWorkspacePrimaryOwner,
+} from '@/server/services/workspacePermission';
+import { after } from '@/server/utils/scheduleAfterResponse';
+import { TransferErrorCode } from '@/types/transferError';
+
+import { isWorkspaceNonOwner } from '../_helpers/assertWorkspaceRowManageable';
+import { agentProcedure } from './procedures';
+
+// Caps per-agent DB reads/writes in a batch transfer (up to 100 agents).
+const AGENT_TRANSFER_CONCURRENCY = 5;
+
+/**
+ * Runs post-commit per-agent writes with bounded concurrency. Once the transfer
+ * has committed, every write must still be attempted even if one fails (pMap's
+ * default stop-on-error would skip the unscheduled rest), so each item settles
+ * first and the first failure is rethrown afterwards, as `Promise.all` did.
+ */
+const runAllPostCommit = async (
+ agentIds: string[],
+ write: (agentId: string) => Promise<unknown>,
+): Promise<void> => {
+ const failures = await pMap(
+ agentIds,
+ async (agentId) => {
+ try {
+ await write(agentId);
+ return undefined;
+ } catch (error) {
+ return { error };
+ }
+ },
+ { concurrency: AGENT_TRANSFER_CONCURRENCY },
+ );
+ const failure = failures.find((outcome) => outcome !== undefined);
+ if (failure) throw failure.error;
+};
+
+export const transferRouter = router({
+ /**
+ * Progress of the async history backfill after a heavy transfer, plus the
+ * topic ids still awaiting their scope rewrite (the UI's gray-out set).
+ * Returns null when no backfill is running for the agent.
+ */
+ getTransferJobStatus: agentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ /**
+ * Topics the client currently shows (sidebar rows + active topic).
+ * `pendingTopicIds` is the intersection with the job's queue, keeping
+ * the 3s poll payload bounded however large the backfill is. Required
+ * so no caller can pull the whole queue (this endpoint ships with the
+ * clients that send it β€” there is no released-client compat to keep).
+ */
+ topicIds: z.array(z.string()).max(1000),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ // Scope check: only report migration state for agents visible to the
+ // caller's current personal/workspace scope (agent ids are guessable).
+ const visibility = await ctx.agentModel.getAgentVisibility(input.agentId);
+ if (!visibility) return null;
+
+ const job = await AgentTransferJobModel.findPendingJobForAgent(ctx.serverDB, input.agentId);
+ if (!job) return null;
+ const pendingTopicIds = await AgentTransferJobModel.getPendingTopicIds(
+ ctx.serverDB,
+ job.id,
+ input.topicIds,
+ );
+ return {
+ completedTopics: job.completedTopics,
+ jobId: job.id,
+ pendingTopicIds,
+ totalTopics: job.totalTopics,
+ // `transfer` vs `copy` β€” the client words its progress hints by it.
+ type: job.type,
+ };
+ }),
+ /**
+ * What moving these agents would do to the chat groups they are in.
+ *
+ * Asked before the move, because both outcomes are invisible otherwise: a
+ * transfer drops every group link the agent holds β€” historically without a
+ * word β€” and a group-owned agent cannot be moved at all. The mutation
+ * enforces the second case regardless; this endpoint exists so the user
+ * learns about it while they can still choose differently.
+ */
+ getGroupMembershipImpact: agentProcedure
+ .input(z.object({ agentIds: z.array(z.string()).min(1).max(100) }))
+ .query(async ({ input, ctx }) =>
+ // Reports only on agents the caller can see β€” the model does that scoping
+ // itself, because the guard path deliberately does not.
+ ctx.agentModel.getGroupMembershipImpact(input.agentIds),
+ ),
+ /**
+ * The user opened a topic whose history is still migrating β€” jump it to the
+ * front of the backfill queue. Returns whether the topic was still pending
+ * (false β†’ already migrated, the client can refetch messages immediately).
+ */
+ prioritizeTransferTopic: agentProcedure
+ .input(z.object({ topicId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ // Scope check: reordering the backfill queue is only allowed for topics
+ // the caller can see (the transfer moves topics to the target scope
+ // synchronously, so a pending topic is visible to its new owner).
+ const topic = await new TopicModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).findById(input.topicId);
+ if (!topic) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });
+ }
+
+ const flagged = await prioritizeAgentTransferTopic(ctx.serverDB, input.topicId);
+ return { pending: flagged };
+ }),
+ transferAgent: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(
+ z.object({
+ agentId: z.string(),
+ /**
+ * Cross-workspace move only: the General Access level the agent gets
+ * in the target workspace. Ignored on a member transfer (`targetMemberId`),
+ * which keeps the agent's existing ACL in place.
+ */
+ targetAccessLevel: z.enum(RESOURCE_ACCESS_LEVELS_BY_TYPE.agent).optional(),
+ /** @deprecated Compatibility for released clients. */
+ targetGeneralAccess: z.enum(['editor', 'viewer']).optional(),
+ /**
+ * Hand ownership to another member of the CURRENT workspace. Mutually
+ * exclusive with `targetWorkspaceId`; creates a pending transfer
+ * request the recipient must accept instead of moving anything now.
+ */
+ targetMemberId: z.string().min(1).optional(),
+ targetVisibility: z.enum(['private', 'public']).optional(),
+ targetWorkspaceId: z.string().nullable(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ // 1. Fetch the agent to check ownership
+ const agent = await ctx.agentModel.getAgentConfigById(input.agentId);
+ if (!agent) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.ResourceNotFound } },
+ code: 'NOT_FOUND',
+ message: 'Agent not found',
+ });
+ }
+
+ // 2. Transferring ownership/scope is always creator-only.
+ if (ctx.workspaceId) {
+ await assertCanPerformResourceAction({
+ action: 'transfer',
+ db: ctx.serverDB,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ }
+
+ // 2a. Member transfer: initiate a pending request instead of moving the
+ // agent. Nothing changes until the recipient accepts.
+ if (input.targetMemberId) {
+ if (!ctx.workspaceId || input.targetWorkspaceId) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.TransferNotSupported } },
+ code: 'BAD_REQUEST',
+ message: 'Member transfer happens inside the current workspace',
+ });
+ }
+ // Group-built/virtual rows are workspace infrastructure, not content
+ // someone can personally hand over.
+ if (agent.virtual) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.TransferNotSupported } },
+ code: 'BAD_REQUEST',
+ message: 'This agent cannot be transferred',
+ });
+ }
+ await assertTransferRecipientValid({
+ currentOwnerId: agent.userId,
+ db: ctx.serverDB,
+ initiatorId: ctx.userId,
+ recipientId: input.targetMemberId,
+ workspaceId: ctx.workspaceId,
+ });
+
+ try {
+ const request = await new ResourceTransferRequestModel(
+ ctx.serverDB,
+ ctx.workspaceId,
+ ).create({
+ initiatorId: ctx.userId,
+ previousOwnerId: agent.userId,
+ recipientId: input.targetMemberId,
+ resourceId: input.agentId,
+ resourceType: 'agent',
+ });
+ // Best-effort: a notification failure must not fail the request.
+ // Scheduled with after() so serverless runtimes keep it alive past
+ // the response.
+ const notifyParams = {
+ event: 'requested' as const,
+ initiatorId: ctx.userId,
+ previousOwnerId: agent.userId,
+ recipientId: input.targetMemberId,
+ requestId: request.id,
+ resourceId: input.agentId,
+ resourceType: 'agent' as const,
+ workspaceId: ctx.workspaceId,
+ };
+ after(() =>
+ notifyResourceTransfer(notifyParams).catch((error) =>
+ console.error('[agent:transferAgent] notify failed', error),
+ ),
+ );
+ return { requestId: request.id, status: 'pending' as const };
+ } catch (error) {
+ if (error instanceof Error && error.message === TRANSFER_REQUEST_ALREADY_PENDING) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.TransferRequestPending } },
+ code: 'CONFLICT',
+ message: 'This agent already has a pending transfer request',
+ });
+ }
+ throw error;
+ }
+ }
+
+ // 3. Validate target workspace access (user must be member+)
+ if (input.targetWorkspaceId) {
+ const canWriteTarget = await hasWorkspaceScopedPermission({
+ action: 'AGENT_CREATE',
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId: input.targetWorkspaceId,
+ });
+
+ if (!canWriteTarget) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.TargetNoWriteAccess } },
+ code: 'FORBIDDEN',
+ message: 'No write access to target workspace',
+ });
+ }
+ }
+
+ // 4. Cannot transfer to the same workspace
+ if (input.targetWorkspaceId === ctx.workspaceId) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.SameWorkspace } },
+ code: 'BAD_REQUEST',
+ message: 'Cannot transfer agent to the same workspace',
+ });
+ }
+
+ // 5. The transfer rehomes every linked topic/message/thread/task β€” only
+ // the primary owner may move teammates' conversations along with an
+ // agent; co-admins and members may not.
+ if (
+ ctx.workspaceId &&
+ !(await isWorkspacePrimaryOwner({
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ })) &&
+ (await ctx.agentModel.transferHasForeignRows(input.agentId))
+ ) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.OwnerOnly } },
+ code: 'FORBIDDEN',
+ message: "Only the workspace owner can transfer an agent carrying others' conversations",
+ });
+ }
+
+ let result;
+ try {
+ result = await ctx.agentModel.transferAgent(
+ input.agentId,
+ input.targetWorkspaceId,
+ ctx.userId,
+ input.targetVisibility,
+ {
+ rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx),
+ },
+ );
+ } catch (error) {
+ if (
+ error instanceof Error &&
+ error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS
+ ) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.OwnerOnly } },
+ code: 'FORBIDDEN',
+ message: "Only workspace owners can transfer an agent carrying others' conversations",
+ });
+ }
+ if (error instanceof AgentOwnedByGroupError) {
+ throw new TRPCError({
+ // The group list travels with the code: "this agent belongs to a
+ // group" is only actionable once the user knows which group.
+ cause: { data: { code: TransferErrorCode.AgentOwnedByGroup, groups: error.groups } },
+ code: 'CONFLICT',
+ message: 'This agent belongs to a chat group and cannot be moved on its own',
+ });
+ }
+ if (error instanceof Error && error.message === AGENT_COPY_IN_PROGRESS) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.CopyInProgress } },
+ code: 'CONFLICT',
+ message: 'A previous copy of this agent is still duplicating its history',
+ });
+ }
+ if (error instanceof Error && error.message === AGENT_TRANSFER_IN_PROGRESS) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.TransferInProgress } },
+ code: 'CONFLICT',
+ message: 'A previous transfer of this agent is still migrating its history',
+ });
+ }
+ if (error instanceof Error && error.message === AGENT_SHARED_TRANSFER_BLOCKED) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.SharedTransferBlocked } },
+ code: 'PRECONDITION_FAILED',
+ message:
+ 'This agent cannot be transferred while a share link exists, including paused links.',
+ });
+ }
+ throw error;
+ }
+
+ // Heavy history goes through an async backfill β€” kick the driver now
+ // that the transfer transaction has committed.
+ if (result.transferJobId) startAgentTransferJob(ctx.serverDB, result.transferJobId);
+
+ if (ctx.workspaceId) {
+ await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).removeAll(
+ 'agent',
+ input.agentId,
+ );
+ // The agent left this workspace β€” a live member-transfer request can
+ // no longer be accepted, so void it.
+ await new ResourceTransferRequestModel(
+ ctx.serverDB,
+ ctx.workspaceId,
+ ).invalidateForResources('agent', [input.agentId]);
+ }
+ if (input.targetWorkspaceId && input.targetVisibility === 'public') {
+ // A released client's two-valued `viewer` is an explicit "less than
+ // editor" choice, so it resolves through the legacy map rather than the
+ // default (which is `edit`); saying nothing at all still means "what a
+ // newly created agent would get".
+ const targetAccessLevel =
+ input.targetAccessLevel ??
+ (input.targetGeneralAccess
+ ? input.targetGeneralAccess === 'editor'
+ ? 'edit'
+ : LEGACY_VIEWER_ACCESS_LEVELS.agent
+ : DEFAULT_RESOURCE_ACCESS_LEVELS.agent);
+ await new ResourcePermissionModel(ctx.serverDB, input.targetWorkspaceId).setAccessLevel(
+ 'agent',
+ input.agentId,
+ targetAccessLevel,
+ ctx.userId,
+ );
+ }
+
+ return result;
+ }),
+ /**
+ * Batch variant of `transferAgent`: one request + one DB transaction for all
+ * selected agents, so a multi-select "Move Agent" is no longer N serial
+ * round-trips (each with its own permission checks and large-table updates).
+ */
+ transferAgents: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(
+ z.object({
+ agentIds: z.array(z.string()).min(1).max(100),
+ targetAccessLevel: z.enum(RESOURCE_ACCESS_LEVELS_BY_TYPE.agent).optional(),
+ targetVisibility: z.enum(['private', 'public']).optional(),
+ targetWorkspaceId: z.string().nullable(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const agentIds = [...new Set(input.agentIds)];
+
+ // 1. All agents must exist in the current scope
+ const existences = await pMap(agentIds, (agentId) => ctx.agentModel.existsById(agentId), {
+ concurrency: AGENT_TRANSFER_CONCURRENCY,
+ });
+ if (existences.some((exists) => !exists)) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.ResourceNotFound } },
+ code: 'NOT_FOUND',
+ message: 'Agent not found',
+ });
+ }
+
+ // 2. Transferring ownership/scope is always creator-only.
+ if (ctx.workspaceId) {
+ await pMap(
+ agentIds,
+ (agentId) =>
+ assertCanPerformResourceAction({
+ action: 'transfer',
+ db: ctx.serverDB,
+ resourceId: agentId,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId!,
+ }),
+ { concurrency: AGENT_TRANSFER_CONCURRENCY },
+ );
+ }
+
+ // 3. Validate target workspace access once (user must be member+)
+ if (input.targetWorkspaceId) {
+ const canWriteTarget = await hasWorkspaceScopedPermission({
+ action: 'AGENT_CREATE',
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId: input.targetWorkspaceId,
+ });
+
+ if (!canWriteTarget) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.TargetNoWriteAccess } },
+ code: 'FORBIDDEN',
+ message: 'No write access to target workspace',
+ });
+ }
+ }
+
+ // 4. Cannot transfer to the same workspace
+ if (input.targetWorkspaceId === ctx.workspaceId) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.SameWorkspace } },
+ code: 'BAD_REQUEST',
+ message: 'Cannot transfer agent to the same workspace',
+ });
+ }
+
+ // 5. The transfer rehomes every linked topic/message/thread/task β€” only
+ // the primary owner may move teammates' conversations along with
+ // agents. One batched check for the whole selection.
+ if (
+ ctx.workspaceId &&
+ !(await isWorkspacePrimaryOwner({
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ })) &&
+ (await ctx.agentModel.transferHasForeignRows(agentIds))
+ ) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.OwnerOnly } },
+ code: 'FORBIDDEN',
+ message: "Only the workspace owner can transfer an agent carrying others' conversations",
+ });
+ }
+
+ let results;
+ try {
+ results = await ctx.agentModel.transferAgents(
+ agentIds,
+ input.targetWorkspaceId,
+ ctx.userId,
+ input.targetVisibility,
+ {
+ rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx),
+ },
+ );
+ } catch (error) {
+ if (
+ error instanceof Error &&
+ error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS
+ ) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.OwnerOnly } },
+ code: 'FORBIDDEN',
+ message: "Only workspace owners can transfer agents carrying others' conversations",
+ });
+ }
+ if (error instanceof AgentOwnedByGroupError) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.AgentOwnedByGroup, groups: error.groups } },
+ code: 'CONFLICT',
+ message: 'One of these agents belongs to a chat group and cannot be moved on its own',
+ });
+ }
+ if (error instanceof Error && error.message === AGENT_COPY_IN_PROGRESS) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.CopyInProgress } },
+ code: 'CONFLICT',
+ message: 'A previous copy of this agent is still duplicating its history',
+ });
+ }
+ if (error instanceof Error && error.message === AGENT_TRANSFER_IN_PROGRESS) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.TransferInProgress } },
+ code: 'CONFLICT',
+ message: 'A previous transfer of these agents is still migrating their history',
+ });
+ }
+ if (error instanceof Error && error.message === AGENT_SHARED_TRANSFER_BLOCKED) {
+ throw new TRPCError({
+ cause: { data: { code: TransferErrorCode.SharedTransferBlocked } },
+ code: 'PRECONDITION_FAILED',
+ message:
+ 'These agents cannot be transferred while a share link exists, including paused links.',
+ });
+ }
+ throw error;
+ }
+
+ // The whole batch shares one backfill job; kick it post-commit.
+ const batchTransferJobId = results[0]?.transferJobId;
+ if (batchTransferJobId) startAgentTransferJob(ctx.serverDB, batchTransferJobId);
+
+ if (ctx.workspaceId) {
+ const sourcePermissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
+ await runAllPostCommit(agentIds, (agentId) =>
+ sourcePermissionModel.removeAll('agent', agentId),
+ );
+ // The agents left this workspace β€” void any live member-transfer requests.
+ await new ResourceTransferRequestModel(
+ ctx.serverDB,
+ ctx.workspaceId,
+ ).invalidateForResources('agent', agentIds);
+ }
+ if (input.targetWorkspaceId && input.targetVisibility === 'public') {
+ const targetAccessLevel = input.targetAccessLevel ?? DEFAULT_RESOURCE_ACCESS_LEVELS.agent;
+ const targetPermissionModel = new ResourcePermissionModel(
+ ctx.serverDB,
+ input.targetWorkspaceId,
+ );
+ await runAllPostCommit(agentIds, (agentId) =>
+ targetPermissionModel.setAccessLevel('agent', agentId, targetAccessLevel, ctx.userId),
+ );
+ }
+
+ return results;
+ }),
+});
diff --git a/apps/server/src/routers/lambda/agent/visibility.ts b/apps/server/src/routers/lambda/agent/visibility.ts
new file mode 100644
index 00000000000..aebf85d894b
--- /dev/null
+++ b/apps/server/src/routers/lambda/agent/visibility.ts
@@ -0,0 +1,184 @@
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { ChatGroupModel } from '@/database/models/chatGroup';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import { TaskModel } from '@/database/models/task';
+import type { ResourceAccessLevel } from '@/database/schemas';
+import { DEFAULT_RESOURCE_ACCESS_LEVELS, RESOURCE_ACCESS_LEVELS_BY_TYPE } from '@/database/schemas';
+import { router } from '@/libs/trpc/lambda';
+import {
+ assertCanPerformResourceAction,
+ buildResourcePermissionState,
+} from '@/server/services/resourcePermission';
+
+import { agentProcedure } from './procedures';
+
+export const visibilityRouter = router({
+ /**
+ * Publish a private agent into the workspace. Only the creator of a
+ * still-private agent can run this; the underlying SQL enforces both rules.
+ * The inverse transition (public β†’ private) goes through
+ * `setAgentVisibility`, which is gated to the creator only.
+ */
+ publishAgentToWorkspace: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(
+ z.object({
+ accessLevel: z.enum(RESOURCE_ACCESS_LEVELS_BY_TYPE.agent).optional(),
+ id: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const result = await ctx.agentModel.publishToWorkspace(input.id);
+ if (ctx.workspaceId) {
+ const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
+ // An explicit request wins; otherwise keep whatever the creator already
+ // chose on the Permission page while the agent was still private β€”
+ // rewriting the default here would silently discard that decision.
+ const accessLevel =
+ input.accessLevel ??
+ (await permissionModel.getAccessLevel('agent', input.id)) ??
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent;
+ await permissionModel.setAccessLevel('agent', input.id, accessLevel, ctx.userId);
+ }
+ return result;
+ }),
+ /**
+ * Bidirectional visibility switch. Rules:
+ * - builtin agents (LobeAI etc., identified by slug) can never change
+ * visibility β€” the workspace copy must stay shared;
+ * - only the agent's creator may pull a published agent back to private
+ *: a workspace owner demoting another member's agent would
+ * effectively appropriate it, so everyone else gets FORBIDDEN. The UI
+ * hides the entry for them, this is the server-side backstop.
+ */
+ setAgentVisibility: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(
+ z.object({
+ accessLevel: z.enum(RESOURCE_ACCESS_LEVELS_BY_TYPE.agent).optional(),
+ id: z.string(),
+ visibility: z.enum(['private', 'public']),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const meta = await ctx.agentModel.getAgentVisibilityMeta(input.id);
+ if (!meta) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
+
+ if (meta.slug && Object.values(BUILTIN_AGENT_SLUGS).includes(meta.slug as any)) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Builtin agents cannot change visibility',
+ });
+ }
+
+ if (!ctx.workspaceId) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Agent visibility only applies inside a workspace',
+ });
+ }
+ const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
+ const permissionMeta = { ...meta, workspaceId: ctx.workspaceId };
+ const blockingTasksPromise =
+ input.visibility === 'private' && meta.visibility !== input.visibility
+ ? new TaskModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ ).countTasksBlockingAgentDemotion(input.id, meta.userId)
+ : Promise.resolve(0);
+ const [, blockingTasks] = await Promise.all([
+ assertCanPerformResourceAction({
+ action: 'changeVisibility',
+ db: ctx.serverDB,
+ grantedPermissions: (ctx as { workspacePermissionCodes?: string[] })
+ .workspacePermissionCodes,
+ meta: permissionMeta,
+ resourceId: input.id,
+ resourceType: 'agent',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ }),
+ blockingTasksPromise,
+ ]);
+
+ if (meta.visibility === input.visibility) {
+ const accessLevel =
+ input.visibility === 'public'
+ ? (input.accessLevel ??
+ (await permissionModel.getEffectiveAccessLevel('agent', input.id)))
+ : 'edit';
+ if (input.visibility === 'public' && input.accessLevel) {
+ await permissionModel.setAccessLevel('agent', input.id, input.accessLevel, ctx.userId);
+ }
+ return buildResourcePermissionState({
+ accessLevel,
+ canManage: true,
+ creatorId: meta.userId,
+ visibility: input.visibility,
+ });
+ }
+
+ // Demoting an agent must not strand tasks that depend on it: public
+ // tasks would violate the `assertAgentVisibilityCompat` invariant
+ // (members keep seeing the task but can no longer see or run the
+ // assignee), and other members' tasks β€” private ones included β€” would
+ // fail future runs/updates because their creators can no longer
+ // resolve the agent. Reject early β€” reassign or demote those tasks
+ // first.
+ if (blockingTasks > 0) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ 'Cannot make this agent private while workspace tasks still depend on it. Reassign those tasks or make them private first.',
+ });
+ }
+
+ // Same source-level guard for group chats, but only for the supervisor
+ // role: a private supervisor is unresolvable for every other viewer and
+ // bricks the whole group. Regular members are not blocked β€” roster
+ // reads drop a non-visible member per viewer instead.
+ if (input.visibility === 'private') {
+ const chatGroupModel = new ChatGroupModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
+ const blockingGroups = await chatGroupModel.countGroupsBlockingAgentDemotion(
+ input.id,
+ meta.userId,
+ );
+ if (blockingGroups > 0) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ 'Cannot make this agent private while it supervises workspace group chats. Remove it as supervisor first.',
+ });
+ }
+ }
+
+ const updated = await ctx.agentModel.setVisibility(input.id, input.visibility);
+ if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
+
+ let accessLevel: ResourceAccessLevel;
+ if (input.visibility === 'private') {
+ accessLevel = 'edit';
+ await permissionModel.removeAll('agent', input.id);
+ } else {
+ // Same rule as `publishAgentToWorkspace`: promotion keeps a level the
+ // creator already set while private instead of resetting to the default.
+ accessLevel =
+ input.accessLevel ??
+ (await permissionModel.getAccessLevel('agent', input.id)) ??
+ DEFAULT_RESOURCE_ACCESS_LEVELS.agent;
+ await permissionModel.setAccessLevel('agent', input.id, accessLevel, ctx.userId);
+ }
+
+ return buildResourcePermissionState({
+ accessLevel,
+ canManage: true,
+ creatorId: meta.userId,
+ visibility: input.visibility,
+ });
+ }),
+});