🤯 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 a user's chat turn message people and Channels for them (#23694)
Arvin Xu6d1b24e2de65
diff --git a/apps/server/src/routers/lambda/channelHistory.ts b/apps/server/src/routers/lambda/channelHistory.tsindex 0fe10e95cf9..4ee7165533e 100644--- a/apps/server/src/routers/lambda/channelHistory.ts+++ b/apps/server/src/routers/lambda/channelHistory.ts@@ -39,9 +39,9 @@ const operationProcedure = (capability: HeteroOperationCapability) =>const result = await next({ctx: {channelHistory: new ChannelHistoryService(...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 }),+ // The token was checked for this capability above; a user's chat turn or an owner's+ // bot run carries `channel:message` without a Channel of its own.+ channelMessaging: new ChannelMessagingService(...args, { allowDirectRun: 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 001fffa7dd9..1e37d61a254 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts@@ -106,6 +106,14 @@ export const prepareHeteroRun = async (// Channels. `isOwner` is decided once, fail-closed, in `buildBotContext`.const isOwnerBotOperation =ctx.trigger === RequestTrigger.Bot && ctx.botContext?.isOwner === true;+ // 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.+ const isUserTurn =+ (ctx.trigger === RequestTrigger.Chat && !!ctx.userMessageId) ||+ ctx.trigger === RequestTrigger.Scheduled;+ // Mirrors the `channel:message` grant in `heteroOperationCapabilities`.+ const canMessageForUser =+ !shareGate && (isOwnerBotOperation || (isUserTurn && !isChannelOperation && !operationTaskId));// Sign an operation-scoped JWT so the CLI can authenticate against// heteroIngest / heteroFinish without full user credentials.@@ -121,11 +129,7 @@ export const prepareHeteroRun = async (ownerBotTurn: isOwnerBotOperation,shareVisitor: !!shareGate,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.- userTurn:- (ctx.trigger === RequestTrigger.Chat && !!ctx.userMessageId) ||- ctx.trigger === RequestTrigger.Scheduled,+ userTurn: isUserTurn,}),operationId,userId: deps.userId,@@ -339,7 +343,7 @@ export const prepareHeteroRun = async (selectionContext,isChannelOperation? CHANNEL_INSTRUCTIONS- : isOwnerBotOperation+ : canMessageForUser? BOT_CHANNEL_MESSAGING_INSTRUCTIONS: undefined,);diff --git a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.tsindex 0d7d23b505e..26a58ffc07f 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts@@ -19,6 +19,21 @@ describe('heteroOperationCapabilities', () => {expect(capabilities).not.toContain('goal:manage');});+ it('lets a turn the user sent in a chat message for them, but not read a Channel', () => {+ const capabilities = heteroOperationCapabilities('send tj a message', { userTurn: true });+ expect(capabilities).toContain('channel:message');+ expect(capabilities).not.toContain('channel:read');+ });++ it('keeps Channel messaging out of Task and server-started runs', () => {+ expect(+ heteroOperationCapabilities('send tj a message', { taskId: 'task_1', userTurn: true }),+ ).not.toContain('channel:message');+ expect(heteroOperationCapabilities('send tj a message', { taskId: 'task_1' })).not.toContain(+ 'channel:message',+ );+ });+it('grants goal management to a /goal run', () => {expect(heteroOperationCapabilities('/goal ship the report')).toContain('goal:manage');});@@ -86,6 +101,7 @@ describe('heteroOperationCapabilities for a share visitor', () => {['a /goal prompt', '/goal ship the report', { userTurn: true }],['a task', 'do the step', { taskId: 'task_1', userTurn: true }],['a channel', 'read the discussion', { channel: true, ownerBotTurn: true }],+ ['a chat turn', 'send tj a message', { userTurn: true }],])('grants only the run callbacks and its own Works for %s', (_, prompt, options) => {expect(heteroOperationCapabilities(prompt, { ...options, shareVisitor: true })).toEqual(['hetero:ingest',diff --git a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.tsindex 688bc4370c3..b2d5bdf1924 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts@@ -23,8 +23,9 @@ import type { HeteroOperationCapability } from '@/libs/trpc/utils/internalJwt';* (`lh channel people|dm`), 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.+ * there as the owner. A turn the user sent in an ordinary chat gets the same, so asking an Agent+ * to "send tj a message" works there too. Neither has a Channel conversation to read; a bot+ * message from anyone else, a Task run and a server-started run get neither.** `acceptance:evidence` lets a Task run file evidence into its own verification* round (`lh acceptance run result submit|ingest --operation`). That round is@@ -54,21 +55,22 @@ export const heteroOperationCapabilities = (/** The run answers a message the user sent: a chat turn or one they scheduled. */userTurn?: boolean;} = {},-): HeteroOperationCapability[] =>- options.shareVisitor- ? ['hetero:ingest', 'hetero:finish', 'hetero:intervention:read', 'work:write']- : [- 'hetero:ingest',- ...(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)- ? (['goal:manage'] as const)- : []),- ...(options.taskId ? (['acceptance:evidence'] as const) : []),- 'work:write',- ];+): HeteroOperationCapability[] => {+ if (options.shareVisitor)+ return ['hetero:ingest', 'hetero:finish', 'hetero:intervention:read', 'work:write'];++ const directUserTurn = !!options.userTurn && !options.channel && !options.taskId;+ return [+ 'hetero:ingest',+ ...(options.channel+ ? (['channel:read', 'channel:message'] as const)+ : options.ownerBotTurn || directUserTurn+ ? (['channel:message'] as const)+ : []),+ 'hetero:finish',+ 'hetero:intervention:read',+ ...(isGoalPrompt(prompt) || directUserTurn ? (['goal:manage'] as const) : []),+ ...(options.taskId ? (['acceptance:evidence'] as const) : []),+ 'work:write',+ ];+};diff --git a/apps/server/src/services/channel/ChannelMessagingService.test.ts b/apps/server/src/services/channel/ChannelMessagingService.test.tsindex 308b2b90680..e3e74ac31ad 100644--- a/apps/server/src/services/channel/ChannelMessagingService.test.ts+++ b/apps/server/src/services/channel/ChannelMessagingService.test.ts@@ -236,10 +236,10 @@ describe('ChannelMessagingService', () => {await service().listChannels();expect(relaySource).toHaveBeenLastCalledWith('op-current', {});const fromBot = new ChannelMessagingService({} as never, 'user-1', 'op-current', undefined, {- allowBotRun: true,+ allowDirectRun: true,});await fromBot.listChannels();- expect(relaySource).toHaveBeenLastCalledWith('op-current', { allowBotRun: true });+ expect(relaySource).toHaveBeenLastCalledWith('op-current', { allowDirectRun: true });});it("relays an owner's bot request with no current Channel and no receipt origin", async () => {diff --git a/apps/server/src/services/channel/ChannelMessagingService.ts b/apps/server/src/services/channel/ChannelMessagingService.tsindex 4fbbb1b6669..dffd1eacb5f 100644--- a/apps/server/src/services/channel/ChannelMessagingService.ts+++ b/apps/server/src/services/channel/ChannelMessagingService.ts@@ -91,10 +91,10 @@ const findAgent = (* `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`).+ * The requester's own direct run may do the same: a chat turn they sent, or the bot's owner+ * messaging their Agent on an IM platform. 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 (`allowDirectRun`).*/export class ChannelMessagingService {private readonly history: ChannelHistoryRepository;@@ -105,7 +105,7 @@ export class ChannelMessagingService {private readonly userId: string,private readonly operationId: string,private readonly workspaceId?: string,- private readonly options: { allowBotRun?: boolean } = {},+ private readonly options: { allowDirectRun?: boolean } = {},) {this.history = new ChannelHistoryRepository(db, userId, workspaceId);this.channels = new ChannelRepository(db, userId, workspaceId, channelContacts);diff --git a/packages/database/src/repositories/channel/__tests__/history.test.ts b/packages/database/src/repositories/channel/__tests__/history.test.tsindex 82e776382c3..1bcd921b3b9 100644--- a/packages/database/src/repositories/channel/__tests__/history.test.ts+++ b/packages/database/src/repositories/channel/__tests__/history.test.ts@@ -257,7 +257,7 @@ 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({+ expect(await state.history.relaySource(operationId, { allowDirectRun: true })).toEqual({channelRun: expect.objectContaining({ channelId: state.channel.id }),origin: { channelId: state.channel.id, threadId: null },requestVia: undefined,@@ -265,7 +265,7 @@ describe('Channel relay source', () => {});});- it("relays an owner's live bot run only when the caller opts in", async () => {+ it("relays the requester's live direct run only when the caller opts in", async () => {const history = new ChannelHistoryRepository(db, fixture.memberId, fixture.workspaceId);const [agent] = await db.insert(agents)@@ -291,20 +291,29 @@ describe('Channel relay source', () => {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({+ expect(await history.relaySource(bot, { allowDirectRun: 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(+ // The user's own chat turn (sent or scheduled) may message for them too.+ for (const trigger of ['chat', 'scheduled']) {+ const direct = await operation(`op-relay-${trigger}`, { trigger });+ await expect(history.relaySource(direct)).rejects.toThrow('Channel operation not found');+ expect(await history.relaySource(direct, { allowDirectRun: true })).toEqual({+ self: { agentId: agent.id, name: 'Telegram Agent' },+ });+ }+ // A server-started run without a Channel never does, whatever its token says.+ const cron = await operation('op-relay-cron', { trigger: 'cron' });+ await expect(history.relaySource(cron, { allowDirectRun: 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(+ await expect(history.relaySource(other, { allowDirectRun: 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(+ await expect(history.relaySource(ended, { allowDirectRun: true })).rejects.toThrow('no longer active',);} finally {diff --git a/packages/database/src/repositories/channel/history.ts b/packages/database/src/repositories/channel/history.tsindex cb22aaf0669..732632769b4 100644--- a/packages/database/src/repositories/channel/history.ts+++ b/packages/database/src/repositories/channel/history.ts@@ -53,6 +53,13 @@ const SUMMARY_LENGTH = 300;/** Latest steps of a running reply shown in a Thread summary. */const ACTIVITY_STEPS = 3;+/** Runs the requester started themselves, which may message for them without a Channel job. */+const DIRECT_RUN_TRIGGERS = new Set<RequestTrigger>([+ RequestTrigger.Bot,+ RequestTrigger.Chat,+ RequestTrigger.Scheduled,+]);+const clip = (text: string | null | undefined, length = SUMMARY_LENGTH) => {const value = (text ?? '').trim();return value.length > length ? `${value.slice(0, length)}…` : value;@@ -273,16 +280,17 @@ export class ChannelHistoryRepository {/*** 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.+ * live direct run, and only when the caller says so (`allowDirectRun`): the requester asked+ * their Agent, in a chat (sent or scheduled) or as the bot's owner on an IM platform, to message+ * someone or post into one of their Channels. Only a caller holding that run's `channel:message`+ * token, minted only for those runs, may set it; the trigger is checked again here so no+ * server-started run without a Channel can relay.*/relaySource = async (operationId: string,- { allowBotRun = false }: { allowBotRun?: boolean } = {},+ { allowDirectRun = false }: { allowDirectRun?: boolean } = {},): Promise<{- /** The Channel run, with what {@link currentRun} reads; absent for a bot run. */+ /** The Channel run, with what {@link currentRun} reads; absent for a direct run. */channelRun?: Awaited<ReturnType<ChannelHistoryRepository['currentRun']>>;origin?: { channelId: string; threadId: string | null };requestVia?: ChannelMessageVia;@@ -293,7 +301,7 @@ export class ChannelHistoryRepository {.from(channelJobs).where(eq(channelJobs.operationId, operationId)).limit(1);- if (job || !allowBotRun) {+ if (job || !allowDirectRun) {const run = await this.currentRun(operationId);return {channelRun: run,@@ -321,7 +329,7 @@ export class ChannelHistoryRepository {!operation?.agentId ||operation.userId !== this.userId ||operation.workspaceId !== this.workspaceId ||- operation.trigger !== RequestTrigger.Bot+ !DIRECT_RUN_TRIGGERS.has(operation.trigger as RequestTrigger))throw new ChannelError('NOT_FOUND', 'Channel operation not found');if (operation.status !== 'running')