Skip to content

Commit c4d3551

Browse files
committed
feat: resolve Buzz room member mentions
1 parent af77477 commit c4d3551

3 files changed

Lines changed: 349 additions & 0 deletions

File tree

‎extensions/buzz/src/directory-state.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { Event } from "nostr-tools";
22
import type { ChannelDirectoryEntry } from "openclaw/plugin-sdk/directory-runtime";
33
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
4+
import type { BuzzMentionMember } from "./mentions.js";
45
import type { BuzzRoomMembership } from "./room-membership.js";
56
import { buildBuzzTarget, parseBuzzTarget } from "./target.js";
67

@@ -330,6 +331,23 @@ export class BuzzDirectoryState {
330331
return applyQueryAndLimit(entries, { limit: params.limit });
331332
}
332333

334+
mentionMembers(roomId: string): BuzzMentionMember[] | undefined {
335+
const normalized = parseBuzzTarget(roomId);
336+
if (this.#rooms.get(normalized)?.archived) {
337+
return undefined;
338+
}
339+
const membership = this.#memberships.get(normalized);
340+
if (!membership) {
341+
return undefined;
342+
}
343+
return [...membership.members]
344+
.map((publicKey) => ({
345+
publicKey,
346+
displayName: this.#profiles.get(publicKey)?.displayName,
347+
}))
348+
.toSorted((left, right) => left.publicKey.localeCompare(right.publicKey));
349+
}
350+
333351
#buildUserEntry(publicKey: string): ChannelDirectoryEntry {
334352
const profile = this.#profiles.get(publicKey);
335353
const name =
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import { nip19 } from "nostr-tools";
2+
import { describe, expect, it } from "vitest";
3+
import { resolveBuzzMessageMentions, type BuzzMentionMember } from "./mentions.js";
4+
5+
const BOT_PUBLIC_KEY = "a".repeat(64);
6+
const ALICE_PUBLIC_KEY = "b".repeat(64);
7+
const SECOND_ALICE_PUBLIC_KEY = "c".repeat(64);
8+
9+
function members(...values: BuzzMentionMember[]): BuzzMentionMember[] {
10+
return [{ publicKey: BOT_PUBLIC_KEY, displayName: "OpenClaw" }, ...values];
11+
}
12+
13+
describe("Buzz outbound mentions", () => {
14+
it("resolves unique room-member names and preserves multi-word matching", () => {
15+
expect(
16+
resolveBuzzMessageMentions({
17+
text: "Thanks @Alice Example, please review.",
18+
members: members({ publicKey: ALICE_PUBLIC_KEY, displayName: "Alice Example" }),
19+
senderPublicKey: BOT_PUBLIC_KEY,
20+
}),
21+
).toEqual([ALICE_PUBLIC_KEY]);
22+
});
23+
24+
it("rejects unknown and ambiguous names without an explicit identity", () => {
25+
expect(() =>
26+
resolveBuzzMessageMentions({
27+
text: "Hello @Missing",
28+
members: members({ publicKey: ALICE_PUBLIC_KEY, displayName: "Alice" }),
29+
senderPublicKey: BOT_PUBLIC_KEY,
30+
}),
31+
).toThrow('Buzz mention "@missing" does not match a current room member');
32+
33+
expect(() =>
34+
resolveBuzzMessageMentions({
35+
text: "Hello @Alice",
36+
members: members(
37+
{ publicKey: ALICE_PUBLIC_KEY, displayName: "Alice" },
38+
{ publicKey: SECOND_ALICE_PUBLIC_KEY, displayName: "Alice" },
39+
),
40+
senderPublicKey: BOT_PUBLIC_KEY,
41+
}),
42+
).toThrow('Buzz mention "@alice" is ambiguous');
43+
});
44+
45+
it("accepts explicit NIP-27 identities and ignores presentation-only ambiguous names", () => {
46+
const explicit = nip19.npubEncode(ALICE_PUBLIC_KEY);
47+
expect(
48+
resolveBuzzMessageMentions({
49+
text: `Hello @Alice (nostr:${explicit})`,
50+
members: members(
51+
{ publicKey: ALICE_PUBLIC_KEY, displayName: "Alice" },
52+
{ publicKey: SECOND_ALICE_PUBLIC_KEY, displayName: "Alice" },
53+
),
54+
senderPublicKey: BOT_PUBLIC_KEY,
55+
}),
56+
).toEqual([ALICE_PUBLIC_KEY]);
57+
});
58+
59+
it("rejects explicit identities outside the room and excludes the bot identity", () => {
60+
const outsider = "d".repeat(64);
61+
expect(() =>
62+
resolveBuzzMessageMentions({
63+
text: `nostr:${nip19.npubEncode(outsider)}`,
64+
members: members({ publicKey: ALICE_PUBLIC_KEY, displayName: "Alice" }),
65+
senderPublicKey: BOT_PUBLIC_KEY,
66+
}),
67+
).toThrow("is not a current room member");
68+
69+
expect(
70+
resolveBuzzMessageMentions({
71+
text: `nostr:${nip19.npubEncode(BOT_PUBLIC_KEY)}`,
72+
members: members(),
73+
senderPublicKey: BOT_PUBLIC_KEY,
74+
}),
75+
).toEqual([]);
76+
});
77+
78+
it("does not resolve mention-like text inside Markdown code regions", () => {
79+
expect(
80+
resolveBuzzMessageMentions({
81+
text: "`@Alice`\n```\nnostr:npub1invalid\n```",
82+
members: undefined,
83+
senderPublicKey: BOT_PUBLIC_KEY,
84+
}),
85+
).toEqual([]);
86+
});
87+
});

