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(channel): contacts, conversations between people, and shared Agents in Channels (#23044)

Arvin Xu7b7bbdfc1b70
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index 3d84b9303cf..d76fac4b64f 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -229,6 +229,20 @@ export const channelRouter = router({
const access = await ctx.channelService.openDirect(input.agentId);
return { data: access?.channel.id ?? null, success: true };
}),
+ /** The direct conversation with another person's Agent, from its share id, handle or link. */
+ openShared: channelProcedure
+ .input(z.object({ share: z.string().trim().min(1).max(512) }))
+ .mutation(async ({ ctx, input }) => {
+ const access = await ctx.channelService.openShared(input.share);
+ return { data: access?.channel.id ?? null, success: true };
+ }),
+ /** The personal conversation with a contact; both people must still be contacts. */
+ openPeer: channelProcedure
+ .input(z.object({ userId: z.string().min(1).max(64) }))
+ .mutation(async ({ ctx, input }) => {
+ const access = await ctx.channelService.openPeer(input.userId);
+ return { data: access.channel.id, success: true };
+ }),
list: channelProcedure.query(async ({ ctx }) => ({
data: await ctx.channelService.repository.list(),
success: true,
diff --git a/apps/server/src/routers/lambda/contact.ts b/apps/server/src/routers/lambda/contact.ts
new file mode 100644
index 00000000000..efa9d4eac73
--- /dev/null
+++ b/apps/server/src/routers/lambda/contact.ts
@@ -0,0 +1,94 @@
+import { CONTACT_REQUEST_MESSAGE_MAX_LENGTH } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { ContactModel } from '@/database/models/contact';
+import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { isChannelEnabled } from '@/server/services/channel/featureGate';
+
+/**
+ * The address book belongs to the Channel experience: contacts are who you can message there.
+ * It is personal, so it never takes a workspace scope.
+ */
+const contactProcedure = authedProcedure.use(serverDatabase).use(async ({ ctx, next }) => {
+ if (!(await isChannelEnabled(ctx.userId)))
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Channels are not enabled for this account',
+ });
+ return next({ ctx: { contactModel: new ContactModel(ctx.serverDB, ctx.userId) } });
+});
+
+const userId = z.string().min(1).max(64);
+const requestId = z.string().uuid();
+/** A username, `@handle`, share id or pasted share link. */
+const handle = z.string().trim().min(1).max(512);
+
+export const contactRouter = router({
+ list: contactProcedure.query(async ({ ctx }) => ctx.contactModel.list()),
+
+ search: contactProcedure
+ .input(z.object({ query: handle }))
+ .query(async ({ ctx, input }) => ctx.contactModel.search(input.query)),
+
+ // ── People ────────────────────────────────────────────────────────────
+
+ listRequests: contactProcedure.query(async ({ ctx }) => ctx.contactModel.listRequests()),
+
+ sendRequest: contactProcedure
+ .input(
+ z.object({
+ message: z.string().max(CONTACT_REQUEST_MESSAGE_MAX_LENGTH).optional(),
+ userId,
+ }),
+ )
+ .mutation(async ({ ctx, input }) => ctx.contactModel.sendRequest(input.userId, input.message)),
+
+ acceptRequest: contactProcedure
+ .input(z.object({ requestId }))
+ .mutation(async ({ ctx, input }) => ctx.contactModel.acceptRequest(input.requestId)),
+
+ declineRequest: contactProcedure
+ .input(z.object({ requestId }))
+ .mutation(async ({ ctx, input }) => {
+ await ctx.contactModel.declineRequest(input.requestId);
+ return { success: true };
+ }),
+
+ cancelRequest: contactProcedure
+ .input(z.object({ requestId }))
+ .mutation(async ({ ctx, input }) => {
+ await ctx.contactModel.cancelRequest(input.requestId);
+ return { success: true };
+ }),
+
+ removeUser: contactProcedure.input(z.object({ userId })).mutation(async ({ ctx, input }) => {
+ await ctx.contactModel.removeUser(input.userId);
+ return { success: true };
+ }),
+
+ /** A person's profile, their relation to me and the Agents they share by link. */
+ userProfile: contactProcedure.input(z.object({ userId })).query(async ({ ctx, input }) => {
+ const [user, relation, sharedAgents] = await Promise.all([
+ ctx.contactModel.findUser(input.userId),
+ ctx.contactModel.relationTo(input.userId),
+ ctx.contactModel.listSharedAgentsOf(input.userId),
+ ]);
+ if (!user) throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found' });
+ return { relation, sharedAgents, user };
+ }),
+
+ // ── Agents ────────────────────────────────────────────────────────────
+
+ addAgent: contactProcedure
+ .input(z.object({ share: handle }))
+ .mutation(async ({ ctx, input }) => ctx.contactModel.addAgent(input.share)),
+
+ removeAgent: contactProcedure
+ .input(z.object({ agentId: z.string().min(1).max(64) }))
+ .mutation(async ({ ctx, input }) => {
+ await ctx.contactModel.removeAgent(input.agentId);
+ return { success: true };
+ }),
+});
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index a12e0a12389..ceebdc1f485 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -58,6 +58,7 @@ import { comfyuiRouter } from './comfyui';
import { composioRouter } from './composio';
import { configRouter } from './config';
import { connectorRouter } from './connector';
+import { contactRouter } from './contact';
import { dashboardRouter } from './dashboard';
import { deviceRouter } from './device';
import { deviceMetricRouter } from './deviceMetric';
@@ -154,6 +155,7 @@ export const lambdaRouter = router({
canvas: canvasRouter,
changelog: changelogRouter,
channel: channelRouter,
+ contact: contactRouter,
brief: briefRouter,
aiAgent: aiAgentRouter,
aiChat: aiChatRouter,
diff --git a/apps/server/src/services/aiAgent/shareGate/allowlist.ts b/apps/server/src/services/aiAgent/shareGate/allowlist.ts
index 4216b940644..2c80734df94 100644
--- a/apps/server/src/services/aiAgent/shareGate/allowlist.ts
+++ b/apps/server/src/services/aiAgent/shareGate/allowlist.ts
@@ -1,3 +1,4 @@
+import { ChannelApiName, ChannelIdentifier } from '@lobechat/builtin-tool-channel';
import {
AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS,
isBuiltinToolIdentifier,
@@ -20,3 +21,25 @@ export const SHARE_VISITOR_ALLOWED_IDENTIFIERS = AGENT_SHARE_ALLOWED_BUILTIN_IDE
* pre-existing (and unaffected) gate for that population.
*/
export const isGovernedByBuiltinAllowlist = isBuiltinToolIdentifier;
+
+/**
+ * The Channel history reads a shared Agent may make when a Channel runs it for a visitor: the
+ * public timeline of that visitor's own conversation, which they already see. Every read
+ * re-authorizes against the run's reserved Channel operation (`ChannelHistoryRepository`), so a
+ * share-page run, which has none, reads nothing. `listChannels` and `sendMessage` stay blocked:
+ * the run executes as the owner, and they would list or post into the owner's own Channels.
+ * Exempt from the owner's `toolGrants`, which picks the Agent's tools, not the Channel's.
+ */
+const SHARE_VISITOR_CHANNEL_READ_APIS = new Set<string>([
+ ChannelApiName.readMessage,
+ ChannelApiName.readMessages,
+]);
+
+export const SHARE_VISITOR_CHANNEL_BLOCKED_APIS = new Set<string>(
+ Object.values(ChannelApiName).filter((name) => !SHARE_VISITOR_CHANNEL_READ_APIS.has(name)),
+);
+
+export const isShareVisitorChannelTool = (identifier: string) => identifier === ChannelIdentifier;
+
+export const isShareVisitorChannelRead = (identifier: string, apiName: string) =>
+ isShareVisitorChannelTool(identifier) && SHARE_VISITOR_CHANNEL_READ_APIS.has(apiName);
diff --git a/apps/server/src/services/aiAgent/shareGate/channel.test.ts b/apps/server/src/services/aiAgent/shareGate/channel.test.ts
new file mode 100644
index 00000000000..3b3630315fc
--- /dev/null
+++ b/apps/server/src/services/aiAgent/shareGate/channel.test.ts
@@ -0,0 +1,54 @@
+import { ChannelApiName, ChannelIdentifier } from '@lobechat/builtin-tool-channel';
+import { describe, expect, it } from 'vitest';
+
+import {
+ applyShareGateToToolSet,
+ isShareBlockedBuiltinDispatch,
+ isShareBlockedDataToolCall,
+} from '.';
+import { buildGate, buildToolSet, toolName } from './testUtils';
+
+/**
+ * A Channel runs another person's shared Agent for a visitor as its owner. The visitor's own
+ * conversation history must stay readable, but nothing may list or post into the owner's
+ * Channels.
+ */
+describe('share gate: the Channel tool of a shared Agent run', () => {
+ const channelTool = () =>
+ buildToolSet([
+ {
+ apis: Object.values(ChannelApiName).map((name) => ({ name })),
+ identifier: ChannelIdentifier,
+ },
+ ]);
+
+ it('keeps only the history reads, even with no tool granted', () => {
+ const toolSet = channelTool();
+ applyShareGateToToolSet(toolSet, buildGate({ toolGrants: [] }));
+
+ expect(toolSet.enabledToolIds).toEqual([ChannelIdentifier]);
+ expect(toolSet.manifestMap[ChannelIdentifier].api.map((api) => api.name).sort()).toEqual([
+ ChannelApiName.readMessage,
+ ChannelApiName.readMessages,
+ ]);
+ expect(toolSet.tools?.map((tool) => tool.function.name).sort()).toEqual(
+ [
+ toolName(ChannelIdentifier, ChannelApiName.readMessage),
+ toolName(ChannelIdentifier, ChannelApiName.readMessages),
+ ].sort(),
+ );
+ });
+
+ it.each([ChannelApiName.readMessage, ChannelApiName.readMessages])('dispatches %s', (apiName) => {
+ expect(isShareBlockedBuiltinDispatch({}, ChannelIdentifier, apiName)).toBe(false);
+ expect(isShareBlockedDataToolCall({}, ChannelIdentifier, apiName)).toBe(false);
+ });
+
+ it.each([ChannelApiName.listChannels, ChannelApiName.sendMessage])(
+ 'refuses %s, which would act in the owner’s Channels',
+ (apiName) => {
+ expect(isShareBlockedBuiltinDispatch({}, ChannelIdentifier, apiName)).toBe(true);
+ expect(isShareBlockedDataToolCall({}, ChannelIdentifier, apiName)).toBe(true);
+ },
+ );
+});
diff --git a/apps/server/src/services/aiAgent/shareGate/dispatch.ts b/apps/server/src/services/aiAgent/shareGate/dispatch.ts
index b4201824da6..9340c77f3bf 100644
--- a/apps/server/src/services/aiAgent/shareGate/dispatch.ts
+++ b/apps/server/src/services/aiAgent/shareGate/dispatch.ts
@@ -1,7 +1,12 @@
import { isShareToolApiGranted } from '@lobechat/const';
import type { AgentShareToolGrant } from '@lobechat/types';
-import { isGovernedByBuiltinAllowlist, SHARE_VISITOR_ALLOWED_IDENTIFIERS } from './allowlist';
+import {
+ isGovernedByBuiltinAllowlist,
+ isShareVisitorChannelRead,
+ isShareVisitorChannelTool,
+ SHARE_VISITOR_ALLOWED_IDENTIFIERS,
+} from './allowlist';
import { DATA_TOOL_ACCESS_RULES } from './dataToolRules';
import { resolveEffectiveShareToolGrants } from './grants';
import { SUB_AGENT_DISPATCH_APIS } from './subAgentDispatch';
@@ -39,6 +44,7 @@ export const isShareBlockedDataToolCall = (
// Outside this gate's jurisdiction entirely β€” MCP/market/custom plugin
// identifiers are governed by the toolGrants picker, not this allowlist.
if (!isGovernedByBuiltinAllowlist(identifier)) return false;
+ if (isShareVisitorChannelTool(identifier)) return !isShareVisitorChannelRead(identifier, apiName);
// Default-deny: a known builtin identifier not on the allowlist is blocked
// unconditionally, including any tool registered after this allowlist was
@@ -86,6 +92,8 @@ export const isShareBlockedBuiltinDispatch = (
): boolean => {
if (!isGovernedByBuiltinAllowlist(identifier)) return false;
+ // A Channel run's history reads only; see `isShareVisitorChannelRead`.
+ if (isShareVisitorChannelTool(identifier)) return !isShareVisitorChannelRead(identifier, apiName);
if (!SHARE_VISITOR_ALLOWED_IDENTIFIERS.has(identifier)) return true;
// The owner's picker must grant this identifier at all (toolset-level or
// naming this specific `apiName`) β€” a grant scoped to a DIFFERENT api on
diff --git a/apps/server/src/services/aiAgent/shareGate/toolSet.ts b/apps/server/src/services/aiAgent/shareGate/toolSet.ts
index 7e57fbca807..199fbc5ba01 100644
--- a/apps/server/src/services/aiAgent/shareGate/toolSet.ts
+++ b/apps/server/src/services/aiAgent/shareGate/toolSet.ts
@@ -10,7 +10,12 @@ import { SkillsIdentifier } from '@lobechat/builtin-tool-skills';
import { hasShareToolGrant, PLUGIN_SCHEMA_SEPARATOR, type ShareToolGrant } from '@lobechat/const';
import { isDeviceOnlyMcpEndpoint } from '@lobechat/utils/mcpEndpoint';
-import { isGovernedByBuiltinAllowlist, SHARE_VISITOR_ALLOWED_IDENTIFIERS } from './allowlist';
+import {
+ isGovernedByBuiltinAllowlist,
+ isShareVisitorChannelTool,
+ SHARE_VISITOR_ALLOWED_IDENTIFIERS,
+ SHARE_VISITOR_CHANNEL_BLOCKED_APIS,
+} from './allowlist';
import { DATA_TOOL_ACCESS_RULES } from './dataToolRules';
import { resolveEffectiveShareToolGrants } from './grants';
import { stripSubAgentDispatchApis } from './subAgentDispatch';
@@ -96,6 +101,8 @@ export const applyShareGateToToolSet = (toolSet: ShareGateToolSet, gate: AgentSh
const isAllowed = (id: string) => {
if (deviceOnlyMcpIds.has(id)) return false;
+ // Only a Channel run injects this tool; its reads are narrowed below.
+ if (isShareVisitorChannelTool(id)) return true;
if (!hasShareToolGrant(grants, id)) return false;
if (!isGovernedByBuiltinAllowlist(id)) return true;
return SHARE_VISITOR_ALLOWED_IDENTIFIERS.has(id);
@@ -144,6 +151,9 @@ export const applyShareGateToToolSet = (toolSet: ShareGateToolSet, gate: AgentSh
}
stripSubAgentDispatchApis(toolSet);
+ for (const id of Object.keys(toolSet.manifestMap))
+ if (isShareVisitorChannelTool(id))
+ stripApisFromTool(toolSet, id, SHARE_VISITOR_CHANNEL_BLOCKED_APIS);
applyShareGateToDataToolAccess(toolSet, gate);
applyShareGateToPerApiGrants(toolSet, grants);
applyShareGateToActivator(toolSet);
diff --git a/apps/server/src/services/channel/ChannelCoordinator.share.test.ts b/apps/server/src/services/channel/ChannelCoordinator.share.test.ts
new file mode 100644
index 00000000000..4d85d3e7d51
--- /dev/null
+++ b/apps/server/src/services/channel/ChannelCoordinator.share.test.ts
@@ -0,0 +1,192 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ChannelCoordinator } from './ChannelCoordinator';
+
+const {
+ checkSpend,
+ execAgent,
+ executions,
+ findOperation,
+ findShare,
+ getScopedOnlineDevices,
+ resolveChannelAttachments,
+ serviceOptions,
+} = vi.hoisted(() => ({
+ checkSpend: vi.fn(),
+ getScopedOnlineDevices: vi.fn(),
+ execAgent: vi.fn(),
+ executions: {
+ accepted: vi.fn(),
+ candidates: vi.fn(),
+ claim: vi.fn(),
+ fail: vi.fn(),
+ finishDispatch: vi.fn(),
+ heartbeat: vi.fn(),
+ input: vi.fn(),
+ openingReply: vi.fn(),
+ primaryReply: vi.fn(),
+ recentContext: vi.fn(),
+ retireReservation: vi.fn(),
+ },
+ findOperation: vi.fn(),
+ findShare: vi.fn(),
+ resolveChannelAttachments: vi.fn(),
+ serviceOptions: [] as Array<{ options: unknown; userId: string }>,
+}));
+vi.mock('@/database/repositories/channel', () => ({
+ ChannelExecutionRepository: class {
+ constructor() {
+ return executions;
+ }
+ },
+}));
+vi.mock('@/database/models/agentShare', () => ({ AgentShareModel: { findByShareId: findShare } }));
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: class {
+ findById = findOperation;
+ },
+}));
+vi.mock('@/business/server/agent-share/spendGate', () => ({
+ checkAgentShareSpendAllowance: checkSpend,
+}));
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: class {
+ execAgent = execAgent;
+ constructor(_db: unknown, userId: string, options: unknown) {
+ serviceOptions.push({ options, userId });
+ }
+ },
+}));
+vi.mock('@/server/globalConfig', () => ({ getServerDefaultAgentConfig: () => ({}) }));
+vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: {} }));
+vi.mock('@/server/services/deviceGateway/scopedDevices', () => ({ getScopedOnlineDevices }));
+vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: () => false }));
+vi.mock('./attachments', () => ({ resolveChannelAttachments }));
+vi.mock('./ChannelRoutingService', () => ({
+ ChannelRoutingService: class {
+ advance = vi.fn().mockResolvedValue(undefined);
+ },
+}));
+vi.mock('./notify', () => ({ notifyChannel: vi.fn() }));
+vi.mock('./queue', () => ({ registerLocalChannelAdvance: vi.fn(), wakeChannel: vi.fn() }));
+vi.mock('./replyOpening', () => ({ openChannelReply: vi.fn() }));
+vi.mock('./worktree', () => ({ createChannelWorktree: vi.fn() }));
+
+const share = { ownerId: 'owner', shareId: 'share-1', workspaceId: 'owner-ws' };
+const liveShare = {
+ agentId: 'agt_shared',
+ ownerId: 'owner',
+ shareConfig: { monthlySpendLimit: 5, toolGrants: [] },
+ shareId: 'share-1',
+ visibility: 'link',
+ workspaceId: 'owner-ws',
+};
+
+const coordinator = () => {
+ executions.candidates.mockResolvedValue({
+ heads: [{ id: 'job', memberId: 'member', status: 'queued' }],
+ inFlight: [],
+ });
+ const query = (rows: unknown[]) => {
+ const result = Object.assign(Promise.resolve(rows), {
+ from: vi.fn(),
+ innerJoin: vi.fn(),
+ leftJoin: vi.fn(),
+ limit: vi.fn(),
+ orderBy: vi.fn(),
+ where: vi.fn(),
+ });
+ for (const method of ['from', 'innerJoin', 'leftJoin', 'where', 'orderBy', 'limit'] as const)
+ result[method].mockReturnValue(result);
+ return result;
+ };
+ const select = vi
+ .fn()
+ .mockReturnValue(query([]))
+ .mockReturnValueOnce(
+ query([{ id: 'channel', projectId: 'visitor-project', workspaceId: null }]),
+ )
+ .mockReturnValueOnce(query([]));
+ return new ChannelCoordinator({ select } as never);
+};
+
+describe('dispatching a contact’s shared Agent', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ serviceOptions.length = 0;
+ getScopedOnlineDevices.mockResolvedValue([]);
+ executions.input.mockResolvedValue([]);
+ executions.recentContext.mockResolvedValue({ messages: [], omitted: 0 });
+ executions.primaryReply.mockResolvedValue(null);
+ executions.openingReply.mockResolvedValue(undefined);
+ executions.heartbeat.mockResolvedValue(true);
+ execAgent.mockResolvedValue({ success: true });
+ findShare.mockResolvedValue(liveShare);
+ checkSpend.mockResolvedValue({ allowed: true });
+ findOperation.mockResolvedValue({ status: 'idle' });
+ executions.claim.mockResolvedValue({
+ job: {
+ channelId: 'channel',
+ executionConfig: { runtime: 'native', share },
+ id: 'job',
+ leaseOwner: 'dispatcher',
+ manifest: {
+ cutoffSequence: 1,
+ requestMessageId: 'message',
+ requesterMemberId: 'visitor-member',
+ self: { agentId: 'agt_shared', memberId: 'member', name: 'Shared' },
+ threadId: null,
+ threadRootSequence: null,
+ },
+ operationId: 'op',
+ },
+ member: { agentId: 'agt_shared' },
+ topic: { id: 'topic', senderId: 'visitor', userId: 'owner' },
+ });
+ });
+
+ it('runs as the owner, in the owner’s scope, under the live share gate', async () => {
+ await coordinator().advance('channel');
+
+ expect(serviceOptions).toEqual([
+ { options: { includeShareVisitor: true, workspaceId: 'owner-ws' }, userId: 'owner' },
+ ]);
+ const [params] = execAgent.mock.calls[0];
+ expect(params.shareGate).toEqual({
+ agentId: 'agt_shared',
+ shareConfig: liveShare.shareConfig,
+ shareId: 'share-1',
+ visitorUserId: 'visitor',
+ });
+ // Neither the visitor's project nor the visitor's files reach the owner's run.
+ expect(params.appContext).toEqual({ topicId: 'topic' });
+ expect(resolveChannelAttachments).not.toHaveBeenCalled();
+ expect(checkSpend).toHaveBeenCalledWith(
+ expect.objectContaining({
+ monthlySpendLimit: 5,
+ ownerUserId: 'owner',
+ visitorUserId: 'visitor',
+ }),
+ );
+ expect(executions.accepted).toHaveBeenCalledWith('channel', 'job');
+ });
+
+ it.each([
+ [
+ 'the share was paused',
+ () => findShare.mockResolvedValue({ ...liveShare, visibility: 'private' }),
+ ],
+ [
+ 'the share moved to another owner',
+ () => findShare.mockResolvedValue({ ...liveShare, ownerId: 'x' }),
+ ],
+ ['the monthly limit is reached', () => checkSpend.mockResolvedValue({ allowed: false })],
+ ])('submits nothing when %s', async (_, arrange) => {
+ arrange();
+ await coordinator().advance('channel');
+
+ expect(execAgent).not.toHaveBeenCalled();
+ expect(executions.retireReservation).toHaveBeenCalledWith('channel', 'job');
+ });
+});
diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.ts
index d71431a1c9b..86ec9c5e8f4 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.ts
@@ -1,14 +1,16 @@
import { ChannelIdentifier } from '@lobechat/builtin-tool-channel';
import type { LobeChatDatabase } from '@lobechat/database';
import { buildChannelPrompt, CHANNEL_INSTRUCTIONS } from '@lobechat/prompts';
-import type { ChannelExecutionConfig } from '@lobechat/types';
+import type { ChannelExecutionConfig, ChannelSharedAgentAccess } from '@lobechat/types';
import { isRecord } from '@lobechat/utils/object';
import { and, eq } from 'drizzle-orm';
import { groupBy } from 'es-toolkit';
import pMap from 'p-map';
+import { checkAgentShareSpendAllowance } from '@/business/server/agent-share/spendGate';
import { getServerDB } from '@/database/core/db-adaptor';
import { AgentOperationModel } from '@/database/models/agentOperation';
+import { AgentShareModel } from '@/database/models/agentShare';
import { MessageModel } from '@/database/models/message';
import { TopicModel } from '@/database/models/topic';
import type { ChannelClaim } from '@/database/repositories/channel';
@@ -18,6 +20,7 @@ import { getServerDefaultAgentConfig } from '@/server/globalConfig';
import { extractTextFromMessage } from '@/server/services/agentRuntime/CompletionLifecycle/messageContent';
import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';
import { AiAgentService } from '@/server/services/aiAgent';
+import type { AgentShareGate } from '@/server/services/aiAgent/shareGate';
import { detectNoReply } from '@/server/services/conversationWake/noReply';
import { deviceGateway } from '@/server/services/deviceGateway';
import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
@@ -44,8 +47,46 @@ export class ChannelCoordinator {
this.executions = new ChannelExecutionRepository(db);
}
- private service(userId: string, workspaceId: string | null) {
- return new AiAgentService(this.db, userId, { workspaceId: workspaceId ?? undefined });
+ /** A shared Agent's run is its owner's, on topics tagged with the requester as sender. */
+ private service(userId: string, workspaceId: string | null, shared?: boolean) {
+ return new AiAgentService(this.db, userId, {
+ ...(shared ? { includeShareVisitor: true } : {}),
+ workspaceId: workspaceId ?? undefined,
+ });
+ }
+
+ /**
+ * Recheck a shared Agent's live share and its owner's spend limit right before submission, as
+ * the share page does for every visitor turn, and build the gate the run executes under.
+ */
+ private async shareGate(
+ access: ChannelSharedAgentAccess,
+ agentId: string,
+ requesterId: string,
+ ): Promise<AgentShareGate> {
+ const share = await AgentShareModel.findByShareId(this.db, access.shareId);
+ if (
+ !share ||
+ share.visibility !== 'link' ||
+ share.agentId !== agentId ||
+ share.ownerId !== access.ownerId
+ )
+ throw new Error('This Agent is no longer shared');
+ const spend = await checkAgentShareSpendAllowance({
+ agentId,
+ monthlySpendLimit: share.shareConfig.monthlySpendLimit,
+ ownerUserId: share.ownerId,
+ shareId: share.shareId,
+ visitorUserId: requesterId,
+ workspaceId: share.workspaceId ?? undefined,
+ });
+ if (!spend.allowed) throw new Error('This shared Agent reached its monthly usage limit');
+ return {
+ agentId,
+ shareConfig: share.shareConfig,
+ shareId: share.shareId,
+ visitorUserId: requesterId,
+ };
}
advance = async (channelId: string) => {
@@ -148,8 +189,8 @@ export class ChannelCoordinator {
*/
private async dispatch(
{ job, member, topic }: ChannelClaim,
- workspaceId: string | null,
- projectId?: string | null,
+ channelWorkspaceId: string | null,
+ channelProjectId?: string | null,
) {
if (
!job.operationId ||
@@ -161,6 +202,10 @@ export class ChannelCoordinator {
)
throw new Error('Incomplete Channel execution claim');
const config: ChannelExecutionConfig = structuredClone(job.executionConfig);
+ const { share } = config;
+ // A shared Agent runs in its owner's scope, never the Channel's, and outside its projects.
+ const workspaceId = share ? share.workspaceId : channelWorkspaceId;
+ const projectId = share ? undefined : channelProjectId;
// A device a member picked for this Agent in the Channel is authoritative for the run.
// Without one the Channel binds nothing: the Agent runs where its own settings say, as the
// requester's ordinary conversation with it would.
@@ -224,17 +269,20 @@ export class ChannelCoordinator {
this.executions.primaryReply(job.channelId, job.id),
this.executions.openingReply(job.channelId, job.id),
]);
- const attachments = await resolveChannelAttachments(
- this.db,
- topic.userId,
- workspaceId,
- input,
- );
+ const shareGate =
+ share && topic.senderId
+ ? await this.shareGate(share, member.agentId, topic.senderId)
+ : undefined;
+ if (share && !shareGate) throw new Error('A shared Agent run needs its requester');
+ // Sending refuses attachments to a shared Agent: the owner's run cannot read them.
+ const attachments = share
+ ? {}
+ : await resolveChannelAttachments(this.db, topic.userId, workspaceId, input);
// The last check before submission. A dispatcher that stalled past its lease stops
// here; one that already passed it can only consume the still-idle reservation.
if (!(await this.executions.heartbeat(job.id, lease)))
throw new Error('The Channel dispatch lease expired before submission');
- const result = await this.service(topic.userId, workspaceId).execAgent({
+ const result = await this.service(topic.userId, workspaceId, !!share).execAgent({
additionalPluginIds: [ChannelIdentifier],
agentId: member.agentId,
agentConfigSnapshot: config,
@@ -254,6 +302,7 @@ export class ChannelCoordinator {
wake: job.wake,
}),
reservedOperationId: job.operationId,
+ shareGate,
trigger: 'channel',
userInterventionConfig: { approvalMode: 'headless' },
});
@@ -322,6 +371,8 @@ export class ChannelCoordinator {
this.db,
operation.userId,
operation.workspaceId ?? undefined,
+ undefined,
+ job.executionConfig?.share ? { includeShareVisitor: true } : undefined,
).findLatestAssistantByOperationId({ operationId, topicId: job.topicId });
const content = final?.tools?.length ? undefined : extractTextFromMessage(final);
// A wake nobody asked for may end in silence. Settled like a reply, not a failure.
@@ -442,6 +493,7 @@ export class ChannelCoordinator {
const result = await this.service(
row.operation.userId,
row.operation.workspaceId,
+ !!row.config?.share,
).interruptTask({
operationId: job.operationId,
topicId: row.operation.topicId ?? undefined,
diff --git a/apps/server/src/services/channel/ChannelService.direct.test.ts b/apps/server/src/services/channel/ChannelService.direct.test.ts
index 03fdb3274d1..c3d2cdc6c48 100644
--- a/apps/server/src/services/channel/ChannelService.direct.test.ts
+++ b/apps/server/src/services/channel/ChannelService.direct.test.ts
@@ -12,6 +12,8 @@ const {
findAccess,
findDevice,
findDirectAccess,
+ findShare,
+ findSharedAgent,
getAgent,
notify,
querySystemInfo,
@@ -22,6 +24,8 @@ const {
findAccess: vi.fn(),
findDevice: vi.fn(),
findDirectAccess: vi.fn(),
+ findShare: vi.fn(),
+ findSharedAgent: vi.fn(),
getAgent: vi.fn(),
notify: vi.fn(),
querySystemInfo: vi.fn(),
@@ -37,6 +41,15 @@ vi.mock('@/database/repositories/channel', async (original) => ({
},
}));
vi.mock('@/database/models/project', () => ({ ProjectModel: class {} }));
+vi.mock('@/database/models/contact', async (original) => ({
+ ...(await original<object>()),
+ ContactModel: class {
+ findAgentAccess = findSharedAgent;
+ },
+}));
+vi.mock('@/database/models/agentShare', () => ({
+ AgentShareModel: { findBySlugOrId: findShare },
+}));
vi.mock('@/database/models/device', () => ({
DeviceModel: class {
findPersonalByDeviceId = findDevice;
@@ -126,6 +139,27 @@ describe('the direct Channel of a new Agent', () => {
await expect(createDirect()).resolves.toBeUndefined();
expect(create).not.toHaveBeenCalled();
});
+
+ it('opens a contact’s shared Agent in a personal conversation without a device', async () => {
+ getAgent.mockResolvedValue(null);
+ findSharedAgent.mockResolvedValue({ name: null, ownerId: 'other', title: 'Shared Helper' });
+ await createDirect();
+ expect(create).toHaveBeenCalledWith({
+ agentConfig: {},
+ agentId: 'agt_new',
+ sharedAgent: true,
+ title: 'Shared Helper',
+ });
+ });
+
+ it('never opens a shared Agent in a workspace', async () => {
+ getAgent.mockResolvedValue(null);
+ findSharedAgent.mockResolvedValue({ name: null, ownerId: 'other', title: 'Shared Helper' });
+ await expect(
+ new ChannelService({} as never, 'owner', 'ws_1').createDirect('agt_1'),
+ ).resolves.toBeUndefined();
+ expect(findSharedAgent).not.toHaveBeenCalled();
+ });
});
describe('opening the direct Channel of an existing Agent', () => {
@@ -189,3 +223,53 @@ describe('inviting from a direct conversation', () => {
expect(createGroupFromDirect).not.toHaveBeenCalled();
});
});
+
+describe('opening another person’s Agent from its share', () => {
+ const share = {
+ agentId: 'agt_shared',
+ agentName: null,
+ agentTitle: 'Shared Helper',
+ ownerId: 'other',
+ visibility: 'link',
+ };
+ beforeEach(() => {
+ vi.resetAllMocks();
+ create.mockResolvedValue({ channel: { id: 'chn_shared' } });
+ findShare.mockResolvedValue(share);
+ });
+ const openShared = (input: string, workspaceId?: string) =>
+ new ChannelService({} as never, 'me', workspaceId).openShared(input);
+
+ it('opens a direct conversation from a pasted link without any contact entry', async () => {
+ await openShared('https://app.lobehub.com/a/shared-helper');
+ expect(findShare).toHaveBeenCalledWith(expect.anything(), 'shared-helper');
+ expect(findSharedAgent).not.toHaveBeenCalled();
+ expect(create).toHaveBeenCalledWith({
+ agentConfig: {},
+ agentId: 'agt_shared',
+ sharedAgent: true,
+ title: 'Shared Helper',
+ });
+ });
+
+ it('reopens the existing conversation', async () => {
+ findDirectAccess.mockResolvedValue({ channel: { id: 'chn_old', isDeleted: false } });
+ await expect(openShared('shared-helper')).resolves.toMatchObject({
+ channel: { id: 'chn_old' },
+ });
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['a paused share', { ...share, visibility: 'private' }],
+ ['a missing share', null],
+ ])('refuses %s', async (_, found) => {
+ findShare.mockResolvedValue(found);
+ await expect(openShared('shared-helper')).rejects.toThrow('Agent not found');
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it('is personal only', async () => {
+ await expect(openShared('shared-helper', 'ws_1')).rejects.toThrow('personal scope');
+ });
+});
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index 058c97d5f44..a10906f74c0 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -7,8 +7,11 @@ import {
defaultChannelAgentDirectory,
isChannelRuntime,
} from '@lobechat/types';
+import { eq } from 'drizzle-orm';
import pMap from 'p-map';
+import { AgentShareModel } from '@/database/models/agentShare';
+import { ContactModel, parseContactHandle } from '@/database/models/contact';
import { DeviceModel } from '@/database/models/device';
import { ProjectModel } from '@/database/models/project';
import type {
@@ -17,6 +20,7 @@ import type {
ChannelStopScope,
} from '@/database/repositories/channel';
import { ChannelError, ChannelRepository } from '@/database/repositories/channel';
+import { users } from '@/database/schemas';
import { AgentService } from '@/server/services/agent';
import { deviceGateway } from '@/server/services/deviceGateway';
import { FileService } from '@/server/services/file';
@@ -198,7 +202,7 @@ export class ChannelService {
*/
createDirect = async (agentId: string) => {
const agent = await this.agentService.getAgentConfigById(agentId);
- if (!agent) return;
+ if (!agent) return this.createSharedDirect(agentId);
if (!isChannelRuntime(agentRuntime(agent))) return;
return this.repository.create({
agentConfig: {},
@@ -207,6 +211,50 @@ export class ChannelService {
});
};
+ /**
+ * Another person's Agent the caller added to their contacts through its link share; the entry
+ * shows they reached the share. The repository rechecks the live share. Always a personal
+ * direct conversation, run in the cloud as the owner.
+ */
+ private createSharedDirect = async (agentId: string) => {
+ if (this.workspaceId) return;
+ const shared = await new ContactModel(this.db, this.userId).findAgentAccess(agentId);
+ if (!shared) return;
+ return this.repository.create({
+ agentConfig: {},
+ agentId,
+ sharedAgent: true,
+ title: agentDisplayName(shared, 'Agent').slice(0, CHANNEL_LIMITS.titleLength),
+ });
+ };
+
+ /**
+ * The direct conversation with another person's Agent, opened from its share (id, handle or
+ * pasted link) β€” no contact entry or friendship needed, since a link share is open to anyone
+ * signed in. Adding it to contacts stays optional. One's own Agent opens as usual.
+ */
+ openShared = async (share: string) => {
+ if (this.workspaceId)
+ throw new ChannelError('BAD_REQUEST', 'A shared Agent is messaged from a personal scope');
+ const key = parseContactHandle(share);
+ const found = key ? await AgentShareModel.findBySlugOrId(this.db, key) : null;
+ if (!found || found.visibility !== 'link')
+ throw new ChannelError('NOT_FOUND', 'Agent not found');
+ if (found.ownerId === this.userId) return this.openDirect(found.agentId);
+
+ const existing = await this.repository.findDirectAccess(found.agentId);
+ if (existing) return existing.channel.isDeleted ? undefined : existing;
+ return this.repository.create({
+ agentConfig: {},
+ agentId: found.agentId,
+ sharedAgent: true,
+ title: agentDisplayName({ name: found.agentName, title: found.agentTitle }, 'Agent').slice(
+ 0,
+ CHANNEL_LIMITS.titleLength,
+ ),
+ });
+ };
+
/**
* The direct conversation a person opens with an existing Agent, e.g. one created before direct
* Channels. An existing conversation opens as it is, without probing its device again; one the
@@ -218,6 +266,26 @@ export class ChannelService {
return this.createDirect(agentId);
};
+ /**
+ * The personal conversation with a contact. The stored title is the other person's name for
+ * whoever opened it; clients title it with whoever the viewer is talking to.
+ */
+ openPeer = async (peerUserId: string) => {
+ const [peer] = await this.db
+ .select({ fullName: users.fullName, username: users.username })
+ .from(users)
+ .where(eq(users.id, peerUserId))
+ .limit(1);
+ if (!peer) throw new ChannelError('NOT_FOUND', 'User not found');
+ const title = (peer.fullName?.trim() || peer.username || 'Conversation').slice(
+ 0,
+ CHANNEL_LIMITS.titleLength,
+ );
+ const access = await this.repository.openPeer(peerUserId, title);
+ await this.changed(access.channel.id);
+ return access;
+ };
+
/**
* The main Agent when it runs natively. An external Agent needs a device and directory that a
* member picks when adding it, so the scope's LobeAI answers in the meantime.
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index b145eb6d281..04d928dddd1 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -231,6 +231,8 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule
changelog: 'open',
// Sending wakes Agent runs on members' devices; no key-based client drives Channels yet
channel: 'blocked',
+ // the address book sends and accepts contact requests and grants access to shared Agents
+ contact: 'blocked',
chunk: rw('knowledge:read', 'knowledge:write'),
comfyui: rw('model:read', 'model:write'),
// third-party integrations hold external credentials
diff --git a/packages/database/src/models/__tests__/contact.test.ts b/packages/database/src/models/__tests__/contact.test.ts
new file mode 100644
index 00000000000..856958c0b7a
--- /dev/null
+++ b/packages/database/src/models/__tests__/contact.test.ts
@@ -0,0 +1,240 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agents, agentShares, userContactRequests, userContacts, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { ContactModel, parseContactHandle } from '../contact';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const alice = 'contact-test-alice';
+const bob = 'contact-test-bob';
+const carol = 'contact-test-carol';
+const bobAgent = 'agt_contact_bob';
+const aliceAgent = 'agt_contact_alice';
+
+const aliceModel = new ContactModel(serverDB, alice);
+const bobModel = new ContactModel(serverDB, bob);
+const carolModel = new ContactModel(serverDB, carol);
+
+let bobShareId: string;
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([
+ { fullName: 'Alice', id: alice, username: 'alice' },
+ { fullName: 'Bob', id: bob, username: 'Bob' },
+ { id: carol, username: 'carol' },
+ ]);
+ await serverDB.insert(agents).values([
+ { id: bobAgent, title: 'Bob Helper', userId: bob },
+ { id: aliceAgent, title: 'Alice Helper', userId: alice },
+ ]);
+ const [share] = await serverDB
+ .insert(agentShares)
+ .values({
+ agentId: bobAgent,
+ shareConfig: { monthlySpendLimit: 1, slug: 'bob-helper' },
+ visibility: 'link',
+ })
+ .returning();
+ bobShareId = share.id;
+ await serverDB
+ .insert(agentShares)
+ .values({ agentId: aliceAgent, shareConfig: { monthlySpendLimit: 1 }, visibility: 'link' });
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await serverDB.delete(userContactRequests);
+ await serverDB.delete(userContacts);
+ await serverDB.delete(users);
+});
+
+describe('parseContactHandle', () => {
+ it('accepts handles, @handles and share links', () => {
+ expect(parseContactHandle('bob')).toBe('bob');
+ expect(parseContactHandle(' @bob ')).toBe('bob');
+ expect(parseContactHandle('https://app.lobehub.com/a/bob-helper/chat?x=1')).toBe('bob-helper');
+ expect(parseContactHandle(' ')).toBeUndefined();
+ });
+});
+
+describe('contact requests', () => {
+ it('becomes mutual contacts once the addressee accepts', async () => {
+ const sent = await aliceModel.sendRequest(bob, 'hi');
+ expect(sent.status).toBe('pending');
+ expect(await aliceModel.relationTo(bob)).toBe('request_sent');
+ expect(await bobModel.relationTo(alice)).toBe('request_received');
+
+ const [incoming] = await bobModel.listRequests();
+ expect(incoming).toMatchObject({ direction: 'incoming', message: 'hi', user: { id: alice } });
+
+ await bobModel.acceptRequest(sent.requestId);
+
+ expect((await aliceModel.list()).map((c) => c.type === 'user' && c.user.id)).toEqual([bob]);
+ expect((await bobModel.list()).map((c) => c.type === 'user' && c.user.id)).toEqual([alice]);
+ expect(await bobModel.listRequests()).toEqual([]);
+ });
+
+ it('repeating a pending request returns it instead of adding another', async () => {
+ const first = await aliceModel.sendRequest(bob);
+ const second = await aliceModel.sendRequest(bob);
+ expect(second).toEqual(first);
+ });
+
+ it('a crossing request accepts the pending one', async () => {
+ const first = await aliceModel.sendRequest(bob);
+ const crossing = await bobModel.sendRequest(alice);
+ expect(crossing).toEqual({ requestId: first.requestId, status: 'accepted' });
+ expect(await aliceModel.isContact(bob)).toBe(true);
+ });
+
+ it('only the addressee can accept or decline, only the requester can cancel', async () => {
+ const { requestId } = await aliceModel.sendRequest(bob);
+ await expect(aliceModel.acceptRequest(requestId)).rejects.toThrow('Request not found');
+ await expect(carolModel.declineRequest(requestId)).rejects.toThrow('Request not found');
+ await expect(bobModel.cancelRequest(requestId)).rejects.toThrow('Request not found');
+
+ await aliceModel.cancelRequest(requestId);
+ expect(await bobModel.listRequests()).toEqual([]);
+ // A new request may follow a cancelled one.
+ expect((await aliceModel.sendRequest(bob)).status).toBe('pending');
+ });
+
+ /**
+ * The requester withdraws after the addressee's answer read the request as pending but before
+ * it wrote: the withdrawal wins and no contacts appear. Simulated by withdrawing right after
+ * the read, inside the answering transaction.
+ */
+ const withdrawAfterRead = (model: ContactModel) => {
+ const target = model as unknown as {
+ incomingPending: (tx: LobeChatDatabase, id: string) => Promise<{ id: string }>;
+ };
+ const read = target.incomingPending.bind(model);
+ vi.spyOn(target, 'incomingPending').mockImplementation(async (tx, id) => {
+ const request = await read(tx, id);
+ await tx
+ .update(userContactRequests)
+ .set({ status: 'cancelled' })
+ .where(eq(userContactRequests.id, request.id));
+ return request;
+ });
+ };
+
+ it('does not accept a request withdrawn while it was being accepted', async () => {
+ const { requestId } = await aliceModel.sendRequest(bob);
+ withdrawAfterRead(bobModel);
+
+ await expect(bobModel.acceptRequest(requestId)).rejects.toThrow('Request not found');
+
+ expect(await aliceModel.isContact(bob)).toBe(false);
+ expect(await bobModel.isContact(alice)).toBe(false);
+ const [row] = await serverDB
+ .select({ status: userContactRequests.status })
+ .from(userContactRequests)
+ .where(eq(userContactRequests.id, requestId));
+ // The refused answer rolls back with its transaction; it never became accepted.
+ expect(row.status).not.toBe('accepted');
+ });
+
+ it('does not decline a request withdrawn while it was being declined', async () => {
+ const { requestId } = await aliceModel.sendRequest(bob);
+ withdrawAfterRead(bobModel);
+
+ await expect(bobModel.declineRequest(requestId)).rejects.toThrow('Request not found');
+
+ const [row] = await serverDB
+ .select({ status: userContactRequests.status })
+ .from(userContactRequests)
+ .where(eq(userContactRequests.id, requestId));
+ expect(row.status).not.toBe('declined');
+ });
+
+ it('rejects requests to yourself and to existing contacts', async () => {
+ await expect(aliceModel.sendRequest(alice)).rejects.toThrow('You cannot add yourself');
+ const { requestId } = await aliceModel.sendRequest(bob);
+ await bobModel.acceptRequest(requestId);
+ await expect(aliceModel.sendRequest(bob)).rejects.toThrow('Already a contact');
+ });
+
+ it('removing a contact removes it on both sides', async () => {
+ const { requestId } = await aliceModel.sendRequest(bob);
+ await bobModel.acceptRequest(requestId);
+ await bobModel.removeUser(alice);
+ expect(await aliceModel.list()).toEqual([]);
+ expect(await bobModel.list()).toEqual([]);
+ });
+});
+
+describe('shared Agents', () => {
+ it('adds another person’s Agent by its share handle and grants access', async () => {
+ const profile = await aliceModel.addAgent('https://app.lobehub.com/a/bob-helper');
+ expect(profile).toMatchObject({ agentId: bobAgent, owner: { id: bob }, shareId: bobShareId });
+
+ const [contact] = await aliceModel.list();
+ expect(contact).toMatchObject({ available: true, type: 'agent' });
+ expect(await aliceModel.findAgentAccess(bobAgent)).toEqual({
+ agentId: bobAgent,
+ name: null,
+ ownerId: bob,
+ shareId: bobShareId,
+ title: 'Bob Helper',
+ workspaceId: null,
+ });
+ // Adding twice keeps one entry.
+ await aliceModel.addAgent(bobShareId);
+ expect(await aliceModel.list()).toHaveLength(1);
+ });
+
+ it('pausing the share keeps the contact but removes access', async () => {
+ await aliceModel.addAgent('bob-helper');
+ await serverDB.update(agentShares).set({ visibility: 'private' });
+
+ const [contact] = await aliceModel.list();
+ expect(contact).toMatchObject({ available: false, type: 'agent' });
+ expect(await aliceModel.findAgentAccess(bobAgent)).toBeUndefined();
+ await expect(carolModel.addAgent('bob-helper')).rejects.toThrow('Agent not found');
+ });
+
+ it('does not grant access without a contact entry or to your own Agent', async () => {
+ expect(await carolModel.findAgentAccess(bobAgent)).toBeUndefined();
+ await expect(bobModel.addAgent('bob-helper')).rejects.toThrow('This Agent is already yours');
+ });
+
+ it('reads only a person’s public profile fields', async () => {
+ expect(await aliceModel.findUser(bob)).toEqual({
+ avatar: null,
+ fullName: 'Bob',
+ id: bob,
+ username: 'Bob',
+ });
+ expect(await aliceModel.findUser('missing')).toBeUndefined();
+ });
+
+ it('lists a person’s link-shared Agents to anyone, contact or not', async () => {
+ expect((await carolModel.listSharedAgentsOf(bob)).map((a) => a.agentId)).toEqual([bobAgent]);
+ await serverDB.update(agentShares).set({ visibility: 'private' });
+ expect(await carolModel.listSharedAgentsOf(bob)).toEqual([]);
+ });
+});
+
+describe('search', () => {
+ it('finds people by exact username, case-insensitively, with their relation', async () => {
+ const [result] = await aliceModel.search('@BOB');
+ expect(result).toMatchObject({ relation: 'none', type: 'user', user: { id: bob } });
+ expect(await aliceModel.search('bo')).toEqual([]);
+ const [self] = await aliceModel.search('alice');
+ expect(self).toMatchObject({ relation: 'self' });
+ });
+
+ it('finds Agents by share handle and link', async () => {
+ const [result] = await aliceModel.search('https://app.lobehub.com/a/bob-helper');
+ expect(result).toMatchObject({ agent: { agentId: bobAgent }, relation: 'none', type: 'agent' });
+ await aliceModel.addAgent('bob-helper');
+ const [added] = await aliceModel.search('bob-helper');
+ expect(added).toMatchObject({ relation: 'contact' });
+ });
+});
diff --git a/packages/database/src/models/contact.ts b/packages/database/src/models/contact.ts
new file mode 100644
index 00000000000..3a680755b53
--- /dev/null
+++ b/packages/database/src/models/contact.ts
@@ -0,0 +1,499 @@
+import type {
+ ContactAgentItem,
+ ContactAgentProfile,
+ ContactItem,
+ ContactRelation,
+ ContactRequestItem,
+ ContactSearchResult,
+ ContactUserItem,
+} from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { and, desc, eq, or, sql } from 'drizzle-orm';
+import { alias } from 'drizzle-orm/pg-core';
+
+import { agents, agentShares, userContactRequests, userContacts, users } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '../utils/inboxAgent';
+import { notTrashed } from '../utils/softDelete';
+import { isUuid } from '../utils/uuid';
+
+const userProfileColumns = {
+ avatar: users.avatar,
+ fullName: users.fullName,
+ id: users.id,
+ username: users.username,
+};
+
+const owners = alias(users, 'contact_agent_owner');
+
+/** 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,
+ 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;
+ 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,
+ 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();
+ if (!trimmed) return undefined;
+ const fromPath = trimmed.match(/\/a\/([^/?#\s]+)/);
+ const handle = (fromPath ? decodeURIComponent(fromPath[1]) : trimmed).replace(/^@/, '');
+ return handle || undefined;
+};
+
+/**
+ * A person's address book and contact requests. Every method acts as `userId`; another
+ * person's rows are only touched as the second half of a mutual relation.
+ */
+export class ContactModel {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.db = db;
+ this.userId = userId;
+ }
+
+ list = async (): Promise<ContactItem[]> => {
+ const [people, sharedAgents] = await Promise.all([
+ this.db
+ .select({ createdAt: userContacts.createdAt, user: userProfileColumns })
+ .from(userContacts)
+ .innerJoin(users, eq(users.id, userContacts.contactUserId))
+ .where(and(eq(userContacts.userId, this.userId), eq(userContacts.type, 'user')))
+ .orderBy(desc(userContacts.createdAt)),
+ this.db
+ .select({ createdAt: userContacts.createdAt, ...agentProfileColumns })
+ .from(userContacts)
+ .innerJoin(agents, eq(agents.id, userContacts.agentId))
+ .innerJoin(agentShares, eq(agentShares.agentId, agents.id))
+ .leftJoin(owners, eq(owners.id, agents.userId))
+ .where(and(eq(userContacts.userId, this.userId), eq(userContacts.type, 'agent')))
+ .orderBy(desc(userContacts.createdAt)),
+ ]);
+
+ const userItems: ContactUserItem[] = people.map((row) => ({
+ createdAt: row.createdAt,
+ type: 'user',
+ user: row.user,
+ }));
+ const agentItems: ContactAgentItem[] = sharedAgents.map((row) => ({
+ agent: toAgentProfile(row),
+ available: row.visibility === 'link' && !row.isDeleted,
+ createdAt: row.createdAt,
+ type: 'agent',
+ }));
+
+ return [...userItems, ...agentItems];
+ };
+
+ // ── People ────────────────────────────────────────────────────────────
+
+ isContact = async (contactUserId: string): Promise<boolean> => {
+ const [row] = await this.db
+ .select({ id: userContacts.id })
+ .from(userContacts)
+ .where(
+ and(eq(userContacts.userId, this.userId), eq(userContacts.contactUserId, contactUserId)),
+ )
+ .limit(1);
+ return !!row;
+ };
+
+ /** A person's public profile; only the fields the address book shows. */
+ findUser = async (userId: string) => {
+ const [user] = await this.db
+ .select(userProfileColumns)
+ .from(users)
+ .where(eq(users.id, userId))
+ .limit(1);
+ return user;
+ };
+
+ relationTo = async (otherUserId: string): Promise<ContactRelation> => {
+ if (otherUserId === this.userId) return 'self';
+ if (await this.isContact(otherUserId)) return 'contact';
+ const [pending] = await this.db
+ .select({ requesterId: userContactRequests.requesterId })
+ .from(userContactRequests)
+ .where(and(eq(userContactRequests.status, 'pending'), this.pairWhere(otherUserId)))
+ .limit(1);
+ if (!pending) return 'none';
+ return pending.requesterId === this.userId ? 'request_sent' : 'request_received';
+ };
+
+ /**
+ * Ask `addresseeId` to become mutual contacts. Repeating a pending request returns it; a
+ * request sent while theirs is pending accepts theirs instead.
+ */
+ sendRequest = async (
+ addresseeId: string,
+ message?: string,
+ ): Promise<{ requestId: string; status: 'accepted' | 'pending' }> => {
+ if (addresseeId === this.userId)
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'You cannot add yourself' });
+
+ return this.db.transaction(async (tx) => {
+ const [addressee] = await tx
+ .select({ id: users.id })
+ .from(users)
+ .where(eq(users.id, addresseeId))
+ .limit(1);
+ if (!addressee) throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found' });
+
+ // Serialize the pair so two crossing requests cannot both stay pending.
+ await this.lockPair(tx, addresseeId);
+
+ const [existing] = await tx
+ .select({ id: userContacts.id })
+ .from(userContacts)
+ .where(
+ and(eq(userContacts.userId, this.userId), eq(userContacts.contactUserId, addresseeId)),
+ )
+ .limit(1);
+ if (existing) throw new TRPCError({ code: 'CONFLICT', message: 'Already a contact' });
+
+ const [pending] = await tx
+ .select({ id: userContactRequests.id, requesterId: userContactRequests.requesterId })
+ .from(userContactRequests)
+ .where(and(eq(userContactRequests.status, 'pending'), this.pairWhere(addresseeId)))
+ .limit(1);
+ if (pending?.requesterId === this.userId) return { requestId: pending.id, status: 'pending' };
+ // Their pending request is answered by mine, unless they withdrew it meanwhile; then mine
+ // goes out as a new request.
+ if (pending && (await this.accept(tx, pending.id, addresseeId)))
+ return { requestId: pending.id, status: 'accepted' };
+
+ const [created] = await tx
+ .insert(userContactRequests)
+ .values({ addresseeId, message: message?.trim() || null, requesterId: this.userId })
+ .returning({ id: userContactRequests.id });
+ return { requestId: created.id, status: 'pending' };
+ });
+ };
+
+ listRequests = async (): Promise<ContactRequestItem[]> => {
+ const rows = await this.db
+ .select({
+ addresseeId: userContactRequests.addresseeId,
+ createdAt: userContactRequests.createdAt,
+ id: userContactRequests.id,
+ message: userContactRequests.message,
+ requesterId: userContactRequests.requesterId,
+ user: userProfileColumns,
+ })
+ .from(userContactRequests)
+ .innerJoin(
+ users,
+ sql`${users.id} = CASE WHEN ${userContactRequests.requesterId} = ${this.userId} THEN ${userContactRequests.addresseeId} ELSE ${userContactRequests.requesterId} END`,
+ )
+ .where(
+ and(
+ eq(userContactRequests.status, 'pending'),
+ or(
+ eq(userContactRequests.requesterId, this.userId),
+ eq(userContactRequests.addresseeId, this.userId),
+ ),
+ ),
+ )
+ .orderBy(desc(userContactRequests.createdAt));
+
+ return rows.map((row) => ({
+ createdAt: row.createdAt,
+ direction: row.requesterId === this.userId ? 'outgoing' : 'incoming',
+ id: row.id,
+ message: row.message,
+ user: row.user,
+ }));
+ };
+
+ /** Accept a pending request sent to me; both people become each other's contact. */
+ acceptRequest = async (requestId: string): Promise<{ contactUserId: string }> =>
+ this.db.transaction(async (tx) => {
+ const request = await this.incomingPending(tx, requestId);
+ await this.lockPair(tx, request.requesterId);
+ if (!(await this.accept(tx, request.id, request.requesterId)))
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
+ return { contactUserId: request.requesterId };
+ });
+
+ declineRequest = async (requestId: string) => {
+ await this.db.transaction(async (tx) => {
+ const request = await this.incomingPending(tx, requestId);
+ // Same rule as accepting: only a request still pending can be answered.
+ const [declined] = await tx
+ .update(userContactRequests)
+ .set({ respondedAt: new Date(), status: 'declined', updatedAt: new Date() })
+ .where(
+ and(eq(userContactRequests.id, request.id), eq(userContactRequests.status, 'pending')),
+ )
+ .returning({ id: userContactRequests.id });
+ if (!declined) throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
+ });
+ };
+
+ cancelRequest = async (requestId: string) => {
+ if (!isUuid(requestId))
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
+ const [cancelled] = await this.db
+ .update(userContactRequests)
+ .set({ respondedAt: new Date(), status: 'cancelled', updatedAt: new Date() })
+ .where(
+ and(
+ eq(userContactRequests.id, requestId),
+ eq(userContactRequests.requesterId, this.userId),
+ eq(userContactRequests.status, 'pending'),
+ ),
+ )
+ .returning({ id: userContactRequests.id });
+ if (!cancelled) throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
+ };
+
+ /** Remove a person from my contacts; the relation is mutual, so both entries go. */
+ removeUser = async (contactUserId: string) => {
+ await this.db
+ .delete(userContacts)
+ .where(
+ or(
+ and(eq(userContacts.userId, this.userId), eq(userContacts.contactUserId, contactUserId)),
+ and(eq(userContacts.userId, contactUserId), eq(userContacts.contactUserId, this.userId)),
+ ),
+ );
+ };
+
+ // ── Agents ────────────────────────────────────────────────────────────
+
+ /** Add another person's Agent through its link share (share id or custom handle). */
+ addAgent = async (shareIdOrSlug: string): Promise<ContactAgentProfile> => {
+ const share = await this.findLinkShare(shareIdOrSlug);
+ if (!share) throw new TRPCError({ code: 'NOT_FOUND', message: 'Agent not found' });
+ if (share.ownerId === this.userId)
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'This Agent is already yours' });
+
+ await this.db
+ .insert(userContacts)
+ .values({ agentId: share.agentId, type: 'agent', userId: this.userId })
+ .onConflictDoNothing();
+ return toAgentProfile(share);
+ };
+
+ removeAgent = async (agentId: string) => {
+ await this.db
+ .delete(userContacts)
+ .where(and(eq(userContacts.userId, this.userId), eq(userContacts.agentId, agentId)));
+ };
+
+ /**
+ * The live share that authorizes me to message another person's Agent: my contact entry for
+ * it plus its link share. Returns undefined for my own Agents, which need no share.
+ */
+ findAgentAccess = async (agentId: string) => {
+ const [row] = await this.db
+ .select({
+ agentId: agents.id,
+ name: agents.name,
+ ownerId: agents.userId,
+ shareId: agentShares.id,
+ title: agents.title,
+ workspaceId: agents.workspaceId,
+ })
+ .from(userContacts)
+ .innerJoin(agents, eq(agents.id, userContacts.agentId))
+ .innerJoin(agentShares, eq(agentShares.agentId, agents.id))
+ .where(
+ and(
+ eq(userContacts.userId, this.userId),
+ eq(userContacts.agentId, agentId),
+ eq(agentShares.visibility, 'link'),
+ notTrashed(agents.isDeleted),
+ ),
+ )
+ .limit(1);
+ if (!row?.ownerId || row.ownerId === this.userId) return undefined;
+ return { ...row, ownerId: row.ownerId };
+ };
+
+ /**
+ * Agents a person shares by link, for their profile card. A link share is open to anyone
+ * signed in, so the list is too; it does not need the person as a contact.
+ */
+ listSharedAgentsOf = async (ownerId: string): Promise<ContactAgentProfile[]> => {
+ const rows = await this.db
+ .select(agentProfileColumns)
+ .from(agentShares)
+ .innerJoin(agents, eq(agents.id, agentShares.agentId))
+ .leftJoin(owners, eq(owners.id, agents.userId))
+ .where(
+ and(
+ eq(agents.userId, ownerId),
+ eq(agentShares.visibility, 'link'),
+ notTrashed(agents.isDeleted),
+ ),
+ )
+ .orderBy(desc(agentShares.createdAt));
+ return rows.map(toAgentProfile);
+ };
+
+ // ── Search ────────────────────────────────────────────────────────────
+
+ /**
+ * Exact handle lookup: a person's username and an Agent's share handle, plus a pasted share
+ * link. No fuzzy search, so a stranger cannot enumerate accounts.
+ */
+ search = async (query: string): Promise<ContactSearchResult[]> => {
+ const handle = parseContactHandle(query);
+ if (!handle) return [];
+ const results: ContactSearchResult[] = [];
+
+ const [person] = await this.db
+ .select(userProfileColumns)
+ .from(users)
+ .where(sql`lower(${users.username}) = ${handle.toLowerCase()}`)
+ .limit(1);
+ if (person)
+ results.push({ relation: await this.relationTo(person.id), type: 'user', user: person });
+
+ const share = await this.findLinkShare(handle);
+ if (share) {
+ const relation =
+ share.ownerId === this.userId
+ ? 'self'
+ : (await this.findAgentAccess(share.agentId))
+ ? 'contact'
+ : 'none';
+ results.push({ agent: toAgentProfile(share), relation, type: 'agent' });
+ }
+
+ return results;
+ };
+
+ // ── Internals ─────────────────────────────────────────────────────────
+
+ private pairWhere(otherUserId: string) {
+ return or(
+ and(
+ eq(userContactRequests.requesterId, this.userId),
+ eq(userContactRequests.addresseeId, otherUserId),
+ ),
+ and(
+ eq(userContactRequests.requesterId, otherUserId),
+ eq(userContactRequests.addresseeId, this.userId),
+ ),
+ );
+ }
+
+ /** Transaction-scoped advisory lock on the unordered pair. */
+ private async lockPair(tx: Pick<LobeChatDatabase, 'execute'>, otherUserId: string) {
+ const [a, b] = [this.userId, otherUserId].sort();
+ await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`contact:${a}:${b}`}))`);
+ }
+
+ private async incomingPending(tx: Pick<LobeChatDatabase, 'select'>, requestId: string) {
+ if (!isUuid(requestId))
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
+ const [request] = await tx
+ .select({ id: userContactRequests.id, requesterId: userContactRequests.requesterId })
+ .from(userContactRequests)
+ .where(
+ and(
+ eq(userContactRequests.id, requestId),
+ eq(userContactRequests.addresseeId, this.userId),
+ eq(userContactRequests.status, 'pending'),
+ ),
+ )
+ .limit(1);
+ if (!request) throw new TRPCError({ code: 'NOT_FOUND', message: 'Request not found' });
+ return request;
+ }
+
+ /**
+ * Move a request from pending to accepted and add both contact entries. The transition is
+ * conditional on the row still being pending: a withdrawal or decline that committed after the
+ * request was read wins, and no contacts are added. Returns whether it was accepted.
+ */
+ private async accept(
+ tx: Pick<LobeChatDatabase, 'insert' | 'update'>,
+ requestId: string,
+ requesterId: string,
+ ): Promise<boolean> {
+ const now = new Date();
+ const [accepted] = await tx
+ .update(userContactRequests)
+ .set({ respondedAt: now, status: 'accepted', updatedAt: now })
+ .where(and(eq(userContactRequests.id, requestId), eq(userContactRequests.status, 'pending')))
+ .returning({ id: userContactRequests.id });
+ if (!accepted) return false;
+ await tx
+ .insert(userContacts)
+ .values([
+ { contactUserId: requesterId, type: 'user', userId: this.userId },
+ { contactUserId: this.userId, type: 'user', userId: requesterId },
+ ])
+ .onConflictDoNothing();
+ return true;
+ }
+
+ private async findLinkShare(shareIdOrSlug: string) {
+ const key = parseContactHandle(shareIdOrSlug);
+ if (!key) return undefined;
+ const [row] = await this.db
+ .select(agentProfileColumns)
+ .from(agentShares)
+ .innerJoin(agents, eq(agents.id, agentShares.agentId))
+ .leftJoin(owners, eq(owners.id, agents.userId))
+ .where(
+ and(
+ isUuid(key)
+ ? eq(agentShares.id, key)
+ : sql`${agentShares.shareConfig} ->> 'slug' = ${key.toLowerCase()}`,
+ eq(agentShares.visibility, 'link'),
+ notTrashed(agents.isDeleted),
+ ),
+ )
+ .limit(1);
+ return row;
+ }
+}
diff --git a/packages/database/src/repositories/channel/README.md b/packages/database/src/repositories/channel/README.md
index 6dc9d1c4348..1779e7e01de 100644
--- a/packages/database/src/repositories/channel/README.md
+++ b/packages/database/src/repositories/channel/README.md
@@ -72,6 +72,37 @@ Updating Agent settings affects the next claim, including already queued request
rewrites an earlier job snapshot. A private, trashed, deleted or moved Agent fails the requester
access check before any topic or operation is created.
+## Shared Agents
+
+A personal direct conversation can also bind another person's Agent through its live link share.
+A link share is open to anyone signed in, so neither friendship nor a contact entry is needed:
+`ChannelService.openShared` opens the conversation from the share id, handle or pasted link, and
+`createSharedDirect` from an Agent the person added to their contacts (which shows they reached the
+share). Only those paths pass `sharedAgent` to `create`; a bare Agent id never binds someone else's
+Agent. `requireChannelAgent` and `resolveExecutionConfig` then accept it for that conversation
+shape only, while the share is `link` and the Agent is not trashed; groups and workspace channels
+never take one. The claim freezes `executionConfig.share` (owner, share and the Agent's scope):
+
+- The run executes as the owner, like a visit to the share page. Its topic and operation belong
+ to the owner and the Agent's scope, with the requester as `topics.senderId`, so the owner's own
+ lists never show it. Owner defaults apply; the requester's never do.
+- It is always a Native cloud run: no device, no Channel project, no attachments (sending refuses
+ them because the owner's run cannot read the requester's files).
+- The coordinator rechecks the live share and its monthly spend limit before submission and runs
+ under the share's `shareGate`. Of the Channel tools it keeps only `readMessages` /
+ `readMessage`, and `ChannelHistoryRepository` authorizes those reads against the frozen share
+ (owner operation, the person's Channel) while every other use of the run (`currentRun`, so
+ `listChannels` / `sendMessage`) is refused: they would act in the owner's Channels.
+- A topic ends at the share's `maxTurnsPerTopic`; the next request starts a new one.
+
+## Conversations between contacts
+
+`channels.peerUserId` marks a personal conversation between two people who are mutual contacts
+(`openPeer`). One exists per pair, whoever opened it: no unique index backs this, so `openPeer` takes an advisory lock on the pair before looking for it. Both people are owner members. It takes no
+Agents and no third person, so messages never route. Sending rechecks the contact relation in
+both directions: removing a contact silences the conversation and keeps its history. The list
+reports `peerUserId` relative to the viewer. Either account's deletion removes it.
+
## Delivery-key retirement rollout
Migration `0197_channel_jobs_message_member_unique` enforces one job per message and Agent
diff --git a/packages/database/src/repositories/channel/__tests__/peer.test.ts b/packages/database/src/repositories/channel/__tests__/peer.test.ts
new file mode 100644
index 00000000000..2f78ec29c06
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/peer.test.ts
@@ -0,0 +1,106 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { ContactModel } from '../../../models/contact';
+import { agents, userContacts } from '../../../schemas';
+import { ChannelRepository } from '..';
+import { createChannelFixture, jobsOf } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-peer');
+
+const alice = fixture.ownerId;
+const bob = fixture.memberId;
+const asAlice = new ChannelRepository(db, alice);
+const asBob = new ChannelRepository(db, bob);
+
+const befriend = async () => {
+ const { requestId } = await new ContactModel(db, alice).sendRequest(bob);
+ await new ContactModel(db, bob).acceptRequest(requestId);
+};
+
+beforeEach(fixture.setup);
+afterEach(async () => {
+ await db.delete(userContacts);
+ await fixture.cleanup();
+});
+
+describe('a conversation between two contacts', () => {
+ it('requires the mutual contact relation', async () => {
+ await expect(asAlice.openPeer(bob, 'Mia')).rejects.toThrow('You are not contacts');
+ await new ContactModel(db, alice).sendRequest(bob);
+ await expect(asAlice.openPeer(bob, 'Mia')).rejects.toThrow('You are not contacts');
+ });
+
+ it('is one conversation per pair, whoever opens it', async () => {
+ await befriend();
+ const opened = await asAlice.openPeer(bob, 'Mia');
+ const reopened = await asBob.openPeer(alice, 'Olivia');
+ expect(reopened.channel.id).toBe(opened.channel.id);
+ expect(opened.channel).toMatchObject({ agentId: null, peerUserId: bob, workspaceId: null });
+ });
+
+ it('stays one conversation when both people open it at once', async () => {
+ await befriend();
+ const opened = await Promise.all([
+ asAlice.openPeer(bob, 'Mia'),
+ asBob.openPeer(alice, 'Olivia'),
+ asAlice.openPeer(bob, 'Mia'),
+ ]);
+ expect(new Set(opened.map(({ channel }) => channel.id)).size).toBe(1);
+ expect(await asAlice.list()).toHaveLength(1);
+ });
+
+ it('is listed for both people with the other person', async () => {
+ await befriend();
+ const { channel } = await asAlice.openPeer(bob, 'Mia');
+
+ const [forAlice] = await asAlice.list();
+ expect(forAlice).toMatchObject({ id: channel.id, peerUserId: bob });
+ expect(forAlice.memberAvatars.map((m) => m.id)).toEqual([bob]);
+ const [forBob] = await asBob.list();
+ expect(forBob).toMatchObject({ id: channel.id, peerUserId: alice });
+ });
+
+ it('carries messages without waking any Agent', async () => {
+ await befriend();
+ const { channel } = await asAlice.openPeer(bob, 'Mia');
+ const message = await asAlice.send(channel.id, {
+ content: 'Hi Mia',
+ requestKey: 'hi',
+ routing: 'fallback',
+ });
+ expect(message.routingStatus).toBe('skipped');
+ expect(await jobsOf(db, message.id)).toEqual([]);
+ const [forBob] = await asBob.list();
+ expect(forBob.unreadCount).toBe(1);
+ });
+
+ it('takes no Agents and no third person', async () => {
+ await befriend();
+ const { channel } = await asAlice.openPeer(bob, 'Mia');
+ const [agent] = await db.insert(agents).values({ title: 'Helper', userId: alice }).returning();
+ await expect(asAlice.addAgent(channel.id, { agentId: agent.id })).rejects.toThrow(
+ 'A conversation between two people has no Agents',
+ );
+ });
+
+ it('goes silent once either person removes the other', async () => {
+ await befriend();
+ const { channel } = await asAlice.openPeer(bob, 'Mia');
+ await new ContactModel(db, bob).removeUser(alice);
+ await expect(
+ asAlice.send(channel.id, { content: 'Still there?', requestKey: 'x', routing: 'fallback' }),
+ ).rejects.toThrow('You are not contacts');
+ // History stays readable.
+ expect((await asAlice.list()).map((c) => c.id)).toEqual([channel.id]);
+ });
+
+ it('is never opened in a workspace', async () => {
+ await befriend();
+ await expect(
+ new ChannelRepository(db, alice, fixture.workspaceId).openPeer(bob, 'Mia'),
+ ).rejects.toThrow('A conversation between people is personal');
+ });
+});
diff --git a/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts b/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts
new file mode 100644
index 00000000000..9443e18181d
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/sharedAgent.test.ts
@@ -0,0 +1,244 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ agentOperations,
+ agents,
+ agentShares,
+ channelJobs,
+ files,
+ messages,
+ userContacts,
+ userSettings,
+} from '../../../schemas';
+import { ChannelExecutionRepository, ChannelHistoryRepository, ChannelRepository } from '..';
+import { createChannelFixture, jobsOf, lease, operationById } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-shared-agent');
+const execution = new ChannelExecutionRepository(db);
+
+// The fixture's member is the visitor; its owner shares an Agent.
+const visitorId = fixture.memberId;
+const ownerId = fixture.ownerId;
+const agentId = 'agt_channel_shared';
+const visitor = new ChannelRepository(db, visitorId);
+
+let shareId: string;
+
+beforeEach(async () => {
+ await fixture.setup();
+ await db.insert(agents).values({
+ id: agentId,
+ model: 'owner-model',
+ provider: 'owner-provider',
+ systemRole: 'Owner prompt',
+ title: 'Shared Helper',
+ userId: ownerId,
+ });
+ const [share] = await db
+ .insert(agentShares)
+ .values({
+ agentId,
+ shareConfig: { maxTurnsPerTopic: 2, monthlySpendLimit: 1, slug: 'shared-helper' },
+ visibility: 'link',
+ })
+ .returning();
+ shareId = share.id;
+});
+
+afterEach(async () => {
+ await db.delete(userContacts);
+ // Users cascade their Agents and topics once the fixture has released its writers.
+ await fixture.cleanup();
+});
+
+const send = async (channelId: string, requestKey: string) => {
+ const message = await visitor.send(channelId, {
+ content: `Request ${requestKey}`,
+ requestKey,
+ routing: 'fallback',
+ });
+ const [job] = await jobsOf(db, message.id);
+ return job;
+};
+
+describe('a contact’s shared Agent in a direct conversation', () => {
+ it('opens through the live share without a contact entry, but never from a bare Agent id', async () => {
+ await expect(visitor.create({ agentId, title: 'Shared Helper' })).rejects.toThrow(
+ 'Agent not found',
+ );
+ const { channel } = await visitor.create({
+ agentId,
+ sharedAgent: true,
+ title: 'Shared Helper',
+ });
+ expect(channel).toMatchObject({ agentId, userId: visitorId, workspaceId: null });
+
+ const [listed] = await visitor.list();
+ expect(listed).toMatchObject({ id: channel.id, sharedAgent: true });
+ expect(listed.memberAvatars).toMatchObject([{ actorType: 'agent', id: agentId }]);
+ });
+
+ it('cannot be added to a group', async () => {
+ const { channel } = await visitor.create({ title: 'Group' });
+ await expect(visitor.addAgent(channel.id, { agentId })).rejects.toThrow('Agent not found');
+ });
+
+ it('runs as its owner, on an owner topic tagged with the visitor', async () => {
+ await db.insert(userSettings).values([
+ { defaultAgent: { config: { params: { temperature: 0.1 } } }, id: ownerId },
+ { defaultAgent: { config: { params: { temperature: 0.9 } } }, id: visitorId },
+ ]);
+ const { channel } = await visitor.create({
+ agentId,
+ sharedAgent: true,
+ title: 'Shared Helper',
+ });
+ const job = await send(channel.id, 'first');
+
+ const claim = (await execution.claim(channel.id, job.id, lease))!;
+ expect(claim.job.executionConfig).toMatchObject({
+ model: 'owner-model',
+ params: { temperature: 0.1 },
+ runtime: 'native',
+ share: { ownerId, shareId, workspaceId: null },
+ systemRole: 'Owner prompt',
+ });
+ expect(claim.job.executionConfig?.deviceId).toBeUndefined();
+ expect(claim.topic).toMatchObject({ senderId: visitorId, userId: ownerId, workspaceId: null });
+ expect(await operationById(db, claim.job.operationId)).toMatchObject({
+ topicId: claim.topic.id,
+ userId: ownerId,
+ });
+ });
+
+ it('is blocked once the owner pauses the share', async () => {
+ const { channel } = await visitor.create({
+ agentId,
+ sharedAgent: true,
+ title: 'Shared Helper',
+ });
+ await db.update(agentShares).set({ visibility: 'private' }).where(eq(agentShares.id, shareId));
+ const job = await send(channel.id, 'paused');
+
+ expect(await execution.claim(channel.id, job.id, lease)).toBeNull();
+ const [blocked] = await db.select().from(channelJobs).where(eq(channelJobs.id, job.id));
+ expect(blocked.blockedCode).toBe('unavailable');
+ });
+
+ it('refuses attachments, which the owner’s run could not read', async () => {
+ const { channel } = await visitor.create({
+ agentId,
+ sharedAgent: true,
+ title: 'Shared Helper',
+ });
+ const [file] = await db
+ .insert(files)
+ .values({
+ fileType: 'text/plain',
+ name: 'note.txt',
+ size: 1,
+ url: 'files/note.txt',
+ userId: visitorId,
+ })
+ .returning();
+ await expect(
+ visitor.send(channel.id, {
+ content: 'See file',
+ fileIds: [file.id],
+ requestKey: 'file',
+ routing: 'fallback',
+ }),
+ ).rejects.toThrow('Attachments cannot be sent to a shared Agent');
+ });
+
+ it('continues its topic until the share’s per-topic turn limit', async () => {
+ const { channel } = await visitor.create({
+ agentId,
+ sharedAgent: true,
+ title: 'Shared Helper',
+ });
+ const claim = async (key: string) =>
+ (await execution.claim(channel.id, (await send(channel.id, key)).id, lease))!;
+ const finish = async (jobId: string) => {
+ await execution.accepted(channel.id, jobId);
+ await execution.saveDraft(channel.id, jobId, 'Answer');
+ await execution.publish(channel.id, jobId);
+ await execution.releaseWriter(channel.id, jobId);
+ };
+
+ const first = await claim('a');
+ await finish(first.job.id);
+ const second = await claim('b');
+ expect(second.topic.id).toBe(first.topic.id);
+
+ // Two visitor turns reach `maxTurnsPerTopic: 2`.
+ await db.insert(messages).values(
+ ['one', 'two'].map((content) => ({
+ content,
+ role: 'user' as const,
+ topicId: first.topic.id,
+ userId: ownerId,
+ })),
+ );
+ await finish(second.job.id);
+ const third = await claim('c');
+ expect(third.topic.id).not.toBe(first.topic.id);
+ expect(third.topic).toMatchObject({ senderId: visitorId, userId: ownerId });
+ });
+
+ describe('reading its conversation history', () => {
+ const start = async () => {
+ const { channel } = await visitor.create({
+ agentId,
+ sharedAgent: true,
+ title: 'Shared Helper',
+ });
+ // An earlier exchange, answered and settled, then the live run.
+ const earlier = await visitor.send(channel.id, {
+ content: 'Earlier note',
+ requestKey: 'earlier',
+ routing: 'fallback',
+ });
+ const [earlierJob] = await jobsOf(db, earlier.id);
+ await execution.claim(channel.id, earlierJob.id, lease);
+ await execution.accepted(channel.id, earlierJob.id);
+ await execution.saveDraft(channel.id, earlierJob.id, 'Earlier answer');
+ await execution.publish(channel.id, earlierJob.id);
+ await execution.releaseWriter(channel.id, earlierJob.id);
+ const first = (await execution.claim(channel.id, (await send(channel.id, 'now')).id, lease))!;
+ await db
+ .update(agentOperations)
+ .set({ status: 'running' })
+ .where(eq(agentOperations.id, first.job.operationId!));
+ return { channel, operationId: first.job.operationId! };
+ };
+
+ it('lets the run, as its owner, read the visitor’s public conversation', async () => {
+ const { operationId } = await start();
+ const history = new ChannelHistoryRepository(db, ownerId);
+ const page = await history.readMessages(operationId);
+ expect(page.messages.map((message) => message.content)).toContain('Earlier note');
+ });
+
+ it('refuses anything that would act in the owner’s Channels', async () => {
+ const { operationId } = await start();
+ await expect(
+ new ChannelHistoryRepository(db, ownerId).currentRun(operationId),
+ ).rejects.toThrow('A shared Agent can only read its own conversation');
+ });
+
+ it('does not open the run to the visitor or to another scope', async () => {
+ const { operationId } = await start();
+ await expect(
+ new ChannelHistoryRepository(db, visitorId).readMessages(operationId),
+ ).rejects.toThrow('Channel operation not found');
+ await expect(
+ new ChannelHistoryRepository(db, ownerId, fixture.workspaceId).readMessages(operationId),
+ ).rejects.toThrow('Channel operation not found');
+ });
+ });
+});
diff --git a/packages/database/src/repositories/channel/__tests__/topicProject.test.ts b/packages/database/src/repositories/channel/__tests__/topicProject.test.ts
index 01158a2eba6..5374a7b05e2 100644
--- a/packages/database/src/repositories/channel/__tests__/topicProject.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/topicProject.test.ts
@@ -83,7 +83,7 @@ describe('resolveTopic β€” the topic inherits the Channel’s project', () => {
channel('proj-1'),
job,
member,
- 'user-1',
+ { userId: 'user-1', workspaceId: 'ws-1' },
2,
executionConfig,
);
@@ -104,7 +104,7 @@ describe('resolveTopic β€” the topic inherits the Channel’s project', () => {
channel('proj-1'),
job,
member,
- 'user-1',
+ { userId: 'user-1', workspaceId: 'ws-1' },
2,
executionConfig,
);
@@ -121,7 +121,7 @@ describe('resolveTopic β€” the topic inherits the Channel’s project', () => {
channel('proj-1'),
job,
member,
- 'user-1',
+ { userId: 'user-1', workspaceId: 'ws-1' },
2,
executionConfig,
);
@@ -138,7 +138,7 @@ describe('resolveTopic β€” the topic inherits the Channel’s project', () => {
channel(null),
job,
member,
- 'user-1',
+ { userId: 'user-1', workspaceId: 'ws-1' },
2,
executionConfig,
);
diff --git a/packages/database/src/repositories/channel/agent.ts b/packages/database/src/repositories/channel/agent.ts
index 50076456358..d0652bc779f 100644
--- a/packages/database/src/repositories/channel/agent.ts
+++ b/packages/database/src/repositories/channel/agent.ts
@@ -1,17 +1,23 @@
import { DEFAULT_PROVIDER } from '@lobechat/business-const';
import { isHeterogeneousAgentModelId } from '@lobechat/const';
-import type { ChannelExecutionConfig, ChannelMemberConfig, LobeAgentConfig } from '@lobechat/types';
+import type {
+ ChannelExecutionConfig,
+ ChannelMemberConfig,
+ ChannelSharedAgentAccess,
+ LobeAgentConfig,
+} from '@lobechat/types';
import { agentDisplayName, isChannelRuntime } from '@lobechat/types';
import { cleanObject } from '@lobechat/utils';
-import { and, eq } from 'drizzle-orm';
+import { and, eq, ne } from 'drizzle-orm';
import type { PartialDeep } from 'type-fest';
import type { ChannelItem, ChannelMemberItem } from '../../schemas';
-import { agents, channelMembers, userSettings } from '../../schemas';
+import { agents, agentShares, channelMembers, userSettings } from '../../schemas';
import type { Transaction } from '../../type';
import { agentUsableByWhere } from '../../utils/agent-access';
import { mergeAgentDefaultConfig } from '../../utils/agentConfig';
import { normalizeInboxAgentTitle } from '../../utils/inboxAgent';
+import { notTrashed } from '../../utils/softDelete';
import { ChannelError } from './error';
/** Explicitly select environment fields so legacy or untyped copies cannot override an Agent. */
@@ -30,21 +36,76 @@ export interface ChannelAddAgentInput {
name?: string;
}
+/**
+ * Another person's Agent that `userId` may talk to through its live link share. A link share is
+ * open to anyone signed in, so no contact entry is needed; only a personal direct conversation
+ * can hold one, because the share admits one person at a time and counts its limits per person.
+ */
+export const findSharedChannelAgent = async (
+ tx: Transaction,
+ userId: string,
+ agentId: string,
+): Promise<
+ (ChannelSharedAgentAccess & { name: string | null; title: string | null }) | undefined
+> => {
+ const [row] = await tx
+ .select({
+ name: agents.name,
+ ownerId: agents.userId,
+ shareId: agentShares.id,
+ slug: agents.slug,
+ title: agents.title,
+ workspaceId: agents.workspaceId,
+ })
+ .from(agents)
+ .innerJoin(agentShares, eq(agentShares.agentId, agents.id))
+ .where(
+ and(
+ eq(agents.id, agentId),
+ eq(agentShares.visibility, 'link'),
+ notTrashed(agents.isDeleted),
+ ne(agents.userId, userId),
+ ),
+ )
+ .for('share', { of: agents });
+ if (!row?.ownerId) return undefined;
+ return {
+ name: row.name,
+ ownerId: row.ownerId,
+ shareId: row.shareId,
+ title: normalizeInboxAgentTitle(row.title, row),
+ workspaceId: row.workspaceId,
+ };
+};
+
+/** Whether a direct conversation may bind another person's Agent through its share. */
+const acceptsSharedAgent = (
+ channel: Pick<ChannelItem, 'agentId' | 'workspaceId'>,
+ agentId: string,
+) => channel.agentId === agentId && !channel.workspaceId;
+
/** Check Agent scope and hold it through creation of the Channel/member reference. */
export const requireChannelAgent = async (
tx: Transaction,
workspaceId: string | null,
userId: string,
agentId: string,
+ options: { allowShared?: boolean } = {},
) => {
const [agent] = await tx
.select({ name: agents.name, slug: agents.slug, title: agents.title })
.from(agents)
.where(agentUsableByWhere(agentId, { userId, workspaceId: workspaceId ?? undefined }))
.for('share');
- if (!agent) throw new ChannelError('NOT_FOUND', 'Agent not found');
- // LobeAI rows are stored without a title; label it the way the rest of the product does.
- return { name: agent.name, title: normalizeInboxAgentTitle(agent.title, agent) };
+ if (agent)
+ // LobeAI rows are stored without a title; label it the way the rest of the product does.
+ return { name: agent.name, title: normalizeInboxAgentTitle(agent.title, agent) };
+ const shared =
+ options.allowShared && !workspaceId
+ ? await findSharedChannelAgent(tx, userId, agentId)
+ : undefined;
+ if (!shared) throw new ChannelError('NOT_FOUND', 'Agent not found');
+ return { name: shared.name, title: shared.title };
};
/** Called under the Channel lock after the caller's admin role has been checked. */
@@ -54,6 +115,8 @@ export const addAgentMember = async (
userId: string,
input: ChannelAddAgentInput,
): Promise<ChannelMemberItem> => {
+ if (channel.peerUserId)
+ throw new ChannelError('BAD_REQUEST', 'A conversation between two people has no Agents');
if (channel.agentId) {
if (input.agentId !== channel.agentId)
throw new ChannelError('BAD_REQUEST', 'A direct conversation is bound to one Agent');
@@ -66,7 +129,9 @@ export const addAgentMember = async (
}
if (!input.agentId.trim())
throw new ChannelError('BAD_REQUEST', 'An Agent reference is required');
- const agent = await requireChannelAgent(tx, channel.workspaceId, userId, input.agentId);
+ const agent = await requireChannelAgent(tx, channel.workspaceId, userId, input.agentId, {
+ allowShared: acceptsSharedAgent(channel, input.agentId),
+ });
// Idempotent per Agent: retrying a partly applied batch must not add a second member that
// answers the same requests again.
const [joined] = await tx
@@ -113,6 +178,27 @@ export const requireAgentMember = async (tx: Transaction, channelId: string, mem
return member as ChannelMemberItem & { agentId: string };
};
+const agentSettingsColumns = {
+ agencyConfig: agents.agencyConfig,
+ avatar: agents.avatar,
+ backgroundColor: agents.backgroundColor,
+ chatConfig: agents.chatConfig,
+ editorData: agents.editorData,
+ fewShots: agents.fewShots,
+ model: agents.model,
+ name: agents.name,
+ openingMessage: agents.openingMessage,
+ openingQuestions: agents.openingQuestions,
+ params: agents.params,
+ plugins: agents.plugins,
+ profile: agents.profile,
+ provider: agents.provider,
+ systemRole: agents.systemRole,
+ title: agents.title,
+ tts: agents.tts,
+ virtual: agents.virtual,
+};
+
/** Read current settings with the requester's Agent permissions, then freeze the effective config. */
export const resolveExecutionConfig = async (
tx: Transaction,
@@ -123,52 +209,67 @@ export const resolveExecutionConfig = async (
): Promise<ChannelExecutionConfig | null> => {
if (!member.agentId) return null;
const [agent] = await tx
- .select({
- agencyConfig: agents.agencyConfig,
- avatar: agents.avatar,
- backgroundColor: agents.backgroundColor,
- chatConfig: agents.chatConfig,
- editorData: agents.editorData,
- fewShots: agents.fewShots,
- model: agents.model,
- name: agents.name,
- openingMessage: agents.openingMessage,
- openingQuestions: agents.openingQuestions,
- params: agents.params,
- plugins: agents.plugins,
- profile: agents.profile,
- provider: agents.provider,
- systemRole: agents.systemRole,
- title: agents.title,
- tts: agents.tts,
- virtual: agents.virtual,
- })
+ .select(agentSettingsColumns)
.from(agents)
.where(
agentUsableByWhere(member.agentId, { userId, workspaceId: channel.workspaceId ?? undefined }),
)
.for('share');
- if (!agent) return null;
- const [settings] = channel.workspaceId
+ if (agent) {
+ const config = await mergeDefaults(tx, agent, userId, channel.workspaceId, serverDefault);
+ const runtime = agentRuntime(config);
+ if (!isChannelRuntime(runtime)) return null;
+ return {
+ ...config,
+ ...memberEnvironment(member.config),
+ provider: config.provider || DEFAULT_PROVIDER,
+ runtime,
+ };
+ }
+
+ // Someone else's Agent: it runs as its owner, in its own scope, with the owner's defaults β€”
+ // exactly what a visitor of its share page gets β€” and only in the cloud.
+ if (!acceptsSharedAgent(channel, member.agentId)) return null;
+ const share = await findSharedChannelAgent(tx, userId, member.agentId);
+ if (!share) return null;
+ const [owned] = await tx
+ .select(agentSettingsColumns)
+ .from(agents)
+ .where(eq(agents.id, member.agentId))
+ .for('share');
+ if (!owned) return null;
+ const config = await mergeDefaults(tx, owned, share.ownerId, share.workspaceId, serverDefault);
+ if (agentRuntime(config) !== 'native') return null;
+ return {
+ ...config,
+ provider: config.provider || DEFAULT_PROVIDER,
+ runtime: 'native',
+ share: { ownerId: share.ownerId, shareId: share.shareId, workspaceId: share.workspaceId },
+ };
+};
+
+// Match ordinary Agent execution, including Agents created before agencyConfig existed.
+const agentRuntime = (config: LobeAgentConfig) =>
+ config.agencyConfig?.heterogeneousProvider?.type ??
+ (isHeterogeneousAgentModelId(config.model) ? config.model : 'native');
+
+/** System, server and (personal scope only) the runner's own defaults, then the Agent. */
+const mergeDefaults = async (
+ tx: Transaction,
+ agent: Record<string, unknown>,
+ userId: string,
+ workspaceId: string | null,
+ serverDefault: PartialDeep<LobeAgentConfig>,
+) => {
+ const [settings] = workspaceId
? []
: await tx
.select({ defaultAgent: userSettings.defaultAgent })
.from(userSettings)
.where(eq(userSettings.id, userId));
- const config = mergeAgentDefaultConfig(agent, {
+ return mergeAgentDefaultConfig(agent, {
serverDefault,
userDefault: settings?.defaultAgent,
- workspaceId: channel.workspaceId,
+ workspaceId,
});
- // Match ordinary Agent execution, including Agents created before agencyConfig existed.
- const runtime =
- config.agencyConfig?.heterogeneousProvider?.type ??
- (isHeterogeneousAgentModelId(config.model) ? config.model : 'native');
- if (!isChannelRuntime(runtime)) return null;
- return {
- ...config,
- ...memberEnvironment(member.config),
- provider: config.provider || DEFAULT_PROVIDER,
- runtime,
- };
};
diff --git a/packages/database/src/repositories/channel/claim.ts b/packages/database/src/repositories/channel/claim.ts
index c42e53582fe..e712cf88287 100644
--- a/packages/database/src/repositories/channel/claim.ts
+++ b/packages/database/src/repositories/channel/claim.ts
@@ -359,12 +359,16 @@ export const claimJob = async (
// A savepoint, so losing the directory race to another channel keeps this transaction
// and leaves no topic or operation behind.
claimed = await tx.transaction(async (savepoint) => {
+ const { share } = executionConfig;
+ const scope = share
+ ? { senderId: requester.userId!, userId: share.ownerId, workspaceId: share.workspaceId }
+ : { userId: requester.userId!, workspaceId: channel.workspaceId };
const topic = await resolveTopic(
savepoint,
channel,
job,
member,
- requester.userId!,
+ scope,
request.sequence,
executionConfig,
);
@@ -380,8 +384,8 @@ export const claimJob = async (
const operationId = `op_${Date.now()}_${member.agentId}_${topic.id}_${createNanoId(8)()}`;
await savepoint.insert(agentOperations).values({
id: operationId,
- userId: requester.userId!,
- workspaceId: channel.workspaceId,
+ userId: scope.userId,
+ workspaceId: scope.workspaceId,
topicId: topic.id,
agentId: member.agentId,
trigger: 'channel',
diff --git a/packages/database/src/repositories/channel/history.ts b/packages/database/src/repositories/channel/history.ts
index 07c0ccbcb33..b5793858a47 100644
--- a/packages/database/src/repositories/channel/history.ts
+++ b/packages/database/src/repositories/channel/history.ts
@@ -55,6 +55,12 @@ export class ChannelHistoryRepository {
private async read<T>(
operationId: string,
fn: (tx: Transaction, channelId: string, manifest: ChannelInputManifest) => Promise<T>,
+ /**
+ * Whether another person's shared Agent may use this read. Only plain history reads opt in:
+ * the run executes as the owner, so anything acting from it (listing or posting into
+ * Channels) would act in the owner's Channels.
+ */
+ { allowShared = false }: { allowShared?: boolean } = {},
): Promise<T> {
// This lookup reveals nothing to the caller; authorization is repeated after taking the lock.
const [reference] = await this.db
@@ -71,14 +77,27 @@ export class ChannelHistoryRepository {
.innerJoin(agentOperations, eq(agentOperations.id, channelJobs.operationId))
.where(and(eq(channelJobs.operationId, operationId), eq(channelJobs.channelId, channel.id)))
.limit(1);
+ // A shared Agent runs as its owner in its own scope for the person of a personal direct
+ // conversation (`executionConfig.share`, frozen at claim): the operation is the owner's,
+ // the Channel and its requester are that person's.
+ const share = row?.job.executionConfig?.share;
+ const requesterId = share ? channel.userId : this.userId;
if (
!row ||
row.operation.userId !== this.userId ||
row.operation.workspaceId !== this.workspaceId ||
- channel.workspaceId !== this.workspaceId ||
- (channel.agentId && channel.userId !== this.userId)
+ (share
+ ? share.ownerId !== this.userId ||
+ share.workspaceId !== this.workspaceId ||
+ channel.workspaceId !== null ||
+ channel.agentId !== row.job.manifest?.self.agentId ||
+ !requesterId
+ : channel.workspaceId !== this.workspaceId ||
+ (channel.agentId && channel.userId !== this.userId))
)
throw new ChannelError('NOT_FOUND', 'Channel operation not found');
+ if (share && !allowShared)
+ throw new ChannelError('FORBIDDEN', 'A shared Agent can only read its own conversation');
const { job, operation } = row;
if (
channel.isDeleted ||
@@ -96,7 +115,7 @@ export class ChannelHistoryRepository {
const agent = members.find((member) => member.id === job.memberId);
if (
requester?.actorType !== 'user' ||
- requester.userId !== this.userId ||
+ requester.userId !== requesterId ||
agent?.actorType !== 'agent' ||
agent.agentId !== job.manifest.self.agentId
)
@@ -158,19 +177,23 @@ export class ChannelHistoryRepository {
params.beforeSequence === undefined
? undefined
: integer(params.beforeSequence, 1, 1, Number.MAX_SAFE_INTEGER);
- return this.read(operationId, async (tx, channelId, manifest) => {
- const rows = await readManifestMessages(tx, channelId, manifest, {
- beforeSequence,
- limit: limit + 1,
- });
- const hasMore = rows.length > limit;
- const page = rows.slice(-limit);
- return {
- cutoffSequence: manifest.cutoffSequence,
- messages: page.map((message) => excerpt(message, 0, EXCERPT_LENGTH)),
- nextBeforeSequence: hasMore ? page[0].sequence : null,
- };
- });
+ return this.read(
+ operationId,
+ async (tx, channelId, manifest) => {
+ const rows = await readManifestMessages(tx, channelId, manifest, {
+ beforeSequence,
+ limit: limit + 1,
+ });
+ const hasMore = rows.length > limit;
+ const page = rows.slice(-limit);
+ return {
+ cutoffSequence: manifest.cutoffSequence,
+ messages: page.map((message) => excerpt(message, 0, EXCERPT_LENGTH)),
+ nextBeforeSequence: hasMore ? page[0].sequence : null,
+ };
+ },
+ { allowShared: true },
+ );
};
readMessage = async (
@@ -179,19 +202,23 @@ export class ChannelHistoryRepository {
): Promise<ChannelHistoryMessageDetail> => {
if (!params.messageId?.trim()) throw new ChannelError('BAD_REQUEST', 'messageId is required');
const offset = integer(params.offset, 0, 0, Number.MAX_SAFE_INTEGER);
- return this.read(operationId, async (tx, channelId, manifest) => {
- const [message] = await readManifestMessages(tx, channelId, manifest, {
- messageId: params.messageId,
- });
- if (!message) throw new ChannelError('NOT_FOUND', 'Message not found in this conversation');
- if (offset > message.content.length)
- throw new ChannelError('BAD_REQUEST', 'Offset exceeds message length');
- const result = excerpt(message, offset, DETAIL_LENGTH);
- return {
- message: result,
- nextOffset: result.truncated ? offset + DETAIL_LENGTH : null,
- offset,
- };
- });
+ return this.read(
+ operationId,
+ async (tx, channelId, manifest) => {
+ const [message] = await readManifestMessages(tx, channelId, manifest, {
+ messageId: params.messageId,
+ });
+ if (!message) throw new ChannelError('NOT_FOUND', 'Message not found in this conversation');
+ if (offset > message.content.length)
+ throw new ChannelError('BAD_REQUEST', 'Offset exceeds message length');
+ const result = excerpt(message, offset, DETAIL_LENGTH);
+ return {
+ message: result,
+ nextOffset: result.truncated ? offset + DETAIL_LENGTH : null,
+ offset,
+ };
+ },
+ { allowShared: true },
+ );
};
}
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index d2a72cefe63..3d2f00b8fd1 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -31,6 +31,7 @@ import {
import { channelAvatarMembers } from './avatars';
import { findThread } from './delivery';
import { ChannelError } from './error';
+import { lockPeerPair, peerOf, requireMutualContacts } from './peer';
import { addChannelUser, channelUserCandidates, newChannelUserCandidates } from './people';
import type { ChannelAgentPostInput } from './post';
import { postAgentMessage } from './post';
@@ -108,6 +109,8 @@ export class ChannelRepository {
title: string;
/** Workspace people a group starts with, checked the same way as adding them later. */
userIds?: string[];
+ /** The direct conversation binds another person's Agent through its live link share. */
+ sharedAgent?: boolean;
visibility?: ChannelVisibility;
}) =>
this.db.transaction(async (tx) => {
@@ -124,7 +127,11 @@ export class ChannelRepository {
'A direct conversation requires an Agent and private visibility',
);
if (agentId) {
- await requireChannelAgent(tx, this.workspaceId, this.userId, agentId);
+ // Only the service opens one with another person's shared Agent, after resolving the
+ // share the person reached; a plain Agent id never does.
+ await requireChannelAgent(tx, this.workspaceId, this.userId, agentId, {
+ allowShared: !!params.sharedAgent,
+ });
const existing = await this.findDirect(tx, agentId);
if (existing) return existing;
}
@@ -433,6 +440,7 @@ export class ChannelRepository {
> => {
const rows = await this.db
.select({
+ agentOwnerId: agents.userId,
channel: channels,
lastReadSequence: channelMembers.lastReadSequence,
memberId: channelMembers.id,
@@ -440,6 +448,7 @@ export class ChannelRepository {
})
.from(channels)
.innerJoin(channelMembers, eq(channelMembers.channelId, channels.id))
+ .leftJoin(agents, eq(agents.id, channels.agentId))
.where(and(this.membershipWhere(), notTrashed(channels.isDeleted)))
.orderBy(desc(channels.createdAt));
@@ -531,24 +540,77 @@ export class ChannelRepository {
: [];
const mentionCountOf = new Map(mentioned.map(({ channelId, count }) => [channelId, count]));
- // A group Channel's list avatar pictures its first members; a direct one shows its Agent.
+ // A group Channel's list avatar pictures its first members; a direct one, its Agent or the
+ // other person, which also pictures a shared Agent the caller has no sidebar row for.
const avatarsOf = await channelAvatarMembers(
this.db,
- rows.filter(({ channel }) => !channel.agentId).map(({ channel }) => channel.id),
+ rows.map(({ channel }) => channel.id),
this.userId,
);
- return rows.map(({ channel, lastReadSequence, role }) => ({
+ return rows.map(({ agentOwnerId, channel, lastReadSequence, role }) => ({
...channel,
+ sharedAgent: !!channel.agentId && !channel.workspaceId && agentOwnerId !== this.userId,
canDelete: hasRole(role, 'admin'),
lastMessage: lastMessageOf.get(channel.id) ?? null,
memberAvatars: avatarsOf.get(channel.id) ?? [],
mentionCount: mentionCountOf.get(channel.id) ?? 0,
+ peerUserId: peerOf(channel, this.userId),
replyJobs: replyJobsOf.get(channel.id) ?? [],
unreadCount: Math.max(0, channel.sequence - (lastReadSequence ?? 0)),
}));
};
+ /**
+ * The caller's personal conversation with a contact, opened by either of them. Requires the
+ * mutual contact relation; an existing conversation opens as it is, trashed or not.
+ */
+ openPeer = (peerUserId: string, title: string): Promise<ChannelAccess> =>
+ this.db.transaction(async (tx) => {
+ if (this.workspaceId)
+ throw new ChannelError('BAD_REQUEST', 'A conversation between people is personal');
+ if (peerUserId === this.userId)
+ throw new ChannelError('BAD_REQUEST', 'You cannot message yourself');
+ await requireMutualContacts(tx, this.userId, peerUserId);
+ // No unique index keeps one conversation per pair: serialize opening it, so two people
+ // opening it at once (or one twice) find the first one instead of creating a second.
+ await lockPeerPair(tx, this.userId, peerUserId);
+ const existing = await this.findPeer(tx, peerUserId);
+ if (existing) return existing;
+
+ const [channel] = await tx
+ .insert(channels)
+ .values({ peerUserId, title, userId: this.userId, visibility: 'private' })
+ .returning();
+ const member = await this.addOwner(tx, channel.id);
+ await tx.insert(channelMembers).values({
+ actorType: 'user',
+ channelId: channel.id,
+ lastReadSequence: 0,
+ role: 'owner',
+ userId: peerUserId,
+ });
+ return { channel, member };
+ });
+
+ private findPeer = async (tx: Transaction, peerUserId: string) => {
+ const [row] = await tx
+ .select({ channel: channels, member: channelMembers })
+ .from(channels)
+ .innerJoin(
+ channelMembers,
+ and(eq(channelMembers.channelId, channels.id), eq(channelMembers.userId, this.userId)),
+ )
+ .where(
+ or(
+ and(eq(channels.userId, this.userId), eq(channels.peerUserId, peerUserId)),
+ and(eq(channels.userId, peerUserId), eq(channels.peerUserId, this.userId)),
+ ),
+ )
+ .limit(1);
+ return row as ChannelAccess | undefined;
+ };
+
/**
* The caller's active Channels with their active Agent members, newest first: where the caller
* can address another Agent. Archived and trashed Channels are left out, since nothing posted
diff --git a/packages/database/src/repositories/channel/peer.ts b/packages/database/src/repositories/channel/peer.ts
new file mode 100644
index 00000000000..97e896a9635
--- /dev/null
+++ b/packages/database/src/repositories/channel/peer.ts
@@ -0,0 +1,43 @@
+import { and, eq, or, sql } from 'drizzle-orm';
+
+import type { ChannelItem } from '../../schemas';
+import { userContacts } from '../../schemas';
+import type { Transaction } from '../../type';
+import { ChannelError } from './error';
+
+/**
+ * A personal conversation between two people exists only between contacts. Opening one and
+ * sending in it both require the relation to still hold in both directions, so removing a
+ * contact silences the conversation without deleting its history.
+ */
+export const requireMutualContacts = async (
+ tx: Transaction,
+ userId: string,
+ peerUserId: string,
+) => {
+ const rows = await tx
+ .select({ userId: userContacts.userId })
+ .from(userContacts)
+ .where(
+ or(
+ and(eq(userContacts.userId, userId), eq(userContacts.contactUserId, peerUserId)),
+ and(eq(userContacts.userId, peerUserId), eq(userContacts.contactUserId, userId)),
+ ),
+ );
+ if (rows.length < 2) throw new ChannelError('FORBIDDEN', 'You are not contacts');
+};
+
+/** The other person of a conversation between two people, relative to `viewerId`. */
+export const peerOf = (
+ channel: Pick<ChannelItem, 'peerUserId' | 'userId'>,
+ viewerId: string,
+): string | null => {
+ if (!channel.peerUserId) return null;
+ return channel.userId === viewerId ? channel.peerUserId : channel.userId;
+};
+
+/** Transaction-scoped lock on the unordered pair, the same either way round. */
+export const lockPeerPair = async (tx: Transaction, userId: string, peerUserId: string) => {
+ const [a, b] = [userId, peerUserId].sort();
+ await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${`channel-peer:${a}:${b}`}))`);
+};
diff --git a/packages/database/src/repositories/channel/send.ts b/packages/database/src/repositories/channel/send.ts
index e7e70637d81..d64b7f83156 100644
--- a/packages/database/src/repositories/channel/send.ts
+++ b/packages/database/src/repositories/channel/send.ts
@@ -3,7 +3,7 @@ import { CHANNEL_LIMITS } from '@lobechat/types';
import { and, asc, eq, inArray } from 'drizzle-orm';
import type { ChannelMessageItem } from '../../schemas';
-import { channelMembers, channelMessages, channelThreads, files } from '../../schemas';
+import { agents, channelMembers, channelMessages, channelThreads, files } from '../../schemas';
import type { Transaction } from '../../type';
import { isUuid } from '../../utils/uuid';
import { buildWorkspaceWhere } from '../../utils/workspace';
@@ -18,6 +18,7 @@ import {
pairedAgent,
} from './delivery';
import { ChannelError } from './error';
+import { peerOf, requireMutualContacts } from './peer';
import { audit } from './transaction';
import type { ChannelAccess } from './types';
import { createChannelThread } from './view';
@@ -155,6 +156,20 @@ export const sendMessage = async (
return existing;
}
+ // Removing a contact silences the conversation for both people; its history stays.
+ if (channel.peerUserId && member.userId)
+ await requireMutualContacts(tx, member.userId, peerOf(channel, member.userId)!);
+
+ if (fileIds.length && channel.agentId) {
+ // Another person's shared Agent runs as its owner, who cannot read the sender's files.
+ const [bound] = await tx
+ .select({ ownerId: agents.userId })
+ .from(agents)
+ .where(eq(agents.id, channel.agentId));
+ if (bound?.ownerId !== member.userId && !channel.workspaceId)
+ throw new ChannelError('BAD_REQUEST', 'Attachments cannot be sent to a shared Agent');
+ }
+
if (fileIds.length) {
// Lock in a stable order so concurrent sends and file cleanup cannot deadlock.
const accessible = await tx
diff --git a/packages/database/src/repositories/channel/topic.ts b/packages/database/src/repositories/channel/topic.ts
index 1063788f847..e3ff1c5f5fc 100644
--- a/packages/database/src/repositories/channel/topic.ts
+++ b/packages/database/src/repositories/channel/topic.ts
@@ -1,9 +1,10 @@
+import { AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC } from '@lobechat/const';
import type { ChannelExecutionConfig } from '@lobechat/types';
-import { and, desc, eq, isNotNull, isNull, ne } from 'drizzle-orm';
+import { and, count, desc, eq, isNotNull, isNull, ne } from 'drizzle-orm';
import isEqual from 'fast-deep-equal';
import type { ChannelItem, ChannelJobItem, ChannelMemberItem } from '../../schemas';
-import { agentOperations, channelJobs, topics } from '../../schemas';
+import { agentOperations, agentShares, channelJobs, messages, topics } from '../../schemas';
import type { Transaction } from '../../type';
import { CHANNEL_TOPIC_TRIGGER } from '../../utils/topicVisibility';
@@ -18,13 +19,25 @@ const TOPIC_STALE_THRESHOLD = 4 * 60 * 60 * 1000;
* their credentials, devices and tool results. Sharing it with another requester's run would
* hand that private transcript to someone else, so a member's work for other people reaches
* this topic only as public replies (marked `self` in the prompt).
+ *
+ * Another person's shared Agent runs as its owner, so the topic belongs to the owner and its
+ * scope, with the requester as `senderId` β€” the same row a visit to the share page would write,
+ * hidden from the owner's own lists. Such a topic also ends at the share's per-topic turn limit,
+ * where the share page would ask for a new conversation.
*/
+export interface ChannelTopicScope {
+ /** The requester when the run executes as a shared Agent's owner. */
+ senderId?: string;
+ userId: string;
+ workspaceId: string | null;
+}
+
export const resolveTopic = async (
tx: Transaction,
channel: ChannelItem,
job: ChannelJobItem,
member: ChannelMemberItem,
- userId: string,
+ scope: ChannelTopicScope,
requestSequence: number,
executionConfig: ChannelExecutionConfig,
) => {
@@ -60,10 +73,12 @@ export const resolveTopic = async (
previous.operation?.status === 'done' &&
isEqual(prior.executionConfig, executionConfig) &&
topic.agentId === member.agentId &&
- topic.userId === userId &&
- topic.workspaceId === channel.workspaceId &&
+ topic.userId === scope.userId &&
+ topic.workspaceId === scope.workspaceId &&
+ (topic.senderId ?? undefined) === scope.senderId &&
!topic.isDeleted &&
- (job.threadId || Date.now() - topic.updatedAt.getTime() <= TOPIC_STALE_THRESHOLD)
+ (job.threadId || Date.now() - topic.updatedAt.getTime() <= TOPIC_STALE_THRESHOLD) &&
+ !(executionConfig.share && (await reachedShareTurnLimit(tx, member.agentId!, topic.id)))
) {
// A Channel that belongs to a project runs inside it, so the topic it works in
// must say which project it belongs to: that binding is what the run resolves
@@ -89,10 +104,25 @@ export const resolveTopic = async (
// The Channel's project, read from the Channel itself (never inferred from the
// Agent), so a conversation started by a project Channel is born in the project.
projectId: channel.projectId ?? undefined,
+ senderId: scope.senderId,
trigger: CHANNEL_TOPIC_TRIGGER,
- userId,
- workspaceId: channel.workspaceId,
+ userId: scope.userId,
+ workspaceId: scope.workspaceId,
})
.returning();
return created;
};
+
+const reachedShareTurnLimit = async (tx: Transaction, agentId: string, topicId: string) => {
+ const [share] = await tx
+ .select({ config: agentShares.shareConfig })
+ .from(agentShares)
+ .where(eq(agentShares.agentId, agentId))
+ .limit(1);
+ const limit = share?.config?.maxTurnsPerTopic ?? AGENT_SHARE_DEFAULT_MAX_TURNS_PER_TOPIC;
+ const [turns] = await tx
+ .select({ value: count() })
+ .from(messages)
+ .where(and(eq(messages.topicId, topicId), eq(messages.role, 'user')));
+ return (turns?.value ?? 0) >= limit;
+};
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index e53cce8ca60..91749e5ad4d 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -221,9 +221,23 @@ export const channelMessageVia = (
};
/** Effective Agent settings and Channel environment, frozen once when a job is claimed. */
+/**
+ * Another person's Agent reached through the requester's contact entry and its link share. The
+ * run executes as the Agent's owner under the share's limits; the topic is the owner's, tagged
+ * with the requester as its sender.
+ */
+export interface ChannelSharedAgentAccess {
+ ownerId: string;
+ shareId: string;
+ /** The Agent's scope, which the run and its topic use; not the Channel's. */
+ workspaceId: string | null;
+}
+
export interface ChannelExecutionConfig extends LobeAgentConfig, ChannelMemberConfig {
provider: string;
runtime: ChannelRuntime;
+ /** Set when the Agent belongs to someone else and is used through its share. */
+ share?: ChannelSharedAgentAccess;
/** Set when the run works in its branch's worktree; `workingDirectory` is then that worktree. */
worktreeBranch?: string;
}
@@ -452,6 +466,11 @@ export interface ChannelListItem {
memberAvatars?: ChannelAvatarMember[];
/** Unread messages, Threads included, that @mention the caller; set by the Channel list. */
mentionCount?: number;
+ /**
+ * On a conversation between two people, the other person (relative to the viewer), who is also
+ * the only entry of `memberAvatars`; null otherwise.
+ */
+ peerUserId?: string | null;
/** The project the channel is grouped under; null for a standalone channel. */
projectId: string | null;
/**
@@ -460,6 +479,11 @@ export interface ChannelListItem {
*/
replyJobs?: ChannelReplyJob[];
sequence: number;
+ /**
+ * A direct conversation with another person's Agent, reached through the caller's contact entry
+ * and its share; pictured by `memberAvatars`, since the caller has no sidebar row for it.
+ */
+ sharedAgent?: boolean;
status: ChannelStatus;
title: string;
/** Main-channel messages the caller has not read; set by the Channel list. */
diff --git a/packages/types/src/contact.ts b/packages/types/src/contact.ts
index a068657b2e5..92148e473f6 100644
--- a/packages/types/src/contact.ts
+++ b/packages/types/src/contact.ts
@@ -9,5 +9,64 @@ export type ContactType = (typeof CONTACT_TYPES)[number];
export const CONTACT_REQUEST_STATUSES = ['pending', 'accepted', 'declined', 'cancelled'] as const;
export type ContactRequestStatus = (typeof CONTACT_REQUEST_STATUSES)[number];
+/** Upper bound for the optional note a person attaches to a contact request. */
+export const CONTACT_REQUEST_MESSAGE_MAX_LENGTH = 200;
+
+export interface ContactUserProfile {
+ avatar: string | null;
+ fullName: string | null;
+ id: string;
+ username: string | null;
+}
+
+export interface ContactAgentProfile {
+ agentId: string;
+ avatar: string | null;
+ backgroundColor: string | null;
+ description: string | null;
+ owner: ContactUserProfile;
+ /** Share id; the visitor page and every run authorize against it. */
+ shareId: string;
+ /** Custom share handle (`/a/<slug>`), when the owner set one. */
+ slug: string | null;
+ title: string | null;
+}
+
+export interface ContactUserItem {
+ createdAt: Date;
+ type: 'user';
+ user: ContactUserProfile;
+}
+
+export interface ContactAgentItem {
+ agent: ContactAgentProfile;
+ /**
+ * False once the owner pauses the share or trashes the Agent. The contact stays so it can
+ * come back when the share resumes; clients show it as unavailable and cannot message it.
+ */
+ available: boolean;
+ createdAt: Date;
+ type: 'agent';
+}
+
+export type ContactItem = ContactUserItem | ContactAgentItem;
+
+export interface ContactRequestItem {
+ createdAt: Date;
+ /** `incoming`: sent to me; `outgoing`: sent by me. */
+ direction: 'incoming' | 'outgoing';
+ id: string;
+ message: string | null;
+ /** The other person. */
+ user: ContactUserProfile;
+}
+
+/** Relation of a search result or profile to the current user. */
+export type ContactRelation = 'self' | 'contact' | 'request_sent' | 'request_received' | 'none';
+
+export type ContactSearchResult =
+ | { relation: ContactRelation; type: 'user'; user: ContactUserProfile }
+ | { agent: ContactAgentProfile; relation: 'self' | 'contact' | 'none'; type: 'agent' };
+
/** Owner-side extras of an address book entry; open for later management features. */
export type ContactMetadata = Record<string, unknown>;