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(openapi): mark personal agents and filter agents.list by them (#21282)

Innei046e23e06f84
diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.yml
index 9bff1fcdd24..c27397dc31c 100644
--- a/packages/openapi/openapi.yml
+++ b/packages/openapi/openapi.yml
@@ -108,6 +108,8 @@ components:
type:
- object
- "null"
+ personal:
+ type: boolean
plugins:
type: array
items:
@@ -1597,6 +1599,13 @@ paths:
name: pageSize
schema:
type: string
+ - in: query
+ name: personal
+ schema:
+ type: string
+ enum:
+ - "true"
+ - "false"
responses:
"200":
content:
@@ -1948,6 +1957,8 @@ paths:
type: string
additionalProperties: {}
- type: "null"
+ personal:
+ type: boolean
provider:
type:
- string
@@ -2397,6 +2408,8 @@ paths:
type: string
additionalProperties: {}
- type: "null"
+ personal:
+ type: boolean
provider:
type:
- string
diff --git a/packages/openapi/src/helpers/public-fields.test.ts b/packages/openapi/src/helpers/public-fields.test.ts
index 9b1ce0f20c2..38c51e0e3d3 100644
--- a/packages/openapi/src/helpers/public-fields.test.ts
+++ b/packages/openapi/src/helpers/public-fields.test.ts
@@ -41,7 +41,9 @@ describe('public response field projections', () => {
workspaceId: 'workspace-1',
} as unknown as AgentItem);
- expect(Object.keys(projected).sort()).toEqual([...PUBLIC_AGENT_FIELDS, 'plugins'].sort());
+ expect(Object.keys(projected).sort()).toEqual(
+ [...PUBLIC_AGENT_FIELDS, 'personal', 'plugins'].sort(),
+ );
expect(projected).not.toHaveProperty('clientId');
expect(projected).not.toHaveProperty('marketIdentifier');
expect(projected).not.toHaveProperty('userId');
diff --git a/packages/openapi/src/helpers/public-fields.ts b/packages/openapi/src/helpers/public-fields.ts
index 010b07d2f73..2f0a472635a 100644
--- a/packages/openapi/src/helpers/public-fields.ts
+++ b/packages/openapi/src/helpers/public-fields.ts
@@ -299,6 +299,7 @@ export const PUBLIC_EVAL_RUN_TOPIC_FIELDS = [
] as const satisfies readonly (keyof AgentEvalRunTopicItem)[];
export type PublicAgent = Pick<AgentItem, (typeof PUBLIC_AGENT_FIELDS)[number]> & {
+ personal: boolean;
plugins: ReturnType<typeof parsePluginEntry>[];
};
export type PublicUser = Pick<UserItem, (typeof PUBLIC_USER_FIELDS)[number]>;
@@ -338,6 +339,7 @@ export type PublicPermission = Pick<PermissionItem, (typeof PUBLIC_PERMISSION_FI
export const projectPublicAgent = (value: AgentItem): PublicAgent => ({
...pickPublicFields(value, PUBLIC_AGENT_FIELDS),
+ personal: value.metadata?.personal === true,
plugins: (value.plugins ?? []).map(parsePluginEntry),
});
diff --git a/packages/openapi/src/routes/agents.route.test.ts b/packages/openapi/src/routes/agents.route.test.ts
new file mode 100644
index 00000000000..73a2cbb7ae3
--- /dev/null
+++ b/packages/openapi/src/routes/agents.route.test.ts
@@ -0,0 +1,137 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { Hono } from 'hono';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '@/database/core/getTestDB';
+import { agents, users } from '@/database/schemas';
+
+const db = await getTestDB();
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: async () => db }));
+vi.mock('@/database/models/rbac', () => ({
+ RbacModel: class {
+ hasAnyPermission = async () => true;
+ },
+}));
+vi.mock('../middleware/auth', () => ({
+ requireAuth: async (_c: any, next: any) => next(),
+}));
+
+const { default: AgentRoutes } = await import('./agents.route');
+
+const USER = 'personal-agent-user';
+
+const request = (path: string, init: { body?: unknown; method?: string } = {}) => {
+ const app = new Hono();
+
+ app.use('*', async (c, next) => {
+ c.set('userId' as never, USER as never);
+ await next();
+ });
+ app.route('/', AgentRoutes);
+
+ return app.request(path, {
+ ...(init.body === undefined
+ ? {}
+ : { body: JSON.stringify(init.body), headers: { 'content-type': 'application/json' } }),
+ method: init.method ?? 'GET',
+ });
+};
+
+const json = async (res: Response) => ((await res.json()) as { data: any }).data;
+
+beforeEach(async () => {
+ await db.delete(agents);
+ await db.delete(users);
+ await db.insert(users).values({ id: USER });
+});
+
+describe('personal agents', () => {
+ it('creates a personal agent and reports the flag', async () => {
+ const res = await request('/', { body: { personal: true, title: 'toby' }, method: 'POST' });
+
+ expect(res.status).toBe(200);
+ const agent = await json(res);
+ expect(agent.personal).toBe(true);
+
+ const [row] = await db.select().from(agents).where(eq(agents.id, agent.id));
+ expect(row.metadata).toEqual({ personal: true });
+ });
+
+ it('defaults to not personal', async () => {
+ const agent = await json(await request('/', { body: { title: 'Writer' }, method: 'POST' }));
+
+ expect(agent.personal).toBe(false);
+ });
+
+ it('filters the list by personal', async () => {
+ await request('/', { body: { personal: true, title: 'toby' }, method: 'POST' });
+ await request('/', { body: { title: 'Writer' }, method: 'POST' });
+
+ const personal = await json(await request('/?personal=true'));
+ const others = await json(await request('/?personal=false'));
+ const all = await json(await request('/'));
+
+ expect(personal.agents.map((agent: any) => agent.title)).toEqual(['toby']);
+ expect(personal.total).toBe(1);
+ expect(others.agents.map((agent: any) => agent.title)).toEqual(['Writer']);
+ expect(all.total).toBe(2);
+ });
+
+ it('treats a non-boolean metadata.personal as not personal instead of failing', async () => {
+ const agent = await json(await request('/', { body: { title: 'Legacy' }, method: 'POST' }));
+ await db
+ .update(agents)
+ .set({ metadata: { personal: 'yes' } })
+ .where(eq(agents.id, agent.id));
+
+ const personal = await request('/?personal=true');
+ const others = await request('/?personal=false');
+
+ expect(personal.status).toBe(200);
+ expect((await json(personal)).total).toBe(0);
+ expect((await json(others)).agents.map((row: any) => row.title)).toEqual(['Legacy']);
+ });
+
+ it('keeps the personal flag on a duplicate', async () => {
+ const agent = await json(
+ await request('/', { body: { personal: true, title: 'toby' }, method: 'POST' }),
+ );
+
+ const res = await request(`/${agent.id}/duplicate`, { body: {}, method: 'POST' });
+ expect(res.status).toBe(201);
+ const copy = await json(res);
+
+ expect(copy.id).not.toBe(agent.id);
+ expect(copy.personal).toBe(true);
+ expect((await json(await request('/?personal=true'))).total).toBe(2);
+ });
+
+ it('rejects a personal filter that is not a boolean', async () => {
+ const res = await request('/?personal=yes');
+
+ expect(res.status).toBe(400);
+ });
+
+ it('toggles the flag on update without dropping other metadata', async () => {
+ const agent = await json(await request('/', { body: { title: 'Writer' }, method: 'POST' }));
+ await db
+ .update(agents)
+ .set({ metadata: { source: 'import' } })
+ .where(eq(agents.id, agent.id));
+
+ const on = await json(
+ await request(`/${agent.id}`, { body: { personal: true }, method: 'PATCH' }),
+ );
+ expect(on.personal).toBe(true);
+
+ const off = await json(
+ await request(`/${agent.id}`, { body: { personal: false }, method: 'PATCH' }),
+ );
+ expect(off.personal).toBe(false);
+
+ const [row] = await db.select().from(agents).where(eq(agents.id, agent.id));
+ expect(row.metadata).toEqual({ personal: false, source: 'import' });
+ });
+});
diff --git a/packages/openapi/src/routes/agents.route.ts b/packages/openapi/src/routes/agents.route.ts
index a2bb6609099..9f6a9f23344 100644
--- a/packages/openapi/src/routes/agents.route.ts
+++ b/packages/openapi/src/routes/agents.route.ts
@@ -7,11 +7,11 @@ import { zValidator } from '../common/validator';
import { AgentController } from '../controllers/agent.controller';
import { requireAuth } from '../middleware/auth';
import { requireAnyPermission } from '../middleware/permission-check';
-import { PaginationQuerySchema } from '../types';
import {
AgentIdParamSchema,
CreateAgentRequestSchema,
DuplicateAgentSchema,
+ GetAgentsQuerySchema,
UpdateAgentRequestSchema,
} from '../types/agent.type';
@@ -30,7 +30,7 @@ AgentRoutes.get(
getScopePermissions('AGENT_READ', ['ALL', 'OWNER']),
'You do not have permission to view the Agent list',
),
- zValidator('query', PaginationQuerySchema),
+ zValidator('query', GetAgentsQuerySchema),
async (c) => {
const controller = new AgentController();
return await controller.queryAgents(c);
diff --git a/packages/openapi/src/services/agent.service.ts b/packages/openapi/src/services/agent.service.ts
index 5a98d89d1ee..4e0a9920252 100644
--- a/packages/openapi/src/services/agent.service.ts
+++ b/packages/openapi/src/services/agent.service.ts
@@ -1,4 +1,4 @@
-import { and, count, desc, eq, ilike, inArray, isNull, or } from 'drizzle-orm';
+import { and, count, desc, eq, ilike, inArray, isNull, not, or, sql } from 'drizzle-orm';
import { AgentModel } from '@/database/models/agent';
import type { FileItem, KnowledgeBaseItem, NewAgent } from '@/database/schemas';
@@ -43,6 +43,18 @@ export class AgentService extends BaseService {
title,
);
if (!result) throw this.createNotFoundError('Agent not found');
+
+ // AgentModel.duplicate copies an explicit field list without metadata, and the
+ // rest of metadata is private, so only the public personal flag is carried over.
+ const source = await this.db.query.agents.findFirst({ where: eq(agents.id, id) });
+ if (source?.metadata?.personal === true) {
+ const copy = await this.db.query.agents.findFirst({ where: eq(agents.id, result.agentId) });
+ await this.db
+ .update(agents)
+ .set({ metadata: { ...copy?.metadata, personal: true } })
+ .where(eq(agents.id, result.agentId));
+ }
+
return this.getAgentById(result.agentId);
}
@@ -55,7 +67,7 @@ export class AgentService extends BaseService {
async queryAgents(request: GetAgentsRequest): ServiceResult<AgentListResponse> {
this.log('info', 'get agent list', { request });
- const { keyword } = request;
+ const { keyword, personal } = request;
try {
// Base filter: current user + exclude virtual agents (inbox, supervisor, etc.)
@@ -64,9 +76,12 @@ export class AgentService extends BaseService {
or(eq(agents.virtual, false), isNull(agents.virtual)),
);
- const whereConditions = keyword
- ? and(baseConditions, ilike(agents.title, `%${keyword}%`))
- : baseConditions;
+ const personalCondition = sql`coalesce(${agents.metadata} -> 'personal' = 'true'::jsonb, false)`;
+ const whereConditions = and(
+ baseConditions,
+ keyword ? ilike(agents.title, `%${keyword}%`) : undefined,
+ personal === undefined ? undefined : personal ? personalCondition : not(personalCondition),
+ );
const query = this.db.query.agents.findMany({
...processPaginationConditions(request),
@@ -108,6 +123,7 @@ export class AgentService extends BaseService {
createdAt: new Date(),
description: request.description || null,
id: idGenerator('agents'),
+ metadata: request.personal ? { personal: true } : null,
model: request.model || null,
params: request.params ?? {},
// JSONB accepts mixed plugin entries; the legacy DB column remains string[].
@@ -219,6 +235,10 @@ export class AgentService extends BaseService {
if (request.systemRole !== undefined) updateData.systemRole = request.systemRole ?? null;
if (request.title !== undefined) updateData.title = request.title;
+ if (request.personal !== undefined) {
+ updateData.metadata = { ...existingAgent.metadata, personal: request.personal };
+ }
+
// Merge params instead of fully overwriting
if (request.params !== undefined) {
updateData.params = mergeJsonPatch(existingAgent.params, request.params);
diff --git a/packages/openapi/src/spec.ts b/packages/openapi/src/spec.ts
index 9ecad3dc5d1..f7e63aa2763 100644
--- a/packages/openapi/src/spec.ts
+++ b/packages/openapi/src/spec.ts
@@ -49,6 +49,7 @@ const resourceSchemas: Record<string, SchemaObject> = {
id: { type: 'string' },
model: nullableString,
params: nullableObject,
+ personal: { type: 'boolean' },
plugins: {
type: 'array',
items: {
diff --git a/packages/openapi/src/types/agent.type.ts b/packages/openapi/src/types/agent.type.ts
index ede88873a16..53a615ce92d 100644
--- a/packages/openapi/src/types/agent.type.ts
+++ b/packages/openapi/src/types/agent.type.ts
@@ -4,6 +4,7 @@ import { z } from 'zod';
import type { PublicAgent, PublicFile, PublicKnowledgeBase } from '../helpers/public-fields';
import type { IPaginationQuery, PaginationQueryResponse } from './common.type';
+import { PaginationQuerySchema } from './common.type';
// ==================== Agent CRUD Types ====================
@@ -17,13 +18,21 @@ export interface CreateAgentRequest {
description?: string;
model?: string;
params?: Record<string, unknown>;
+ personal?: boolean;
plugins?: Array<{ identifier: string; mode?: 'pinned' | 'auto' | 'disabled' }>;
provider?: string;
systemRole?: string;
title: string;
}
-export type GetAgentsRequest = IPaginationQuery;
+export type GetAgentsRequest = IPaginationQuery & { personal?: boolean };
+
+export const GetAgentsQuerySchema = PaginationQuerySchema.extend({
+ personal: z
+ .enum(['true', 'false'])
+ .transform((value) => value === 'true')
+ .optional(),
+});
export const CreateAgentRequestSchema = z.object({
agencyConfig: z
@@ -68,6 +77,7 @@ export const CreateAgentRequestSchema = z.object({
)
.optional(),
params: z.record(z.string(), z.unknown()).nullish(),
+ personal: z.boolean().optional(),
provider: z.string().nullish(),
systemRole: z.string().nullish(),
title: z.string().min(1, 'Title cannot be empty'),
diff --git a/packages/sdk/src/generated/types.gen.ts b/packages/sdk/src/generated/types.gen.ts
index 8b69ef7f76a..230a127b310 100644
--- a/packages/sdk/src/generated/types.gen.ts
+++ b/packages/sdk/src/generated/types.gen.ts
@@ -33,6 +33,7 @@ export type Agent = {
params?: {
[key: string]: unknown;
} | null;
+ personal?: boolean;
plugins?: Array<{
identifier: string;
mode: 'pinned' | 'auto' | 'disabled';
@@ -701,6 +702,7 @@ export type GetApiV1AgentsData = {
keyword?: string;
page?: string;
pageSize?: string;
+ personal?: 'true' | 'false';
};
url: '/api/v1/agents';
};
@@ -838,6 +840,7 @@ export type PostApiV1AgentsData = {
params?: {
[key: string]: unknown;
} | null;
+ personal?: boolean;
provider?: string | null;
systemRole?: string | null;
title: string;
@@ -1098,6 +1101,7 @@ export type PatchApiV1AgentsByIdData = {
params?: {
[key: string]: unknown;
} | null;
+ personal?: boolean;
provider?: string | null;
systemRole?: string | null;
title?: string;