Skip to content

Commit 8fb9dcd

Browse files
committed
feat: emit native Buzz mention tags
1 parent c4d3551 commit 8fb9dcd

8 files changed

Lines changed: 229 additions & 9 deletions

File tree

‎extensions/buzz/src/buzz-bus.lifecycle.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,44 @@ describe("Buzz bus lifecycle", () => {
305305
expect(relayMocks.close).toHaveBeenCalledOnce();
306306
});
307307

308+
it("resolves standalone native mentions from the room snapshot before publishing", async () => {
309+
relayMocks.auth.mockResolvedValue("ok");
310+
relayMocks.profileEvents = [
311+
finalizeEvent(
312+
{
313+
kind: 0,
314+
created_at: 1_700_000_000,
315+
content: JSON.stringify({ display_name: "Alice" }),
316+
tags: [],
317+
},
318+
Uint8Array.from(Buffer.from(SENDER_PRIVATE_KEY, "hex")),
319+
),
320+
];
321+
322+
await sendBuzzTextOneShot({
323+
relayUrl: "wss://buzz.example.com",
324+
privateKey: PRIVATE_KEY,
325+
channelId: CHANNEL_ID,
326+
text: "Hello @Alice",
327+
threadId: "root-id",
328+
});
329+
330+
expect(relayMocks.publish.mock.calls[0]?.[0]).toMatchObject({
331+
kind: 9,
332+
content: "Hello @Alice",
333+
tags: [
334+
["h", CHANNEL_ID],
335+
["e", "root-id", "", "reply"],
336+
["p", SENDER_PUBLIC_KEY],
337+
],
338+
});
339+
expect(relayMocks.subscriptions.some((entry) => subscriptionIncludesKind(entry, 39002))).toBe(
340+
true,
341+
);
342+
expect(relayMocks.subscriptions.some((entry) => subscriptionIncludesKind(entry, 0))).toBe(true);
343+
expect(relayMocks.close).toHaveBeenCalledOnce();
344+
});
345+
308346
it("sends room and thread typing without waiting for a relay acknowledgement", async () => {
309347
relayMocks.auth.mockResolvedValue("ok");
310348
const bus = await startBuzzBus({

‎extensions/buzz/src/buzz-bus.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,19 @@ describe("Buzz message events", () => {
199199
["e", "root-id", "", "root"],
200200
["e", "parent-id", "", "reply"],
201201
]);
202+
expect(
203+
buildBuzzMessageTags({
204+
channelId: "channel-id",
205+
threadId: "root-id",
206+
replyToId: "parent-id",
207+
mentionedPubkeys: ["B".repeat(64), "b".repeat(64)],
208+
}),
209+
).toEqual([
210+
["h", "channel-id"],
211+
["e", "root-id", "", "root"],
212+
["e", "parent-id", "", "reply"],
213+
["p", "b".repeat(64)],
214+
]);
202215
});
203216

204217
it("validates the Buzz NIP-OA authentication tag shape", () => {

‎extensions/buzz/src/buzz-bus.ts‎

Lines changed: 59 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
import { type Relay, finalizeEvent, type Event } from "nostr-tools";
22
import { createChannelReplayGuard } from "openclaw/plugin-sdk/persistent-dedupe";
3-
import { queryBuzzDirectoryRooms, startBuzzDirectoryRelay } from "./directory-relay.js";
3+
import {
4+
queryBuzzDirectoryProfiles,
5+
queryBuzzDirectoryRooms,
6+
startBuzzDirectoryRelay,
7+
} from "./directory-relay.js";
48
import { BuzzDirectoryState } from "./directory-state.js";
9+
import { hasBuzzMentionSyntax, resolveBuzzMessageMentions } from "./mentions.js";
510
import {
611
BUZZ_NORMAL_MESSAGE_KIND,
712
BUZZ_TYPING_INDICATOR_KIND,
@@ -21,6 +26,7 @@ import {
2126
resolveBuzzRoomHistoryLimit,
2227
} from "./replay-dispatch.js";
2328
import { startBuzzRoomMembershipNotifications } from "./room-membership-notification.js";
29+
import { queryBuzzRoomMemberships } from "./room-membership-query.js";
2430
import { createBuzzRoomMembershipTracker } from "./room-membership-tracker.js";
2531
import { resolveBuzzSubscriptionBudget } from "./subscription-budget.js";
2632
import { decodeBuzzPrivateKey, resolveBuzzPublicKey } from "./types.js";
@@ -41,6 +47,7 @@ export interface BuzzBus {
4147
text: string;
4248
threadId?: string;
4349
replyToId?: string;
50+
mentionedPubkeys?: string[];
4451
}) => Promise<string>;
4552
sendTyping: (params: {
4653
channelId: string;
@@ -56,6 +63,7 @@ function buildBuzzTextEvent(params: {
5663
text: string;
5764
threadId?: string;
5865
replyToId?: string;
66+
mentionedPubkeys?: string[];
5967
}): Event {
6068
return finalizeEvent(
6169
{
@@ -150,6 +158,47 @@ export async function sendBuzzTextOneShot(params: {
150158
replyToId?: string;
151159
}): Promise<string> {
152160
const secretKey = decodeBuzzPrivateKey(params.privateKey);
161+
if (hasBuzzMentionSyntax(params.text)) {
162+
const signal = AbortSignal.timeout(30_000);
163+
const publicKey = resolveBuzzPublicKey(params.privateKey);
164+
const { relay, relayPublicKey } = await connectAuthenticatedBuzzRelaySession({
165+
relayUrl: params.relayUrl,
166+
secretKey,
167+
authTag: parseBuzzAuthTag(params.authTag ?? ""),
168+
signal,
169+
});
170+
try {
171+
const directory = new BuzzDirectoryState({
172+
publicKey,
173+
fallbackProfileName: "OpenClaw",
174+
channelIds: [params.channelId],
175+
});
176+
directory.replaceMemberships(
177+
await queryBuzzRoomMemberships({
178+
relay,
179+
relayPublicKey,
180+
channelIds: [params.channelId],
181+
signal,
182+
}),
183+
);
184+
await queryBuzzDirectoryProfiles({
185+
relay,
186+
state: directory,
187+
publicKeys: directory.profilePublicKeys(),
188+
signal,
189+
});
190+
const mentionedPubkeys = resolveBuzzMessageMentions({
191+
text: params.text,
192+
members: directory.mentionMembers(params.channelId),
193+
senderPublicKey: publicKey,
194+
});
195+
const event = buildBuzzTextEvent({ ...params, secretKey, mentionedPubkeys });
196+
await relay.publish(event);
197+
return event.id;
198+
} finally {
199+
relay.close();
200+
}
201+
}
153202
const relay = await connectAuthenticatedBuzzRelay({
154203
relayUrl: params.relayUrl,
155204
secretKey,
@@ -237,9 +286,16 @@ export async function startBuzzBus(options: {
237286
publicKey,
238287
directory,
239288
refreshDirectory: async () => await directoryRelay?.refreshRooms(options.channelIds),
240-
sendText: async ({ channelId, text, threadId, replyToId }) => {
289+
sendText: async ({ channelId, text, threadId, replyToId, mentionedPubkeys }) => {
241290
signal.throwIfAborted();
242-
const event = buildBuzzTextEvent({ secretKey, channelId, text, threadId, replyToId });
291+
const event = buildBuzzTextEvent({
292+
secretKey,
293+
channelId,
294+
text,
295+
threadId,
296+
replyToId,
297+
mentionedPubkeys,
298+
});
243299
await relay.publish(event);
244300
return event.id;
245301
},

‎extensions/buzz/src/gateway.lifecycle.test.ts‎

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ const gatewayMocks = vi.hoisted(() => ({
1818
| undefined,
1919
onMessageError: undefined as ((error: Error) => void) | undefined,
2020
onFatalError: undefined as ((error: Error) => void) | undefined,
21+
currentBus: undefined as BuzzBus | undefined,
2122
resolveAgentIdentity: vi.fn(),
2223
resolveAgentRoute: vi.fn(),
2324
startBuzzBus: vi.fn(),
@@ -63,6 +64,7 @@ describe("Buzz gateway lifecycle", () => {
6364
gatewayMocks.onMessage = undefined;
6465
gatewayMocks.onMessageError = undefined;
6566
gatewayMocks.onFatalError = undefined;
67+
gatewayMocks.currentBus = undefined;
6668
gatewayMocks.busSendText.mockResolvedValue("event-id");
6769
gatewayMocks.busSendTyping.mockResolvedValue(undefined);
6870
gatewayMocks.sendBuzzTextOneShot.mockResolvedValue("standalone-event-id");
@@ -95,7 +97,9 @@ describe("Buzz gateway lifecycle", () => {
9597
gatewayMocks.onMessage = options.onMessage;
9698
gatewayMocks.onMessageError = options.onMessageError;
9799
gatewayMocks.onFatalError = options.onFatalError;
98-
return createMockBus();
100+
const bus = createMockBus();
101+
gatewayMocks.currentBus = bus;
102+
return bus;
99103
},
100104
);
101105
});
@@ -250,6 +254,84 @@ describe("Buzz gateway lifecycle", () => {
250254
await expect(lifecycle).resolves.toBeUndefined();
251255
});
252256

257+
it("resolves native mentions from the active bus directory without a relay lookup", async () => {
258+
const abortController = new AbortController();
259+
const memberPublicKey = "b".repeat(64);
260+
const cfg = {
261+
channels: {
262+
buzz: {
263+
relayUrl: "wss://buzz.example.com",
264+
privateKey: PRIVATE_KEY,
265+
groups: { [CHANNEL_ID]: {} },
266+
},
267+
},
268+
} as OpenClawConfig;
269+
const account = resolveBuzzAccount({ cfg });
270+
const ctx = {
271+
cfg,
272+
accountId: account.accountId,
273+
account,
274+
runtime: {},
275+
abortSignal: abortController.signal,
276+
log: { info: vi.fn(), error: vi.fn() },
277+
getStatus: vi.fn(),
278+
setStatus: vi.fn(),
279+
} as unknown as ChannelGatewayContext<ResolvedBuzzAccount>;
280+
const lifecycle = startBuzzGatewayAccount(ctx);
281+
await vi.waitFor(() => expect(gatewayMocks.currentBus).toBeDefined());
282+
const bus = gatewayMocks.currentBus;
283+
if (!bus) {
284+
throw new Error("expected active Buzz bus");
285+
}
286+
bus.directory.replaceMemberships(
287+
new Map([
288+
[
289+
CHANNEL_ID,
290+
{
291+
roomId: CHANNEL_ID,
292+
createdAt: 1_700_000_000,
293+
eventId: "1".repeat(64),
294+
publisherPublicKey: "f".repeat(64),
295+
members: new Set([BOT_PUBLIC_KEY, memberPublicKey]),
296+
roles: new Map([
297+
[BOT_PUBLIC_KEY, "bot"],
298+
[memberPublicKey, "member"],
299+
]),
300+
},
301+
],
302+
]),
303+
);
304+
bus.directory.applyProfileEvent({
305+
id: "2".repeat(64),
306+
kind: 0,
307+
pubkey: memberPublicKey,
308+
created_at: 1_700_000_000,
309+
content: JSON.stringify({ display_name: "Alice" }),
310+
sig: "e".repeat(128),
311+
tags: [],
312+
});
313+
314+
await buzzOutboundAdapter.sendText({
315+
cfg,
316+
to: `buzz:${CHANNEL_ID}`,
317+
text: "Hello @Alice",
318+
accountId: "default",
319+
threadId: "root-id",
320+
});
321+
322+
expect(gatewayMocks.busSendText).toHaveBeenCalledWith({
323+
channelId: CHANNEL_ID,
324+
text: "Hello @Alice",
325+
threadId: "root-id",
326+
replyToId: undefined,
327+
mentionedPubkeys: [memberPublicKey],
328+
});
329+
expect(gatewayMocks.sendBuzzTextOneShot).not.toHaveBeenCalled();
330+
331+
abortController.abort();
332+
await expect(lifecycle).resolves.toBeUndefined();
333+
});
334+
253335
it("uses the active bus for heartbeat typing without destabilizing the account", async () => {
254336
const abortController = new AbortController();
255337
const cfg = {

‎extensions/buzz/src/gateway.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { computeBackoff, sleepWithAbort } from "openclaw/plugin-sdk/runtime-env"
55
import type { ChannelGatewayContext } from "../runtime-api.js";
66
import { sendBuzzTextOneShot, startBuzzBus, type BuzzBus } from "./buzz-bus.js";
77
import { handleBuzzInbound } from "./inbound.js";
8+
import { resolveBuzzMessageMentions } from "./mentions.js";
89
import { getBuzzRuntime } from "./runtime.js";
910
import { buildBuzzTarget, isConfiguredBuzzChannel, parseBuzzTarget } from "./target.js";
1011
import {
@@ -241,8 +242,18 @@ export const buzzOutboundAdapter = {
241242
threadId: threadId == null ? undefined : String(threadId),
242243
replyToId: replyToId == null ? undefined : String(replyToId),
243244
};
245+
const mentionedPubkeys = bus
246+
? resolveBuzzMessageMentions({
247+
text: message,
248+
members: bus.directory.mentionMembers(channelId),
249+
senderPublicKey: bus.publicKey,
250+
})
251+
: [];
244252
const messageId = bus
245-
? await bus.sendText(outboundMessage)
253+
? await bus.sendText({
254+
...outboundMessage,
255+
...(mentionedPubkeys.length > 0 ? { mentionedPubkeys } : {}),
256+
})
246257
: await sendBuzzTextOneShot({
247258
relayUrl: account.relayUrl,
248259
privateKey: account.privateKey,

‎extensions/buzz/src/mentions.test.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import { nip19 } from "nostr-tools";
22
import { describe, expect, it } from "vitest";
3-
import { resolveBuzzMessageMentions, type BuzzMentionMember } from "./mentions.js";
3+
import {
4+
hasBuzzMentionSyntax,
5+
resolveBuzzMessageMentions,
6+
type BuzzMentionMember,
7+
} from "./mentions.js";
48

59
const BOT_PUBLIC_KEY = "a".repeat(64);
610
const ALICE_PUBLIC_KEY = "b".repeat(64);
@@ -83,5 +87,6 @@ describe("Buzz outbound mentions", () => {
8387
senderPublicKey: BOT_PUBLIC_KEY,
8488
}),
8589
).toEqual([]);
90+
expect(hasBuzzMentionSyntax("mail [email protected]")).toBe(false);
8691
});
8792
});

‎extensions/buzz/src/mentions.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ function normalizeMembers(members: readonly BuzzMentionMember[]): Map<string, Bu
164164

165165
export function hasBuzzMentionSyntax(text: string): boolean {
166166
const stripped = stripCodeRegions(text);
167-
return stripped.includes("@") || stripped.includes(NIP_27_PREFIX);
167+
return extractMentionNames(stripped, []).length > 0 || extractNostrPubkeys(stripped).length > 0;
168168
}
169169

170170
export function resolveBuzzMessageMentions(params: {
@@ -174,7 +174,8 @@ export function resolveBuzzMessageMentions(params: {
174174
}): string[] {
175175
const stripped = stripCodeRegions(params.text);
176176
const explicitPublicKeys = extractNostrPubkeys(stripped);
177-
const hasMentionText = stripped.includes("@") || explicitPublicKeys.length > 0;
177+
const fallbackNames = extractMentionNames(stripped, []);
178+
const hasMentionText = fallbackNames.length > 0 || explicitPublicKeys.length > 0;
178179
if (!hasMentionText) {
179180
return [];
180181
}

‎extensions/buzz/src/message-event.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Buffer } from "node:buffer";
22
import type { Event } from "nostr-tools";
33
import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
4+
import { BUZZ_MENTION_MAX_COUNT } from "./mentions.js";
45

56
export const BUZZ_NORMAL_MESSAGE_KIND = 9;
67
export const BUZZ_TYPING_INDICATOR_KIND = 20_002;
@@ -18,7 +19,7 @@ type BuzzInboundMessageKind = (typeof BUZZ_INBOUND_MESSAGE_KINDS)[number];
1819
// own stricter validator. Keep inbound admission aligned with those limits.
1920
const BUZZ_MESSAGE_CONTENT_MAX_BYTES = 256 * 1024;
2021
const BUZZ_DIFF_CONTENT_MAX_BYTES = 60 * 1024;
21-
const BUZZ_MENTION_MAX_COUNT = 50;
22+
const HEX_PUBLIC_KEY_PATTERN = /^[0-9a-f]{64}$/u;
2223
const BUZZ_DIFF_CONTEXT_FIELD_MAX_CHARS = 256;
2324
const BUZZ_DIFF_AGENT_CONTEXT_MAX_CHARS = 4_000;
2425
const BUZZ_DIFF_AGENT_CONTEXT_TRUNCATED_SUFFIX = "\n...[Buzz diff truncated for model context]";
@@ -260,6 +261,7 @@ export function buildBuzzMessageTags(params: {
260261
channelId: string;
261262
threadId?: string;
262263
replyToId?: string;
264+
mentionedPubkeys?: readonly string[];
263265
}): string[][] {
264266
const tags: string[][] = [["h", params.channelId]];
265267
const parentId = params.replyToId ?? params.threadId;
@@ -269,5 +271,17 @@ export function buildBuzzMessageTags(params: {
269271
if (parentId) {
270272
tags.push(["e", parentId, "", "reply"]);
271273
}
274+
const mentionedPubkeys = [
275+
...new Set((params.mentionedPubkeys ?? []).map((publicKey) => publicKey.trim().toLowerCase())),
276+
];
277+
if (mentionedPubkeys.length > BUZZ_MENTION_MAX_COUNT) {
278+
throw new Error(`Buzz messages support at most ${BUZZ_MENTION_MAX_COUNT} mentions`);
279+
}
280+
for (const publicKey of mentionedPubkeys) {
281+
if (!HEX_PUBLIC_KEY_PATTERN.test(publicKey)) {
282+
throw new Error("Buzz mentions require 64-character hex public keys");
283+
}
284+
tags.push(["p", publicKey]);
285+
}
272286
return tags;
273287
}

0 commit comments

Comments
 (0)