π€― 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(contact): list owner-listed link shares as a paged shared-Agent market (#23580)
Arvin Xu81b8637a2e04
diff --git a/apps/server/src/routers/lambda/agentShare.ts b/apps/server/src/routers/lambda/agentShare.tsindex b94358f540d..6c61613fa69 100644--- a/apps/server/src/routers/lambda/agentShare.ts+++ b/apps/server/src/routers/lambda/agentShare.ts@@ -87,6 +87,8 @@ export const agentShareConfigSchema = z.max(100).refine((ids) => new Set(ids).size === ids.length, 'Duplicate featured Work').optional(),+ /** Lists the share in the shared-Agent market; see `AgentShareConfig.listedInMarket`. */+ listedInMarket: z.boolean().optional(),/** Bytes; `0` is a real value (attachments off), so non-negative rather than positive. */maxFileStorage: z.number().int().nonnegative().optional(),maxMessagesPerVisitor: z.number().int().positive().optional(),diff --git a/apps/server/src/routers/lambda/contact.ts b/apps/server/src/routers/lambda/contact.tsindex d11b57cb636..deaab229de0 100644--- a/apps/server/src/routers/lambda/contact.ts+++ b/apps/server/src/routers/lambda/contact.ts@@ -181,6 +181,17 @@ export const contactRouter = router({// ββ Agents ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ /** The shared-Agent market: link shares their owners listed, paged by `nextCursor`. */+ listMarketAgents: contactProcedure+ .input(+ z.object({+ cursor: z.object({ createdAt: z.iso.datetime(), id: z.uuid() }).optional(),+ limit: z.number().int().min(1).max(50).default(20),+ query: z.string().trim().max(100).optional(),+ }),+ )+ .query(async ({ ctx, input }) => ctx.contactModel.listMarketAgents(input)),+// Changing a workspace's address book takes a member; a viewer only reads it.addAgent: contactProcedure.use(requireWorkspaceRoleWhenScoped('member'))diff --git a/packages/database/src/models/__tests__/agentShare.coverage.test.ts b/packages/database/src/models/__tests__/agentShare.coverage.test.tsindex 5f5ce83bc54..4ed39de2fc9 100644--- a/packages/database/src/models/__tests__/agentShare.coverage.test.ts+++ b/packages/database/src/models/__tests__/agentShare.coverage.test.ts@@ -162,6 +162,20 @@ describe('AgentShareModel coverage edges', () => {});});+ describe('listedInMarket', () => {+ it('reads back the ownerβs market listing from the update and the share status', async () => {+ const model = new AgentShareModel(serverDB, userId);+ await model.create(agentId);++ const listed = await model.updateConfig(agentId, { listedInMarket: true });+ expect(listed?.shareConfig.listedInMarket).toBe(true);+ expect((await model.getByAgentId(agentId))?.shareConfig.listedInMarket).toBe(true);++ await model.updateConfig(agentId, { listedInMarket: false });+ expect((await model.getByAgentId(agentId))?.shareConfig.listedInMarket).toBe(false);+ });+ });+describe('updateSlug', () => {it('returns null when clearing the slug of an owned agent that has no share', async () => {const model = new AgentShareModel(serverDB, userId);diff --git a/packages/database/src/models/__tests__/contact.test.ts b/packages/database/src/models/__tests__/contact.test.tsindex 9ba035c6639..1c6b268a270 100644--- a/packages/database/src/models/__tests__/contact.test.ts+++ b/packages/database/src/models/__tests__/contact.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { eq } from 'drizzle-orm';+import { eq, sql } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../core/getTestDB';@@ -249,6 +249,79 @@ describe('shared Agents', () => {});});+describe('shared-Agent market', () => {+ const listIn = (shareConfig: Record<string, unknown>) => ({+ monthlySpendLimit: 1,+ ...shareConfig,+ });++ it('lists only link shares their owners listed, without the trashed', async () => {+ expect((await carolModel.listMarketAgents({ limit: 10 })).items).toEqual([]);++ await serverDB+ .update(agentShares)+ .set({ shareConfig: listIn({ listedInMarket: true, slug: 'bob-helper' }) })+ .where(eq(agentShares.agentId, bobAgent));+ const { items, nextCursor } = await carolModel.listMarketAgents({ limit: 10 });+ expect(items).toMatchObject([+ { agentId: bobAgent, owner: { id: bob }, slug: 'bob-helper', title: 'Bob Helper' },+ ]);+ expect(nextCursor).toBeNull();++ // A paused share or a trashed Agent leaves the market even while still marked listed.+ await serverDB+ .update(agentShares)+ .set({ visibility: 'card' })+ .where(eq(agentShares.agentId, bobAgent));+ expect((await carolModel.listMarketAgents({ limit: 10 })).items).toEqual([]);+ await serverDB+ .update(agentShares)+ .set({ visibility: 'link' })+ .where(eq(agentShares.agentId, bobAgent));+ await serverDB.update(agents).set({ isDeleted: true }).where(eq(agents.id, bobAgent));+ expect((await carolModel.listMarketAgents({ limit: 10 })).items).toEqual([]);+ });++ it('pages newest first without repeating a share, and filters by title', async () => {+ await serverDB.update(agentShares).set({ shareConfig: listIn({ listedInMarket: true }) });+ await serverDB+ .update(agentShares)+ .set({ createdAt: new Date('2026-01-01') })+ .where(eq(agentShares.agentId, bobAgent));+ await serverDB+ .update(agentShares)+ .set({ createdAt: new Date('2026-02-01') })+ .where(eq(agentShares.agentId, aliceAgent));++ const first = await carolModel.listMarketAgents({ limit: 1 });+ expect(first.items.map((a) => a.agentId)).toEqual([aliceAgent]);+ expect(first.nextCursor).not.toBeNull();+ const second = await carolModel.listMarketAgents({+ cursor: first.nextCursor!,+ limit: 1,+ });+ expect(second.items.map((a) => a.agentId)).toEqual([bobAgent]);+ expect(second.nextCursor).toBeNull();++ // Two shares inside one millisecond: the cursor keeps microseconds, so none is skipped.+ await serverDB+ .update(agentShares)+ .set({ createdAt: sql`'2026-03-01T00:00:00.123900Z'::timestamptz` })+ .where(eq(agentShares.agentId, aliceAgent));+ await serverDB+ .update(agentShares)+ .set({ createdAt: sql`'2026-03-01T00:00:00.123800Z'::timestamptz` })+ .where(eq(agentShares.agentId, bobAgent));+ const sameMs = await carolModel.listMarketAgents({ limit: 1 });+ expect(sameMs.nextCursor?.createdAt).toBe('2026-03-01T00:00:00.123900Z');+ const rest = await carolModel.listMarketAgents({ cursor: sameMs.nextCursor!, limit: 1 });+ expect(rest.items.map((a) => a.agentId)).toEqual([bobAgent]);++ const found = await carolModel.listMarketAgents({ limit: 10, query: 'bob' });+ expect(found.items.map((a) => a.agentId)).toEqual([bobAgent]);+ });+});+describe('shared Agents in a workspace', () => {it('belong to the workspace: every member sees and can message them', async () => {await aliceInTeam.addAgent('bob-helper');diff --git a/packages/database/src/models/agentShare.ts b/packages/database/src/models/agentShare.tsindex 36e53628d2b..ccbe9478c5e 100644--- a/packages/database/src/models/agentShare.ts+++ b/packages/database/src/models/agentShare.ts@@ -52,6 +52,7 @@ const normalizeAgentShareConfig = (deviceAccess: config?.deviceAccess ?? 'none',deviceAllowUserIds: config?.deviceAllowUserIds ?? [],featuredWorkIds: config?.featuredWorkIds ?? [],+ listedInMarket: config?.listedInMarket,maxFileStorage: config?.maxFileStorage ?? DEFAULT_AGENT_SHARE_CONFIG.maxFileStorage,maxMessagesPerVisitor:config?.maxMessagesPerVisitor ?? DEFAULT_AGENT_SHARE_CONFIG.maxMessagesPerVisitor,diff --git a/packages/database/src/models/contact.ts b/packages/database/src/models/contact.tsindex 91982ae6a5a..8dc0c3903aa 100644--- a/packages/database/src/models/contact.ts+++ b/packages/database/src/models/contact.ts@@ -15,7 +15,7 @@ import type {import { agentDisplayName, channelMessageDeletedAt, contactCardOf } from '@lobechat/types';import { TRPCError } from '@trpc/server';import type { SQLWrapper } from 'drizzle-orm';-import { and, desc, eq, exists, inArray, isNotNull, isNull, not, or, sql } from 'drizzle-orm';+import { and, desc, eq, exists, inArray, isNotNull, isNull, lt, not, or, sql } from 'drizzle-orm';import { alias } from 'drizzle-orm/pg-core';import {@@ -31,11 +31,11 @@ import {} from '../schemas';import type { LobeChatDatabase } from '../type';import { agentShareAdmits } from '../utils/agentShareAdmits';-import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '../utils/inboxAgent';import { ilikeContains } from '../utils/like';import { notTrashed } from '../utils/softDelete';import { isUuid } from '../utils/uuid';import { AgentShareModel } from './agentShare';+import { agentProfileColumns, owners, toAgentProfile } from './contactAgentProfile';const userProfileColumns = {avatar: users.avatar,@@ -44,9 +44,20 @@ const userProfileColumns = {username: users.username,};-const owners = alias(users, 'contact_agent_owner');const referrers = alias(users, 'contact_request_referrer');+/**+ * A share's creation time as microsecond ISO text: a `Date` keeps only milliseconds, and a+ * cursor cut to them would skip shares created later within the same millisecond.+ */+const shareCreatedAtIso = sql<string>`to_char(${agentShares.createdAt} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`;++/** Where a market page ends: the last share's creation time (microsecond ISO) and id. */+export interface MarketAgentCursor {+ createdAt: string;+ id: string;+}+/** Who the caller is in the active scope. */type ScopeRole = 'personal' | 'member' | 'external';@@ -60,58 +71,6 @@ const activeMemberWhere = (workspaceId: string, userId: string | SQLWrapper) =>isNull(workspaceMembers.deletedAt),);-/** Columns of an Agent reached through its share, with the owner joined as `owners`. */-const agentProfileColumns = {- agentAvatar: agents.avatar,- agentBackgroundColor: agents.backgroundColor,- agentDescription: agents.description,- agentId: agents.id,- agentName: agents.name,- agentSlug: agents.slug,- agentTitle: agents.title,- isDeleted: agents.isDeleted,- ownerAvatar: owners.avatar,- ownerFullName: owners.fullName,- ownerId: owners.id,- ownerUsername: owners.username,- shareId: agentShares.id,- shareSlug: sql<string | null>`${agentShares.shareConfig} ->> 'slug'`,- visibility: agentShares.visibility,-};--type AgentProfileRow = {- agentAvatar: string | null;- agentBackgroundColor: string | null;- agentDescription: string | null;- agentId: string;- agentName: string | null;- agentSlug: string | null;- agentTitle: string | null;- ownerAvatar: string | null;- ownerFullName: string | null;- ownerId: string | null;- ownerUsername: string | null;- shareId: string;- shareSlug: string | null;-};--const toAgentProfile = (row: AgentProfileRow): ContactAgentProfile => ({- agentId: row.agentId,- avatar: normalizeInboxAgentAvatar(row.agentAvatar, { slug: row.agentSlug }) ?? null,- backgroundColor: row.agentBackgroundColor,- description: row.agentDescription,- name: row.agentName?.trim() || null,- owner: {- avatar: row.ownerAvatar,- fullName: row.ownerFullName,- id: row.ownerId ?? '',- username: row.ownerUsername,- },- shareId: row.shareId,- slug: row.shareSlug,- title: normalizeInboxAgentTitle(row.agentTitle, { slug: row.agentSlug }) ?? null,-});-/** Share handles are stored lowercase; accept `@handle`, `/a/handle` and full share URLs. */export const parseContactHandle = (query: string): string | undefined => {const trimmed = query.trim();@@ -1056,6 +1015,54 @@ export class ContactModel {return rows.map(toAgentProfile);};+ /**+ * The shared-Agent market: link shares whose owners listed them, newest first, one page at a+ * time. Keyset-paged on the share's creation time (id breaks ties), so a share listed while+ * someone scrolls neither repeats nor skips a row. `query` matches the title or description.+ */+ listMarketAgents = async (options: {+ cursor?: MarketAgentCursor;+ limit: number;+ query?: string;+ }): Promise<{ items: ContactAgentProfile[]; nextCursor: MarketAgentCursor | null }> => {+ const { cursor, limit } = options;+ const query = options.query?.trim();+ const rows = await this.db+ .select({ ...agentProfileColumns, shareCreatedAt: shareCreatedAtIso })+ .from(agentShares)+ .innerJoin(agents, eq(agents.id, agentShares.agentId))+ .leftJoin(owners, eq(owners.id, agents.userId))+ .where(+ and(+ eq(agentShares.visibility, 'link'),+ sql`(${agentShares.shareConfig} ->> 'listedInMarket')::boolean IS TRUE`,+ notTrashed(agents.isDeleted),+ query+ ? or(ilikeContains(agents.title, query), ilikeContains(agents.description, query))+ : undefined,+ cursor+ ? or(+ sql`${agentShares.createdAt} < ${cursor.createdAt}::timestamptz`,+ and(+ sql`${agentShares.createdAt} = ${cursor.createdAt}::timestamptz`,+ lt(agentShares.id, cursor.id),+ ),+ )+ : undefined,+ ),+ )+ .orderBy(desc(agentShares.createdAt), desc(agentShares.id))+ .limit(limit + 1);++ const page = rows.slice(0, limit);+ const last = page.at(-1);+ return {+ items: page.map(toAgentProfile),+ nextCursor:+ rows.length > limit && last ? { createdAt: last.shareCreatedAt, id: last.shareId } : null,+ };+ };+// ββ Search ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ/**diff --git a/packages/database/src/models/contactAgentProfile.ts b/packages/database/src/models/contactAgentProfile.tsnew file mode 100644index 00000000000..cece1afea8f--- /dev/null+++ b/packages/database/src/models/contactAgentProfile.ts@@ -0,0 +1,61 @@+import type { ContactAgentProfile } from '@lobechat/types';+import { sql } from 'drizzle-orm';+import { alias } from 'drizzle-orm/pg-core';++import { agents, agentShares, users } from '../schemas';+import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '../utils/inboxAgent';++/** An Agent's owner, joined next to `agents` when an Agent is read through its share. */+export const owners = alias(users, 'contact_agent_owner');++/** Columns of an Agent reached through its share, with the owner joined as `owners`. */+export const agentProfileColumns = {+ agentAvatar: agents.avatar,+ agentBackgroundColor: agents.backgroundColor,+ agentDescription: agents.description,+ agentId: agents.id,+ agentName: agents.name,+ agentSlug: agents.slug,+ agentTitle: agents.title,+ isDeleted: agents.isDeleted,+ ownerAvatar: owners.avatar,+ ownerFullName: owners.fullName,+ ownerId: owners.id,+ ownerUsername: owners.username,+ shareId: agentShares.id,+ shareSlug: sql<string | null>`${agentShares.shareConfig} ->> 'slug'`,+ visibility: agentShares.visibility,+};++type AgentProfileRow = {+ agentAvatar: string | null;+ agentBackgroundColor: string | null;+ agentDescription: string | null;+ agentId: string;+ agentName: string | null;+ agentSlug: string | null;+ agentTitle: string | null;+ ownerAvatar: string | null;+ ownerFullName: string | null;+ ownerId: string | null;+ ownerUsername: string | null;+ shareId: string;+ shareSlug: string | null;+};++export const toAgentProfile = (row: AgentProfileRow): ContactAgentProfile => ({+ agentId: row.agentId,+ avatar: normalizeInboxAgentAvatar(row.agentAvatar, { slug: row.agentSlug }) ?? null,+ backgroundColor: row.agentBackgroundColor,+ description: row.agentDescription,+ name: row.agentName?.trim() || null,+ owner: {+ avatar: row.ownerAvatar,+ fullName: row.ownerFullName,+ id: row.ownerId ?? '',+ username: row.ownerUsername,+ },+ shareId: row.shareId,+ slug: row.shareSlug,+ title: normalizeInboxAgentTitle(row.agentTitle, { slug: row.agentSlug }) ?? null,+});diff --git a/packages/database/src/schemas/agentShare.ts b/packages/database/src/schemas/agentShare.tsindex 04b80fd10dd..df5aa41251b 100644--- a/packages/database/src/schemas/agentShare.ts+++ b/packages/database/src/schemas/agentShare.ts@@ -77,6 +77,11 @@ export interface AgentShareConfig {deviceAllowUserIds?: string[];/** Ordered, explicitly selected creator Works for this share's public profile. */featuredWorkIds?: string[];+ /**+ * The owner lists this share in the shared-Agent market, where anyone signed in can browse+ * it. Only read while the share is `link`; a link alone never puts an Agent in the market.+ */+ listedInMarket?: boolean;/*** Total bytes this share's visitor uploads may occupy in the Agent's owning* scope (settled files plus in-flight reservations). Mandatory like