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.

✨ feat(agent): query and set a plugin's mode across my agents in one call (#23658)

Arvin Xudc7b20e7104a
diff --git a/apps/server/src/routers/lambda/agent/config.ts b/apps/server/src/routers/lambda/agent/config.ts
index ef197276a9a..af6b38c4df3 100644
--- a/apps/server/src/routers/lambda/agent/config.ts
+++ b/apps/server/src/routers/lambda/agent/config.ts
@@ -1,5 +1,5 @@
import { DEFAULT_AGENT_CONFIG, INBOX_SESSION_ID } from '@lobechat/const';
-import { AGENT_PERMISSION_POLICY_KEYS } from '@lobechat/types';
+import { AGENT_PERMISSION_POLICY_KEYS, AgentPluginModeSchema } from '@lobechat/types';
import { isRecord } from '@lobechat/utils/object';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -143,6 +143,35 @@ export const configRouter = router({
const config = await ctx.agentService.getBuiltinAgent(input.slug);
return config?.id ? protectAgentConfig(ctx, config.id, config) : config;
}),
+ /**
+ * Which of the caller's own agents carry a plugin or skill (`pinned` or
+ * `disabled`), in one query over `plugins` instead of a full config per agent.
+ */
+ getPluginAgentModes: agentProcedure
+ .input(z.object({ identifier: z.string().min(1) }))
+ .query(async ({ input, ctx }) => ctx.agentModel.listPluginModes(input.identifier)),
+ /**
+ * Sets a plugin or skill's mode on the caller's own agents in one atomic
+ * write. `auto` removes it; without `agentIds` it removes it from every own
+ * agent carrying it.
+ */
+ setPluginMode: agentProcedure
+ .use(withScopedPermission('agent:update'))
+ .input(
+ z
+ .object({
+ agentIds: z.array(z.string()).max(500).optional(),
+ identifier: z.string().min(1),
+ mode: AgentPluginModeSchema,
+ })
+ .refine((input) => input.mode === 'auto' || !!input.agentIds, {
+ message: 'agentIds is required unless removing',
+ path: ['agentIds'],
+ }),
+ )
+ .mutation(async ({ input, ctx }) =>
+ ctx.agentModel.setPluginMode(input.identifier, input.mode, input.agentIds),
+ ),
updateAgentConfig: agentProcedure
.use(withScopedPermission('agent:update'))
.input(
diff --git a/apps/server/src/routers/lambda/agent/index.procedures.test.ts b/apps/server/src/routers/lambda/agent/index.procedures.test.ts
index 9586d400f4c..72d675bdbbf 100644
--- a/apps/server/src/routers/lambda/agent/index.procedures.test.ts
+++ b/apps/server/src/routers/lambda/agent/index.procedures.test.ts
@@ -44,6 +44,7 @@ function expected(): Array<
['getBuiltinAgent', 'query', 12],
['getGroupMembershipImpact', 'query', 12],
['getKnowledgeBasesAndFiles', 'query', 12],
+ ['getPluginAgentModes', 'query', 12],
['getTransferJobStatus', 'query', 12],
['prioritizeTransferTopic', 'mutation', 12],
['publishAgentToWorkspace', 'mutation', 13],
@@ -54,6 +55,7 @@ function expected(): Array<
['resolveAgentIdBySlug', 'query', 12],
['resolveAgentRoute', 'query', 12],
['setAgentVisibility', 'mutation', 13],
+ ['setPluginMode', 'mutation', 13],
['toggleFile', 'mutation', 13],
['toggleKnowledgeBase', 'mutation', 13],
['transferAgent', 'mutation', 13],
diff --git a/packages/database/src/models/__tests__/agent.plugins.test.ts b/packages/database/src/models/__tests__/agent.plugins.test.ts
new file mode 100644
index 00000000000..a77abc38908
--- /dev/null
+++ b/packages/database/src/models/__tests__/agent.plugins.test.ts
@@ -0,0 +1,116 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agents, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AgentModel } from '../agent';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'plugin-modes-user';
+const otherUserId = 'plugin-modes-other';
+
+const insertAgent = (id: string, plugins: unknown, extra: Record<string, unknown> = {}) =>
+ serverDB.insert(agents).values({ id, plugins: plugins as any, slug: id, userId, ...extra });
+
+const pluginsOf = async (id: string) =>
+ (await serverDB.query.agents.findFirst({ where: (t, { eq }) => eq(t.id, id) }))?.plugins;
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('AgentModel.listPluginModes', () => {
+ it('finds both entry shapes and reports their mode', async () => {
+ await insertAgent('a-legacy', ['pptx', 'web']);
+ await insertAgent('a-pinned', [{ identifier: 'pptx' }]);
+ await insertAgent('a-disabled', ['web', { identifier: 'pptx', mode: 'disabled' }]);
+ await insertAgent('a-none', ['web']);
+ await insertAgent('a-null', null);
+
+ const model = new AgentModel(serverDB, userId);
+ const result = await model.listPluginModes('pptx');
+
+ expect(result.sort((a, b) => a.agentId.localeCompare(b.agentId))).toEqual([
+ { agentId: 'a-disabled', mode: 'disabled' },
+ { agentId: 'a-legacy', mode: 'pinned' },
+ { agentId: 'a-pinned', mode: 'pinned' },
+ ]);
+ });
+
+ it('skips other users, virtual and heterogeneous agents', async () => {
+ await insertAgent('a-other', ['pptx'], { userId: otherUserId });
+ await insertAgent('a-virtual', ['pptx'], { virtual: true });
+ await insertAgent('a-hetero', ['pptx'], {
+ agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },
+ });
+ await insertAgent('a-mine', ['pptx'], { agencyConfig: {} });
+
+ const model = new AgentModel(serverDB, userId);
+
+ expect(await model.listPluginModes('pptx')).toEqual([{ agentId: 'a-mine', mode: 'pinned' }]);
+ });
+});
+
+describe('AgentModel.setPluginMode', () => {
+ it('pins by appending, and rewrites an existing entry in place', async () => {
+ await insertAgent('a-empty', null);
+ await insertAgent('a-legacy', ['web', 'pptx', 'search']);
+ await insertAgent('a-object', [{ identifier: 'pptx', mode: 'pinned' }, 'web']);
+
+ const model = new AgentModel(serverDB, userId);
+ const rows = await model.setPluginMode('pptx', 'disabled', ['a-empty', 'a-legacy', 'a-object']);
+
+ expect(rows).toHaveLength(3);
+ expect(await pluginsOf('a-empty')).toEqual([{ identifier: 'pptx', mode: 'disabled' }]);
+ expect(await pluginsOf('a-legacy')).toEqual([
+ 'web',
+ { identifier: 'pptx', mode: 'disabled' },
+ 'search',
+ ]);
+ expect(await pluginsOf('a-object')).toEqual([{ identifier: 'pptx', mode: 'disabled' }, 'web']);
+ });
+
+ it('auto removes the entry and keeps the rest in order', async () => {
+ await insertAgent('a-1', ['web', { identifier: 'pptx', mode: 'disabled' }, 'search']);
+ await insertAgent('a-2', ['pptx']);
+
+ const model = new AgentModel(serverDB, userId);
+ await model.setPluginMode('pptx', 'auto', ['a-1', 'a-2']);
+
+ expect(await pluginsOf('a-1')).toEqual(['web', 'search']);
+ expect(await pluginsOf('a-2')).toEqual([]);
+ });
+
+ it('auto without agentIds removes it from every own agent carrying it, and only those', async () => {
+ await insertAgent('a-1', ['pptx']);
+ await insertAgent('a-2', [{ identifier: 'pptx', mode: 'disabled' }]);
+ await insertAgent('a-3', ['web']);
+ await insertAgent('a-other', ['pptx'], { userId: otherUserId });
+
+ const model = new AgentModel(serverDB, userId);
+ const rows = await model.setPluginMode('pptx', 'auto');
+
+ expect(rows.map((row) => row.id).sort()).toEqual(['a-1', 'a-2']);
+ expect(await pluginsOf('a-1')).toEqual([]);
+ expect(await pluginsOf('a-2')).toEqual([]);
+ expect(await pluginsOf('a-3')).toEqual(['web']);
+ expect(await pluginsOf('a-other')).toEqual(['pptx']);
+ });
+
+ it("never writes another user's agent", async () => {
+ await insertAgent('a-other', ['web'], { userId: otherUserId });
+
+ const model = new AgentModel(serverDB, userId);
+ const rows = await model.setPluginMode('pptx', 'pinned', ['a-other']);
+
+ expect(rows).toEqual([]);
+ expect(await pluginsOf('a-other')).toEqual(['web']);
+ });
+});
diff --git a/packages/database/src/models/agent/index.ts b/packages/database/src/models/agent/index.ts
index 2b7b904e273..ea6c0890ce9 100644
--- a/packages/database/src/models/agent/index.ts
+++ b/packages/database/src/models/agent/index.ts
@@ -15,6 +15,7 @@ import * as find from './find';
import * as groupMembership from './groupMembership';
import * as knowledge from './knowledge';
import * as list from './list';
+import * as plugins from './plugins';
import * as transfer from './transfer';
import * as transferOwnership from './transferOwnership';
import * as trash from './trash';
@@ -27,6 +28,7 @@ export {
AGENT_SHARED_TRANSFER_BLOCKED,
AgentOwnedByGroupError,
} from './errors';
+export type { AgentPluginModeItem } from './plugins';
export type { AgentGroupMembershipRef, DeviceBindingCandidate } from './types';
export class AgentModel {
@@ -55,6 +57,11 @@ export class AgentModel {
getAgentAvatarsByIds = this.withContext(list.getAgentAvatarsByIds);
listMessengerBindableAgents = this.withContext(list.listMessengerBindableAgents);
+ // **************** Plugins *************** //
+
+ listPluginModes = this.withContext(plugins.listPluginModes);
+ setPluginMode = this.withContext(plugins.setPluginMode);
+
// **************** Read *************** //
getAgentDisplayFields = this.withContext(find.getAgentDisplayFields);
diff --git a/packages/database/src/models/agent/plugins.ts b/packages/database/src/models/agent/plugins.ts
new file mode 100644
index 00000000000..71ff5e144dc
--- /dev/null
+++ b/packages/database/src/models/agent/plugins.ts
@@ -0,0 +1,110 @@
+import { INBOX_SESSION_ID } from '@lobechat/const';
+import { type AgentPluginEntry, type AgentPluginMode, getPluginMode } from '@lobechat/types';
+import { and, eq, inArray, isNull, or, type SQL, sql } from 'drizzle-orm';
+
+import { agents } from '../../schemas';
+import { type AgentModelContext } from './context';
+
+export interface AgentPluginModeItem {
+ agentId: string;
+ /** Only the explicit states: an agent without an entry is `auto` and not listed. */
+ mode: Exclude<AgentPluginMode, 'auto'>;
+}
+
+/**
+ * `agents.plugins` mixes legacy bare identifiers with `{ identifier, mode }`
+ * objects, so "carries the plugin" is one containment test per shape. Both
+ * are plain `@>` checks a GIN index on `plugins` could serve.
+ */
+const carriesPlugin = (identifier: string): SQL =>
+ sql`(${agents.plugins} @> ${JSON.stringify([identifier])}::jsonb OR ${agents.plugins} @> ${JSON.stringify([{ identifier }])}::jsonb)`;
+
+/** One `plugins[]` element (aliased `e`) that names `identifier`, in either shape. */
+const isEntryFor = (identifier: string): SQL =>
+ sql`(e.value = to_jsonb(${identifier}::text) OR (jsonb_typeof(e.value) = 'object' AND e.value->>'identifier' = ${identifier}))`;
+
+/**
+ * The caller's own LobeHub agents: created by them (not just visible in the
+ * workspace), real agents plus the inbox, and not heterogeneous — external
+ * runtimes (Claude Code, Codex, …) do not run plugins or skills.
+ */
+const ownPluginAgents = (ctx: AgentModelContext): SQL | undefined =>
+ and(
+ ctx.ownership(),
+ eq(agents.userId, ctx.userId),
+ or(isNull(agents.virtual), eq(agents.virtual, false), eq(agents.slug, INBOX_SESSION_ID)),
+ sql`jsonb_typeof(${agents.agencyConfig}->'heterogeneousProvider') IS DISTINCT FROM 'object'`,
+ );
+
+/**
+ * Which of the caller's agents carry a plugin or skill, and in which mode —
+ * one query over `plugins`, instead of loading every agent's full config.
+ */
+export const listPluginModes = async (
+ ctx: AgentModelContext,
+ identifier: string,
+): Promise<AgentPluginModeItem[]> => {
+ const rows = await ctx.db
+ .select({ id: agents.id, plugins: agents.plugins })
+ .from(agents)
+ .where(and(ownPluginAgents(ctx), carriesPlugin(identifier)));
+
+ return rows.flatMap(({ id, plugins }) => {
+ const mode = getPluginMode(plugins ?? undefined, identifier);
+ return mode === 'auto' ? [] : [{ agentId: id, mode }];
+ });
+};
+
+/**
+ * Sets a plugin's mode on several agents in one statement, rewriting
+ * `plugins` in the database so a concurrent write to another entry of the
+ * same list is never overwritten by a stale client copy.
+ *
+ * - `auto` drops every entry for the identifier (absence is `auto`). Without
+ * `agentIds` it applies to every own agent carrying it: "remove from all".
+ * - `pinned` / `disabled` rewrite the existing entry in place (a legacy string
+ * becomes an object) or append one; `agentIds` is required.
+ *
+ * Returns the rows written with their new `plugins`.
+ */
+export const setPluginMode = async (
+ ctx: AgentModelContext,
+ identifier: string,
+ mode: AgentPluginMode,
+ agentIds?: string[],
+): Promise<{ id: string; plugins: AgentPluginEntry[] }[]> => {
+ if (agentIds?.length === 0) return [];
+ if (mode !== 'auto' && !agentIds) throw new Error('setPluginMode: agentIds is required');
+
+ const current = sql`CASE WHEN jsonb_typeof(${agents.plugins}) = 'array' THEN ${agents.plugins} ELSE '[]'::jsonb END`;
+
+ const next =
+ mode === 'auto'
+ ? sql`(SELECT coalesce(jsonb_agg(e.value ORDER BY e.ord), '[]'::jsonb)
+ FROM jsonb_array_elements(${current}) WITH ORDINALITY AS e(value, ord)
+ WHERE NOT ${isEntryFor(identifier)})`
+ : sql`CASE WHEN ${carriesPlugin(identifier)}
+ THEN (SELECT jsonb_agg(
+ CASE WHEN NOT ${isEntryFor(identifier)} THEN e.value
+ WHEN jsonb_typeof(e.value) = 'object' THEN e.value || jsonb_build_object('mode', ${mode}::text)
+ ELSE jsonb_build_object('identifier', e.value, 'mode', ${mode}::text) END
+ ORDER BY e.ord)
+ FROM jsonb_array_elements(${current}) WITH ORDINALITY AS e(value, ord))
+ ELSE ${current} || jsonb_build_array(jsonb_build_object('identifier', ${identifier}::text, 'mode', ${mode}::text))
+ END`;
+
+ const rows = await ctx.db
+ .update(agents)
+ .set({ plugins: next as unknown as AgentPluginEntry[] })
+ .where(
+ and(
+ ownPluginAgents(ctx),
+ agentIds ? inArray(agents.id, agentIds) : undefined,
+ // Removing touches only rows that carry the plugin.
+ mode === 'auto' ? carriesPlugin(identifier) : undefined,
+ ),
+ )
+ .returning({ id: agents.id, plugins: agents.plugins });
+
+ return rows.map(({ id, plugins }) => ({ id, plugins: (plugins ?? []) as AgentPluginEntry[] }));
+};