Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(channel): turn @Name in Agent replies into real mentions with a ping-pong limit (#23288)

Arvin Xua1b0dc2ddcc1
diff --git a/apps/server/src/services/channel/ChannelCoordinator.silence.test.ts b/apps/server/src/services/channel/ChannelCoordinator.silence.test.ts
index 5fe7d591b6d..dcbfb866a87 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.silence.test.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.silence.test.ts
@@ -7,6 +7,9 @@ const { executions, findLatest } = vi.hoisted(() => ({
executions: {
accepted: vi.fn(),
deliverAnswerToAsker: vi.fn(),
+ deliverReplyMentions: vi
+ .fn()
+ .mockResolvedValue({ mentions: [], woke: false, workspaceId: null }),
publish: vi.fn(),
// An untouched reservation short-circuits the physical stop: not what these tests are about.
retireReservation: vi.fn().mockResolvedValue(true),
diff --git a/apps/server/src/services/channel/ChannelCoordinator.test.ts b/apps/server/src/services/channel/ChannelCoordinator.test.ts
index 6a80c49bb7c..d291ec73039 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.test.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.test.ts
@@ -8,6 +8,9 @@ const { executions, executeToolCall, interruptTask } = vi.hoisted(() => ({
executions: {
input: vi.fn(),
deliverAnswerToAsker: vi.fn(),
+ deliverReplyMentions: vi
+ .fn()
+ .mockResolvedValue({ mentions: [], woke: false, workspaceId: null }),
publish: vi.fn(),
releaseWriter: vi.fn(),
retireReservation: vi.fn().mockResolvedValue(false),
diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.ts
index 2dc71790abe..cb0ddc9b587 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.ts
@@ -32,6 +32,7 @@ import { SystemAgentService } from '@/server/services/systemAgent';
import { reportAgentExchange } from './agentExchange';
import { resolveChannelAttachments } from './attachments';
import { ChannelRoutingService } from './ChannelRoutingService';
+import { notifyChannelMentions } from './mention';
import { notifyChannel } from './notify';
import { registerLocalChannelAdvance, wakeChannel } from './queue';
import { deliverRelayReceipt } from './relayReceipt';
@@ -436,7 +437,26 @@ export class ChannelCoordinator {
}
const replyMessageId = await this.executions.publish(channelId, jobId);
await this.stopWriters([job]);
+ // `@Name` in the reply addresses people and Agents like a person's mention does.
+ const mentioned = await this.executions
+ .deliverReplyMentions(channelId, replyMessageId)
+ .catch((error) => {
+ console.error('[channel:reply-mentions]', error);
+ return undefined;
+ });
await notifyChannel(this.db, channelId);
+ if (mentioned?.mentions.length && operation.userId)
+ notifyChannelMentions(
+ this.db,
+ {
+ // The Agent wrote it, so the person it ran for is notified like anyone else.
+ includeActor: true,
+ userId: operation.userId,
+ workspaceId: mentioned.workspaceId ?? undefined,
+ },
+ { channelId, id: replyMessageId, mentions: mentioned.mentions },
+ );
+ if (mentioned?.woke) await wakeChannel(channelId);
// Between Agents, an answer wakes the Agent that asked, and what that Agent concludes from
// it is posted where its asking began.
if (await this.executions.deliverAnswerToAsker(channelId, replyMessageId))
diff --git a/apps/server/src/services/channel/README.md b/apps/server/src/services/channel/README.md
index bf92c1f7c84..1c4dda915fe 100644
--- a/apps/server/src/services/channel/README.md
+++ b/apps/server/src/services/channel/README.md
@@ -251,6 +251,15 @@ chosen Agents (`ChannelMessagingService`).
Agent's own message (`postAgentMessage`, with `metadata.receipt` linking back and naming the
answering Agent in `receipt.agent`; the timeline shows a "Messages from <Agent>" line above it). Asking again
from that run continues the exchange (`hops + 1`) up to three asks; the answering Agent's run (`requestByAgent`) cannot pass the question on. `deliverRelayReceipt` skips Agent-written requests.
+- **@mentions in replies.** An Agent's published reply has its `@Name` text turned into real
+ mentions (`ChannelExecutionRepository.deliverReplyMentions`, called from
+ `ChannelCoordinator.complete`): the reply is parsed as Markdown (remark + GFM) and only its
+ text nodes are matched against active members, like the timeline highlight. Code, link and
+ image destinations, HTML and an autolink's own address never count; the replying Agent itself
+ is skipped. People are notified; each mentioned Agent is queued on the reply for the same requester and follows the Thread. The reply records the
+ Agent-to-Agent hops since a person spoke (`metadata.mentionHops`); past
+ `MAX_REPLY_MENTION_HOPS` (3) the mentions are still recorded but wake no one. A conversation
+ between two Agents only records them; its exchange has its own limit.
- **External runtimes.** `lh channel list` and `lh channel send` call the same service through
`channel.listChannels` / `channel.sendMessage`, authorised by the run's operation token with
the `channel:message` capability that every Channel dispatch is minted alongside
diff --git a/apps/server/src/services/channel/mention.ts b/apps/server/src/services/channel/mention.ts
index 6b5d2f43f46..6ecfb694615 100644
--- a/apps/server/src/services/channel/mention.ts
+++ b/apps/server/src/services/channel/mention.ts
@@ -18,10 +18,11 @@ interface MentionedMessage {
*/
export const notifyChannelMentions = (
db: LobeChatDatabase,
- context: { userId: string; workspaceId?: string },
+ /** `includeActor` notifies `userId` too: an Agent wrote the message on their behalf. */
+ context: { includeActor?: boolean; userId: string; workspaceId?: string },
message: MentionedMessage,
) => {
- const { userId, workspaceId } = context;
+ const { includeActor, userId, workspaceId } = context;
if (!workspaceId || !message.mentions.length) return;
after(async () => {
@@ -48,7 +49,7 @@ export const notifyChannelMentions = (
);
const recipientUserIds = [
...new Set(members.flatMap((member) => (member.userId ? [member.userId] : []))),
- ].filter((id) => id !== userId);
+ ].filter((id) => includeActor || id !== userId);
if (!recipientUserIds.length) return;
await notifyChannelMention({
diff --git a/packages/database/package.json b/packages/database/package.json
index 1b9834bc076..ff627d667c7 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -24,9 +24,13 @@
"@lobechat/utils": "workspace:*",
"p-map": "^7.0.6",
"random-words": "^2.0.1",
+ "remark-gfm": "^4.0.1",
+ "remark-parse": "^11.0.0",
"remove-markdown": "^0.6.4",
"ts-md5": "^2.0.1",
"type-fest": "^5.7.0",
+ "unified": "^11.0.5",
+ "unist-util-visit": "^5.1.0",
"ws": "^8.21.0"
},
"devDependencies": {
diff --git a/packages/database/src/repositories/channel/__tests__/replyMentions.test.ts b/packages/database/src/repositories/channel/__tests__/replyMentions.test.ts
new file mode 100644
index 00000000000..385daec0aed
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/replyMentions.test.ts
@@ -0,0 +1,121 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { channelMessages } from '../../../schemas';
+import { ChannelExecutionRepository } from '..';
+import { MAX_REPLY_MENTION_HOPS } from '../replyMentions';
+import { createChannelFixture, jobsOf, lease } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-reply-mentions');
+const execution = new ChannelExecutionRepository(db);
+beforeEach(fixture.setup);
+afterEach(fixture.cleanup);
+
+const setup = async () => {
+ const team = await fixture.createTeamChannel();
+ const alpha = await fixture.addAgent(team.channel.id, 'Alpha');
+ const beta = await fixture.addAgent(team.channel.id, 'Beta');
+ const channelId = team.channel.id;
+
+ /** Runs the job `memberId` has on `messageId` and publishes `content` as its reply. */
+ const answer = async (messageId: string, memberId: string, content: string) => {
+ const job = (await jobsOf(db, messageId)).find((item) => item.memberId === memberId)!;
+ await execution.claim(channelId, job.id, lease);
+ await execution.accepted(channelId, job.id);
+ await execution.saveDraft(channelId, job.id, content);
+ const replyId = await execution.publish(channelId, job.id);
+ await execution.releaseWriter(channelId, job.id);
+ return replyId;
+ };
+ const reply = async (id: string) =>
+ (await db.select().from(channelMessages).where(eq(channelMessages.id, id)))[0];
+
+ const request = await team.asOwner.send(channelId, {
+ content: '@Alpha start',
+ mentions: [alpha.id],
+ requestKey: 'person',
+ routing: 'fallback',
+ });
+
+ return { alpha, answer, beta, channelId, reply, request, team };
+};
+
+describe('@mentions in Agent replies', () => {
+ it('records them and wakes the mentioned Agent for the same requester', async () => {
+ const { alpha, answer, beta, channelId, reply, request, team } = await setup();
+ const replyId = await answer(request.id, alpha.id, '@Beta please review, `@Alpha` stays code');
+
+ const result = await execution.deliverReplyMentions(channelId, replyId);
+ expect(result).toMatchObject({ mentions: [beta.id], woke: true });
+ expect(await reply(replyId)).toMatchObject({
+ mentions: [beta.id],
+ metadata: { mentionHops: 1 },
+ });
+ const [job] = await jobsOf(db, replyId);
+ expect(job).toMatchObject({ memberId: beta.id, requesterMemberId: team.owner.id });
+
+ // Idempotent: a retried completion queues nothing more.
+ expect(await execution.deliverReplyMentions(channelId, replyId)).toMatchObject({
+ mentions: [],
+ woke: false,
+ });
+ expect(await jobsOf(db, replyId)).toHaveLength(1);
+ });
+
+ it('ignores the replying Agent naming itself', async () => {
+ const { alpha, answer, channelId, request } = await setup();
+ const replyId = await answer(request.id, alpha.id, 'I am @Alpha');
+
+ expect(await execution.deliverReplyMentions(channelId, replyId)).toMatchObject({
+ mentions: [],
+ woke: false,
+ });
+ });
+
+ it("never resolves the speaker's own name to a shorter or shared one", async () => {
+ const team = await fixture.createTeamChannel();
+ const speaker = await fixture.addAgent(team.channel.id, 'Sam Smith');
+ // A shorter name it starts with, and another member sharing it.
+ await fixture.addAgent(team.channel.id, 'Sam');
+ await fixture.addAgent(team.channel.id, 'Sam Smith');
+ const request = await team.asOwner.send(team.channel.id, {
+ content: '@Sam Smith start',
+ mentions: [speaker.id],
+ requestKey: 'person',
+ routing: 'fallback',
+ });
+ const [job] = (await jobsOf(db, request.id)).filter((item) => item.memberId === speaker.id);
+ await execution.claim(team.channel.id, job.id, lease);
+ await execution.accepted(team.channel.id, job.id);
+ await execution.saveDraft(team.channel.id, job.id, 'I am @Sam Smith');
+ const replyId = await execution.publish(team.channel.id, job.id);
+
+ expect(await execution.deliverReplyMentions(team.channel.id, replyId)).toMatchObject({
+ mentions: [],
+ woke: false,
+ });
+ expect(await jobsOf(db, replyId)).toEqual([]);
+ });
+
+ it('stops waking after the ping-pong limit but keeps the mention', async () => {
+ const { alpha, answer, beta, channelId, reply, request } = await setup();
+ let messageId = request.id;
+ let speaker = alpha;
+ for (let hop = 1; hop <= MAX_REPLY_MENTION_HOPS + 1; hop++) {
+ const other = speaker.id === alpha.id ? beta : alpha;
+ const replyId = await answer(messageId, speaker.id, `@${other.name} your turn`);
+ const result = await execution.deliverReplyMentions(channelId, replyId);
+ expect(result.mentions).toEqual([other.id]);
+ expect(result.woke).toBe(hop <= MAX_REPLY_MENTION_HOPS);
+ if (hop > MAX_REPLY_MENTION_HOPS) {
+ expect(await jobsOf(db, replyId)).toEqual([]);
+ expect((await reply(replyId)).metadata).not.toHaveProperty('mentionHops');
+ }
+ messageId = replyId;
+ speaker = other;
+ }
+ });
+});
diff --git a/packages/database/src/repositories/channel/execution.ts b/packages/database/src/repositories/channel/execution.ts
index a69e48971d9..7e5fd262039 100644
--- a/packages/database/src/repositories/channel/execution.ts
+++ b/packages/database/src/repositories/channel/execution.ts
@@ -13,15 +13,18 @@ import {
channelMembers,
channelMessages,
channels,
+ channelThreads,
+ users,
} from '../../schemas';
import type { LobeChatDatabase, Transaction } from '../../type';
import type { ChannelClaim, ChannelClaimOptions } from './claim';
import { claimJob } from './claim';
-import { appendMessage, deliver } from './delivery';
+import { activeMembers, appendMessage, deliver } from './delivery';
import { ChannelError } from './error';
import { countManifestMessages, readManifestMessages } from './manifest';
import type { ChannelOpeningDecision } from './opening';
import { applyOpening, findCoAddressed, findOpeningCandidate, findOpeningReply } from './opening';
+import { findTextMentions, MAX_REPLY_MENTION_HOPS, replyMentionHops } from './replyMentions';
import type { ChannelRoutingDecision } from './routing';
import { resolveRouting } from './routing';
import type { ChannelStopScope } from './stop';
@@ -543,6 +546,120 @@ export class ChannelExecutionRepository {
return true;
});
+ /**
+ * Turns the `@Name` text of a published reply into real mentions: records them on the reply,
+ * so people are notified and see it in their mentions, and queues each mentioned Agent on it,
+ * for the same requester, unless the exchange already took {@link MAX_REPLY_MENTION_HOPS}
+ * Agent-to-Agent hops since a person spoke. A conversation between two Agents has its own
+ * exchange and only records them. Idempotent: a retry finds the mentions already recorded.
+ */
+ deliverReplyMentions = async (
+ channelId: string,
+ replyMessageId: string,
+ ): Promise<{ mentions: string[]; woke: boolean; workspaceId: string | null }> =>
+ withChannelLock(this.db, channelId, async (tx) => {
+ const [row] = await tx
+ .select({ channel: channels, reply: channelMessages })
+ .from(channelMessages)
+ .innerJoin(channels, eq(channels.id, channelMessages.channelId))
+ .where(
+ and(eq(channelMessages.channelId, channelId), eq(channelMessages.id, replyMessageId)),
+ )
+ .limit(1);
+ const none = { mentions: [], woke: false, workspaceId: row?.channel.workspaceId ?? null };
+ if (!row || row.reply.routingStatus !== 'reply' || row.reply.mentions.length) return none;
+ const [job] = await tx
+ .select({
+ memberId: channelJobs.memberId,
+ requesterMemberId: channelJobs.requesterMemberId,
+ })
+ .from(channelJobs)
+ .where(
+ and(
+ eq(channelJobs.channelId, channelId),
+ eq(channelJobs.publishedMessageId, replyMessageId),
+ ),
+ )
+ .limit(1);
+ if (!job) return none;
+
+ const members = await tx
+ .select({
+ actorType: channelMembers.actorType,
+ id: channelMembers.id,
+ name: sql<string>`coalesce(nullif(${channelMembers.name}, ''), nullif(${users.fullName}, ''), ${users.username}, '')`,
+ })
+ .from(channelMembers)
+ .leftJoin(users, eq(users.id, channelMembers.userId))
+ .where(and(eq(channelMembers.channelId, channelId), eq(channelMembers.status, 'active')));
+ // Resolve against everyone, the speaker included, so a longer or shared name is still
+ // recognised as the speaker's; only then drop the speaker naming itself.
+ const mentions = findTextMentions(row.reply.content, members).filter(
+ (id) => id !== job.memberId,
+ );
+ if (!mentions.length) return none;
+
+ const [request] = row.reply.replyToId
+ ? await tx
+ .select({
+ metadata: channelMessages.metadata,
+ routingStatus: channelMessages.routingStatus,
+ })
+ .from(channelMessages)
+ .where(
+ and(
+ eq(channelMessages.channelId, channelId),
+ eq(channelMessages.id, row.reply.replyToId),
+ ),
+ )
+ .limit(1)
+ : [];
+ // Only a person's message resets the count; an Agent's reply carries the hops so far.
+ const hops =
+ (request?.routingStatus === 'reply' ? replyMentionHops(request.metadata) : 0) + 1;
+ const agentIds = new Set(
+ members.filter((member) => member.actorType === 'agent').map((member) => member.id),
+ );
+ const targets =
+ row.channel.agentPairKey || hops > MAX_REPLY_MENTION_HOPS
+ ? []
+ : await activeMembers(
+ tx,
+ channelId,
+ mentions.filter((id) => agentIds.has(id)),
+ );
+
+ await tx
+ .update(channelMessages)
+ .set({
+ mentions,
+ ...(targets.length && { metadata: { ...row.reply.metadata, mentionHops: hops } }),
+ })
+ .where(eq(channelMessages.id, replyMessageId));
+ if (row.reply.threadId) {
+ // Like a person's mention, the mentioned follow the Thread they were called into.
+ const [thread] = await tx
+ .select({ followerMemberIds: channelThreads.followerMemberIds })
+ .from(channelThreads)
+ .where(eq(channelThreads.id, row.reply.threadId));
+ if (thread && mentions.some((id) => !thread.followerMemberIds.includes(id)))
+ await tx
+ .update(channelThreads)
+ .set({ followerMemberIds: [...new Set([...thread.followerMemberIds, ...mentions])] })
+ .where(eq(channelThreads.id, row.reply.threadId));
+ }
+ const woke = targets.length
+ ? (await deliver(tx, { ...row.reply, mentions }, targets, job.requesterMemberId)).length > 0
+ : false;
+ await audit(tx, channelId, 'reply_mentioned', replyMessageId, {
+ hops,
+ mentions,
+ woke: targets.map((target) => target.id),
+ });
+
+ return { mentions, woke, workspaceId: row.channel.workspaceId };
+ });
+
/**
* The run chose not to answer a `followup` wake (`NO_REPLY`). Settles the job as `silent`:
* nothing is published, and its conversation stays reusable like a published reply's. Only a
diff --git a/packages/database/src/repositories/channel/replyMentions.test.ts b/packages/database/src/repositories/channel/replyMentions.test.ts
new file mode 100644
index 00000000000..f6215c5a989
--- /dev/null
+++ b/packages/database/src/repositories/channel/replyMentions.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from 'vitest';
+
+import { findTextMentions, replyMentionHops } from './replyMentions';
+
+const members = [
+ { id: 'arvin', name: 'Arvin Xu' },
+ { id: 'pi', name: 'Pi' },
+ { id: 'pilot', name: 'Pilot' },
+];
+
+describe('findTextMentions', () => {
+ it('matches names that end at a space, punctuation or the end', () => {
+ expect(findTextMentions('@Arvin Xu 拉到了', members)).toEqual(['arvin']);
+ expect(findTextMentions('问下 @Pi,再看 @Pilot', members)).toEqual(['pi', 'pilot']);
+ expect(findTextMentions('@Arvin Xu', members)).toEqual(['arvin']);
+ });
+
+ it('never matches a name inside a longer word', () => {
+ expect(findTextMentions('@Pix', members)).toEqual([]);
+ });
+
+ it('ignores code', () => {
+ expect(findTextMentions('`@Pi` and\n```\n@Pilot\n```', members)).toEqual([]);
+ });
+
+ it('ignores fenced blocks opened with tildes or a longer run', () => {
+ expect(findTextMentions('~~~\n@Pi\n~~~', members)).toEqual([]);
+ expect(findTextMentions('````md\n```\n@Pi\n```\n````', members)).toEqual([]);
+ });
+
+ it('ignores indented code blocks', () => {
+ expect(findTextMentions('示例:\n\n @Pi\n @Pilot', members)).toEqual([]);
+ expect(findTextMentions('\t@Pi', members)).toEqual([]);
+ });
+
+ it('still reads an indented line that continues a paragraph', () => {
+ expect(findTextMentions('@Pi 接着写\n 这一行还是同一段', members)).toEqual(['pi']);
+ });
+
+ it('ignores code spans of any backtick length, including multiline ones', () => {
+ expect(findTextMentions('``a ` @Pi``', members)).toEqual([]);
+ expect(findTextMentions('`@Pi\n@Pilot`', members)).toEqual([]);
+ });
+
+ it('reads a mention after an unmatched backtick run', () => {
+ expect(findTextMentions('`` @Pi', members)).toEqual(['pi']);
+ });
+
+ it('ignores link and image destinations but reads link text', () => {
+ expect(findTextMentions('[profile](https://example.com/@Pi)', members)).toEqual([]);
+ expect(findTextMentions('![@Pi](https://example.com/@Pilot.png)', members)).toEqual([]);
+ expect(findTextMentions('[ask @Pi](https://example.com)', members)).toEqual(['pi']);
+ expect(findTextMentions('[x][ref]\n\n[ref]: https://example.com/@Pi', members)).toEqual([]);
+ });
+
+ it('ignores the address of a bare or bracketed link', () => {
+ expect(findTextMentions('见 https://example.com/@Pi 的主页', members)).toEqual([]);
+ expect(findTextMentions('<https://example.com/@Pilot>', members)).toEqual([]);
+ expect(findTextMentions('www.example.com/@Pi', members)).toEqual([]);
+ });
+
+ it('lists each member once, in order of appearance', () => {
+ expect(findTextMentions('@Pilot @Arvin Xu @Pilot', members)).toEqual(['pilot', 'arvin']);
+ });
+
+ it('skips a name two members share', () => {
+ expect(
+ findTextMentions('@Sam', [
+ { id: 'a', name: 'Sam' },
+ { id: 'b', name: 'Sam' },
+ ]),
+ ).toEqual([]);
+ });
+});
+
+describe('replyMentionHops', () => {
+ it('reads positive integers only', () => {
+ expect(replyMentionHops({ mentionHops: 2 })).toBe(2);
+ expect(replyMentionHops({ mentionHops: 'x' })).toBe(0);
+ expect(replyMentionHops(null)).toBe(0);
+ });
+});
diff --git a/packages/database/src/repositories/channel/replyMentions.ts b/packages/database/src/repositories/channel/replyMentions.ts
new file mode 100644
index 00000000000..a100fbb4a4d
--- /dev/null
+++ b/packages/database/src/repositories/channel/replyMentions.ts
@@ -0,0 +1,75 @@
+import remarkGfm from 'remark-gfm';
+import remarkParse from 'remark-parse';
+import { unified } from 'unified';
+import { visit } from 'unist-util-visit';
+
+/**
+ * Agent replies that @mention another Agent wake it, so two Agents can hand work to each other
+ * in the open. Each wake carries the number of Agent-to-Agent hops since the last person spoke
+ * (`metadata.mentionHops` on the waking reply); past this many, mentions are still recorded and
+ * shown, but wake no one. A person's message starts the count again.
+ */
+export const MAX_REPLY_MENTION_HOPS = 3;
+
+export interface MentionableMember {
+ id: string;
+ name: string;
+}
+
+const escapeRegExp = (value: string) => value.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&');
+
+const markdown = unified().use(remarkParse).use(remarkGfm);
+
+/** A bare or `<…>` link shows its own address as its text; that address addresses no one. */
+const isAutolinkText = (value: string, parent: { type: string; url?: string } | undefined) =>
+ parent?.type === 'link' &&
+ !!parent.url &&
+ [value, `http://${value}`, `mailto:${value}`].includes(parent.url);
+
+/**
+ * The text a reader sees, one entry per Markdown text node — the nodes the timeline's
+ * `remarkChannelMentions` highlights. Code, link and image destinations and HTML are not text
+ * nodes, and an autolink's text is its address, so an `@Name` there is never addressed.
+ */
+const renderedText = (content: string) => {
+ const parts: string[] = [];
+ visit(markdown.parse(content), 'text', (node: { value: string }, _index, parent: any) => {
+ if (!isAutolinkText(node.value, parent)) parts.push(node.value);
+ });
+ return parts;
+};
+
+/**
+ * Members an Agent's reply addresses as plain `@Name` text, matched the way the timeline
+ * highlights mentions: a longer name wins over a shorter prefix, and a name must end at a space,
+ * punctuation or the end (`@Pi` never matches inside `@Pilot`). A name two members share is
+ * ambiguous and matches neither. Returns member ids in order of first appearance.
+ */
+export const findTextMentions = (content: string, members: MentionableMember[]): string[] => {
+ const byName = new Map<string, string | null>();
+ for (const { id, name } of members) {
+ const key = name.trim();
+ if (!key) continue;
+ byName.set(key, byName.has(key) && byName.get(key) !== id ? null : id);
+ }
+ const names = [...byName.keys()].sort((a, b) => b.length - a.length);
+ if (!names.length) return [];
+
+ const pattern = new RegExp(
+ `@(${names.map(escapeRegExp).join('|')})(?=$|[\\s\\p{P}\\p{S}])`,
+ 'gu',
+ );
+ const found: string[] = [];
+ for (const text of renderedText(content))
+ for (const match of text.matchAll(pattern)) {
+ const id = byName.get(match[1]);
+ if (id && !found.includes(id)) found.push(id);
+ }
+ return found;
+};
+
+/** Hops recorded on a reply that woke Agents; 0 for anything else. */
+export const replyMentionHops = (metadata: Record<string, unknown> | null | undefined) => {
+ const hops = metadata?.mentionHops;
+ return typeof hops === 'number' && Number.isSafeInteger(hops) && hops > 0 ? hops : 0;
+};