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(cli): `lh topic send` / `lh message reply` to wake another conversation (#21938)

Arvin Xu553c4e6ab736
diff --git a/apps/cli/src/commands/message.ts b/apps/cli/src/commands/message.ts
index 477226c0591..9ff8c415d96 100644
--- a/apps/cli/src/commands/message.ts
+++ b/apps/cli/src/commands/message.ts
@@ -14,6 +14,7 @@ import {
import { log } from '../utils/logger';
import type { TimeWindow } from '../utils/timeWindow';
import { parseTimeWindow, TIME_POINT_HELP } from '../utils/timeWindow';
+import { registerMessageReplyCommand } from './message/reply';
import { resolveUrlBuilder, resourcePath, withUrls } from './resourceUrl';
interface MessageSearchOptions {
@@ -404,7 +405,9 @@ export function registerMessageCommand(program: Command) {
message
.command('create')
- .description('Create a message')
+ .description(
+ "Write a message row without running anything: no agent sees or answers it. To have another conversation's agent act on a message, use 'lh topic send'",
+ )
.requiredOption('-r, --role <role>', 'Message role (user, assistant, system)')
.requiredOption('-c, --content <content>', 'Message content')
.option('--agent-id <id>', 'Agent ID')
@@ -619,4 +622,6 @@ export function registerMessageCommand(program: Command) {
console.log(`${e.date || e.day || ''}: ${pc.bold(String(e.count || e.value || 0))}`);
}
});
+
+ registerMessageReplyCommand(message);
}
diff --git a/apps/cli/src/commands/message/reply.ts b/apps/cli/src/commands/message/reply.ts
new file mode 100644
index 00000000000..b0913982ec2
--- /dev/null
+++ b/apps/cli/src/commands/message/reply.ts
@@ -0,0 +1,50 @@
+import type { Command } from 'commander';
+
+import { getTrpcClient } from '../../api/client';
+import { resolveWorkspaceRef } from '../../api/workspaceRef';
+import { reportConversationSend, sendToConversation } from '../topic/send';
+
+export function registerMessageReplyCommand(message: Command) {
+ message
+ .command('reply <messageId>')
+ .description(
+ 'Answer a message another agent sent you: the reply goes to the conversation it came from and wakes its agent',
+ )
+ .requiredOption('-c, --content <content>', 'Reply content')
+ .option(
+ '--workspace <id|slug>',
+ "The workspace the message lives in (overrides LOBEHUB_WORKSPACE_ID and 'workspace use')",
+ )
+ .option('--json', 'Output JSON')
+ .action(
+ async (
+ messageId: string,
+ options: { content: string; json?: boolean; workspace?: string },
+ ) => {
+ const client = await getTrpcClient(await resolveWorkspaceRef(options.workspace));
+
+ await reportConversationSend(async () => {
+ const origin = await client.message.getMessageOrigin.query({ id: messageId });
+ if (!origin) throw new Error(`Message ${messageId} not found in this workspace.`);
+
+ const sender = origin.agentSender;
+ if (!sender) {
+ throw new Error(
+ `Message ${messageId} was not sent by an agent, so there is no conversation to reply to. To write to a conversation, use 'lh topic send <topicId>'.`,
+ );
+ }
+ if (!sender.topicId) {
+ throw new Error(
+ `The conversation message ${messageId} came from cannot be reached from here; tell the user instead.`,
+ );
+ }
+
+ return sendToConversation(client, {
+ content: options.content,
+ threadId: sender.threadId,
+ topicId: sender.topicId,
+ });
+ }, options);
+ },
+ );
+}
diff --git a/apps/cli/src/commands/topic.ts b/apps/cli/src/commands/topic.ts
index e72fcd289c1..2d4d9413a19 100644
--- a/apps/cli/src/commands/topic.ts
+++ b/apps/cli/src/commands/topic.ts
@@ -8,6 +8,7 @@ import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/for
import { log } from '../utils/logger';
import { resolveUrlBuilder, resourcePath, withUrls } from './resourceUrl';
import { registerTopicExportCommand } from './topic/export';
+import { registerTopicSendCommand } from './topic/send';
import { registerTopicViewCommand } from './topic/view';
export function registerTopicCommand(program: Command) {
@@ -353,4 +354,5 @@ export function registerTopicCommand(program: Command) {
registerTopicExportCommand(topic);
registerTopicViewCommand(topic);
+ registerTopicSendCommand(topic);
}
diff --git a/apps/cli/src/commands/topic/send.test.ts b/apps/cli/src/commands/topic/send.test.ts
new file mode 100644
index 00000000000..9285a1e0da9
--- /dev/null
+++ b/apps/cli/src/commands/topic/send.test.ts
@@ -0,0 +1,180 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { log } from '../../utils/logger';
+import { registerMessageReplyCommand } from '../message/reply';
+import { registerTopicSendCommand } from './send';
+
+const { client, mockGetTrpcClient } = vi.hoisted(() => ({
+ client: {
+ agentSteerQueue: { append: { mutate: vi.fn() } },
+ aiAgent: { execAgent: { mutate: vi.fn() } },
+ message: { getMessageOrigin: { query: vi.fn() } },
+ topic: { getTopicDetail: { query: vi.fn() } },
+ },
+ mockGetTrpcClient: vi.fn(),
+}));
+
+vi.mock('../../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
+vi.mock('../../api/workspaceRef', () => ({ resolveWorkspaceRef: vi.fn(async () => undefined) }));
+
+const run = async (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerTopicSendCommand(program.command('topic'));
+ registerMessageReplyCommand(program.command('message'));
+ await program.parseAsync(['node', 'lh', ...args]);
+};
+
+describe('lh topic send', () => {
+ let exit: ReturnType<typeof vi.spyOn>;
+ let logged: string[];
+
+ beforeEach(() => {
+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-sender');
+ vi.stubEnv('LOBEHUB_TOPIC_ID', 'tpc-here');
+ mockGetTrpcClient.mockResolvedValue(client);
+ client.topic.getTopicDetail.query.mockResolvedValue({ agentId: 'agt-target', groupId: null });
+ client.agentSteerQueue.append.mutate.mockResolvedValue({ queued: false, reason: 'idle' });
+ client.aiAgent.execAgent.mutate.mockResolvedValue({ operationId: 'op-new', success: true });
+ logged = [];
+ vi.spyOn(console, 'log').mockImplementation((...parts) => {
+ logged.push(parts.join(' '));
+ });
+ exit = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
+ });
+
+ afterEach(() => {
+ vi.mocked(log.error).mockClear();
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ Object.values(client).forEach((router) =>
+ Object.values(router).forEach((procedure) =>
+ Object.values(procedure).forEach((fn) => (fn as any).mockReset()),
+ ),
+ );
+ });
+
+ it("starts the topic's own agent on the message, authored by the sending run", async () => {
+ await run('topic', 'send', 'tpc-target', '-c', 'Please iterate the verifier.');
+
+ const request = {
+ agentId: 'agt-target',
+ appContext: { topicId: 'tpc-target' },
+ prompt: 'Please iterate the verifier.',
+ sourceOperationId: 'op-sender',
+ trigger: 'cli',
+ userInterventionConfig: { approvalMode: 'headless' },
+ };
+ // Tried as a queued follow-up first, so a busy topic is never interrupted,
+ // and started without superseding a run that begins in between.
+ expect(client.agentSteerQueue.append.mutate).toHaveBeenCalledWith({
+ id: expect.any(String),
+ request,
+ });
+ expect(client.aiAgent.execAgent.mutate).toHaveBeenCalledWith({
+ ...request,
+ supersedeLiveRun: false,
+ });
+ expect(logged.join('\n')).toContain('op-new');
+ });
+
+ it('queues behind a running turn instead of starting a second run', async () => {
+ client.agentSteerQueue.append.mutate.mockResolvedValue({ id: 'q-1', queued: true });
+
+ await run('topic', 'send', 'tpc-target', '-c', 'hello', '--json');
+
+ expect(client.aiAgent.execAgent.mutate).not.toHaveBeenCalled();
+ expect(JSON.parse(logged[0])).toMatchObject({ delivery: 'queued', topicId: 'tpc-target' });
+ });
+
+ // ROOT CAUSE:
+ //
+ // The queue answered "idle", then a person started a turn, and the direct
+ // start — an interactive one — interrupted that person's turn.
+ //
+ // Before: execAgent superseded whatever run owned the topic.
+ // After: the start refuses with CONFLICT and the message is queued instead.
+ it('queues the message when a turn starts between the idle check and the start', async () => {
+ client.agentSteerQueue.append.mutate
+ .mockResolvedValueOnce({ queued: false, reason: 'idle' })
+ .mockResolvedValueOnce({ id: 'q-1', queued: true });
+ client.aiAgent.execAgent.mutate.mockRejectedValueOnce(
+ Object.assign(new Error('busy'), { data: { code: 'CONFLICT' } }),
+ );
+
+ await run('topic', 'send', 'tpc-target', '-c', 'hello', '--json');
+
+ expect(client.aiAgent.execAgent.mutate).toHaveBeenCalledTimes(1);
+ const [first, second] = client.agentSteerQueue.append.mutate.mock.calls.map(([input]) => input);
+ // The same entry id, so a retried append is stored at most once.
+ expect(second.id).toBe(first.id);
+ expect(JSON.parse(logged[0])).toMatchObject({ delivery: 'queued', topicId: 'tpc-target' });
+ });
+
+ it('refuses to send into the conversation it runs in', async () => {
+ await run('topic', 'send', 'tpc-here', '-c', 'hello');
+
+ expect(client.topic.getTopicDetail.query).not.toHaveBeenCalled();
+ expect(exit).toHaveBeenCalledWith(1);
+ });
+
+ it('refuses a group conversation and a full queue', async () => {
+ client.topic.getTopicDetail.query.mockResolvedValueOnce({ agentId: null, groupId: 'grp-1' });
+ await run('topic', 'send', 'tpc-group', '-c', 'hello');
+ expect(client.agentSteerQueue.append.mutate).not.toHaveBeenCalled();
+
+ client.agentSteerQueue.append.mutate.mockResolvedValueOnce({ queued: false, reason: 'full' });
+ await run('topic', 'send', 'tpc-target', '-c', 'hello');
+ expect(client.aiAgent.execAgent.mutate).not.toHaveBeenCalled();
+
+ expect(exit).toHaveBeenCalledTimes(2);
+ });
+
+ it('passes the relay-limit refusal through to the agent', async () => {
+ client.agentSteerQueue.append.mutate.mockRejectedValue(
+ new Error('Agent relay limit reached: this would be agent-to-agent send #6 in a row'),
+ );
+
+ await run('topic', 'send', 'tpc-target', '-c', 'hello');
+
+ expect(vi.mocked(log.error).mock.calls[0][0]).toContain('Agent relay limit reached');
+ expect(exit).toHaveBeenCalledWith(1);
+ });
+
+ describe('lh message reply', () => {
+ it("answers into the sender's conversation, waking it", async () => {
+ client.message.getMessageOrigin.query.mockResolvedValue({
+ agentSender: { agentId: 'agt-writer', threadId: 'thd-1', topicId: 'tpc-writer' },
+ id: 'msg-1',
+ });
+ client.topic.getTopicDetail.query.mockResolvedValue({ agentId: 'agt-writer' });
+
+ await run('message', 'reply', 'msg-1', '-c', 'Verifier v1.2 is ready.');
+
+ expect(client.topic.getTopicDetail.query).toHaveBeenCalledWith({ id: 'tpc-writer' });
+ expect(client.aiAgent.execAgent.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agt-writer',
+ appContext: { threadId: 'thd-1', topicId: 'tpc-writer' },
+ prompt: 'Verifier v1.2 is ready.',
+ sourceOperationId: 'op-sender',
+ }),
+ );
+ });
+
+ it('refuses a message a person wrote, and one whose origin was not kept', async () => {
+ client.message.getMessageOrigin.query.mockResolvedValueOnce({ agentSender: null, id: 'm' });
+ await run('message', 'reply', 'msg-1', '-c', 'hi');
+ client.message.getMessageOrigin.query.mockResolvedValueOnce({
+ agentSender: { agentId: 'agt-writer' },
+ id: 'm',
+ });
+ await run('message', 'reply', 'msg-1', '-c', 'hi');
+
+ expect(client.topic.getTopicDetail.query).not.toHaveBeenCalled();
+ expect(exit).toHaveBeenCalledTimes(2);
+ expect(vi.mocked(log.error).mock.calls[0][0]).toContain('lh topic send');
+ });
+ });
+});
diff --git a/apps/cli/src/commands/topic/send.ts b/apps/cli/src/commands/topic/send.ts
new file mode 100644
index 00000000000..293f2c705db
--- /dev/null
+++ b/apps/cli/src/commands/topic/send.ts
@@ -0,0 +1,175 @@
+import { randomUUID } from 'node:crypto';
+
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import type { TrpcClient } from '../../api/client';
+import { getTrpcClient } from '../../api/client';
+import { resolveWorkspaceRef } from '../../api/workspaceRef';
+import { outputJson } from '../../utils/format';
+import { log } from '../../utils/logger';
+
+/** Rounds of queue-or-start before giving up on a topic that keeps getting busy. */
+const MAX_DELIVERY_ATTEMPTS = 3;
+
+export interface ConversationSendResult {
+ agentId: string;
+ /** Started a run of the conversation's agent (`started`), or queued behind its running turn. */
+ delivery: 'queued' | 'started';
+ operationId?: string;
+ threadId?: string;
+ topicId: string;
+}
+
+/**
+ * Deliver a message into another conversation and have its own agent act on
+ * it, the way typing into that conversation's composer would: start a turn when
+ * it is idle, or queue behind the running turn instead of interrupting it.
+ *
+ * When an agent runs this, its `LOBEHUB_OPERATION_ID` goes along, so the
+ * server records that agent as the author (`metadata.agentSender`) — which is
+ * what lets the receiving agent see who wrote and `lh message reply` to it.
+ *
+ * @throws with a message fit for the user when the send is refused
+ */
+export const sendToConversation = async (
+ client: TrpcClient,
+ params: { content: string; threadId?: string; topicId: string },
+): Promise<ConversationSendResult> => {
+ const { content, threadId, topicId } = params;
+
+ if (!threadId && topicId === process.env.LOBEHUB_TOPIC_ID) {
+ throw new Error(
+ `${topicId} is the conversation you are running in; answer here instead of sending to it.`,
+ );
+ }
+
+ const topic = (await client.topic.getTopicDetail.query({ id: topicId })) as {
+ agentId?: null | string;
+ groupId?: null | string;
+ } | null;
+ if (!topic) throw new Error(`Topic ${topicId} not found in this workspace.`);
+ if (topic.groupId) {
+ throw new Error(
+ `Topic ${topicId} is a group conversation; sending into groups is not supported yet.`,
+ );
+ }
+ if (!topic.agentId)
+ throw new Error(`Topic ${topicId} belongs to no agent, so nothing could act on it.`);
+
+ const request: Record<string, any> = {
+ agentId: topic.agentId,
+ appContext: threadId ? { threadId, topicId } : { topicId },
+ prompt: content,
+ trigger: 'cli',
+ // Nobody is at that conversation's composer to approve tool calls.
+ userInterventionConfig: { approvalMode: 'headless' },
+ };
+ const sourceOperationId = process.env.LOBEHUB_OPERATION_ID;
+ if (sourceOperationId) request.sourceOperationId = sourceOperationId;
+
+ // Queue behind a running turn, start a turn when idle — never interrupt. The
+ // start refuses (CONFLICT) if a turn began after the queue saw the topic idle;
+ // then the message goes back to the queue. One entry id across attempts, so a
+ // retried append is stored at most once.
+ const entryId = randomUUID();
+ let started: { error?: string; operationId?: string; success?: boolean } | undefined;
+ for (let attempt = 0; attempt < MAX_DELIVERY_ATTEMPTS && !started; attempt += 1) {
+ const queued = await client.agentSteerQueue.append.mutate({ id: entryId, request } as any);
+ if (queued.queued) {
+ return { agentId: topic.agentId, delivery: 'queued', threadId, topicId };
+ }
+ if (queued.reason !== 'idle') {
+ throw new Error(
+ queued.reason === 'full'
+ ? `Topic ${topicId} already has too many messages waiting behind its running turn; try again after it finishes.`
+ : `Could not queue the message behind the running turn of ${topicId}; try again.`,
+ );
+ }
+
+ try {
+ started = (await client.aiAgent.execAgent.mutate({
+ ...request,
+ supersedeLiveRun: false,
+ } as any)) as typeof started;
+ } catch (error) {
+ if ((error as { data?: { code?: string } })?.data?.code !== 'CONFLICT') throw error;
+ }
+ }
+ if (!started) {
+ throw new Error(`Topic ${topicId} kept starting new turns; try again in a moment.`);
+ }
+ if (!started.success) {
+ throw new Error(`Failed to start the agent of ${topicId}: ${started.error || 'unknown error'}`);
+ }
+
+ return {
+ agentId: topic.agentId,
+ delivery: 'started',
+ operationId: started.operationId,
+ threadId,
+ topicId,
+ };
+};
+
+/** Print a send's outcome, or the reason it was refused, and set the exit code. */
+export const reportConversationSend = async (
+ send: () => Promise<ConversationSendResult>,
+ options: { json?: boolean },
+) => {
+ let result: ConversationSendResult;
+ try {
+ result = await send();
+ } catch (error) {
+ log.error((error as Error).message);
+ process.exit(1);
+ return;
+ }
+
+ if (options.json) {
+ outputJson(result);
+ return;
+ }
+
+ console.log(
+ result.delivery === 'started'
+ ? `${pc.green('✓')} Sent to ${pc.bold(result.topicId)}; its agent is working on it (operation ${pc.dim(result.operationId ?? 'n/a')}).`
+ : `${pc.green('✓')} Sent to ${pc.bold(result.topicId)}; it is busy, so its agent takes the message right after the current turn.`,
+ );
+ console.log(
+ pc.dim(
+ 'The answer arrives in that conversation. If it replies to you, the reply wakes this one.',
+ ),
+ );
+};
+
+export function registerTopicSendCommand(topic: Command) {
+ topic
+ .command('send <topicId>')
+ .description(
+ "Send a message to another conversation and have its agent act on it (queued if it is busy). Unlike 'lh message create', this wakes the agent",
+ )
+ .requiredOption('-c, --content <content>', 'Message content')
+ .option(
+ '--workspace <id|slug>',
+ "The workspace the topic lives in (overrides LOBEHUB_WORKSPACE_ID and 'workspace use')",
+ )
+ .option('--json', 'Output JSON')
+ .addHelpText(
+ 'after',
+ `
+Run by an agent, the message is shown as written by that agent, and the
+receiving agent can answer it with 'lh message reply <messageId>', which wakes
+the sending conversation. Agents that keep sending to each other are stopped
+after a few rounds, so a person can step in.`,
+ )
+ .action(
+ async (topicId: string, options: { content: string; json?: boolean; workspace?: string }) => {
+ const client = await getTrpcClient(await resolveWorkspaceRef(options.workspace));
+ await reportConversationSend(
+ () => sendToConversation(client, { content: options.content, topicId }),
+ options,
+ );
+ },
+ );
+}
diff --git a/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.ts b/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.ts
index 65f57bcdb7c..21fb39c3cc4 100644
--- a/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.ts
@@ -12,9 +12,14 @@ const mocks = vi.hoisted(() => ({
list: vi.fn(),
liveCandidates: vi.fn(),
remove: vi.fn(),
+ resolveAgentSender: vi.fn(),
snapshot: vi.fn(),
}));
+vi.mock('@/server/services/aiAgent/agentSenderResolver', () => ({
+ resolveAgentSender: mocks.resolveAgentSender,
+}));
+
vi.mock('@/database/models/topic', () => ({
TopicModel: vi.fn().mockImplementation(function () {
return { isRunningOperationAlive: mocks.isRunningOperationAlive };
@@ -141,6 +146,45 @@ describe('agentSteerQueueRouter.append', () => {
expect(entry.request.streamFeatures).toBeUndefined();
});
+ it('stores the sending agent, resolved while its run can still vouch for it', async () => {
+ const sender = { agentId: 'agt-writer', hop: 2, topicId: 'tpc-writer' };
+ mocks.resolveAgentSender.mockResolvedValue(sender);
+
+ await caller().append({
+ ...appendInput,
+ request: { ...appendInput.request, sourceOperationId: 'op-writer' },
+ });
+
+ expect(mocks.resolveAgentSender).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: 'user-1' }),
+ { destinationAgentId: 'agt-1', sourceOperationId: 'op-writer' },
+ );
+ const [, entry] = mocks.append.mock.calls[0];
+ expect(entry.agentSender).toEqual(sender);
+ // The follow-up usually starts after the sending run settled: only the
+ // resolved sender is kept, never the operation id.
+ expect(entry.request).not.toHaveProperty('sourceOperationId');
+ });
+
+ it('refuses an agent send past the relay bound, queueing nothing', async () => {
+ mocks.resolveAgentSender.mockResolvedValue({ agentId: 'agt-writer', hop: 6 });
+
+ await expect(
+ caller().append({
+ ...appendInput,
+ request: { ...appendInput.request, sourceOperationId: 'op-writer' },
+ }),
+ ).rejects.toMatchObject({ code: 'TOO_MANY_REQUESTS' });
+ expect(mocks.append).not.toHaveBeenCalled();
+ });
+
+ it('resolves no sender for a person’s follow-up', async () => {
+ await caller().append(appendInput);
+
+ expect(mocks.resolveAgentSender).not.toHaveBeenCalled();
+ expect(mocks.append.mock.calls[0][1].agentSender).toBeUndefined();
+ });
+
it('keeps the composer state it was sent from, up to a cap', async () => {
const editorData = { root: { children: [], type: 'root' } };
await caller().append({ ...appendInput, composer: { editorData } });
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.agentRelayHop.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.agentRelayHop.test.ts
new file mode 100644
index 00000000000..81faf7f7b3e
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.agentRelayHop.test.ts
@@ -0,0 +1,214 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { agentOperations, agents, messages, topics } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { and, eq } from 'drizzle-orm';
+import type * as ModelBankModule from 'model-bank';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as InternalJwtModule from '@/libs/trpc/utils/internalJwt';
+import { MAX_AGENT_RELAY_HOPS } from '@/server/services/aiAgent/sourceAttribution';
+
+import { aiAgentRouter } from '../aiAgent';
+import { cleanupTestUser, createTestUser } from './integration/setup';
+
+// Mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return testDB;
+ }),
+}));
+
+// Mock AgentRuntimeService since we only want to test the router's business logic
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return {
+ createOperation: vi.fn(async (params: any) => {
+ // The real runtime invokes this before the run's first step, with the
+ // operation it is about to start; mirror it so the router's Task-run
+ // reopen path runs when a test seeds a Task run. It is a no-op for the
+ // ordinary conversation, which attaches no hooks.
+ await params?.onOperationCreated?.(params?.operationId);
+ return {
+ success: true,
+ operationId: params?.operationId ?? 'mock-operation-id',
+ autoStarted: true,
+ messageId: 'mock-message-id',
+ };
+ }),
+ };
+ }),
+}));
+
+// Mock serverMessagesEngine
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: vi.fn(function () {
+ return {
+ generateToolsDetailed: vi.fn(function () {
+ return { tools: [] };
+ }),
+ getEnabledPluginManifests: vi.fn(function () {
+ return new Map();
+ }),
+ };
+ }),
+ serverMessagesEngine: vi.fn().mockResolvedValue({
+ messages: [
+ { role: 'system', content: 'You are a helpful assistant.' },
+ { role: 'user', content: 'Hello' },
+ ],
+ metadata: {},
+ }),
+}));
+
+// Mock AiChatService to avoid S3 dependency
+vi.mock('@/server/services/aiChat', () => ({
+ AiChatService: vi.fn().mockImplementation(function () {
+ return {
+ getMessagesAndTopics: vi.fn().mockResolvedValue({ messages: [], topics: [] }),
+ };
+ }),
+}));
+
+// Mock FileService to avoid S3 dependency
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {
+ getFullFileUrl: vi.fn(function (path: string | null) {
+ return path;
+ }),
+ };
+ }),
+}));
+
+// Mock the resource-permission guard so workspace-mode tests can assert the
+// router resolves slug → agent id and runs the `use` guard (the guard's own
+// RBAC evaluation is covered by its service tests).
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanPerformResourceAction: vi.fn(),
+ getResourceMeta: vi.fn(),
+}));
+
+// The user-hub token is a real RS256 signature in production; the integration
+// DB has no JWKS_KEY, so pin the signer and assert the subject it is asked for.
+const mockSignUserJWT = vi.fn();
+vi.mock('@/libs/trpc/utils/internalJwt', async (importOriginal) => ({
+ ...(await importOriginal<typeof InternalJwtModule>()),
+ signUserJWT: (...args: any[]) => mockSignUserJWT(...args),
+}));
+
+// Mock model-bank with dynamic import to preserve other exports
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelBankModule>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ {
+ id: 'gpt-4o-mini',
+ providerId: 'openai',
+ abilities: { functionCall: true, vision: true, video: false },
+ },
+ ],
+ };
+});
+
+describe('aiAgent router - agent relay hops', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let writerAgentId: string;
+ let verifierAgentId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+ const rows = await serverDB
+ .insert(agents)
+ .values(
+ ['Writer', 'Verifier'].map((title) => ({
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant.',
+ title,
+ userId,
+ })),
+ )
+ .returning();
+ writerAgentId = rows[0].id;
+ verifierAgentId = rows[1].id;
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.restoreAllMocks();
+ });
+
+ /**
+ * The writer's run is in flight in its own conversation, started by `trigger`
+ * — a person (no sender) or another agent's message `hop` sends deep.
+ */
+ const seedSendingRun = async (triggerHop?: number) => {
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({ agentId: writerAgentId, title: 'Storytelling', userId })
+ .returning();
+ await serverDB.insert(messages).values({
+ agentId: writerAgentId,
+ content: 'feedback',
+ metadata: triggerHop
+ ? { agentSender: { agentId: verifierAgentId, hop: triggerHop } }
+ : undefined,
+ role: 'user',
+ topicId: topic.id,
+ userId,
+ });
+ const operationId = `op-writer-${triggerHop ?? 0}`;
+ await serverDB.insert(agentOperations).values({
+ agentId: writerAgentId,
+ id: operationId,
+ status: 'running',
+ topicId: topic.id,
+ userId,
+ });
+ return { operationId, topicId: topic.id };
+ };
+
+ const send = (sourceOperationId: string) =>
+ aiAgentRouter
+ .createCaller({ jwtPayload: { userId }, userId })
+ .execAgent({ agentId: verifierAgentId, prompt: 'Iterate the verifier', sourceOperationId });
+
+ it('stamps the next hop on the message an agent sends', async () => {
+ const { operationId, topicId } = await seedSendingRun(2);
+
+ const result = await send(operationId);
+
+ const [sent] = await serverDB
+ .select({ metadata: messages.metadata })
+ .from(messages)
+ .where(and(eq(messages.topicId, result.topicId!), eq(messages.role, 'user')));
+ expect(sent.metadata).toMatchObject({
+ agentSender: { agentId: writerAgentId, hop: 3, topicId },
+ });
+ });
+
+ // ROOT CAUSE:
+ //
+ // An agent told to report back to another agent after every round woke it,
+ // which woke it back, with nothing to stop the pair.
+ //
+ // Before: every agent → agent send started a run.
+ // After: a send past MAX_AGENT_RELAY_HOPS in a row is refused.
+ it('refuses a send past the relay bound and starts nothing', async () => {
+ const { operationId } = await seedSendingRun(MAX_AGENT_RELAY_HOPS);
+
+ await expect(send(operationId)).rejects.toMatchObject({ code: 'TOO_MANY_REQUESTS' });
+
+ const verifierTopics = await serverDB
+ .select({ id: topics.id })
+ .from(topics)
+ .where(eq(topics.agentId, verifierAgentId));
+ expect(verifierTopics).toHaveLength(0);
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.noSupersede.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.noSupersede.test.ts
new file mode 100644
index 00000000000..ba5fad593c2
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.noSupersede.test.ts
@@ -0,0 +1,201 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { agentOperations, agents, messages, topics } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import type * as ModelBankModule from 'model-bank';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as InternalJwtModule from '@/libs/trpc/utils/internalJwt';
+
+import { aiAgentRouter } from '../aiAgent';
+import { cleanupTestUser, createTestUser } from './integration/setup';
+
+// Mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return testDB;
+ }),
+}));
+
+// Mock AgentRuntimeService since we only want to test the router's business logic
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return {
+ createOperation: vi.fn(async (params: any) => {
+ // The real runtime invokes this before the run's first step, with the
+ // operation it is about to start; mirror it so the router's Task-run
+ // reopen path runs when a test seeds a Task run. It is a no-op for the
+ // ordinary conversation, which attaches no hooks.
+ await params?.onOperationCreated?.(params?.operationId);
+ return {
+ success: true,
+ operationId: params?.operationId ?? 'mock-operation-id',
+ autoStarted: true,
+ messageId: 'mock-message-id',
+ };
+ }),
+ };
+ }),
+}));
+
+// Mock serverMessagesEngine
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: vi.fn(function () {
+ return {
+ generateToolsDetailed: vi.fn(function () {
+ return { tools: [] };
+ }),
+ getEnabledPluginManifests: vi.fn(function () {
+ return new Map();
+ }),
+ };
+ }),
+ serverMessagesEngine: vi.fn().mockResolvedValue({
+ messages: [
+ { role: 'system', content: 'You are a helpful assistant.' },
+ { role: 'user', content: 'Hello' },
+ ],
+ metadata: {},
+ }),
+}));
+
+// Mock AiChatService to avoid S3 dependency
+vi.mock('@/server/services/aiChat', () => ({
+ AiChatService: vi.fn().mockImplementation(function () {
+ return {
+ getMessagesAndTopics: vi.fn().mockResolvedValue({ messages: [], topics: [] }),
+ };
+ }),
+}));
+
+// Mock FileService to avoid S3 dependency
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {
+ getFullFileUrl: vi.fn(function (path: string | null) {
+ return path;
+ }),
+ };
+ }),
+}));
+
+// Mock the resource-permission guard so workspace-mode tests can assert the
+// router resolves slug → agent id and runs the `use` guard (the guard's own
+// RBAC evaluation is covered by its service tests).
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanPerformResourceAction: vi.fn(),
+ getResourceMeta: vi.fn(),
+}));
+
+// The user-hub token is a real RS256 signature in production; the integration
+// DB has no JWKS_KEY, so pin the signer and assert the subject it is asked for.
+const mockSignUserJWT = vi.fn();
+vi.mock('@/libs/trpc/utils/internalJwt', async (importOriginal) => ({
+ ...(await importOriginal<typeof InternalJwtModule>()),
+ signUserJWT: (...args: any[]) => mockSignUserJWT(...args),
+}));
+
+// Mock model-bank with dynamic import to preserve other exports
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelBankModule>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ {
+ id: 'gpt-4o-mini',
+ providerId: 'openai',
+ abilities: { functionCall: true, vision: true, video: false },
+ },
+ ],
+ };
+});
+
+describe('aiAgent router - non-superseding start', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let agentId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant.',
+ title: 'Verifier',
+ userId,
+ })
+ .returning();
+ agentId = agent.id;
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.restoreAllMocks();
+ });
+
+ /** A topic whose foreground run is live, as a person's turn in progress leaves it. */
+ const seedLiveTopic = async () => {
+ const operationId = 'op-person-turn';
+ const [topic] = await serverDB
+ .insert(topics)
+ .values({
+ agentId,
+ metadata: {
+ runningOperation: {
+ assistantMessageId: 'msg-1',
+ operationId,
+ startedAt: new Date().toISOString(),
+ },
+ },
+ title: 'Busy',
+ userId,
+ })
+ .returning();
+ await serverDB.insert(agentOperations).values({
+ agentId,
+ id: operationId,
+ status: 'running',
+ topicId: topic.id,
+ userId,
+ });
+ return { operationId, topicId: topic.id };
+ };
+
+ // ROOT CAUSE:
+ //
+ // `lh topic send` saw the topic idle in the queue, then a person started a
+ // turn; its direct start was interactive and interrupted that turn.
+ //
+ // Before: execAgent always superseded the run owning the topic.
+ // After: `supersedeLiveRun: false` refuses with CONFLICT and writes nothing.
+ it('refuses with CONFLICT instead of interrupting a live run, writing nothing', async () => {
+ const { operationId, topicId } = await seedLiveTopic();
+ const caller = aiAgentRouter.createCaller({ jwtPayload: { userId }, userId });
+
+ await expect(
+ caller.execAgent({
+ agentId,
+ appContext: { topicId },
+ prompt: 'From another agent',
+ supersedeLiveRun: false,
+ }),
+ ).rejects.toMatchObject({ code: 'CONFLICT' });
+
+ const [operation] = await serverDB
+ .select({ status: agentOperations.status })
+ .from(agentOperations)
+ .where(eq(agentOperations.id, operationId));
+ expect(operation.status).toBe('running');
+ const written = await serverDB
+ .select({ id: messages.id })
+ .from(messages)
+ .where(eq(messages.topicId, topicId));
+ expect(written).toHaveLength(0);
+ }, 20_000);
+});
diff --git a/apps/server/src/routers/lambda/agentSteerQueue.ts b/apps/server/src/routers/lambda/agentSteerQueue.ts
index b1085a62c6d..2bbc94d7678 100644
--- a/apps/server/src/routers/lambda/agentSteerQueue.ts
+++ b/apps/server/src/routers/lambda/agentSteerQueue.ts
@@ -9,6 +9,11 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceA
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';
+import { resolveAgentSender } from '@/server/services/aiAgent/agentSenderResolver';
+import {
+ AgentRelayHopLimitError,
+ assertAgentRelayHop,
+} from '@/server/services/aiAgent/sourceAttribution';
import type { QueuedFollowUp } from '@/server/services/aiAgent/steerQueue';
import { findOwnLiveRuns, isRunAlive } from '@/server/services/aiAgent/steerQueue/liveRuns';
import { redisService } from '@/server/services/redis';
@@ -26,7 +31,9 @@ const log = debug('lobe-lambda-router:agent-steer-queue');
/**
* A composer send queued behind the running turn: the fresh-send part of an
* `aiAgent.execAgent` request. Resume / regenerate / supersede fields are not
- * accepted — a follow-up always starts a new turn of its own.
+ * accepted — a follow-up always starts a new turn of its own. `sourceOperationId`
+ * is accepted — another agent queueing through `lh topic send` — but resolved
+ * into the sender right away and never stored.
*/
const QueuedRequestSchema = ExecAgentFieldsSchema.omit({
autoStart: true,
@@ -38,8 +45,8 @@ const QueuedRequestSchema = ExecAgentFieldsSchema.omit({
resumeApproval: true,
resumeApprovals: true,
resumeToolResult: true,
- sourceOperationId: true,
steer: true,
+ supersedeLiveRun: true,
}).refine((data) => data.agentId || data.slug, {
message: 'Either agentId or slug must be provided',
});
@@ -114,7 +121,7 @@ export const agentSteerQueueRouter = router({
* error means the outcome is unknown: retry with the same `id`.
*/
append: steerQueueWriteProcedure.input(AppendSchema).mutation(async ({ input, ctx }) => {
- const { streamFeatures, ...request } = input.request;
+ const { sourceOperationId, streamFeatures, ...request } = input.request;
const topicId = request.appContext?.topicId;
if (!topicId) return { queued: false as const, reason: 'idle' as const };
@@ -159,7 +166,24 @@ export const agentSteerQueueRouter = router({
// run that ends later leaves entries bound to a live run alone.
const [behindOperationId] = liveRuns;
+ // Resolved now, while the sending run is still in flight to vouch for it:
+ // the follow-up usually starts after that run has settled.
+ const agentSender =
+ sourceOperationId && request.agentId
+ ? await resolveAgentSender(
+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ { destinationAgentId: request.agentId, sourceOperationId },
+ )
+ : undefined;
+ try {
+ assertAgentRelayHop(agentSender);
+ } catch (error) {
+ if (!(error instanceof AgentRelayHopLimitError)) throw error;
+ throw new TRPCError({ cause: error, code: 'TOO_MANY_REQUESTS', message: error.message });
+ }
+
const entry: QueuedFollowUp = {
+ agentSender,
audit: { clientIp: ctx.clientIp ?? undefined, userAgent: ctx.userAgent ?? undefined },
composer: storedComposer(input.composer),
createdAt: Date.now(),
diff --git a/apps/server/src/routers/lambda/aiAgent/exec.ts b/apps/server/src/routers/lambda/aiAgent/exec.ts
index 03bedbfb364..507f1d6b2d7 100644
--- a/apps/server/src/routers/lambda/aiAgent/exec.ts
+++ b/apps/server/src/routers/lambda/aiAgent/exec.ts
@@ -18,6 +18,8 @@ import { unwrapPgError } from '@/server/modules/AgentRuntime/pgError';
import { toClientExecAgentResult } from '@/server/routers/lambda/_helpers/groupMemberContinuationResult';
import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';
import { startComposerRun } from '@/server/services/aiAgent/composerRun';
+import { AgentRelayHopLimitError } from '@/server/services/aiAgent/sourceAttribution';
+import { TopicStartReservationError } from '@/server/services/aiAgent/topicStartReservation';
import type { ExecAgentInput } from './execSchemas';
import {
@@ -214,6 +216,7 @@ export const execRouter = router({
resumeApproval,
resumeApprovals,
resumeToolResult,
+ supersedeLiveRun = true,
} = input;
log('execAgent: identifier=%s, prompt=%s', agentId || slug, prompt.slice(0, 50));
@@ -262,19 +265,24 @@ export const execRouter = router({
);
if (bridged) return bridged;
+ const { supersedeLiveRun: _supersede, ...request } = foldLegacyUserMessageFields(input);
const result = await startComposerRun(
{
aiAgentService: ctx.aiAgentService,
clientIp: ctx.clientIp ?? undefined,
db: ctx.serverDB,
+ supersedeLiveRun,
userAgent: ctx.userAgent ?? undefined,
userId: ctx.userId,
workspaceId: ctx.workspaceId,
},
{
- ...foldLegacyUserMessageFields(input),
+ ...request,
acceptsFileWorks: acceptsFileWorksOf(input.streamFeatures),
acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),
+ // A non-superseding start waits on the surface like a server-started
+ // follow-up, so a thread's live run is refused as well.
+ ...(supersedeLiveRun ? {} : { queuedSuccessor: true }),
},
);
@@ -286,6 +294,22 @@ export const execRouter = router({
throw error;
}
+ // A send that must not interrupt found the topic owned by a live run;
+ // nothing was written, so the caller can queue it behind that run.
+ if (!supersedeLiveRun && error instanceof TopicStartReservationError) {
+ throw new TRPCError({
+ cause: error,
+ code: 'CONFLICT',
+ message: 'The conversation is busy with a running turn; queue the message behind it.',
+ });
+ }
+
+ // An agent → agent send past the relay bound: the sending agent has to
+ // hand back to a person, so the reason travels to it verbatim.
+ if (error instanceof AgentRelayHopLimitError) {
+ throw new TRPCError({ cause: error, code: 'TOO_MANY_REQUESTS', message: error.message });
+ }
+
if (error instanceof HumanApprovalAlreadyResolvedError) {
throw new TRPCError({
cause: error,
diff --git a/apps/server/src/routers/lambda/aiAgent/execSchemas.ts b/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
index c8abfb3f61a..e04280ba1ba 100644
--- a/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
+++ b/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
@@ -304,6 +304,14 @@ export const ExecAgentFieldsSchema = z.object({
* waited in queue and starts a turn of its own is not marked.
*/
steer: z.boolean().optional(),
+ /**
+ * Whether this send may take the topic over from a run that still owns it,
+ * as a person at the composer does (default). `false` — another agent
+ * delivering through `lh topic send` — never interrupts: a live run makes the
+ * call fail with `CONFLICT` before anything is written, and the caller queues
+ * the message behind that run instead.
+ */
+ supersedeLiveRun: z.boolean().optional(),
trigger: z
.string()
.refine((value) => value !== RequestTrigger.Bot, {
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index 133e99d43d7..fff924a0a40 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -1,5 +1,6 @@
import { projectToolViewModels } from '@lobechat/tool-view-model';
import {
+ AgentSenderMetadataSchema,
CreateNewMessageParamsSchema,
omitServerOwnedMessageMetadata,
UpdateMessageParamsSchema,
@@ -419,6 +420,32 @@ export const messageRouter = router({
return ctx.messageService.getToolResultPayloads(input.messageIds);
}),
+ /**
+ * Where a message came from, for answering it: its conversation and, for a
+ * message another agent sent, that agent and its conversation
+ * (`metadata.agentSender`). Read by `lh message reply`.
+ */
+ getMessageOrigin: messageProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ input, ctx }) => {
+ await assertCanViewMessageTargets(guardCtx(ctx), [input.id]);
+
+ const message = await ctx.messageModel.findById(input.id);
+ if (!message) return null;
+
+ const agentSender = AgentSenderMetadataSchema.safeParse(
+ (message.metadata as Record<string, unknown> | null)?.agentSender,
+ );
+ return {
+ agentId: message.agentId ?? null,
+ agentSender: agentSender.success ? agentSender.data : null,
+ id: message.id,
+ role: message.role,
+ threadId: message.threadId ?? null,
+ topicId: message.topicId ?? null,
+ };
+ }),
+
getToolResultPayload: messageProcedure
.input(z.object({ messageId: z.string() }))
.query(async ({ input, ctx }) => {
diff --git a/apps/server/src/services/aiAgent/agentSenderResolver.ts b/apps/server/src/services/aiAgent/agentSenderResolver.ts
new file mode 100644
index 00000000000..f46b3de2cd7
--- /dev/null
+++ b/apps/server/src/services/aiAgent/agentSenderResolver.ts
@@ -0,0 +1,40 @@
+import type { AgentSenderMetadata } from '@lobechat/types';
+
+import { AgentModel } from '@/database/models/agent';
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { ChatGroupModel } from '@/database/models/chatGroup';
+import { MessageModel } from '@/database/models/message';
+import { TopicModel } from '@/database/models/topic';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { resolveAgentSenderFromOperation } from './sourceAttribution';
+
+/**
+ * Resolve the sending agent of an agent → agent send outside an
+ * `AiAgentService` — for a follow-up queued behind a running turn, whose sender
+ * has to be resolved while the sending run is still in flight to vouch for it.
+ * Same trust and shareability rules as the service's own resolution.
+ */
+export const resolveAgentSender = (
+ ctx: { db: LobeChatDatabase; userId: string; workspaceId?: null | string },
+ params: { destinationAgentId: string; sourceOperationId?: string },
+): Promise<AgentSenderMetadata | undefined> => {
+ const workspaceId = ctx.workspaceId ?? undefined;
+ const agentModel = new AgentModel(ctx.db, ctx.userId, workspaceId);
+
+ return resolveAgentSenderFromOperation(params.sourceOperationId, {
+ destinationAgentId: params.destinationAgentId,
+ findAgentDisplayFields: (agentId) => agentModel.getAgentDisplayFields(agentId),
+ findAgentVisibility: (agentId) => agentModel.getAgentVisibility(agentId),
+ findChatGroupVisibility: async (chatGroupId) =>
+ (await new ChatGroupModel(ctx.db, ctx.userId, workspaceId).findById(chatGroupId))
+ ?.visibility ?? null,
+ findOperation: (operationId) =>
+ new AgentOperationModel(ctx.db, ctx.userId, workspaceId).findById(operationId),
+ findTopic: (topicId) => new TopicModel(ctx.db, ctx.userId, workspaceId).findById(topicId),
+ findTriggerHop: (hopParams) =>
+ new MessageModel(ctx.db, ctx.userId, workspaceId).findLatestUserTurnHop(hopParams),
+ userId: ctx.userId,
+ workspaceId,
+ });
+};
diff --git a/apps/server/src/services/aiAgent/composerRun.ts b/apps/server/src/services/aiAgent/composerRun.ts
index 973a0596b1e..df26ff0fdb8 100644
--- a/apps/server/src/services/aiAgent/composerRun.ts
+++ b/apps/server/src/services/aiAgent/composerRun.ts
@@ -18,6 +18,7 @@ export type ComposerRunRequest = Pick<
| 'acceptsFileWorks'
| 'acceptsMemberRuntimeEnd'
| 'agentId'
+ | 'agentSender'
| 'appContext'
| 'autoStart'
| 'clientIds'
@@ -155,6 +156,7 @@ export const startComposerRun = async (ctx: ComposerRunContext, input: ComposerR
selectedSkillIds: input.selectedSkillIds,
selectedToolIds: input.selectedToolIds,
slug: input.slug,
+ agentSender: input.agentSender,
sourceOperationId: input.sourceOperationId,
steer: input.steer,
trigger: input.trigger ?? RequestTrigger.Chat,
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index dec5c90e53f..b057dc085be 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -637,6 +637,7 @@ export class AiAgentService {
?.visibility ?? null,
findOperation: (operationId) => this.agentOperationModel.findById(operationId),
findTopic: (topicId) => this.topicModel.findById(topicId),
+ findTriggerHop: (params) => this.messageModel.findLatestUserTurnHop(params),
userId: this.userId,
workspaceId: this.workspaceId,
});
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index c3f6529ace1..7a3d24ccd4d 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -26,6 +26,7 @@ import type { MarketService } from '@/server/services/market';
import { createRunFacts, type RunFacts } from '../runFacts';
import { applyShareGateToAgentConfig } from '../shareGate';
+import { assertAgentRelayHop } from '../sourceAttribution';
import type { ExecRunContext, InternalExecAgentParams } from '../types';
import type { ApprovalClaimState } from './approvalResume';
import { claimApprovalResume, tryReuseInterventionContinuation } from './approvalResume';
@@ -386,10 +387,12 @@ export const execAgentTurn = async (
// Agent → agent attribution: resolve the launching run's agent into a
// display snapshot once, before the turn rows exist, so the persisted user
// message carries a self-contained sender block.
- const agentSender = await deps.resolveSourceAgentSnapshot(
- resolvedAgentId,
- params.sourceOperationId,
- );
+ const agentSender =
+ params.agentSender ??
+ (await deps.resolveSourceAgentSnapshot(resolvedAgentId, params.sourceOperationId));
+ // Two agents told to report back to each other would otherwise wake each
+ // other forever; past the bound a person has to step in.
+ assertAgentRelayHop(agentSender);
// Stage 3 + shared turn setup — topic creation/reuse (with the pinned
// model), device-access policy, hetero detection, attachment ingestion, and
diff --git a/apps/server/src/services/aiAgent/sourceAttribution.test.ts b/apps/server/src/services/aiAgent/sourceAttribution.test.ts
index abbbb9a9d3c..304cd394353 100644
--- a/apps/server/src/services/aiAgent/sourceAttribution.test.ts
+++ b/apps/server/src/services/aiAgent/sourceAttribution.test.ts
@@ -1,7 +1,12 @@
import type { AgentOperationStatus } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
-import { resolveAgentSenderFromOperation } from './sourceAttribution';
+import {
+ AgentRelayHopLimitError,
+ assertAgentRelayHop,
+ MAX_AGENT_RELAY_HOPS,
+ resolveAgentSenderFromOperation,
+} from './sourceAttribution';
const CALLER = 'user-1';
@@ -30,6 +35,8 @@ const buildDeps = (overrides?: {
| null
| undefined
| { agentId?: null | string; title?: null | string; workspaceId?: null | string };
+ /** Hop of the newest user message on the sending conversation; rejects to simulate a failed read. */
+ triggerHop?: Error | number;
workspaceId?: string;
}) => ({
destinationAgentId: 'agt-destination',
@@ -51,6 +58,10 @@ const buildDeps = (overrides?: {
{ status: 'running', ...overrides.operation },
),
findTopic: vi.fn().mockResolvedValue(overrides?.topic === undefined ? null : overrides.topic),
+ findTriggerHop:
+ overrides?.triggerHop instanceof Error
+ ? vi.fn().mockRejectedValue(overrides.triggerHop)
+ : vi.fn().mockResolvedValue(overrides?.triggerHop),
userId: CALLER,
workspaceId: overrides?.workspaceId,
});
@@ -327,6 +338,7 @@ describe('resolveAgentSenderFromOperation', () => {
await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toEqual({
agentId: 'agt-coco',
+ hop: 1,
avatar: '🐶',
name: 'Coco',
title: 'Product Assistant',
@@ -351,6 +363,7 @@ describe('resolveAgentSenderFromOperation', () => {
await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toEqual({
agentId: 'agt-child',
+ hop: 1,
avatar: '🤖',
name: 'Release Bot',
title: 'Release Bot',
@@ -369,6 +382,7 @@ describe('resolveAgentSenderFromOperation', () => {
await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toEqual({
agentId: 'agt-coco',
+ hop: 1,
topicAgentId: 'agt-coco',
topicId: 'tpc-source',
topicTitle: 'Source',
@@ -384,9 +398,73 @@ describe('resolveAgentSenderFromOperation', () => {
await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toEqual({
agentId: 'agt-coco',
+ hop: 1,
topicAgentId: 'agt-coco',
topicId: 'tpc-source',
topicTitle: 'Source',
});
});
+
+ describe('relay hops', () => {
+ const operation = { agentId: 'agt-coco', topicId: 'tpc-source', userId: CALLER };
+ const topic = { agentId: 'agt-coco', title: 'Source' };
+
+ it('counts one hop when a person started the sending turn', async () => {
+ const deps = buildDeps({ operation, topic });
+
+ await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toMatchObject({
+ hop: 1,
+ });
+ });
+
+ it('counts one more than the agent message that started the sending turn', async () => {
+ const deps = buildDeps({
+ operation: { ...operation, threadId: 'thd-1' },
+ topic,
+ triggerHop: 2,
+ });
+
+ await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toMatchObject({
+ hop: 3,
+ });
+ // Read on the conversation the sending turn runs in.
+ expect(deps.findTriggerHop).toHaveBeenCalledWith({
+ threadId: 'thd-1',
+ topicId: 'tpc-source',
+ });
+ });
+
+ it('still counts on a source whose origin is hidden from the destination', async () => {
+ const deps = buildDeps({
+ agentVisibility: { 'agt-coco': 'private', 'agt-destination': 'public' },
+ operation: { ...operation, workspaceId: 'ws-1' },
+ topic: { ...topic, workspaceId: 'ws-1' },
+ triggerHop: 4,
+ workspaceId: 'ws-1',
+ });
+
+ const sender = await resolveAgentSenderFromOperation('op-1', deps);
+
+ expect(sender?.topicId).toBeUndefined();
+ expect(sender?.hop).toBe(5);
+ });
+
+ it('starts over at one when the trigger cannot be read', async () => {
+ const deps = buildDeps({ operation, topic, triggerHop: new Error('db down') });
+
+ await expect(resolveAgentSenderFromOperation('op-1', deps)).resolves.toMatchObject({
+ hop: 1,
+ });
+ });
+
+ it('refuses a send past the bound, and nothing up to it', () => {
+ expect(() => assertAgentRelayHop(undefined)).not.toThrow();
+ expect(() =>
+ assertAgentRelayHop({ agentId: 'agt-coco', hop: MAX_AGENT_RELAY_HOPS }),
+ ).not.toThrow();
+ expect(() =>
+ assertAgentRelayHop({ agentId: 'agt-coco', hop: MAX_AGENT_RELAY_HOPS + 1 }),
+ ).toThrow(AgentRelayHopLimitError);
+ });
+ });
});
diff --git a/apps/server/src/services/aiAgent/sourceAttribution.ts b/apps/server/src/services/aiAgent/sourceAttribution.ts
index 6851ec31ed3..9c8b75bc014 100644
--- a/apps/server/src/services/aiAgent/sourceAttribution.ts
+++ b/apps/server/src/services/aiAgent/sourceAttribution.ts
@@ -4,6 +4,31 @@ import debug from 'debug';
const log = debug('lobe-server:ai-agent-source-attribution');
+/**
+ * How many agent → agent sends may follow each other before a person has to
+ * step in. Each send started by an agent turn that was itself started by
+ * another agent's send counts one more (`AgentSenderMetadata.hop`); without a
+ * bound, two agents told to report back to each other wake each other forever.
+ */
+export const MAX_AGENT_RELAY_HOPS = 5;
+
+/** A send would exceed {@link MAX_AGENT_RELAY_HOPS}; the run is not started. */
+export class AgentRelayHopLimitError extends Error {
+ constructor(readonly hop: number) {
+ super(
+ `Agent relay limit reached: this would be agent-to-agent send #${hop} in a row (at most ${MAX_AGENT_RELAY_HOPS}). Ask the user how to continue instead of sending again.`,
+ );
+ this.name = 'AgentRelayHopLimitError';
+ }
+}
+
+/** Refuse a resolved sender past the relay bound — see {@link MAX_AGENT_RELAY_HOPS}. */
+export const assertAgentRelayHop = (sender: AgentSenderMetadata | undefined) => {
+ if (sender?.hop && sender.hop > MAX_AGENT_RELAY_HOPS) {
+ throw new AgentRelayHopLimitError(sender.hop);
+ }
+};
+
/** The slice of an `agent_operations` row this decision reads. */
export interface SourceOperationRow {
/** The agent that RAN the operation — the sender, which is not always the topic's owner. */
@@ -40,6 +65,12 @@ export interface SourceAttributionDeps {
findChatGroupVisibility: (chatGroupId: string) => Promise<'private' | 'public' | null>;
findOperation: (operationId: string) => Promise<null | SourceOperationRow | undefined>;
findTopic: (topicId: string) => Promise<null | SourceTopicRow | undefined>;
+ /**
+ * The relay hop of the newest user message on the sending conversation —
+ * the one that started (or last steered) the sending turn — or undefined when
+ * a person wrote it.
+ */
+ findTriggerHop: (params: { threadId?: string; topicId: string }) => Promise<number | undefined>;
/** The authenticated caller — attribution may only rest on THEIR OWN work. */
userId: string;
/** The caller's active workspace; undefined in personal scope. */
@@ -147,12 +178,22 @@ export const resolveAgentSenderFromOperation = async (
topicAgentId: topic?.agentId ?? undefined,
});
+ // Counted on the conversation the sending turn runs in, whether or not its
+ // origin may be shown: the bound protects the runtime, not the display.
+ const triggerHop = await deps
+ .findTriggerHop({ threadId: operation.threadId ?? undefined, topicId: operation.topicId })
+ .catch((error) => {
+ log('failed to read the trigger hop of %s: %O', operation.topicId, error);
+ return undefined;
+ });
+
const base: AgentSenderMetadata = {
agentId: senderAgentId,
// Group and thread are where the turn actually happened: without them the
// jump-back opens the agent's own topic instead of the group, or the topic's
// main transcript instead of the thread.
chatGroupId: operation.chatGroupId ?? undefined,
+ hop: (triggerHop ?? 0) + 1,
threadId: operation.threadId ?? undefined,
topicAgentId: topic?.agentId ?? undefined,
topicId: shareable ? operation.topicId : undefined,
diff --git a/apps/server/src/services/aiAgent/steerQueue/index.test.ts b/apps/server/src/services/aiAgent/steerQueue/index.test.ts
index 50f959454dc..79bf72b6b80 100644
--- a/apps/server/src/services/aiAgent/steerQueue/index.test.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/index.test.ts
@@ -1,7 +1,12 @@
import { TRPCError } from '@trpc/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { mergeQueuedFollowUps, type QueuedFollowUp, startQueuedFollowUp } from './index';
+import {
+ mergeQueuedFollowUps,
+ type QueuedFollowUp,
+ startQueuedFollowUp,
+ takeSameSenderFollowUps,
+} from './index';
const {
assertCanUseAgentRunConversation,
@@ -106,6 +111,35 @@ describe('mergeQueuedFollowUps', () => {
});
});
+describe('takeSameSenderFollowUps', () => {
+ const writer = { agentId: 'agt-writer', topicId: 'tpc-writer' };
+ const reviewer = { agentId: 'agt-reviewer', topicId: 'tpc-reviewer' };
+
+ it('takes the leading follow-ups of one author, in queue order', () => {
+ const a = { ...followUp('a', 2, {}), agentSender: writer };
+ const b = { ...followUp('b', 1, {}), agentSender: writer };
+ const c = { ...followUp('c', 3, {}), agentSender: reviewer };
+ const d = followUp('d', 4, {});
+
+ expect(takeSameSenderFollowUps([a, c, b, d])).toEqual({
+ agentSender: writer,
+ rest: [c, d],
+ taken: [b, a],
+ });
+ });
+
+ it('keeps a person’s follow-ups together, with no sender', () => {
+ const entries = [followUp('a', 1, {}), followUp('b', 2, {})];
+
+ expect(takeSameSenderFollowUps(entries)).toEqual({
+ agentSender: undefined,
+ rest: [],
+ taken: entries,
+ });
+ expect(takeSameSenderFollowUps([])).toEqual({ rest: [], taken: [] });
+ });
+});
+
describe('startQueuedFollowUp', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -173,6 +207,25 @@ describe('startQueuedFollowUp', () => {
expect(request).not.toHaveProperty('pageSelections');
});
+ it('starts an agent’s follow-ups as a turn authored by that agent, one author at a time', async () => {
+ const writer = { agentId: 'agt-writer', hop: 2, topicId: 'tpc-writer' };
+ const typed = followUp('typed', 3, {});
+ drain.mockResolvedValue([
+ { ...followUp('a', 1, {}), agentSender: writer },
+ { ...followUp('b', 2, {}), agentSender: writer },
+ typed,
+ ]);
+
+ await startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }));
+
+ expect(startComposerRun).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ agentSender: writer, prompt: 'a\n\nb' }),
+ );
+ // The person's follow-up waits for the turn this starts to finish.
+ expect(settle).toHaveBeenCalledWith(expect.anything(), expect.any(String), [typed.id]);
+ });
+
it('puts the follow-ups back when the next turn cannot start', async () => {
const entries = [followUp('a', 1, {})];
drain.mockResolvedValue(entries);
diff --git a/apps/server/src/services/aiAgent/steerQueue/index.ts b/apps/server/src/services/aiAgent/steerQueue/index.ts
index a16bee54ee2..4700540f766 100644
--- a/apps/server/src/services/aiAgent/steerQueue/index.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/index.ts
@@ -1,6 +1,6 @@
import { randomUUID } from 'node:crypto';
-import type { ComposerUserMessage, MessageMetadata } from '@lobechat/types';
+import type { AgentSenderMetadata, ComposerUserMessage, MessageMetadata } from '@lobechat/types';
import { COMPOSER_USER_MESSAGE_METADATA_KEYS, toComposerUserMessage } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
@@ -38,6 +38,13 @@ export type QueuedFollowUpRequest = Omit<
>;
export interface QueuedFollowUp extends SteerQueueEntry {
+ /**
+ * The sending agent, when another agent queued this (`lh topic send` into a
+ * busy conversation). Resolved by the server when it was queued: by the time
+ * the follow-up starts, the sending run has usually settled and can no longer
+ * vouch for it.
+ */
+ agentSender?: AgentSenderMetadata;
/** Server-derived provenance of the request that queued it. */
audit?: { clientIp?: string; userAgent?: string };
/**
@@ -104,6 +111,34 @@ export const mergeQueuedFollowUps = (entries: QueuedFollowUp[]): QueuedFollowUpR
};
};
+const senderKey = (entry: QueuedFollowUp) =>
+ entry.agentSender
+ ? [entry.agentSender.agentId, entry.agentSender.topicId, entry.agentSender.threadId].join('|')
+ : '';
+
+/**
+ * Split off the leading follow-ups that share one author — the person, or one
+ * sending agent's conversation. Merged follow-ups become one user message with
+ * one author, so an agent's message must not be folded into the person's (it
+ * would read as typed by them) nor into another agent's (the reply would go to
+ * only one of them). The rest wait for the next turn.
+ */
+export const takeSameSenderFollowUps = (
+ entries: QueuedFollowUp[],
+): { agentSender?: AgentSenderMetadata; rest: QueuedFollowUp[]; taken: QueuedFollowUp[] } => {
+ const sorted = [...entries].sort((a, b) => a.createdAt - b.createdAt);
+ if (sorted.length === 0) return { rest: [], taken: [] };
+ const key = senderKey(sorted[0]);
+ const firstOther = sorted.findIndex((entry) => senderKey(entry) !== key);
+ const taken = firstOther === -1 ? sorted : sorted.slice(0, firstOther);
+
+ return {
+ agentSender: sorted[0].agentSender,
+ rest: sorted.slice(taken.length),
+ taken,
+ };
+};
+
/** Guard outcomes that mean the user may no longer start this turn. */
const DENIED_CODES = new Set<TRPCError['code']>(['FORBIDDEN', 'NOT_FOUND']);
@@ -270,8 +305,11 @@ export const startQueuedFollowUp = async (
const { scope } = params;
const drained = await drainOwnFollowUps(ctx, scope, params.operationId);
- const { entries } = drained;
- if (entries.length === 0) return;
+ if (drained.entries.length === 0) return;
+
+ // One author per turn; the run this starts picks the others up when it ends.
+ const { agentSender, rest, taken: entries } = takeSameSenderFollowUps(drained.entries);
+ await returnFollowUps(scope, drained, rest, 'sent by another author');
const request = mergeQueuedFollowUps(entries);
const audit = entries.at(-1)!.audit;
@@ -307,6 +345,7 @@ export const startQueuedFollowUp = async (
{ ...ctx, clientIp: audit?.clientIp, supersedeLiveRun: false, userAgent: audit?.userAgent },
{
...request,
+ agentSender,
appContext: { ...request.appContext, threadId: scope.threadId, topicId: scope.topicId },
// A drained follow-up starts its own turn — it did not steer the run
// it waited behind, so the user message stays unmarked.
diff --git a/apps/server/src/services/aiAgent/steerQueue/inject.test.ts b/apps/server/src/services/aiAgent/steerQueue/inject.test.ts
index 9167fa9386d..474f8a5a5f6 100644
--- a/apps/server/src/services/aiAgent/steerQueue/inject.test.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/inject.test.ts
@@ -190,6 +190,27 @@ describe('injectQueuedFollowUp', () => {
);
});
+ it('joins an agent’s follow-up under that agent, and leaves another author’s for later', async () => {
+ const writer = { agentId: 'agt-writer', hop: 1, topicId: 'tpc-writer' };
+ const fromWriter = [
+ { ...followUp('one', 1), agentSender: writer },
+ { ...followUp('two', 2), agentSender: writer },
+ ];
+ const typed = followUp('typed', 3);
+ mocks.drain.mockResolvedValue([...fromWriter, typed]);
+
+ await expect(inject()).resolves.toEqual({ messageId: 'msg-steer' });
+
+ // One message, one author: the person's text must not read as the agent's.
+ expect(mocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: 'one\n\ntwo',
+ metadata: expect.objectContaining({ agentSender: writer, steer: true }),
+ }),
+ );
+ expect(mocks.settle).toHaveBeenCalledWith(scope, expect.any(String), [typed.id]);
+ });
+
it('joins nothing when the first follow-up needs a turn of its own', async () => {
const entries = [followUp('with-file', 1, { fileIds: ['f1'] })];
mocks.drain.mockResolvedValue(entries);
diff --git a/apps/server/src/services/aiAgent/steerQueue/inject.ts b/apps/server/src/services/aiAgent/steerQueue/inject.ts
index 52bcb4334ec..61be164ec2d 100644
--- a/apps/server/src/services/aiAgent/steerQueue/inject.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/inject.ts
@@ -15,6 +15,7 @@ import {
mergeQueuedFollowUps,
type QueuedFollowUp,
returnFollowUps,
+ takeSameSenderFollowUps,
} from './index';
const log = debug('lobe-server:steer-queue');
@@ -106,8 +107,10 @@ export const injectQueuedFollowUp = async (
if (entries.length === 0) return;
const firstHeld = entries.findIndex((entry) => !canJoinRunningTurn(entry, state));
- const joining = firstHeld === -1 ? entries : entries.slice(0, firstHeld);
- const held = entries.slice(joining.length);
+ const joinable = firstHeld === -1 ? entries : entries.slice(0, firstHeld);
+ // One author per message: a different sender's follow-ups wait their turn.
+ const { agentSender, taken: joining } = takeSameSenderFollowUps(joinable);
+ const held = entries.filter((entry) => !joining.includes(entry));
// Back at the head, for the hand-back at the next decision point. Should
// that fail, they stay in the batch and return when it lapses.
await returnFollowUps(scope, drained, held, 'needs a turn of its own');
@@ -141,6 +144,7 @@ export const injectQueuedFollowUp = async (
editorData: request.userMessage?.editorData,
groupId,
metadata: buildUserTurnMetadata({
+ agentSender,
steer: true,
trigger: request.trigger ?? RequestTrigger.Chat,
}),
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index c2f8610f762..0643810815a 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -1,6 +1,7 @@
import type { AgentRunLlmExecutor } from '@lobechat/agent-runtime';
import type { BotPlatformContext } from '@lobechat/context-engine';
import type {
+ AgentSenderMetadata,
BotSenderMetadata,
ChatTopicBotContext,
ExecAgentParams,
@@ -111,6 +112,13 @@ export interface InternalExecAgentParams extends ExecAgentParams {
additionalPluginIds?: string[];
/** Trusted settings frozen by a durable dispatcher, never accepted from a client. */
agentConfigSnapshot?: LobeAgentConfig;
+ /**
+ * The sending agent of an agent → agent turn, already resolved from its
+ * `sourceOperationId` by the server. Set by a queued follow-up, whose sender
+ * was resolved when it was queued: by the time it starts, the sending run may
+ * have settled and could no longer vouch for it. Never client-passable.
+ */
+ agentSender?: AgentSenderMetadata;
/**
* Server-authored generic intervention claim id. When present, the message
* claim stores this exact id so a retry after dispatch-but-before-publish can
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index 1093c41557c..093feeaafa6 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -6,6 +6,7 @@ import { ContextEngine } from '../../pipeline';
import {
ActivationResultTrimProcessor,
AgentCouncilFlattenProcessor,
+ AgentSenderMessageProcessor,
cacheEconomicsForProvider,
CompressedGroupRoleTransformProcessor,
DisabledToolCallFilter,
@@ -14,6 +15,7 @@ import {
GroupRoleTransformProcessor,
HistoryTruncateProcessor,
InputTemplateProcessor,
+ LH_COMMAND_TOOL_IDENTIFIERS,
MessageCleanupProcessor,
MessageContentProcessor,
PlaceholderMessageFilterProcessor,
@@ -594,6 +596,14 @@ export class MessagesEngine {
// Reaction feedback
new ReactionFeedbackProcessor({ enabled: true }),
+ // Who sent an agent → agent message, and how to reply (string content only)
+ new AgentSenderMessageProcessor({
+ // Enabled now or activatable on demand: either way the agent can run `lh`.
+ canRunLhCommand: [
+ ...(toolsConfig?.manifests ?? []).map((manifest) => manifest.identifier),
+ ...(toolDiscoveryConfig?.availableTools ?? []).map((tool) => tool.identifier),
+ ].some((identifier) => LH_COMMAND_TOOL_IDENTIFIERS.includes(identifier)),
+ }),
// Message content processing (image encoding, multimodal)
new MessageContentProcessor({
canReadAttachment,
diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.agentSender.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.agentSender.test.ts
new file mode 100644
index 00000000000..1002603983e
--- /dev/null
+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.agentSender.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from 'vitest';
+
+import type { UIChatMessage } from '@/types/index';
+
+import { MessagesEngine } from '../MessagesEngine';
+import type { MessagesEngineParams } from '../types';
+
+const agentSentMessages = (): UIChatMessage[] => [
+ {
+ content: 'Please iterate the verifier.',
+ createdAt: 1,
+ id: 'msg_from_writer',
+ metadata: { agentSender: { agentId: 'agt_writer', name: 'Writer', topicId: 'tpc_writer' } },
+ role: 'user',
+ updatedAt: 1,
+ } as UIChatMessage,
+];
+
+const userContent = async (overrides: Partial<MessagesEngineParams>) => {
+ const engine = new MessagesEngine({
+ enableSystemDate: false,
+ messages: agentSentMessages(),
+ model: 'gpt-4',
+ provider: 'openai',
+ ...overrides,
+ });
+ const result = await engine.process();
+ // Injectors may add user messages of their own (e.g. available tools); read the sent one.
+ return result.messages
+ .filter((message) => message.role === 'user')
+ .map((message) =>
+ typeof message.content === 'string' ? message.content : JSON.stringify(message.content),
+ )
+ .find((content) => content.includes('Please iterate the verifier.'));
+};
+
+describe('MessagesEngine — agent-sent messages', () => {
+ it('offers `lh message reply` when the agent can activate a command tool', async () => {
+ const content = await userContent({
+ toolDiscoveryConfig: {
+ availableTools: [
+ { description: 'Run shell commands', identifier: 'lobe-local-system', name: 'Local' },
+ ],
+ },
+ });
+
+ expect(content).toContain('<agent_sender name="Writer"');
+ expect(content).toContain('lh message reply msg_from_writer');
+ });
+
+ it('asks for a relay through the user when no tool can run commands', async () => {
+ const content = await userContent({});
+
+ expect(content).toContain('<agent_sender name="Writer"');
+ expect(content).not.toContain('lh message reply');
+ });
+});
diff --git a/packages/context-engine/src/processors/AgentSenderMessage.ts b/packages/context-engine/src/processors/AgentSenderMessage.ts
new file mode 100644
index 00000000000..c78487edb05
--- /dev/null
+++ b/packages/context-engine/src/processors/AgentSenderMessage.ts
@@ -0,0 +1,111 @@
+import type { AgentSenderMetadata } from '@lobechat/types';
+import debug from 'debug';
+
+import { BaseProcessor } from '../base/BaseProcessor';
+import type { PipelineContext, ProcessorOptions } from '../types';
+
+declare module '../types' {
+ interface PipelineContextMetadataOverrides {
+ agentSenderMessagesProcessed?: number;
+ }
+}
+
+const log = debug('context-engine:processor:AgentSenderMessageProcessor');
+
+/**
+ * Tools that can run the `lh` CLI: a shell on the user's device, or the cloud
+ * sandbox (which routes `lh` commands to LobeHub). Without one of them enabled
+ * or activatable, the receiving agent cannot run `lh message reply`.
+ */
+export const LH_COMMAND_TOOL_IDENTIFIERS = ['lobe-local-system', 'lobe-cloud-sandbox'];
+
+export interface AgentSenderMessageConfig {
+ /**
+ * Whether the receiving agent has a tool that can run `lh` (see
+ * {@link LH_COMMAND_TOOL_IDENTIFIERS}). Without it the header keeps the
+ * attribution but asks for a relay through the user instead of a command it
+ * could never run.
+ */
+ canRunLhCommand?: boolean;
+}
+
+const escapeAttribute = (value: string) =>
+ value.replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll('<', '&lt;');
+
+/**
+ * The header that tells the model who sent an agent → agent message and how to
+ * answer it. Without it the message reads exactly like the person typed it:
+ * the model answers in its own conversation, where the sending agent never
+ * sees the reply.
+ */
+export const formatAgentSenderHeader = (
+ messageId: string,
+ sender: AgentSenderMetadata,
+ { canRunLhCommand = false }: AgentSenderMessageConfig = {},
+) => {
+ const attributes = [
+ ['name', sender.name ?? sender.title],
+ ['agent_id', sender.agentId],
+ ['topic_id', sender.topicId],
+ ['message_id', messageId],
+ ]
+ .filter((entry): entry is [string, string] => !!entry[1])
+ .map(([key, value]) => `${key}="${escapeAttribute(value)}"`)
+ .join(' ');
+
+ // The reply is routed through the message's own origin, so it can only be
+ // offered when the origin was kept (a private source shown in a shared
+ // conversation is not), and only to an agent that can run commands at all.
+ const instruction = !sender.topicId
+ ? 'Sent by another agent, not typed by the user. Its conversation cannot be reached from here, so tell the user if it needs an answer.'
+ : canRunLhCommand
+ ? `Sent by another agent, not typed by the user. To answer that agent, run \`lh message reply ${messageId} -c "<your reply>"\`: the reply wakes its conversation. Your own response here is not delivered to it.`
+ : 'Sent by another agent, not typed by the user. You cannot run commands here, so you cannot answer that agent directly and your response stays in this conversation: if it needs an answer, tell the user so they can pass it on.';
+
+ return `<agent_sender ${attributes}>${instruction}</agent_sender>`;
+};
+
+/**
+ * Agent Sender Message Processor
+ *
+ * A user message another agent sent (`lh topic send`, `lh message reply`,
+ * `lh agent run`) carries `metadata.agentSender`, which the UI renders as the
+ * author. This puts the same fact in front of the model, with how to reply.
+ *
+ * Must run before {@link MessageContentProcessor}, while user content is still
+ * a string.
+ */
+export class AgentSenderMessageProcessor extends BaseProcessor {
+ readonly name = 'AgentSenderMessageProcessor';
+
+ constructor(
+ private config: AgentSenderMessageConfig = {},
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const clonedContext = this.cloneContext(context);
+ let processedCount = 0;
+
+ for (let i = 0; i < clonedContext.messages.length; i++) {
+ const message = clonedContext.messages[i];
+ const sender = message.metadata?.agentSender as AgentSenderMetadata | undefined;
+ if (message.role !== 'user' || !sender?.agentId || typeof message.content !== 'string') {
+ continue;
+ }
+
+ clonedContext.messages[i] = {
+ ...message,
+ content: `${formatAgentSenderHeader(message.id, sender, this.config)}\n\n${message.content}`,
+ };
+ processedCount++;
+ }
+
+ clonedContext.metadata.agentSenderMessagesProcessed = processedCount;
+ log('Marked %d agent-sent messages', processedCount);
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/processors/__tests__/AgentSenderMessage.test.ts b/packages/context-engine/src/processors/__tests__/AgentSenderMessage.test.ts
new file mode 100644
index 00000000000..725733458ed
--- /dev/null
+++ b/packages/context-engine/src/processors/__tests__/AgentSenderMessage.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from 'vitest';
+
+import { AgentSenderMessageProcessor } from '../AgentSenderMessage';
+
+const createContext = (messages: any[]) => ({
+ initialState: {
+ messages: [],
+ model: 'gpt-4',
+ provider: 'openai',
+ systemRole: '',
+ tools: [],
+ },
+ isAborted: false,
+ messages,
+ metadata: {
+ maxTokens: 4096,
+ model: 'gpt-4',
+ },
+});
+
+const message = (id: string, role: string, content: any, metadata?: Record<string, unknown>) => ({
+ content,
+ createdAt: 1,
+ id,
+ role,
+ updatedAt: 1,
+ ...(metadata ? { metadata } : {}),
+});
+
+describe('AgentSenderMessageProcessor', () => {
+ it('tells the model who sent the message and how to reply to it', async () => {
+ const result = await new AgentSenderMessageProcessor({ canRunLhCommand: true }).process(
+ createContext([
+ message('msg_1', 'user', 'Please iterate the verifier.', {
+ agentSender: { agentId: 'agt_a', hop: 1, name: 'Writer "W"', topicId: 'tpc_src' },
+ }),
+ ]),
+ );
+
+ expect(result.messages[0].content).toBe(
+ '<agent_sender name="Writer &quot;W&quot;" agent_id="agt_a" topic_id="tpc_src" message_id="msg_1">' +
+ 'Sent by another agent, not typed by the user. To answer that agent, run ' +
+ '`lh message reply msg_1 -c "<your reply>"`: the reply wakes its conversation. ' +
+ 'Your own response here is not delivered to it.</agent_sender>\n\nPlease iterate the verifier.',
+ );
+ expect(result.metadata.agentSenderMessagesProcessed).toBe(1);
+ });
+
+ // ROOT CAUSE:
+ //
+ // The header told every receiving agent to run `lh message reply`, including
+ // one in chat mode or with a custom tool set that has no way to run a
+ // command — the report-back it promised could never happen.
+ //
+ // Before: the command was offered unconditionally.
+ // After: only with a tool that can run `lh`; otherwise relay via the user.
+ it('keeps the attribution but asks for a relay when the agent cannot run commands', async () => {
+ const result = await new AgentSenderMessageProcessor().process(
+ createContext([
+ message('msg_1', 'user', 'hi', {
+ agentSender: { agentId: 'agt_a', name: 'Writer', topicId: 'tpc_src' },
+ }),
+ ]),
+ );
+
+ const content = result.messages[0].content as string;
+ expect(content).toContain('name="Writer" agent_id="agt_a" topic_id="tpc_src"');
+ expect(content).not.toContain('lh message reply');
+ expect(content).toContain('tell the user so they can pass it on');
+ });
+
+ it('offers no reply when the origin was not kept', async () => {
+ const result = await new AgentSenderMessageProcessor({ canRunLhCommand: true }).process(
+ createContext([message('msg_1', 'user', 'hi', { agentSender: { agentId: 'agt_a' } })]),
+ );
+
+ expect(result.messages[0].content).not.toContain('lh message reply');
+ expect(result.messages[0].content).toContain('agent_id="agt_a"');
+ });
+
+ it('leaves messages a person wrote, and non-user messages, untouched', async () => {
+ const messages = [
+ message('msg_1', 'user', 'typed by a person'),
+ message('msg_2', 'assistant', 'answer', { agentSender: { agentId: 'agt_a' } }),
+ message('msg_3', 'user', [{ text: 'already parts', type: 'text' }], {
+ agentSender: { agentId: 'agt_a' },
+ }),
+ ];
+
+ const result = await new AgentSenderMessageProcessor().process(createContext(messages));
+
+ expect(result.messages.map((m: any) => m.content)).toEqual(messages.map((m) => m.content));
+ expect(result.metadata.agentSenderMessagesProcessed).toBe(0);
+ });
+});
diff --git a/packages/context-engine/src/processors/index.ts b/packages/context-engine/src/processors/index.ts
index 3b7ba4fa702..41b3e47f700 100644
--- a/packages/context-engine/src/processors/index.ts
+++ b/packages/context-engine/src/processors/index.ts
@@ -4,6 +4,12 @@ export {
ActivationResultTrimProcessor,
} from './ActivationResultTrim';
export { AgentCouncilFlattenProcessor } from './AgentCouncilFlatten';
+export {
+ type AgentSenderMessageConfig,
+ AgentSenderMessageProcessor,
+ formatAgentSenderHeader,
+ LH_COMMAND_TOOL_IDENTIFIERS,
+} from './AgentSenderMessage';
export { CompressedGroupRoleTransformProcessor } from './CompressedGroupRoleTransform';
export { DisabledToolCallFilter } from './DisabledToolCallFilter';
export { GroupMessageFlattenProcessor } from './GroupMessageFlatten';
diff --git a/packages/database/src/models/__tests__/messages/message.userTurnHop.test.ts b/packages/database/src/models/__tests__/messages/message.userTurnHop.test.ts
new file mode 100644
index 00000000000..0370c828c42
--- /dev/null
+++ b/packages/database/src/models/__tests__/messages/message.userTurnHop.test.ts
@@ -0,0 +1,130 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { messages, threads, topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { MessageModel } from '../../message';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'user-turn-hop-user';
+const otherUserId = 'user-turn-hop-other';
+const messageModel = new MessageModel(serverDB, userId);
+
+const at = (minute: number) => new Date(Date.UTC(2026, 9, 30, 10, minute));
+
+beforeEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(topics).values([
+ { id: 'hop-topic', userId },
+ { id: 'hop-other-topic', userId: otherUserId },
+ ]);
+ await serverDB
+ .insert(threads)
+ .values({ id: 'hop-thread', topicId: 'hop-topic', type: 'isolation', userId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+});
+
+describe('MessageModel.findLatestUserTurnHop', () => {
+ it('reads the hop of the newest user message, ignoring other roles', async () => {
+ await serverDB.insert(messages).values([
+ {
+ content: 'from an agent',
+ createdAt: at(1),
+ id: 'hop-1',
+ metadata: { agentSender: { agentId: 'agt-a', hop: 2 } },
+ role: 'user',
+ topicId: 'hop-topic',
+ userId,
+ },
+ {
+ content: 'reply',
+ createdAt: at(2),
+ id: 'hop-2',
+ role: 'assistant',
+ topicId: 'hop-topic',
+ userId,
+ },
+ ]);
+
+ await expect(messageModel.findLatestUserTurnHop({ topicId: 'hop-topic' })).resolves.toBe(2);
+ });
+
+ it('is undefined once a person wrote the newest user message', async () => {
+ await serverDB.insert(messages).values([
+ {
+ content: 'from an agent',
+ createdAt: at(1),
+ id: 'hop-1',
+ metadata: { agentSender: { agentId: 'agt-a', hop: 3 } },
+ role: 'user',
+ topicId: 'hop-topic',
+ userId,
+ },
+ {
+ content: 'typed',
+ createdAt: at(2),
+ id: 'hop-2',
+ role: 'user',
+ topicId: 'hop-topic',
+ userId,
+ },
+ ]);
+
+ await expect(
+ messageModel.findLatestUserTurnHop({ topicId: 'hop-topic' }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('keeps the main transcript and a thread apart', async () => {
+ await serverDB.insert(messages).values([
+ {
+ content: 'main',
+ createdAt: at(1),
+ id: 'hop-main',
+ metadata: { agentSender: { agentId: 'agt-a', hop: 1 } },
+ role: 'user',
+ topicId: 'hop-topic',
+ userId,
+ },
+ {
+ content: 'thread',
+ createdAt: at(2),
+ id: 'hop-thread-msg',
+ metadata: { agentSender: { agentId: 'agt-a', hop: 4 } },
+ role: 'user',
+ threadId: 'hop-thread',
+ topicId: 'hop-topic',
+ userId,
+ },
+ ]);
+
+ await expect(messageModel.findLatestUserTurnHop({ topicId: 'hop-topic' })).resolves.toBe(1);
+ await expect(
+ messageModel.findLatestUserTurnHop({ threadId: 'hop-thread', topicId: 'hop-topic' }),
+ ).resolves.toBe(4);
+ });
+
+ it("does not read another user's conversation", async () => {
+ await serverDB.insert(messages).values({
+ content: 'theirs',
+ id: 'hop-foreign',
+ metadata: { agentSender: { agentId: 'agt-a', hop: 2 } },
+ role: 'user',
+ topicId: 'hop-other-topic',
+ userId: otherUserId,
+ });
+
+ await expect(
+ messageModel.findLatestUserTurnHop({ topicId: 'hop-other-topic' }),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/packages/database/src/models/message/index.ts b/packages/database/src/models/message/index.ts
index d06d66944a2..bf07b249515 100644
--- a/packages/database/src/models/message/index.ts
+++ b/packages/database/src/models/message/index.ts
@@ -35,6 +35,7 @@ export class MessageModel {
findShareVisitorMessageIds: MessageLookupQueries['findShareVisitorMessageIds'];
findByClientId: MessageLookupQueries['findByClientId'];
findLatestAssistantMessageByThread: MessageLookupQueries['findLatestAssistantMessageByThread'];
+ findLatestUserTurnHop: MessageLookupQueries['findLatestUserTurnHop'];
findVerifyMessageByOperationId: MessageLookupQueries['findVerifyMessageByOperationId'];
findLatestAssistantByOperationId: MessageLookupQueries['findLatestAssistantByOperationId'];
listLatestTurnAssistantContents: MessageLookupQueries['listLatestTurnAssistantContents'];
@@ -155,6 +156,7 @@ export class MessageModel {
this.findShareVisitorMessageIds = lookups.findShareVisitorMessageIds;
this.findByClientId = lookups.findByClientId;
this.findLatestAssistantMessageByThread = lookups.findLatestAssistantMessageByThread;
+ this.findLatestUserTurnHop = lookups.findLatestUserTurnHop;
this.findVerifyMessageByOperationId = lookups.findVerifyMessageByOperationId;
this.findLatestAssistantByOperationId = lookups.findLatestAssistantByOperationId;
this.listLatestTurnAssistantContents = lookups.listLatestTurnAssistantContents;
diff --git a/packages/database/src/models/message/lookup.ts b/packages/database/src/models/message/lookup.ts
index 9d84edd1b70..e0d94728916 100644
--- a/packages/database/src/models/message/lookup.ts
+++ b/packages/database/src/models/message/lookup.ts
@@ -146,6 +146,37 @@ export class MessageLookupQueries extends MessageScope {
),
});
+ /**
+ * The agent relay hop (`metadata.agentSender.hop`) of the newest user
+ * message in a conversation — the main transcript, or one thread — or
+ * undefined when a person wrote it. Read when an agent turn sends to another
+ * conversation, to count how many agent → agent sends led to it.
+ */
+ findLatestUserTurnHop = async ({
+ threadId,
+ topicId,
+ }: {
+ threadId?: string;
+ topicId: string;
+ }): Promise<number | undefined> => {
+ const [row] = await this.db
+ .select({ hop: sql<null | string>`${messages.metadata}->'agentSender'->>'hop'` })
+ .from(messages)
+ .where(
+ and(
+ this.ownership(),
+ eq(messages.topicId, topicId),
+ threadId ? eq(messages.threadId, threadId) : isNull(messages.threadId),
+ eq(messages.role, 'user'),
+ ),
+ )
+ .orderBy(desc(messages.createdAt), desc(messages.id))
+ .limit(1);
+
+ const hop = Number(row?.hop);
+ return Number.isInteger(hop) && hop > 0 ? hop : undefined;
+ };
+
/**
* Resolve the `role='verify'` delivery-checker card for an Agent Run (created
* with `metadata.verifyOperationId = operationId`). Used by auto-repair to
diff --git a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
index 3803d58dae0..d5a253611a1 100644
--- a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
+++ b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
@@ -78,6 +78,7 @@ const lobeHubCliGuideBody = [
'- **When to use it:** only when the user asks for something that lives in LobeHub rather than in this working directory — saving a document, recalling an earlier conversation, generating an image, or changing your own agent configuration. A request about local files, code or another tool does not need `lh`. Say what you did and where it landed.',
"- **You already know where you are.** `LOBEHUB_TOPIC_ID` (this conversation) and `LOBEHUB_OPERATION_ID` (this run) are in your environment, and `LOBEHUB_AGENT_ID` (you) and `LOBEHUB_WORKSPACE_ID` (the workspace this conversation belongs to, which scopes every `lh` call) are too whenever the run carries them. They are ordinary environment variables, so every sub-shell, script or tool you spawn inherits them. Pass them straight to commands rather than listing agents or topics to find yourself; if the one you need is empty, say so instead of guessing an id. LobeHub topic ids start with `tpc_` — an id in the user's message without that prefix belongs to something else.",
'- **Earlier conversations:** read one with `lh topic view <id>`. This run can always read its own conversation and the ones the user names in it (a `tpc_…` id or a `<refer_topic>` tag); for any other, ask the user to name it here.',
+ '- **Talking to another conversation:** `lh topic send <tpc_id> -c "…"` delivers a message to that conversation and has its agent act on it (queued behind its current turn if it is busy). `lh message create` only writes a row — nobody sees or answers it. A message another agent sent you starts with an `<agent_sender>` header; answer it with `lh message reply <message_id> -c "…"`, which wakes the sender\'s conversation. Your ordinary response is not delivered to that agent.',
'- **If `lh` is older than this app**, the shell may have found a stale global install first: `lh man` lacks a command you expect, or `lh` reports an unknown command. When `LOBEHUB_CLI` is set it is the path of the CLI this app ships — run that path instead of `lh` for the rest of the session.',
'- **Look commands up, do not guess them.** `lh man` lists every command, and `lh man <command>` (e.g. `lh man doc create`) prints the manual for the CLI actually installed here, including exactly which flags that command takes. Many commands offer `--json` for structured output, but not all of them — the manual is what says so, and an invented flag just fails the call.',
'- **What it reaches:** `lh kb` knowledge bases · `lh doc` documents · `lh file` files · `lh artifact` artifacts · `lh topic` / `lh message` past conversations · `lh agent` agents · `lh task` / `lh project` work · `lh widget` / `lh dashboard` monitoring widgets and dashboards · `lh search` local resources and the web · `lh recall` past messages, topics, goals and pages in a time window · `lh gen` text/image/video/TTS/ASR generation · `lh memory` user memory · `lh notify` notifications to the user · `lh model` / `lh provider` / `lh plugin` / `lh skill` platform configuration · `lh bot` chat-platform bots.',
diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.ts
index a1fd100fd6a..4b12e4dcd0f 100644
--- a/packages/types/src/message/common/metadata.ts
+++ b/packages/types/src/message/common/metadata.ts
@@ -236,6 +236,13 @@ export interface AgentSenderMetadata {
* own conversation instead of the group the turn actually came from.
*/
chatGroupId?: string;
+ /**
+ * How many agent → agent sends in a row led to this message: 1 when the
+ * sending turn was started by a person, one more than the message that
+ * started the sending turn otherwise. The server refuses a send past
+ * `MAX_AGENT_RELAY_HOPS`, so two agents cannot keep waking each other.
+ */
+ hop?: number;
/** Sending agent's personal name at send time; resolve the label with `agentDisplayName`. */
name?: string;
/**
@@ -266,6 +273,7 @@ export const AgentSenderMetadataSchema = z.object({
agentId: z.string(),
avatar: z.string().optional(),
chatGroupId: z.string().optional(),
+ hop: z.number().int().positive().optional(),
name: z.string().optional(),
threadId: z.string().optional(),
title: z.string().optional(),