🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent): filter the agent list by tag (lh agent list --tag) (#23016)
Rdmclin2e5d6033293ca
diff --git a/apps/cli/src/commands/agent.list.test.ts b/apps/cli/src/commands/agent.list.test.tsnew file mode 100644index 00000000000..ac9b8bf73ce--- /dev/null+++ b/apps/cli/src/commands/agent.list.test.ts@@ -0,0 +1,99 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type * as WorkspaceModule from '../api/workspace';+import { log } from '../utils/logger';+import { registerAgentCommand } from './agent';++const { mockTrpcClient } = vi.hoisted(() => ({+ mockTrpcClient: {+ agent: {+ queryAgents: { query: vi.fn() },+ },+ },+}));++const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({+ getTrpcClient: vi.fn(),+}));++vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));+vi.mock('../api/workspace', async (importOriginal) => ({+ ...(await importOriginal<typeof WorkspaceModule>()),+ resolveWorkspaceId: () => undefined,+}));++describe('agent list --tag', () => {+ let consoleSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);+ mockTrpcClient.agent.queryAgents.query.mockReset();+ mockTrpcClient.agent.queryAgents.query.mockResolvedValue([]);+ });++ afterEach(() => {+ consoleSpy.mockRestore();+ });++ const run = (...args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerAgentCommand(program);+ return program.parseAsync(['node', 'test', 'agent', 'list', ...args]);+ };++ it('passes the tag to the server so it filters before the limit', async () => {+ await run('--tag', ' lobe-pet ', '--json');++ expect(mockTrpcClient.agent.queryAgents.query).toHaveBeenCalledWith(+ expect.objectContaining({ tag: 'lobe-pet' }),+ );+ });++ it('sends no tag when the option is absent or blank', async () => {+ await run();+ await run('--tag', ' ');++ for (const [input] of mockTrpcClient.agent.queryAgents.query.mock.calls) {+ expect(input).not.toHaveProperty('tag');+ }+ });++ it('prints only rows carrying the tag', async () => {+ mockTrpcClient.agent.queryAgents.query.mockResolvedValue([+ { id: 'pet', tags: ['lobe-pet'], title: 'Pet' },+ { id: 'crm', tags: [], title: 'CRM' },+ ]);++ await run('--tag', 'lobe-pet', '--json');++ const out = JSON.parse(consoleSpy.mock.calls[0][0]);+ expect(out.map((a: { id: string }) => a.id)).toEqual(['pet']);+ });++ it('prints nothing and warns when an older server ignored the tag', async () => {+ const warn = vi.spyOn(log, 'warn').mockImplementation(() => {});+ mockTrpcClient.agent.queryAgents.query.mockResolvedValue([+ { id: 'crm', title: 'CRM' },+ { id: 'coder', title: 'Coder' },+ ]);++ await run('--tag', 'lobe-pet', '--json');++ expect(JSON.parse(consoleSpy.mock.calls[0][0])).toEqual([]);+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('does not filter agents by tag'));+ warn.mockRestore();+ });++ it('leaves the list untouched without --tag', async () => {+ mockTrpcClient.agent.queryAgents.query.mockResolvedValue([{ id: 'crm', title: 'CRM' }]);++ await run('--json');++ expect(JSON.parse(consoleSpy.mock.calls[0][0]).map((a: { id: string }) => a.id)).toEqual([+ 'crm',+ ]);+ });+});diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.tsindex 5b59a3b382d..b7b54772deb 100644--- a/apps/cli/src/commands/agent.ts+++ b/apps/cli/src/commands/agent.ts@@ -51,6 +51,13 @@ type AgentVisibility = (typeof AGENT_VISIBILITIES)[number];const readAgencyConfig = (agencyConfigFile: string): Promise<Record<string, unknown>> =>readJsonObjectFile(agencyConfigFile, 'agencyConfig');+interface AgentListOptions {+ json?: string | boolean;+ keyword?: string;+ limit?: string;+ tag?: string;+}+export function registerAgentCommand(program: Command) {const agent = program.command('agent').description('Manage agents');registerAgentSpaceFsCommand(agent);@@ -64,8 +71,9 @@ export function registerAgentCommand(program: Command) {.description('List agents').option('-L, --limit <n>', 'Maximum number of items', '30').option('-k, --keyword <keyword>', 'Filter by keyword')+ .option('--tag <tag>', 'Only agents carrying this tag').option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')- .action(async (options: { json?: string | boolean; keyword?: string; limit?: string }) => {+ .action(async (options: AgentListOptions) => {const client = await getTrpcClient();// The inbox (Lobe AI) is a real assistant the user can open, and this is@@ -77,12 +85,25 @@ export function registerAgentCommand(program: Command) {keyword?: string;limit?: number;offset?: number;+ tag?: string;} = { includeInbox: true };if (options.keyword) input.keyword = options.keyword;+ if (options.tag?.trim()) input.tag = options.tag.trim();if (options.limit) input.limit = Number.parseInt(options.limit, 10);const result = await client.agent.queryAgents.query(input);- const items = Array.isArray(result) ? result : ((result as any).items ?? []);+ const listed: any[] = Array.isArray(result) ? result : ((result as any).items ?? []);+ // An older server drops the unknown `tag` input and returns an unfiltered+ // page whose rows carry no `tags`: keep only rows that really carry the+ // tag, so unrelated agents are never printed as a filtered result.+ const tag = input.tag;+ const items =+ tag === undefined+ ? listed+ : listed.filter((a) => Array.isArray(a?.tags) && a.tags.includes(tag));+ if (tag !== undefined && listed.length > 0 && !listed.some((a) => Array.isArray(a?.tags))) {+ log.warn('This server does not filter agents by tag; upgrade it to use --tag.');+ }if (options.json !== undefined) {const fields = typeof options.json === 'string' ? options.json : undefined;diff --git a/apps/server/src/routers/lambda/agent/lifecycle.tagInput.test.ts b/apps/server/src/routers/lambda/agent/lifecycle.tagInput.test.tsnew file mode 100644index 00000000000..ecbf1dfb5c1--- /dev/null+++ b/apps/server/src/routers/lambda/agent/lifecycle.tagInput.test.ts@@ -0,0 +1,29 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { agentRouter } from '.';++/**+ * `createAgent` stores tag strings exactly as given (`CreateAgentSchema`: no+ * length cap, no trimming), so the list/count filters must look up that exact+ * value, the empty string included: a stricter or normalizing read side would leave agents that+ * `lh agent list --tag` can never return.+ */+describe('queryAgents / countAgents tag input', () => {+ const procedures = (agentRouter as any)._def.procedures as Record<string, any>;+ const parse = (name: string, input: unknown) => procedures[name]._def.inputs[0].parse(input);++ it.each(['queryAgents', 'countAgents'])('%s accepts a long tag', (name) => {+ const longTag = `team-${'x'.repeat(120)}`;+ expect(parse(name, { tag: longTag })).toMatchObject({ tag: longTag });+ });++ it.each(['queryAgents', 'countAgents'])('%s keeps the tag exactly as stored', (name) => {+ expect(parse(name, { tag: ' tenant-A ' })).toMatchObject({ tag: ' tenant-A ' });+ expect(parse(name, { tag: ' ' })).toMatchObject({ tag: ' ' });+ });++ it.each(['queryAgents', 'countAgents'])('%s keeps an empty tag (a stored value too)', (name) => {+ expect(parse(name, { tag: '' })).toMatchObject({ tag: '' });+ });+});diff --git a/apps/server/src/routers/lambda/agent/lifecycle.ts b/apps/server/src/routers/lambda/agent/lifecycle.tsindex 4cdc1ab477d..3e9b13d9cb8 100644--- a/apps/server/src/routers/lambda/agent/lifecycle.ts+++ b/apps/server/src/routers/lambda/agent/lifecycle.ts@@ -44,6 +44,7 @@ export const lifecycleRouter = router({keyword: z.string().optional(),range: z.tuple([z.string(), z.string()]).optional(),startDate: z.string().optional(),+ tag: z.string().optional(),}).optional(),)@@ -184,7 +185,8 @@ export const lifecycleRouter = router({/*** 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`.+ * when the caller passes `includeInbox: true`; `tag` keeps only agents+ * carrying that tag.* Returns agents with minimal info (id, name, title, description, avatar,* backgroundColor).* Used by AddGroupMemberModal and group-management tool to search/select agents.@@ -197,6 +199,7 @@ export const lifecycleRouter = router({keyword: z.string().optional(),limit: z.number().max(100).optional(),offset: z.number().optional(),+ tag: z.string().optional(),}).optional(),)diff --git a/packages/database/src/models/__tests__/agent.tagFilter.test.ts b/packages/database/src/models/__tests__/agent.tagFilter.test.tsnew file mode 100644index 00000000000..a7d20d76a1a--- /dev/null+++ b/packages/database/src/models/__tests__/agent.tagFilter.test.ts@@ -0,0 +1,103 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { agents, users, workspaces } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { AgentModel } from '../agent';++const serverDB: LobeChatDatabase = await getTestDB();++const owner = 'tag-filter-owner';+const member = 'tag-filter-member';+let workspaceId = '';++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: owner }, { id: member }]);+ const [ws] = await serverDB+ .insert(workspaces)+ .values({ name: 'tag-filter-ws', primaryOwnerId: owner, slug: 'tag-filter-ws' })+ .returning();+ workspaceId = ws.id;+});++afterEach(async () => {+ await serverDB.delete(users);+});++describe('AgentModel queryAgents / countAgents — tag filter', () => {+ it('keeps only agents carrying the tag in a personal scope, and returns their tags', async () => {+ await serverDB.insert(agents).values([+ { id: 'pet-agent', tags: ['lobe-pet', 'cat'], title: 'Mimi', userId: owner },+ { id: 'plain-agent', tags: [], title: 'Writer', userId: owner },+ { id: 'other-tag-agent', tags: ['lobe-pet-x'], title: 'Near miss', userId: owner },+ { id: 'untagged-agent', title: 'Legacy', userId: owner },+ ]);+ const model = new AgentModel(serverDB, owner);++ const tagged = await model.queryAgents({ tag: 'lobe-pet' });+ expect(tagged.map((a) => a.id)).toEqual(['pet-agent']);+ expect(tagged[0].tags).toEqual(['lobe-pet', 'cat']);+ await expect(model.countAgents({ tag: 'lobe-pet' })).resolves.toBe(1);++ // without a tag nothing changes+ await expect(model.queryAgents()).resolves.toHaveLength(4);+ await expect(model.countAgents()).resolves.toBe(4);+ });++ it('applies the tag before the limit and leaves the inbox out', async () => {+ await serverDB.insert(agents).values([+ { id: 'inbox', slug: 'inbox', title: 'Lobe', userId: owner, virtual: true },+ {+ id: 'pet-old',+ tags: ['lobe-pet'],+ title: 'Old pet',+ updatedAt: new Date(1000),+ userId: owner,+ },+ { id: 'plain-new', tags: [], title: 'New plain', updatedAt: new Date(5000), userId: owner },+ ]);+ const model = new AgentModel(serverDB, owner);++ const result = await model.queryAgents({ includeInbox: true, limit: 1, tag: 'lobe-pet' });+ expect(result.map((a) => a.id)).toEqual(['pet-old']);+ });++ it('filters on an empty tag instead of treating it as no filter', async () => {+ await serverDB.insert(agents).values([+ { id: 'empty-tag', tags: [''], userId: owner },+ { id: 'plain', tags: ['a'], userId: owner },+ ]);+ const model = new AgentModel(serverDB, owner);++ expect((await model.queryAgents({ tag: '' })).map((a) => a.id)).toEqual(['empty-tag']);+ await expect(model.countAgents({ tag: '' })).resolves.toBe(1);+ });++ it('lists a member only the tagged agents the workspace already shows them', async () => {+ await serverDB.insert(agents).values([+ { id: 'ws-pet-public', tags: ['lobe-pet'], userId: owner, visibility: 'public', workspaceId },+ {+ id: 'ws-pet-private',+ tags: ['lobe-pet'],+ userId: owner,+ visibility: 'private',+ workspaceId,+ },+ { id: 'ws-crm', tags: [], userId: owner, visibility: 'public', workspaceId },+ {+ id: 'ws-member-pet',+ tags: ['lobe-pet'],+ userId: member,+ visibility: 'private',+ workspaceId,+ },+ ]);+ const model = new AgentModel(serverDB, member, workspaceId);++ const ids = (await model.queryAgents({ tag: 'lobe-pet' })).map((a) => a.id).sort();+ expect(ids).toEqual(['ws-member-pet', 'ws-pet-public']);+ await expect(model.countAgents({ tag: 'lobe-pet' })).resolves.toBe(2);+ });+});diff --git a/packages/database/src/models/agent/list.ts b/packages/database/src/models/agent/list.tsindex 5e3e51cc5a9..61ccbe18a00 100644--- a/packages/database/src/models/agent/list.ts+++ b/packages/database/src/models/agent/list.ts@@ -141,7 +141,7 @@ export const queryAgencyRoutingByIds = async (/*** Build the where condition shared by queryAgents / countAgents: the current- * user's agents, with optional keyword filter.+ * user's agents, with optional keyword and tag filters.** Virtual rows are infrastructure (group-built members, supervisors) and stay* excluded. That includes the inbox (Lobe AI): it is the product-owned@@ -160,6 +160,7 @@ export const buildQueryAgentsWhere = (ctx: AgentModelContext,keyword?: string,includeInbox = false,+ tag?: string,) => {// Include agents where virtual is false OR null (legacy data without virtual// field), plus the inbox when the caller opts into it.@@ -168,6 +169,9 @@ export const buildQueryAgentsWhere = (includeInbox? or(eq(agents.virtual, false), isNull(agents.virtual), eq(agents.slug, INBOX_SESSION_ID)): or(eq(agents.virtual, false), isNull(agents.virtual)),+ // A client that marks the agents it creates with a tag+ // lists only those: filtered here so `limit` is spent on matching rows.+ tag === undefined ? undefined : sql`${agents.tags} @> ${JSON.stringify([tag])}::jsonb`,);// `name` is the user-facing display name (see `agents.name`); resolving the@@ -200,7 +204,7 @@ export const buildQueryAgentsWhere = (/*** Query the user's agents with an optional keyword filter.* Returns minimal agent info (id, title, name, description, avatar,- * backgroundColor), plus `userId`/`visibility` so callers can gate per-agent+ * backgroundColor, tags), plus `userId`/`visibility` so callers can gate per-agent* actions (e.g. transfer is creator/primary-owner only), a compact* `heteroType` derived from `agencyConfig` so callers can tell which results* are heterogeneous (external CLI/device) agents, and `isInbox` so callers can@@ -208,7 +212,7 @@ export const buildQueryAgentsWhere = (* slug the row shape no longer carries.* Excludes virtual agents (supervisors, group-built members) and, unless the* caller opts in with `includeInbox: true`, the product-owned inbox (Lobe AI).- * See `buildQueryAgentsWhere`.+ * `tag` keeps only agents whose `tags` contain it. See `buildQueryAgentsWhere`.*/export const queryAgents = async (ctx: AgentModelContext,@@ -217,10 +221,11 @@ export const queryAgents = async (keyword?: string;limit?: number;offset?: number;+ tag?: string;},) => {- const { includeInbox = false, keyword, limit = 9999, offset = 0 } = params ?? {};- const searchCondition = buildQueryAgentsWhere(ctx, keyword, includeInbox);+ const { includeInbox = false, keyword, limit = 9999, offset = 0, tag } = params ?? {};+ const searchCondition = buildQueryAgentsWhere(ctx, keyword, includeInbox, tag);const rows = await ctx.db.select({@@ -231,6 +236,7 @@ export const queryAgents = async (id: agents.id,name: agents.name,slug: agents.slug,+ tags: agents.tags,title: agents.title,userId: agents.userId,visibility: agents.visibility,@@ -271,6 +277,7 @@ export const countAgents = async (keyword?: string;range?: [string, string];startDate?: string;+ tag?: string;},): Promise<number> => {const result = await ctx.db@@ -278,7 +285,7 @@ export const countAgents = async (.from(agents).where(genWhere([- buildQueryAgentsWhere(ctx, params?.keyword, params?.includeInbox ?? false),+ buildQueryAgentsWhere(ctx, params?.keyword, params?.includeInbox ?? false, params?.tag),params?.range? genRangeWhere(params.range, agents.createdAt, (date) => date.toDate()): undefined,