🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent-identity): post what a mail-woken run concludes to the owner's Channel (#22578)
Arvin Xuccad89a25881
diff --git a/apps/server/src/router-hono/agent/handlers/agentInboxReport.ts b/apps/server/src/router-hono/agent/handlers/agentInboxReport.tsnew file mode 100644index 00000000000..8883323c53c--- /dev/null+++ b/apps/server/src/router-hono/agent/handlers/agentInboxReport.ts@@ -0,0 +1,29 @@+import type { Context } from 'hono';+import { z } from 'zod';++import { getServerDB } from '@/database/core/db-adaptor';+import { reportRunToOwnerChannel } from '@/server/services/agentIdentity/ownerChannel';++const payloadSchema = z.object({+ accountId: z.string().uuid(),+ operationId: z.string().min(1),+});++/**+ * Completion of a run an inbound mail woke: posts its answer to the owner's direct Channel.+ * The envelope carries identity only; the answer is read from storage, and a redelivery finds+ * the post already there.+ */+export async function agentInboxReport(c: Context): Promise<Response> {+ const body = payloadSchema.safeParse(await c.req.json().catch(() => null));+ if (!body.success) return c.json({ error: 'Invalid inbox report' }, 400);++ try {+ const result = await reportRunToOwnerChannel(await getServerDB(), body.data);++ return c.json({ result, success: true });+ } catch (error) {+ console.error('[agentInboxReport] reporting run %s failed:', body.data.operationId, error);+ return c.json({ error: 'Inbox report failed' }, 500);+ }+}diff --git a/apps/server/src/router-hono/agent/index.ts b/apps/server/src/router-hono/agent/index.tsindex dd3dfda7e4c..3751b5f7ddf 100644--- a/apps/server/src/router-hono/agent/index.ts+++ b/apps/server/src/router-hono/agent/index.ts@@ -2,6 +2,7 @@ import { Hono } from 'hono';import { agentAccountDigestFlush } from './handlers/agentAccountDigestFlush';import { agentAccountWebhook, agentAccountWebhookBodyLimit } from './handlers/agentAccountWebhook';+import { agentInboxReport } from './handlers/agentInboxReport';import { botCallback } from './handlers/botCallback';import { botReplay } from './handlers/botReplay';import { botWakeFlush } from './handlers/botWakeFlush';@@ -48,6 +49,10 @@ app.get('/run', runStepHealth);app.post('/channel/advance', qstashAuth(), channelAdvance);app.post('/webhooks/channel-callback', qstashAuth(), channelCallback);+// POST /api/agent/webhooks/inbox-report — a mail-woken run finished: post its answer to the+// owner's direct Channel (QStash)+app.post('/webhooks/inbox-report', qstashAuth(), agentInboxReport);+// POST /api/agent/tool-result — gateway-side tool result LPUSH'd to Redisapp.post('/tool-result', serviceTokenAuth(), toolResult);diff --git a/apps/server/src/services/agentIdentity/__tests__/inboundChain.test.ts b/apps/server/src/services/agentIdentity/__tests__/inboundChain.test.tsindex 2fa0c68cd48..88d6090a3ff 100644--- a/apps/server/src/services/agentIdentity/__tests__/inboundChain.test.ts+++ b/apps/server/src/services/agentIdentity/__tests__/inboundChain.test.ts@@ -323,7 +323,14 @@ describe('Agent inbound webhook — end to end over the real route', () => {// The sender's words reach the run only inside the untrusted fence on the// user side: the sentence we write ourselves carries no sender content.const prompt: string = agentCalls[0].execAgent.prompt;- const [ownSentence, fenced] = prompt.split('\n\n');+ const [ownSentence, instruction, fenced] = prompt.split('\n\n');+ // The run reports to its owner's Channel; that sentence is ours too.+ expect(instruction).toContain('direct Channel');+ // Nobody watches this run: it must end, not park on an approval its report would miss.+ expect(agentCalls[0].execAgent.userInterventionConfig).toEqual({ approvalMode: 'headless' });+ expect(agentCalls[0].execAgent.hooks).toEqual([+ expect.objectContaining({ id: `agent-inbox-report:${accountId}`, type: 'onComplete' }),+ ]);expect(ownSentence).not.toContain('[email protected]');expect(ownSentence).not.toContain('839201');expect(fenced.startsWith('<untrusted_inbox>')).toBe(true);diff --git a/apps/server/src/services/agentIdentity/__tests__/mailWake.test.ts b/apps/server/src/services/agentIdentity/__tests__/mailWake.test.tsindex 878ab8dcc8a..076b06a4f86 100644--- a/apps/server/src/services/agentIdentity/__tests__/mailWake.test.ts+++ b/apps/server/src/services/agentIdentity/__tests__/mailWake.test.ts@@ -512,7 +512,12 @@ describe('mail digest flush', () => {userId,});const prompt: string = runs[0].params.prompt;- const [own, , fenced] = prompt.split('\n\n');+ const [own, , instruction, fenced] = prompt.split('\n\n');+ expect(instruction).toContain('direct Channel');+ expect(runs[0].params.userInterventionConfig).toEqual({ approvalMode: 'headless' });+ expect(runs[0].params.hooks).toEqual([+ expect.objectContaining({ id: `agent-inbox-report:${accountId}`, type: 'onComplete' }),+ ]);expect(own).toContain('2 messages arrived');expect(own).not.toContain('launchdriftcloud');expect(fenced.startsWith('<untrusted_inbox>')).toBe(true);diff --git a/apps/server/src/services/agentIdentity/__tests__/ownerChannel.test.ts b/apps/server/src/services/agentIdentity/__tests__/ownerChannel.test.tsnew file mode 100644index 00000000000..bfb9420222b--- /dev/null+++ b/apps/server/src/services/agentIdentity/__tests__/ownerChannel.test.ts@@ -0,0 +1,157 @@+// @vitest-environment node+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { AgentAccountModel } from '@/database/models/agentAccount';+import { ChannelRepository } from '@/database/repositories/channel';+import {+ agentAccounts,+ agentOperations,+ agents,+ channelJobs,+ channelMessages,+ channels,+ messages,+ topics,+ users,+} from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { reportRunToOwnerChannel } from '../ownerChannel';++/**+ * A mail-woken run reports to its owner's direct Channel. Real: the models and Channel repository+ * on PGlite. Faked: the gateway nudge that tells open clients to refresh.+ */++const notified = vi.hoisted(() => [] as string[]);+vi.mock('@/server/services/channel/notify', () => ({+ notifyChannel: async (_db: unknown, channelId: string) => {+ notified.push(channelId);+ },+}));++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'owner-channel-user';+const agentId = 'owner-channel-agent';+const topicId = 'tpc_owner_channel';+let accountId = '';+let channelId = '';++/** A finished run in its own topic whose last assistant message says `content`. */+const finishedRun = async (operationId: string, content: string, status = 'done') => {+ await serverDB+ .insert(agentOperations)+ .values({ agentId, id: operationId, status, topicId, userId });+ await serverDB.insert(messages).values({+ agentId,+ content,+ metadata: { operationId },+ role: 'assistant',+ topicId,+ userId,+ });+};++const channelPosts = () =>+ serverDB.select().from(channelMessages).where(eq(channelMessages.channelId, channelId));++beforeEach(async () => {+ notified.length = 0;+ await serverDB.delete(users);+ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(agents).values({ id: agentId, title: '邮件秘书', userId });+ await serverDB.insert(topics).values({ agentId, id: topicId, userId });+ accountId = (+ await new AgentAccountModel(serverDB, userId).create({+ agentId,+ capabilities: { receive: true, send: true },+ identifier: '[email protected]',+ kind: 'mail',+ provider: 'agent-mail',+ })+ ).id;+ const { channel } = await new ChannelRepository(serverDB, userId).create({+ agentConfig: {},+ agentId,+ title: '邮件秘书',+ });+ channelId = channel.id;+});++afterEach(async () => {+ await serverDB.delete(channelJobs);+ await serverDB.delete(channels);+ await serverDB.delete(agentAccounts);+ await serverDB.delete(users);+});++describe('reportRunToOwnerChannel', () => {+ it("posts the run's final answer to the direct Channel as the agent, once", async () => {+ await finishedRun('op_report', '有 1 件需要你处理:David 回复了外链合作,问你是否同意。');++ expect(await reportRunToOwnerChannel(serverDB, { accountId, operationId: 'op_report' })).toBe(+ 'posted',+ );+ // A redelivered completion posts nothing new.+ await reportRunToOwnerChannel(serverDB, { accountId, operationId: 'op_report' });++ expect(await channelPosts()).toEqual([+ expect.objectContaining({+ agentId,+ content: '有 1 件需要你处理:David 回复了外链合作,问你是否同意。',+ metadata: {+ accountId,+ operationId: 'op_report',+ source: 'agent-inbox',+ topicId,+ },+ replyToId: null,+ routingStatus: 'reply',+ userId: null,+ }),+ ]);+ expect(notified).toContain(channelId);+ // The post wakes no Agent: nobody asked it anything.+ expect(await serverDB.select().from(channelJobs)).toEqual([]);+ });++ it('posts nothing when the agent chose silence', async () => {+ await finishedRun('op_silent', 'NO_REPLY');++ expect(await reportRunToOwnerChannel(serverDB, { accountId, operationId: 'op_silent' })).toBe(+ 'silent',+ );+ expect(await channelPosts()).toEqual([]);+ });++ it('posts nothing for a run that has not finished', async () => {+ await finishedRun('op_running', 'half a thought', 'running');++ expect(await reportRunToOwnerChannel(serverDB, { accountId, operationId: 'op_running' })).toBe(+ 'not-done',+ );+ expect(await channelPosts()).toEqual([]);+ });++ it('leaves a direct Channel the owner moved to the trash alone', async () => {+ await new ChannelRepository(serverDB, userId).remove(channelId);+ await finishedRun('op_trashed', 'Something for you.');++ expect(await reportRunToOwnerChannel(serverDB, { accountId, operationId: 'op_trashed' })).toBe(+ 'no-channel',+ );+ expect(await channelPosts()).toEqual([]);+ });++ it('ignores an account that no longer exists', async () => {+ await expect(+ reportRunToOwnerChannel(serverDB, {+ accountId: '00000000-0000-0000-0000-000000000000',+ operationId: 'op_any',+ }),+ ).resolves.toBe('no-account');+ });+});diff --git a/apps/server/src/services/agentIdentity/ownerChannel.ts b/apps/server/src/services/agentIdentity/ownerChannel.tsnew file mode 100644index 00000000000..aee449dd6c4--- /dev/null+++ b/apps/server/src/services/agentIdentity/ownerChannel.ts@@ -0,0 +1,126 @@+import type { LobeChatDatabase } from '@lobechat/database';+import { BOT_NO_REPLY_TOKEN } from '@lobechat/types';+import debug from 'debug';++import { AgentAccountModel } from '@/database/models/agentAccount';+import { AgentOperationModel } from '@/database/models/agentOperation';+import { MessageModel } from '@/database/models/message';+import { ChannelRepository } from '@/database/repositories/channel';+import { extractTextFromMessage } from '@/server/services/agentRuntime/CompletionLifecycle/messageContent';+import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';+import { ChannelService } from '@/server/services/channel/ChannelService';+import { notifyChannel } from '@/server/services/channel/notify';+import { detectNoReply } from '@/server/services/conversationWake/noReply';+import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';++const log = debug('lobe-server:agent-identity:owner-channel');++export const INBOX_REPORT_WEBHOOK = '/api/agent/webhooks/inbox-report';++/**+ * Where the result goes, told to the woken agent. A run nobody watches would otherwise end in a+ * topic its owner never opens.+ */+export const OWNER_CHANNEL_INSTRUCTION = `Your final answer is posted to your owner in your direct Channel with them, so write it to them. If nothing here needs them, answer exactly ${BOT_NO_REPLY_TOKEN} and nothing will be posted. You cannot send mail from this run: a send is refused. If a reply is warranted, put the draft in your answer for your owner to approve.`;++/**+ * A woken run has nobody watching it, so it must end rather than park on an approval: a parked+ * segment would settle this report's hook with no answer, and its continuation would not carry it.+ * A call that needs the owner comes back to the agent as refused.+ */+export const INBOX_RUN_INTERVENTION = { approvalMode: 'headless' } as const;++export type OwnerChannelReportResult =+ | 'no-account'+ | 'no-channel'+ | 'not-done'+ | 'posted'+ /** The agent chose silence (`NO_REPLY`), or ended without a text answer. */+ | 'silent';++/**+ * Posts what an inbox-woken run concluded to the account owner's direct Channel with the agent.+ *+ * The run stays in its own topic; only its final answer — the agent's words, never the mail it+ * read — reaches the Channel, as the agent's message. Opens the direct Channel when there is none+ * yet; one the owner moved to the trash stays there and nothing is posted.+ *+ * Idempotent per run: a repeated completion callback finds the post already there.+ */+export const reportRunToOwnerChannel = async (+ db: LobeChatDatabase,+ params: { accountId: string; operationId: string },+): Promise<OwnerChannelReportResult> => {+ const account = await AgentAccountModel.findByIdUnscoped(db, params.accountId);+ if (!account) return 'no-account';++ const workspaceId = account.workspaceId ?? undefined;+ const operation = await new AgentOperationModel(db, account.userId, workspaceId).findById(+ params.operationId,+ );+ if (operation?.status !== 'done' || !operation.topicId) return 'not-done';++ const final = await new MessageModel(+ db,+ account.userId,+ workspaceId,+ ).findLatestAssistantByOperationId({+ operationId: params.operationId,+ topicId: operation.topicId,+ });+ // A run that stopped on a tool call (out of steps) has nothing to tell yet.+ const content = final?.tools?.length ? undefined : extractTextFromMessage(final);+ if (!content?.trim() || detectNoReply({ content, wakeKind: 'followup' })) return 'silent';++ const access = await new ChannelService(db, account.userId, workspaceId).openDirect(+ account.agentId,+ );+ if (!access) return 'no-channel';++ const channelId = access.channel.id;+ await new ChannelRepository(db, account.userId, workspaceId).postAgentMessage(channelId, {+ agentId: account.agentId,+ content,+ metadata: {+ accountId: account.id,+ operationId: params.operationId,+ source: 'agent-inbox',+ topicId: operation.topicId,+ },+ requestKey: `agent-inbox:${params.operationId}`,+ });+ await notifyChannel(db, channelId);+ log('posted the run %s of account %s to channel %s', params.operationId, account.id, channelId);++ return 'posted';+};++/**+ * The completion hook an inbox-woken run carries: on the queue runtime a QStash webhook (the+ * process that started the run may be gone), otherwise an in-process handler.+ */+export const createOwnerChannelReportHook = (+ db: LobeChatDatabase,+ accountId: string,+): AgentHook => ({+ id: `agent-inbox-report:${accountId}`,+ type: 'onComplete',+ ...(isQueueAgentRuntimeEnabled()+ ? {+ webhook: {+ body: { accountId },+ delivery: 'qstash' as const,+ // Identity only: the answer is read back from storage, never carried in the envelope.+ eventFields: ['operationId'],+ fallback: 'none' as const,+ url: INBOX_REPORT_WEBHOOK,+ },+ }+ : {+ handler: async (event) => {+ await reportRunToOwnerChannel(db, { accountId, operationId: event.operationId }).catch(+ (error) => console.error('[agentInbox] reporting the run failed:', error),+ );+ },+ }),+});diff --git a/apps/server/src/services/agentIdentity/wake/digest.ts b/apps/server/src/services/agentIdentity/wake/digest.tsindex 48b58eabbde..9360d58b04f 100644--- a/apps/server/src/services/agentIdentity/wake/digest.ts+++ b/apps/server/src/services/agentIdentity/wake/digest.ts@@ -11,6 +11,11 @@ import { AiAgentService } from '@/server/services/aiAgent';import { QueueService } from '@/server/services/queue';import { agentSignalScopeFlowControl } from '@/server/workflows/agentSignal';+import {+ createOwnerChannelReportHook,+ INBOX_RUN_INTERVENTION,+ OWNER_CHANNEL_INSTRUCTION,+} from '../ownerChannel';import { fenceUntrustedInbox, toUntrustedInboxEntry } from '../untrusted';import type { ResolvedWakeConfig } from './config';import { resolveWakeConfig } from './config';@@ -88,7 +93,8 @@ export const holdForDigest = (export const buildDigestPrompt = (account: AgentAccountView, messages: AgentInboxEntry[]): string =>[`${messages.length} message${messages.length === 1 ? '' : 's'} arrived for your ${account.kind} account ${account.identifier} and were held for this digest, oldest first.`,- 'Go through them together: work out which ones need your owner, which ones you can take care of, and which are noise. Tell your owner only about what needs them, briefly, and say why. Any message you send is held for their approval.',+ 'Go through them together: work out which ones need your owner, which ones you can take care of, and which are noise. Tell your owner only about what needs them, briefly, and say why.',+ OWNER_CHANNEL_INSTRUCTION,fenceUntrustedInbox(messages.map((message) =>toUntrustedInboxEntry(message, { maxBodyChars: DIGEST_BODY_PREVIEW_CHARS }),@@ -112,8 +118,10 @@ export const createDigestRunStarter =const result = await service.execAgent({agentId: account.agentId,appContext: { scope: 'agent' },+ hooks: [createOwnerChannelReportHook(db, account.id)],prompt: buildDigestPrompt(account, messages),trigger: RequestTrigger.Inbox,+ userInterventionConfig: INBOX_RUN_INTERVENTION,});return { error: result.error, topicId: result.topicId };diff --git a/apps/server/src/services/agentIdentity/waker.ts b/apps/server/src/services/agentIdentity/waker.tsindex 1328a4c50cf..b3c3d5fe419 100644--- a/apps/server/src/services/agentIdentity/waker.ts+++ b/apps/server/src/services/agentIdentity/waker.ts@@ -9,6 +9,11 @@ import { AiAgentService } from '@/server/services/aiAgent';import { TopicStartReservationError } from '@/server/services/aiAgent/topicStartReservation';import type { AgentInboundWakeInput, AgentInboundWaker } from './inbound';+import {+ createOwnerChannelReportHook,+ INBOX_RUN_INTERVENTION,+ OWNER_CHANNEL_INSTRUCTION,+} from './ownerChannel';import { fenceUntrustedInbox, toUntrustedInboxEntry } from './untrusted';/** Body budget for the wake prompt; the full text stays readable through the tool. */@@ -22,6 +27,7 @@ const WAKE_BODY_PREVIEW_CHARS = 2000;export const buildInboundPrompt = (account: AgentAccountView, message: AgentInboxEntry): string =>[`A new message arrived for your ${account.kind} account ${account.identifier}. Decide whether it needs anything from you.`,+ OWNER_CHANNEL_INSTRUCTION,fenceUntrustedInbox([toUntrustedInboxEntry(message, { maxBodyChars: WAKE_BODY_PREVIEW_CHARS }),]),@@ -57,8 +63,10 @@ export const createAgentInboundWaker = (db: LobeChatDatabase): AgentInboundWakerservice.execAgent({agentId: account.agentId,appContext: { scope: 'agent', topicId },+ hooks: [createOwnerChannelReportHook(db, account.id)],prompt: buildInboundPrompt(account, message),trigger: RequestTrigger.Inbox,+ userInterventionConfig: INBOX_RUN_INTERVENTION,});/**diff --git a/packages/database/src/repositories/channel/__tests__/agentPost.test.ts b/packages/database/src/repositories/channel/__tests__/agentPost.test.tsnew file mode 100644index 00000000000..66640adb8c6--- /dev/null+++ b/packages/database/src/repositories/channel/__tests__/agentPost.test.ts@@ -0,0 +1,66 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { channelJobs, channelMembers } from '../../../schemas';+import { ChannelRepository } from '..';+import { createChannelFixture } from './testUtils';++const db = await getTestDB();+const fixture = createChannelFixture(db, 'channel-agent-post');+beforeEach(fixture.setup);+afterEach(fixture.cleanup);++describe('ChannelRepository.postAgentMessage', () => {+ it('posts as the Agent, answering no request and waking no one, once per key', async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ const secretary = await fixture.addAgent(channel.id, 'Secretary');+ const post = {+ agentId: secretary.agentId!,+ content: '3 mails need you today.',+ metadata: { source: 'agent-inbox' },+ requestKey: 'agent-inbox:op_1',+ };++ const message = await asOwner.postAgentMessage(channel.id, post);+ expect(message).toMatchObject({+ agentId: secretary.agentId,+ content: '3 mails need you today.',+ metadata: { source: 'agent-inbox' },+ replyToId: null,+ routingStatus: 'reply',+ userId: null,+ });+ expect(+ await db.select().from(channelJobs).where(eq(channelJobs.channelId, channel.id)),+ ).toEqual([]);++ // A redelivered completion finds the post already there.+ expect((await asOwner.postAgentMessage(channel.id, post)).id).toBe(message.id);++ const { messages } = await asOwner.detail(channel.id);+ expect(messages.filter((item) => item.id === message.id)).toEqual([+ expect.objectContaining({ author: expect.objectContaining({ type: 'agent' }) }),+ ]);+ });++ it('refuses an Agent that is not an active member, and a caller who is not one', async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ const secretary = await fixture.addAgent(channel.id, 'Secretary');+ const post = { agentId: secretary.agentId!, content: 'hi', requestKey: 'k' };++ await db+ .update(channelMembers)+ .set({ status: 'removed' })+ .where(eq(channelMembers.id, secretary.id));+ await expect(asOwner.postAgentMessage(channel.id, post)).rejects.toMatchObject({+ code: 'CONFLICT',+ });++ const stranger = new ChannelRepository(db, 'nobody', fixture.workspaceId);+ await expect(stranger.postAgentMessage(channel.id, post)).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ });+});diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 6dc4e6d88f4..5d7bf0f5a95 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -29,6 +29,8 @@ import {import { findThread } from './delivery';import { ChannelError } from './error';import { addChannelUser, channelUserCandidates, newChannelUserCandidates } from './people';+import type { ChannelAgentPostInput } from './post';+import { postAgentMessage } from './post';import { retryRouting } from './routing';import type { ChannelSendInput } from './send';import { sendMessage } from './send';@@ -49,6 +51,7 @@ export type { ChannelErrorCode } from './error';export { ChannelError } from './error';export { ChannelExecutionRepository } from './execution';export { ChannelHistoryRepository } from './history';+export type { ChannelAgentPostInput } from './post';export type { AppliedChannelRouting, ChannelRoutingDecision } from './routing';export type { ChannelSendInput } from './send';export type { ChannelStopScope } from './stop';@@ -554,6 +557,16 @@ export class ChannelRepository {return fn(tx, access);});+ /**+ * Posts what an Agent member wrote outside any job into a Channel the caller belongs to.+ * See {@link postAgentMessage}.+ */+ postAgentMessage = async (+ channelId: string,+ input: ChannelAgentPostInput,+ ): Promise<ChannelMessageItem> =>+ this.write(channelId, (tx) => postAgentMessage(tx, channelId, input));+/** Posts a message as the caller. See {@link sendMessage} for routing. */send = async (channelId: string, input: ChannelSendInput): Promise<ChannelMessageItem> =>this.write(channelId, (tx, access) => sendMessage(tx, access, input));diff --git a/packages/database/src/repositories/channel/post.ts b/packages/database/src/repositories/channel/post.tsnew file mode 100644index 00000000000..5ec2fe47353--- /dev/null+++ b/packages/database/src/repositories/channel/post.ts@@ -0,0 +1,69 @@+import type { ChannelMessageMetadata } from '@lobechat/types';+import { and, eq } from 'drizzle-orm';++import type { ChannelMessageItem } from '../../schemas';+import { channelMembers, channelMessages } from '../../schemas';+import type { Transaction } from '../../type';+import { appendMessage } from './delivery';+import { ChannelError } from './error';+import { audit } from './transaction';++export interface ChannelAgentPostInput {+ /** The Agent that wrote it; must be an active member of the Channel. */+ agentId: string;+ content: string;+ metadata?: ChannelMessageMetadata;+ /** Identity of what produced the post (e.g. the run). Posting it again returns the stored one. */+ requestKey: string;+}++/**+ * Posts a message an Agent wrote outside any Channel job — what it found after something+ * outside the Channel woke it — at the end of the main timeline. Stored like a published reply+ * that answers no request, so it reads as the Agent's and wakes no one.+ *+ * Expects the caller to hold the Channel lock.+ */+export const postAgentMessage = async (+ tx: Transaction,+ channelId: string,+ input: ChannelAgentPostInput,+): Promise<ChannelMessageItem> => {+ const [existing] = await tx+ .select()+ .from(channelMessages)+ .where(+ and(+ eq(channelMessages.channelId, channelId),+ eq(channelMessages.requestKey, input.requestKey),+ ),+ )+ .limit(1);+ if (existing) return existing;++ const [member] = await tx+ .select({ id: channelMembers.id })+ .from(channelMembers)+ .where(+ and(+ eq(channelMembers.channelId, channelId),+ eq(channelMembers.actorType, 'agent'),+ eq(channelMembers.agentId, input.agentId),+ eq(channelMembers.status, 'active'),+ ),+ )+ .limit(1);+ if (!member) throw new ChannelError('CONFLICT', 'The Agent is not a member of this Channel');++ const message = await appendMessage(tx, {+ agentId: input.agentId,+ channelId,+ content: input.content,+ metadata: input.metadata ?? {},+ requestKey: input.requestKey,+ routingStatus: 'reply',+ });+ await audit(tx, channelId, 'agent_posted', member.id, { messageId: message.id });++ return message;+};