🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(channel): let an owner's bot run message Agents in their Channels (#23159)
Arvin Xu063171519da9
diff --git a/apps/server/src/routers/lambda/channelHistory.ts b/apps/server/src/routers/lambda/channelHistory.tsindex f75daf292aa..e20238524e6 100644--- a/apps/server/src/routers/lambda/channelHistory.ts+++ b/apps/server/src/routers/lambda/channelHistory.ts@@ -39,7 +39,9 @@ const operationProcedure = (capability: HeteroOperationCapability) =>const result = await next({ctx: {channelHistory: new ChannelHistoryService(...args),- channelMessaging: new ChannelMessagingService(...args),+ // The token was checked for this capability above; an owner's bot run carries+ // `channel:message` without a Channel of its own.+ channelMessaging: new ChannelMessagingService(...args, { allowBotRun: true }),},});if (!result.ok && result.error.cause instanceof ChannelError)diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.tsindex 075b810c6e2..04af97fca8d 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts@@ -8,6 +8,7 @@ import {resolveDispatchedClaudeCodeEntrypoint,} from '@lobechat/heterogeneous-agents';import {+ BOT_CHANNEL_MESSAGING_INSTRUCTIONS,CHANNEL_INSTRUCTIONS,formatContextSelections,formatPageSelections,@@ -57,6 +58,7 @@ export const prepareHeteroRun = async (| 'agentConfig'| 'appContext'| 'assistantMessageId'+ | 'botContext'| 'prompt'| 'shareGate'| 'topicId'@@ -91,6 +93,10 @@ export const prepareHeteroRun = async (workspaceId: deps.workspaceId,});const isChannelOperation = ctx.trigger === 'channel' && input.reservedOperationId === operationId;+ // The bot's owner messaging their own Agent (e.g. on Telegram) may have it post into their+ // Channels. `isOwner` is decided once, fail-closed, in `buildBotContext`.+ const isOwnerBotOperation =+ ctx.trigger === RequestTrigger.Bot && ctx.botContext?.isOwner === true;// Sign an operation-scoped JWT so the CLI can authenticate against// heteroIngest / heteroFinish without full user credentials.@@ -103,6 +109,7 @@ export const prepareHeteroRun = async (// `acceptance:evidence` for its own verification round.capabilities: heteroOperationCapabilities(prompt, {channel: isChannelOperation,+ ownerBotTurn: isOwnerBotOperation,taskId: operationTaskId,// A scheduled run replays the user's own message off history, so it has// no fresh user row; server-started `chat` deliveries have none either.@@ -303,7 +310,11 @@ export const prepareHeteroRun = async (projectContext,viewedTaskContext,selectionContext,- isChannelOperation ? CHANNEL_INSTRUCTIONS : undefined,+ isChannelOperation+ ? CHANNEL_INSTRUCTIONS+ : isOwnerBotOperation+ ? BOT_CHANNEL_MESSAGING_INSTRUCTIONS+ : undefined,),prompt,);diff --git a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.tsindex e273967c1ca..3cfa5fc4d9d 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts@@ -10,6 +10,15 @@ describe('heteroOperationCapabilities', () => {expect(heteroOperationCapabilities('read the discussion')).not.toContain('channel:read');expect(heteroOperationCapabilities('read the discussion')).not.toContain('channel:message');});+ it("lets an owner's bot run message Channels, but not read one", () => {+ const capabilities = heteroOperationCapabilities('tell the LobeHub agent', {+ ownerBotTurn: true,+ });+ expect(capabilities).toContain('channel:message');+ expect(capabilities).not.toContain('channel:read');+ expect(capabilities).not.toContain('goal:manage');+ });+it('grants goal management to a /goal run', () => {expect(heteroOperationCapabilities('/goal ship the report')).toContain('goal:manage');});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.tsindex eba2c5e570f..b390d6d6dcc 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts@@ -19,7 +19,11 @@ import type { HeteroOperationCapability } from '@/libs/trpc/utils/internalJwt';** `channel:read` and `channel:message` let a Channel dispatch read its own conversation* (`lh channel history|message`) and message Agents in the requester's other Channels- * (`lh channel list|send`), as the requester, never as the device owner.+ * (`lh channel list|send`), as the requester, never as the device owner. A bot run whose+ * sender is the bot's owner (`botContext.isOwner`, e.g. the owner messaging their Agent on+ * Telegram) gets `channel:message` alone: it may list the owner's Channels and post a request+ * there as the owner. It has no Channel conversation to read, and a bot message from anyone+ * else gets neither.** `acceptance:evidence` lets a Task run file evidence into its own verification* round (`lh acceptance run result submit|ingest --operation`). That round is@@ -33,13 +37,19 @@ export const heteroOperationCapabilities = (prompt: unknown,options: {channel?: boolean;+ /** The run answers a bot message its owner sent (`botContext.isOwner`). */+ ownerBotTurn?: boolean;taskId?: string;/** The run answers a message the user sent: a chat turn or one they scheduled. */userTurn?: boolean;} = {},): HeteroOperationCapability[] => ['hetero:ingest',- ...(options.channel ? (['channel:read', 'channel:message'] as const) : []),+ ...(options.channel+ ? (['channel:read', 'channel:message'] as const)+ : options.ownerBotTurn+ ? (['channel:message'] as const)+ : []),'hetero:finish','hetero:intervention:read',...(isGoalPrompt(prompt) || (options.userTurn && !options.channel && !options.taskId)diff --git a/apps/server/src/services/channel/ChannelMessagingService.test.ts b/apps/server/src/services/channel/ChannelMessagingService.test.tsindex f461a2b919c..c1a81cf6792 100644--- a/apps/server/src/services/channel/ChannelMessagingService.test.ts+++ b/apps/server/src/services/channel/ChannelMessagingService.test.ts@@ -3,15 +3,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { ChannelMessagingService } from './ChannelMessagingService';-const { currentRun, directory, send } = vi.hoisted(() => ({- currentRun: vi.fn(),+const { directory, relaySource, send } = vi.hoisted(() => ({+ relaySource: vi.fn(),directory: vi.fn(),send: vi.fn(),}));vi.mock('@/database/repositories/channel', async (original) => ({...(await original<object>()),ChannelHistoryRepository: class {- currentRun = currentRun;+ relaySource = relaySource;},ChannelRepository: class {directory = directory;@@ -32,10 +32,12 @@ vi.mock('./ChannelService', () => ({const self = { agentId: 'agent-self', memberId: 'member-self', name: 'Project Agent' };const run = (requestVia?: { agentId: string; name: string }) => ({- channelId: 'channel-current',- manifest: { self, threadId: null },+ origin: { channelId: 'channel-current', threadId: null },requestVia,+ self: { agentId: self.agentId, name: self.name },});+/** An owner's bot run: no Channel of its own. */+const botRun = { self: { agentId: self.agentId, name: self.name } };const lobehub = {agents: [{@@ -55,7 +57,7 @@ const current = {describe('ChannelMessagingService', () => {beforeEach(() => {vi.resetAllMocks();- currentRun.mockResolvedValue(run());+ relaySource.mockResolvedValue(run());directory.mockResolvedValue([current, lobehub]);send.mockResolvedValue({ id: 'message-sent' });});@@ -126,7 +128,7 @@ describe('ChannelMessagingService', () => {it('refuses relays that would loop, target the current Channel or miss the Agent', async () => {const message = { agentIds: ['agent-lobehub'], channelId: 'channel-lobehub', content: 'Hi' };- currentRun.mockResolvedValueOnce(run({ agentId: 'agent-other', name: 'Other Agent' }));+ relaySource.mockResolvedValueOnce(run({ agentId: 'agent-other', name: 'Other Agent' }));await expect(service().sendMessage(message, 'call')).rejects.toThrow('relayed by Other Agent');await expect(service().sendMessage({ ...message, channelId: 'channel-current' }, 'call'),@@ -145,4 +147,36 @@ describe('ChannelMessagingService', () => {);expect(send).not.toHaveBeenCalled();});++ it('only lets the token-checked route relay from a bot run', async () => {+ await service().listChannels();+ expect(relaySource).toHaveBeenLastCalledWith('op-current', {});+ const fromBot = new ChannelMessagingService({} as never, 'user-1', 'op-current', undefined, {+ allowBotRun: true,+ });+ await fromBot.listChannels();+ expect(relaySource).toHaveBeenLastCalledWith('op-current', { allowBotRun: true });+ });++ it("relays an owner's bot request with no current Channel and no receipt origin", async () => {+ relaySource.mockResolvedValue(botRun);+ expect((await service().listChannels()).channels.map(({ current }) => current)).toEqual([+ false,+ false,+ ]);++ await service().sendMessage(+ { agentIds: ['agent-lobehub'], channelId: 'channel-lobehub', content: 'Please fix T-1' },+ 'call-1',+ );+ expect(send.mock.calls[0][1].metadata).toEqual({+ via: { agentId: 'agent-self', name: 'Project Agent', operationId: 'op-current' },+ });+ await expect(+ service().sendMessage(+ { agentIds: ['agent-self'], channelId: 'channel-current', content: 'Hi' },+ 'call-2',+ ),+ ).rejects.toThrow('yourself');+ });});diff --git a/apps/server/src/services/channel/ChannelMessagingService.ts b/apps/server/src/services/channel/ChannelMessagingService.tsindex fd73845e14e..bdd2667820c 100644--- a/apps/server/src/services/channel/ChannelMessagingService.ts+++ b/apps/server/src/services/channel/ChannelMessagingService.ts@@ -31,6 +31,11 @@ const escapeRegExp = (value: string) => value.replaceAll(/[$()*+.?[\\\]^{|}]/g,* identity, so the target Channel's own membership, routing and permissions decide what happens;* `metadata.via` only records which Agent relayed it. The run itself (live, unrevoked, requester* still a member) is checked first, exactly as a history read checks it.+ *+ * The bot's owner messaging their Agent on an IM platform may do the same from that bot run. It+ * has no Channel of its own, so nothing is current, and the reply stays in the target Channel:+ * there is no origin to deliver a receipt back to. Only the CLI route, which has checked the+ * run's operation token for `channel:message`, opts in (`allowBotRun`).*/export class ChannelMessagingService {private readonly history: ChannelHistoryRepository;@@ -41,6 +46,7 @@ export class ChannelMessagingService {private readonly userId: string,private readonly operationId: string,private readonly workspaceId?: string,+ private readonly options: { allowBotRun?: boolean } = {},) {this.history = new ChannelHistoryRepository(db, userId, workspaceId);this.channels = new ChannelRepository(db, userId, workspaceId);@@ -48,7 +54,7 @@ export class ChannelMessagingService {listChannels = async (params: ChannelListChannelsParams = {}): Promise<ChannelDirectoryPage> => {await assertChannelEnabled(this.userId);- const run = await this.history.currentRun(this.operationId);+ const run = await this.history.relaySource(this.operationId, this.options);const limit = params.limit ?? DEFAULT_LIMIT;if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_LIMIT)throw new ChannelError('BAD_REQUEST', `Expected a limit between 1 and ${MAX_LIMIT}`);@@ -64,7 +70,7 @@ export class ChannelMessagingService {return {channels: matched.slice(0, limit).map(({ agents, channel }) => ({agents: agents.map(({ agentId, description, name }) => ({ agentId, description, name })),- current: channel.id === run.channelId,+ current: channel.id === run.origin?.channelId,id: channel.id,kind: channel.agentId ? 'direct' : 'group',projectId: channel.projectId,@@ -83,7 +89,7 @@ export class ChannelMessagingService {requestId: string,): Promise<ChannelSentMessage> => {await assertChannelEnabled(this.userId);- const run = await this.history.currentRun(this.operationId);+ const run = await this.history.relaySource(this.operationId, this.options);// One hop only: a relayed request is answered where it arrived, so two Agents cannot keep// relaying to each other on the requester's behalf.if (run.requestVia)@@ -91,7 +97,7 @@ export class ChannelMessagingService {'FORBIDDEN',`This request was relayed by ${run.requestVia.name}; answer it here instead of relaying it again`,);- if (params.channelId === run.channelId)+ if (params.channelId === run.origin?.channelId)throw new ChannelError('BAD_REQUEST','That is the Channel you are answering in; your final answer is posted there',@@ -105,7 +111,7 @@ export class ChannelMessagingService {'BAD_REQUEST',`Address between 1 and ${MAX_RECIPIENTS} Agents with agentIds`,);- if (agentIds.includes(run.manifest.self.agentId))+ if (agentIds.includes(run.self.agentId))throw new ChannelError('BAD_REQUEST', 'You cannot send a message to yourself');const target = (await this.channels.directory()).find(@@ -138,11 +144,11 @@ export class ChannelMessagingService {mentions: agents.map(({ memberId }) => memberId),metadata: {via: {- agentId: run.manifest.self.agentId,- name: run.manifest.self.name,+ agentId: run.self.agentId,+ name: run.self.name,operationId: this.operationId,// Where the addressed Agents' replies are delivered back (`deliverRelayReceipts`).- origin: { channelId: run.channelId, threadId: run.manifest.threadId },+ ...(run.origin && { origin: run.origin }),},},requestKey: `agent-relay:${this.operationId}:${requestId}`,diff --git a/packages/database/src/repositories/channel/__tests__/history.test.ts b/packages/database/src/repositories/channel/__tests__/history.test.tsindex 6177557a043..2567b0c3d6a 100644--- a/packages/database/src/repositories/channel/__tests__/history.test.ts+++ b/packages/database/src/repositories/channel/__tests__/history.test.ts@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';import {agentOperations,+ agents,channelJobs,channelMembers,channels,@@ -251,3 +252,62 @@ describe('Channel on-demand history', () => {},);});++describe('Channel relay source', () => {+ it('relays a Channel run from its own Channel and request', async () => {+ const state = await setup();+ const { operationId } = await state.run();+ expect(await state.history.relaySource(operationId, { allowBotRun: true })).toEqual({+ origin: { channelId: state.channel.id, threadId: null },+ requestVia: undefined,+ self: { agentId: expect.any(String), name: 'Reader' },+ });+ });++ it("relays an owner's live bot run only when the caller opts in", async () => {+ const history = new ChannelHistoryRepository(db, fixture.memberId, fixture.workspaceId);+ const [agent] = await db+ .insert(agents)+ .values({+ name: 'Telegram Agent',+ userId: fixture.memberId,+ workspaceId: fixture.workspaceId,+ })+ .returning();+ const operation = async (id: string, values: Partial<typeof agentOperations.$inferInsert>) => {+ await db.insert(agentOperations).values({+ agentId: agent.id,+ id,+ status: 'running',+ trigger: 'bot',+ userId: fixture.memberId,+ workspaceId: fixture.workspaceId,+ ...values,+ });+ return id;+ };+ try {+ const bot = await operation('op-relay-bot', {});+ // The native tool path never opts in, so a bot run without a Channel stays refused there.+ await expect(history.relaySource(bot)).rejects.toThrow('Channel operation not found');+ expect(await history.relaySource(bot, { allowBotRun: true })).toEqual({+ self: { agentId: agent.id, name: 'Telegram Agent' },+ });++ const chat = await operation('op-relay-chat', { trigger: 'chat' });+ await expect(history.relaySource(chat, { allowBotRun: true })).rejects.toThrow(+ 'Channel operation not found',+ );+ const other = await operation('op-relay-other', { userId: fixture.ownerId });+ await expect(history.relaySource(other, { allowBotRun: true })).rejects.toThrow(+ 'Channel operation not found',+ );+ const ended = await operation('op-relay-ended', { status: 'completed' });+ await expect(history.relaySource(ended, { allowBotRun: true })).rejects.toThrow(+ 'no longer active',+ );+ } finally {+ await db.delete(agentOperations).where(eq(agentOperations.agentId, agent.id));+ }+ });+});diff --git a/packages/database/src/repositories/channel/history.ts b/packages/database/src/repositories/channel/history.tsindex b5793858a47..f9a2abf484a 100644--- a/packages/database/src/repositories/channel/history.ts+++ b/packages/database/src/repositories/channel/history.ts@@ -8,10 +8,16 @@ import type {ChannelReadMessageParams,ChannelReadMessagesParams,} from '@lobechat/types';-import { channelMessageVia } from '@lobechat/types';+import { agentDisplayName, channelMessageVia, RequestTrigger } from '@lobechat/types';import { and, eq, isNull } from 'drizzle-orm';-import { agentOperations, channelJobs, channelMessages, workspaceMembers } from '../../schemas';+import {+ agentOperations,+ agents,+ channelJobs,+ channelMessages,+ workspaceMembers,+} from '../../schemas';import type { LobeChatDatabase, Transaction } from '../../type';import { normalizeWorkspaceId } from '../../utils/workspace';import { activeMembers, findThread } from './delivery';@@ -168,6 +174,67 @@ export class ChannelHistoryRepository {return { channelId, manifest, requestVia: channelMessageVia(request?.metadata) };});+ /**+ * Who a run relays as, and from where. A Channel run relays from its Channel and request+ * (`currentRun`, all its checks). A run with no Channel job may only be the requester's own+ * live bot run, and only when the caller says so (`allowBotRun`): the bot's owner asked their+ * Agent from an IM platform to post into one of their Channels. Only a caller holding that run's+ * `channel:message` token, minted only for an owner's bot message, may set it; the trigger is+ * checked again here so no other run without a Channel can relay.+ */+ relaySource = async (+ operationId: string,+ { allowBotRun = false }: { allowBotRun?: boolean } = {},+ ): Promise<{+ origin?: { channelId: string; threadId: string | null };+ requestVia?: ChannelMessageVia;+ self: { agentId: string; name: string };+ }> => {+ const [job] = await this.db+ .select({ id: channelJobs.id })+ .from(channelJobs)+ .where(eq(channelJobs.operationId, operationId))+ .limit(1);+ if (job || !allowBotRun) {+ const run = await this.currentRun(operationId);+ return {+ origin: { channelId: run.channelId, threadId: run.manifest.threadId },+ requestVia: run.requestVia,+ self: { agentId: run.manifest.self.agentId, name: run.manifest.self.name },+ };+ }++ const [operation] = await this.db+ .select({+ agentId: agentOperations.agentId,+ agentName: agents.name,+ agentTitle: agents.title,+ status: agentOperations.status,+ trigger: agentOperations.trigger,+ userId: agentOperations.userId,+ workspaceId: agentOperations.workspaceId,+ })+ .from(agentOperations)+ .leftJoin(agents, eq(agents.id, agentOperations.agentId))+ .where(eq(agentOperations.id, operationId))+ .limit(1);+ if (+ !operation?.agentId ||+ operation.userId !== this.userId ||+ operation.workspaceId !== this.workspaceId ||+ operation.trigger !== RequestTrigger.Bot+ )+ throw new ChannelError('NOT_FOUND', 'Channel operation not found');+ if (operation.status !== 'running')+ throw new ChannelError('CONFLICT', 'Channel operation is no longer active');+ return {+ self: {+ agentId: operation.agentId,+ name: agentDisplayName({ name: operation.agentName, title: operation.agentTitle }, 'Agent'),+ },+ };+ };+readMessages = async (operationId: string,params: ChannelReadMessagesParams = {},diff --git a/packages/prompts/src/chains/channel.ts b/packages/prompts/src/chains/channel.tsindex 0a4d6be46a1..3c86fa031a8 100644--- a/packages/prompts/src/chains/channel.ts+++ b/packages/prompts/src/chains/channel.ts@@ -27,6 +27,12 @@ Only your final answer is published to the Channel. Keep reasoning and tool acti${CHANNEL_REPLY_GUIDELINES}Do not restart tasks that were already completed in this conversation. A new request may ask you to build on them.`;+/**+ * What an owner's bot run (e.g. the owner messaging their Agent on Telegram) is told about the+ * one Channel tool its token carries: posting a request to Agents in the owner's Channels.+ */+export const BOT_CHANNEL_MESSAGING_INSTRUCTIONS = `To tell or ask an Agent in one of the user's LobeHub Channels, find it with \`lh channel list --json\` (\`--agent <agentId>\` or \`--query <text>\`), then \`lh channel send <channelId> --agent <agentId> -c "<self-contained message>" --json\`. It is posted there as the user and the Agent answers in that Channel, not here, so link the returned url in your reply instead of waiting. When LOBEHUB_CLI is set, invoke that executable instead of the global \`lh\`.`;+/** What a follow-up deferred behind the message's primary responder is told. */const DEFERRED_WAKE_HINT = `Another participant was asked to answer this request first, and you were woken only after they finished. Their published answer, if any, is the \`channel_reply\` block. Do not repeat or rephrase it: if it already covers the request, stay silent. Reply only to add something distinct, or to correct a mistake in it.`;diff --git a/packages/prompts/src/index.ts b/packages/prompts/src/index.tsindex 87128ee05ea..754286b1729 100644--- a/packages/prompts/src/index.ts+++ b/packages/prompts/src/index.ts@@ -1,6 +1,10 @@export * from './agents';export * from './chains';-export { buildChannelPrompt, CHANNEL_INSTRUCTIONS } from './chains/channel';+export {+ BOT_CHANNEL_MESSAGING_INSTRUCTIONS,+ buildChannelPrompt,+ CHANNEL_INSTRUCTIONS,+} from './chains/channel';export * from './chains/goalExplore';export * from './chains/goalSupervisor';export * from './contexts';