‎extensions/buzz/src/mentions.ts‎

Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
import { nip19 } from "nostr-tools";
2+
3+
export const BUZZ_MENTION_MAX_COUNT = 50;
4+
5+
export type BuzzMentionMember = {
6+
publicKey: string;
7+
displayName?: string;
8+
};
9+
10+
const HEX_PUBLIC_KEY_PATTERN = /^[0-9a-f]{64}$/u;
11+
const NIP_27_PREFIX = "nostr:npub1";
12+
const NPUB_LENGTH = 63;
13+
14+
function asciiLowercase(value: string): string {
15+
return value.replace(/[A-Z]/gu, (character) => character.toLowerCase());
16+
}
17+
18+
function isAsciiWhitespace(character: string | undefined): boolean {
19+
return character !== undefined && /^[\t-\r ]$/u.test(character);
20+
}
21+
22+
function isMentionBoundary(value: string): boolean {
23+
const character = value[0];
24+
return character === undefined || isAsciiWhitespace(character) || ",;.!?:)]}".includes(character);
25+
}
26+
27+
function stripCodeRegions(content: string): string {
28+
let output = "";
29+
let index = 0;
30+
while (index < content.length) {
31+
if (content.startsWith("```", index)) {
32+
const lineStart = content.lastIndexOf("\n", index - 1) + 1;
33+
const beforeFence = content.slice(lineStart, index);
34+
if ([...beforeFence].every(isAsciiWhitespace)) {
35+
const openingLineEnd = content.indexOf("\n", index + 3);
36+
let searchFrom = openingLineEnd === -1 ? content.length : openingLineEnd + 1;
37+
let closeEnd = content.length;
38+
while (searchFrom < content.length) {
39+
const closingFence = content.indexOf("```", searchFrom);
40+
if (closingFence === -1) {
41+
break;
42+
}
43+
const closingLineStart = content.lastIndexOf("\n", closingFence - 1) + 1;
44+
const beforeClosingFence = content.slice(closingLineStart, closingFence);
45+
if ([...beforeClosingFence].every(isAsciiWhitespace)) {
46+
const closingLineEnd = content.indexOf("\n", closingFence + 3);
47+
closeEnd = closingLineEnd === -1 ? content.length : closingLineEnd + 1;
48+
break;
49+
}
50+
searchFrom = closingFence + 3;
51+
}
52+
output += " ";
53+
index = closeEnd;
54+
continue;
55+
}
56+
}
57+
58+
if (content[index] === "`") {
59+
const closingTick = content.indexOf("`", index + 1);
60+
if (closingTick !== -1 && !content.slice(index + 1, closingTick).includes("\n")) {
61+
output += " ";
62+
index = closingTick + 1;
63+
continue;
64+
}
65+
}
66+
67+
output += content[index];
68+
index += 1;
69+
}
70+
return output;
71+
}
72+
73+
function extractNostrPubkeys(content: string): string[] {
74+
const publicKeys: string[] = [];
75+
const seen = new Set<string>();
76+
let searchFrom = 0;
77+
while (searchFrom < content.length) {
78+
const start = content.indexOf(NIP_27_PREFIX, searchFrom);
79+
if (start === -1) {
80+
break;
81+
}
82+
const npubStart = start + "nostr:".length;
83+
const candidate = content.slice(npubStart, npubStart + NPUB_LENGTH);
84+
searchFrom = start + NIP_27_PREFIX.length;
85+
if (candidate.length !== NPUB_LENGTH || !/^[0-9a-z]+$/iu.test(candidate)) {
86+
continue;
87+
}
88+
try {
89+
const decoded = nip19.decode(asciiLowercase(candidate));
90+
if (decoded.type !== "npub" || typeof decoded.data !== "string") {
91+
continue;
92+
}
93+
const publicKey = decoded.data.toLowerCase();
94+
if (HEX_PUBLIC_KEY_PATTERN.test(publicKey) && !seen.has(publicKey)) {
95+
seen.add(publicKey);
96+
publicKeys.push(publicKey);
97+
}
98+
} catch {
99+
// Invalid NIP-27 references remain presentation text, matching Buzz.
100+
}
101+
}
102+
return publicKeys;
103+
}
104+
105+
function extractMentionNames(content: string, knownNames: readonly string[]): string[] {
106+
if (!content.includes("@")) {
107+
return [];
108+
}
109+
const sortedNames = knownNames
110+
.map((name) => name.trim())
111+
.filter(Boolean)
112+
.toSorted((left, right) => right.length - left.length);
113+
const names: string[] = [];
114+
const seen = new Set<string>();
115+
116+
for (let index = 0; index < content.length; index += 1) {
117+
if (
118+
content[index] !== "@" ||
119+
(index > 0 && !isAsciiWhitespace(content[index - 1])) ||
120+
index + 1 >= content.length
121+
) {
122+
continue;
123+
}
124+
const rest = content.slice(index + 1);
125+
const knownName = sortedNames.find((name) => {
126+
const candidate = rest.slice(0, name.length);
127+
return (
128+
candidate.length === name.length &&
129+
asciiLowercase(candidate) === asciiLowercase(name) &&
130+
isMentionBoundary(rest.slice(name.length))
131+
);
132+
});
133+
let name = knownName;
134+
if (!name) {
135+
const match = /^[a-z0-9._-]+/iu.exec(rest);
136+
name = match?.[0];
137+
}
138+
if (!name) {
139+
continue;
140+
}
141+
const normalized = asciiLowercase(name);
142+
if (!seen.has(normalized)) {
143+
seen.add(normalized);
144+
names.push(normalized);
145+
}
146+
}
147+
return names;
148+
}
149+
150+
function normalizeMembers(members: readonly BuzzMentionMember[]): Map<string, BuzzMentionMember> {
151+
const normalized = new Map<string, BuzzMentionMember>();
152+
for (const member of members) {
153+
const publicKey = member.publicKey.trim().toLowerCase();
154+
if (!HEX_PUBLIC_KEY_PATTERN.test(publicKey)) {
155+
continue;
156+
}
157+
normalized.set(publicKey, {
158+
publicKey,
159+
displayName: member.displayName?.trim() || undefined,
160+
});
161+
}
162+
return normalized;
163+
}
164+
165+
export function hasBuzzMentionSyntax(text: string): boolean {
166+
const stripped = stripCodeRegions(text);
167+
return stripped.includes("@") || stripped.includes(NIP_27_PREFIX);
168+
}
169+
170+
export function resolveBuzzMessageMentions(params: {
171+
text: string;
172+
members: readonly BuzzMentionMember[] | undefined;
173+
senderPublicKey: string;
174+
}): string[] {
175+
const stripped = stripCodeRegions(params.text);
176+
const explicitPublicKeys = extractNostrPubkeys(stripped);
177+
const hasMentionText = stripped.includes("@") || explicitPublicKeys.length > 0;
178+
if (!hasMentionText) {
179+
return [];
180+
}
181+
if (!params.members) {
182+
throw new Error("Buzz room membership is unavailable; retry after the room directory loads");
183+
}
184+
185+
const members = normalizeMembers(params.members);
186+
const senderPublicKey = params.senderPublicKey.trim().toLowerCase();
187+
const mentions: string[] = [];
188+
for (const publicKey of explicitPublicKeys) {
189+
if (publicKey !== senderPublicKey && !mentions.includes(publicKey)) {
190+
mentions.push(publicKey);
191+
}
192+
}
193+
if (mentions.length > BUZZ_MENTION_MAX_COUNT) {
194+
throw new Error(`Buzz messages support at most ${BUZZ_MENTION_MAX_COUNT} mentions`);
195+
}
196+
const missingPublicKeys = mentions.filter((publicKey) => !members.has(publicKey));
197+
if (missingPublicKeys.length > 0) {
198+
throw new Error(
199+
`Buzz mentioned public key is not a current room member: ${missingPublicKeys.join(", ")}`,
200+
);
201+
}
202+
203+
const namesToPublicKeys = new Map<string, string[]>();
204+
for (const member of members.values()) {
205+
if (!member.displayName) {
206+
continue;
207+
}
208+
const name = asciiLowercase(member.displayName);
209+
const matches = namesToPublicKeys.get(name) ?? [];
210+
matches.push(member.publicKey);
211+
namesToPublicKeys.set(name, matches);
212+
}
213+
const names = extractMentionNames(
214+
stripped,
215+
[...members.values()]
216+
.map((member) => member.displayName)
217+
.filter((name): name is string => Boolean(name)),
218+
);
219+
const hasExplicitMentions = explicitPublicKeys.length > 0;
220+
for (const name of names) {
221+
const matches = namesToPublicKeys.get(name) ?? [];
222+
if (matches.length !== 1) {
223+
if (hasExplicitMentions) {
224+
continue;
225+
}
226+
if (matches.length === 0) {
227+
throw new Error(
228+
`Buzz mention "@${name}" does not match a current room member; use nostr:npub... for an explicit identity`,
229+
);
230+
}
231+
throw new Error(
232+
`Buzz mention "@${name}" is ambiguous; use nostr:npub... for an explicit identity`,
233+
);
234+
}
235+
const publicKey = matches[0];
236+
if (publicKey !== senderPublicKey && !mentions.includes(publicKey)) {
237+
if (mentions.length >= BUZZ_MENTION_MAX_COUNT) {
238+
throw new Error(`Buzz messages support at most ${BUZZ_MENTION_MAX_COUNT} mentions`);
239+
}
240+
mentions.push(publicKey);
241+
}
242+
}
243+
return mentions;
244+
}

0 commit comments

Comments
 (0)