@openclaw/bluebubbles 2026.1.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/monitor.ts ADDED
@@ -0,0 +1,2276 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+
3
+ import type { OpenClawConfig } from "openclaw/plugin-sdk";
4
+ import {
5
+ logAckFailure,
6
+ logInboundDrop,
7
+ logTypingFailure,
8
+ resolveAckReaction,
9
+ resolveControlCommandGate,
10
+ } from "openclaw/plugin-sdk";
11
+ import { markBlueBubblesChatRead, sendBlueBubblesTyping } from "./chat.js";
12
+ import { resolveChatGuidForTarget, sendMessageBlueBubbles } from "./send.js";
13
+ import { downloadBlueBubblesAttachment } from "./attachments.js";
14
+ import { formatBlueBubblesChatTarget, isAllowedBlueBubblesSender, normalizeBlueBubblesHandle } from "./targets.js";
15
+ import { sendBlueBubblesMedia } from "./media-send.js";
16
+ import type { BlueBubblesAccountConfig, BlueBubblesAttachment } from "./types.js";
17
+ import type { ResolvedBlueBubblesAccount } from "./accounts.js";
18
+ import { getBlueBubblesRuntime } from "./runtime.js";
19
+ import { normalizeBlueBubblesReactionInput, sendBlueBubblesReaction } from "./reactions.js";
20
+ import { fetchBlueBubblesServerInfo } from "./probe.js";
21
+
22
+ export type BlueBubblesRuntimeEnv = {
23
+ log?: (message: string) => void;
24
+ error?: (message: string) => void;
25
+ };
26
+
27
+ export type BlueBubblesMonitorOptions = {
28
+ account: ResolvedBlueBubblesAccount;
29
+ config: OpenClawConfig;
30
+ runtime: BlueBubblesRuntimeEnv;
31
+ abortSignal: AbortSignal;
32
+ statusSink?: (patch: { lastInboundAt?: number; lastOutboundAt?: number }) => void;
33
+ webhookPath?: string;
34
+ };
35
+
36
+ const DEFAULT_WEBHOOK_PATH = "/bluebubbles-webhook";
37
+ const DEFAULT_TEXT_LIMIT = 4000;
38
+ const invalidAckReactions = new Set<string>();
39
+
40
+ const REPLY_CACHE_MAX = 2000;
41
+ const REPLY_CACHE_TTL_MS = 6 * 60 * 60 * 1000;
42
+
43
+ type BlueBubblesReplyCacheEntry = {
44
+ accountId: string;
45
+ messageId: string;
46
+ shortId: string;
47
+ chatGuid?: string;
48
+ chatIdentifier?: string;
49
+ chatId?: number;
50
+ senderLabel?: string;
51
+ body?: string;
52
+ timestamp: number;
53
+ };
54
+
55
+ // Best-effort cache for resolving reply context when BlueBubbles webhooks omit sender/body.
56
+ const blueBubblesReplyCacheByMessageId = new Map<string, BlueBubblesReplyCacheEntry>();
57
+
58
+ // Bidirectional maps for short ID ↔ message GUID resolution (token savings optimization)
59
+ const blueBubblesShortIdToUuid = new Map<string, string>();
60
+ const blueBubblesUuidToShortId = new Map<string, string>();
61
+ let blueBubblesShortIdCounter = 0;
62
+
63
+ function trimOrUndefined(value?: string | null): string | undefined {
64
+ const trimmed = value?.trim();
65
+ return trimmed ? trimmed : undefined;
66
+ }
67
+
68
+ function generateShortId(): string {
69
+ blueBubblesShortIdCounter += 1;
70
+ return String(blueBubblesShortIdCounter);
71
+ }
72
+
73
+ function rememberBlueBubblesReplyCache(
74
+ entry: Omit<BlueBubblesReplyCacheEntry, "shortId">,
75
+ ): BlueBubblesReplyCacheEntry {
76
+ const messageId = entry.messageId.trim();
77
+ if (!messageId) {
78
+ return { ...entry, shortId: "" };
79
+ }
80
+
81
+ // Check if we already have a short ID for this GUID
82
+ let shortId = blueBubblesUuidToShortId.get(messageId);
83
+ if (!shortId) {
84
+ shortId = generateShortId();
85
+ blueBubblesShortIdToUuid.set(shortId, messageId);
86
+ blueBubblesUuidToShortId.set(messageId, shortId);
87
+ }
88
+
89
+ const fullEntry: BlueBubblesReplyCacheEntry = { ...entry, messageId, shortId };
90
+
91
+ // Refresh insertion order.
92
+ blueBubblesReplyCacheByMessageId.delete(messageId);
93
+ blueBubblesReplyCacheByMessageId.set(messageId, fullEntry);
94
+
95
+ // Opportunistic prune.
96
+ const cutoff = Date.now() - REPLY_CACHE_TTL_MS;
97
+ for (const [key, value] of blueBubblesReplyCacheByMessageId) {
98
+ if (value.timestamp < cutoff) {
99
+ blueBubblesReplyCacheByMessageId.delete(key);
100
+ // Clean up short ID mappings for expired entries
101
+ if (value.shortId) {
102
+ blueBubblesShortIdToUuid.delete(value.shortId);
103
+ blueBubblesUuidToShortId.delete(key);
104
+ }
105
+ continue;
106
+ }
107
+ break;
108
+ }
109
+ while (blueBubblesReplyCacheByMessageId.size > REPLY_CACHE_MAX) {
110
+ const oldest = blueBubblesReplyCacheByMessageId.keys().next().value as string | undefined;
111
+ if (!oldest) break;
112
+ const oldEntry = blueBubblesReplyCacheByMessageId.get(oldest);
113
+ blueBubblesReplyCacheByMessageId.delete(oldest);
114
+ // Clean up short ID mappings for evicted entries
115
+ if (oldEntry?.shortId) {
116
+ blueBubblesShortIdToUuid.delete(oldEntry.shortId);
117
+ blueBubblesUuidToShortId.delete(oldest);
118
+ }
119
+ }
120
+
121
+ return fullEntry;
122
+ }
123
+
124
+ /**
125
+ * Resolves a short message ID (e.g., "1", "2") to a full BlueBubbles GUID.
126
+ * Returns the input unchanged if it's already a GUID or not found in the mapping.
127
+ */
128
+ export function resolveBlueBubblesMessageId(
129
+ shortOrUuid: string,
130
+ opts?: { requireKnownShortId?: boolean },
131
+ ): string {
132
+ const trimmed = shortOrUuid.trim();
133
+ if (!trimmed) return trimmed;
134
+
135
+ // If it looks like a short ID (numeric), try to resolve it
136
+ if (/^\d+$/.test(trimmed)) {
137
+ const uuid = blueBubblesShortIdToUuid.get(trimmed);
138
+ if (uuid) return uuid;
139
+ if (opts?.requireKnownShortId) {
140
+ throw new Error(
141
+ `BlueBubbles short message id "${trimmed}" is no longer available. Use MessageSidFull.`,
142
+ );
143
+ }
144
+ }
145
+
146
+ // Return as-is (either already a UUID or not found)
147
+ return trimmed;
148
+ }
149
+
150
+ /**
151
+ * Resets the short ID state. Only use in tests.
152
+ * @internal
153
+ */
154
+ export function _resetBlueBubblesShortIdState(): void {
155
+ blueBubblesShortIdToUuid.clear();
156
+ blueBubblesUuidToShortId.clear();
157
+ blueBubblesReplyCacheByMessageId.clear();
158
+ blueBubblesShortIdCounter = 0;
159
+ }
160
+
161
+ /**
162
+ * Gets the short ID for a message GUID, if one exists.
163
+ */
164
+ function getShortIdForUuid(uuid: string): string | undefined {
165
+ return blueBubblesUuidToShortId.get(uuid.trim());
166
+ }
167
+
168
+ function resolveReplyContextFromCache(params: {
169
+ accountId: string;
170
+ replyToId: string;
171
+ chatGuid?: string;
172
+ chatIdentifier?: string;
173
+ chatId?: number;
174
+ }): BlueBubblesReplyCacheEntry | null {
175
+ const replyToId = params.replyToId.trim();
176
+ if (!replyToId) return null;
177
+
178
+ const cached = blueBubblesReplyCacheByMessageId.get(replyToId);
179
+ if (!cached) return null;
180
+ if (cached.accountId !== params.accountId) return null;
181
+
182
+ const cutoff = Date.now() - REPLY_CACHE_TTL_MS;
183
+ if (cached.timestamp < cutoff) {
184
+ blueBubblesReplyCacheByMessageId.delete(replyToId);
185
+ return null;
186
+ }
187
+
188
+ const chatGuid = trimOrUndefined(params.chatGuid);
189
+ const chatIdentifier = trimOrUndefined(params.chatIdentifier);
190
+ const cachedChatGuid = trimOrUndefined(cached.chatGuid);
191
+ const cachedChatIdentifier = trimOrUndefined(cached.chatIdentifier);
192
+ const chatId = typeof params.chatId === "number" ? params.chatId : undefined;
193
+ const cachedChatId = typeof cached.chatId === "number" ? cached.chatId : undefined;
194
+
195
+ // Avoid cross-chat collisions if we have identifiers.
196
+ if (chatGuid && cachedChatGuid && chatGuid !== cachedChatGuid) return null;
197
+ if (!chatGuid && chatIdentifier && cachedChatIdentifier && chatIdentifier !== cachedChatIdentifier) {
198
+ return null;
199
+ }
200
+ if (!chatGuid && !chatIdentifier && chatId && cachedChatId && chatId !== cachedChatId) {
201
+ return null;
202
+ }
203
+
204
+ return cached;
205
+ }
206
+
207
+ type BlueBubblesCoreRuntime = ReturnType<typeof getBlueBubblesRuntime>;
208
+
209
+ function logVerbose(core: BlueBubblesCoreRuntime, runtime: BlueBubblesRuntimeEnv, message: string): void {
210
+ if (core.logging.shouldLogVerbose()) {
211
+ runtime.log?.(`[bluebubbles] ${message}`);
212
+ }
213
+ }
214
+
215
+ function logGroupAllowlistHint(params: {
216
+ runtime: BlueBubblesRuntimeEnv;
217
+ reason: string;
218
+ entry: string | null;
219
+ chatName?: string;
220
+ accountId?: string;
221
+ }): void {
222
+ const log = params.runtime.log ?? console.log;
223
+ const nameHint = params.chatName ? ` (group name: ${params.chatName})` : "";
224
+ const accountHint = params.accountId
225
+ ? ` (or channels.bluebubbles.accounts.${params.accountId}.groupAllowFrom)`
226
+ : "";
227
+ if (params.entry) {
228
+ log(
229
+ `[bluebubbles] group message blocked (${params.reason}). Allow this group by adding ` +
230
+ `"${params.entry}" to channels.bluebubbles.groupAllowFrom${nameHint}.`,
231
+ );
232
+ log(
233
+ `[bluebubbles] add to config: channels.bluebubbles.groupAllowFrom=["${params.entry}"]${accountHint}.`,
234
+ );
235
+ return;
236
+ }
237
+ log(
238
+ `[bluebubbles] group message blocked (${params.reason}). Allow groups by setting ` +
239
+ `channels.bluebubbles.groupPolicy="open" or adding a group id to ` +
240
+ `channels.bluebubbles.groupAllowFrom${accountHint}${nameHint}.`,
241
+ );
242
+ }
243
+
244
+ type WebhookTarget = {
245
+ account: ResolvedBlueBubblesAccount;
246
+ config: OpenClawConfig;
247
+ runtime: BlueBubblesRuntimeEnv;
248
+ core: BlueBubblesCoreRuntime;
249
+ path: string;
250
+ statusSink?: (patch: { lastInboundAt?: number; lastOutboundAt?: number }) => void;
251
+ };
252
+
253
+ /**
254
+ * Entry type for debouncing inbound messages.
255
+ * Captures the normalized message and its target for later combined processing.
256
+ */
257
+ type BlueBubblesDebounceEntry = {
258
+ message: NormalizedWebhookMessage;
259
+ target: WebhookTarget;
260
+ };
261
+
262
+ /**
263
+ * Default debounce window for inbound message coalescing (ms).
264
+ * This helps combine URL text + link preview balloon messages that BlueBubbles
265
+ * sends as separate webhook events when no explicit inbound debounce config exists.
266
+ */
267
+ const DEFAULT_INBOUND_DEBOUNCE_MS = 350;
268
+
269
+ /**
270
+ * Combines multiple debounced messages into a single message for processing.
271
+ * Used when multiple webhook events arrive within the debounce window.
272
+ */
273
+ function combineDebounceEntries(entries: BlueBubblesDebounceEntry[]): NormalizedWebhookMessage {
274
+ if (entries.length === 0) {
275
+ throw new Error("Cannot combine empty entries");
276
+ }
277
+ if (entries.length === 1) {
278
+ return entries[0].message;
279
+ }
280
+
281
+ // Use the first message as the base (typically the text message)
282
+ const first = entries[0].message;
283
+
284
+ // Combine text from all entries, filtering out duplicates and empty strings
285
+ const seenTexts = new Set<string>();
286
+ const textParts: string[] = [];
287
+
288
+ for (const entry of entries) {
289
+ const text = entry.message.text.trim();
290
+ if (!text) continue;
291
+ // Skip duplicate text (URL might be in both text message and balloon)
292
+ const normalizedText = text.toLowerCase();
293
+ if (seenTexts.has(normalizedText)) continue;
294
+ seenTexts.add(normalizedText);
295
+ textParts.push(text);
296
+ }
297
+
298
+ // Merge attachments from all entries
299
+ const allAttachments = entries.flatMap((e) => e.message.attachments ?? []);
300
+
301
+ // Use the latest timestamp
302
+ const timestamps = entries
303
+ .map((e) => e.message.timestamp)
304
+ .filter((t): t is number => typeof t === "number");
305
+ const latestTimestamp = timestamps.length > 0 ? Math.max(...timestamps) : first.timestamp;
306
+
307
+ // Collect all message IDs for reference
308
+ const messageIds = entries
309
+ .map((e) => e.message.messageId)
310
+ .filter((id): id is string => Boolean(id));
311
+
312
+ // Prefer reply context from any entry that has it
313
+ const entryWithReply = entries.find((e) => e.message.replyToId);
314
+
315
+ return {
316
+ ...first,
317
+ text: textParts.join(" "),
318
+ attachments: allAttachments.length > 0 ? allAttachments : first.attachments,
319
+ timestamp: latestTimestamp,
320
+ // Use first message's ID as primary (for reply reference), but we've coalesced others
321
+ messageId: messageIds[0] ?? first.messageId,
322
+ // Preserve reply context if present
323
+ replyToId: entryWithReply?.message.replyToId ?? first.replyToId,
324
+ replyToBody: entryWithReply?.message.replyToBody ?? first.replyToBody,
325
+ replyToSender: entryWithReply?.message.replyToSender ?? first.replyToSender,
326
+ // Clear balloonBundleId since we've combined (the combined message is no longer just a balloon)
327
+ balloonBundleId: undefined,
328
+ };
329
+ }
330
+
331
+ const webhookTargets = new Map<string, WebhookTarget[]>();
332
+
333
+ /**
334
+ * Maps webhook targets to their inbound debouncers.
335
+ * Each target gets its own debouncer keyed by a unique identifier.
336
+ */
337
+ const targetDebouncers = new Map<
338
+ WebhookTarget,
339
+ ReturnType<BlueBubblesCoreRuntime["channel"]["debounce"]["createInboundDebouncer"]>
340
+ >();
341
+
342
+ function resolveBlueBubblesDebounceMs(
343
+ config: OpenClawConfig,
344
+ core: BlueBubblesCoreRuntime,
345
+ ): number {
346
+ const inbound = config.messages?.inbound;
347
+ const hasExplicitDebounce =
348
+ typeof inbound?.debounceMs === "number" || typeof inbound?.byChannel?.bluebubbles === "number";
349
+ if (!hasExplicitDebounce) return DEFAULT_INBOUND_DEBOUNCE_MS;
350
+ return core.channel.debounce.resolveInboundDebounceMs({ cfg: config, channel: "bluebubbles" });
351
+ }
352
+
353
+ /**
354
+ * Creates or retrieves a debouncer for a webhook target.
355
+ */
356
+ function getOrCreateDebouncer(target: WebhookTarget) {
357
+ const existing = targetDebouncers.get(target);
358
+ if (existing) return existing;
359
+
360
+ const { account, config, runtime, core } = target;
361
+
362
+ const debouncer = core.channel.debounce.createInboundDebouncer<BlueBubblesDebounceEntry>({
363
+ debounceMs: resolveBlueBubblesDebounceMs(config, core),
364
+ buildKey: (entry) => {
365
+ const msg = entry.message;
366
+ // Build key from account + chat + sender to coalesce messages from same source
367
+ const chatKey =
368
+ msg.chatGuid?.trim() ??
369
+ msg.chatIdentifier?.trim() ??
370
+ (msg.chatId ? String(msg.chatId) : "dm");
371
+ return `bluebubbles:${account.accountId}:${chatKey}:${msg.senderId}`;
372
+ },
373
+ shouldDebounce: (entry) => {
374
+ const msg = entry.message;
375
+ // Skip debouncing for messages with attachments - process immediately
376
+ if (msg.attachments && msg.attachments.length > 0) return false;
377
+ // Skip debouncing for from-me messages (they're just cached, not processed)
378
+ if (msg.fromMe) return false;
379
+ // Skip debouncing for control commands - process immediately
380
+ if (core.channel.text.hasControlCommand(msg.text, config)) return false;
381
+ // Debounce normal text messages and URL balloon messages
382
+ return true;
383
+ },
384
+ onFlush: async (entries) => {
385
+ if (entries.length === 0) return;
386
+
387
+ // Use target from first entry (all entries have same target due to key structure)
388
+ const flushTarget = entries[0].target;
389
+
390
+ if (entries.length === 1) {
391
+ // Single message - process normally
392
+ await processMessage(entries[0].message, flushTarget);
393
+ return;
394
+ }
395
+
396
+ // Multiple messages - combine and process
397
+ const combined = combineDebounceEntries(entries);
398
+
399
+ if (core.logging.shouldLogVerbose()) {
400
+ const count = entries.length;
401
+ const preview = combined.text.slice(0, 50);
402
+ runtime.log?.(
403
+ `[bluebubbles] coalesced ${count} messages: "${preview}${combined.text.length > 50 ? "..." : ""}"`,
404
+ );
405
+ }
406
+
407
+ await processMessage(combined, flushTarget);
408
+ },
409
+ onError: (err) => {
410
+ runtime.error?.(`[${account.accountId}] [bluebubbles] debounce flush failed: ${String(err)}`);
411
+ },
412
+ });
413
+
414
+ targetDebouncers.set(target, debouncer);
415
+ return debouncer;
416
+ }
417
+
418
+ /**
419
+ * Removes a debouncer for a target (called during unregistration).
420
+ */
421
+ function removeDebouncer(target: WebhookTarget): void {
422
+ targetDebouncers.delete(target);
423
+ }
424
+
425
+ function normalizeWebhookPath(raw: string): string {
426
+ const trimmed = raw.trim();
427
+ if (!trimmed) return "/";
428
+ const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
429
+ if (withSlash.length > 1 && withSlash.endsWith("/")) {
430
+ return withSlash.slice(0, -1);
431
+ }
432
+ return withSlash;
433
+ }
434
+
435
+ export function registerBlueBubblesWebhookTarget(target: WebhookTarget): () => void {
436
+ const key = normalizeWebhookPath(target.path);
437
+ const normalizedTarget = { ...target, path: key };
438
+ const existing = webhookTargets.get(key) ?? [];
439
+ const next = [...existing, normalizedTarget];
440
+ webhookTargets.set(key, next);
441
+ return () => {
442
+ const updated = (webhookTargets.get(key) ?? []).filter((entry) => entry !== normalizedTarget);
443
+ if (updated.length > 0) {
444
+ webhookTargets.set(key, updated);
445
+ } else {
446
+ webhookTargets.delete(key);
447
+ }
448
+ // Clean up debouncer when target is unregistered
449
+ removeDebouncer(normalizedTarget);
450
+ };
451
+ }
452
+
453
+ async function readJsonBody(req: IncomingMessage, maxBytes: number) {
454
+ const chunks: Buffer[] = [];
455
+ let total = 0;
456
+ return await new Promise<{ ok: boolean; value?: unknown; error?: string }>((resolve) => {
457
+ req.on("data", (chunk: Buffer) => {
458
+ total += chunk.length;
459
+ if (total > maxBytes) {
460
+ resolve({ ok: false, error: "payload too large" });
461
+ req.destroy();
462
+ return;
463
+ }
464
+ chunks.push(chunk);
465
+ });
466
+ req.on("end", () => {
467
+ try {
468
+ const raw = Buffer.concat(chunks).toString("utf8");
469
+ if (!raw.trim()) {
470
+ resolve({ ok: false, error: "empty payload" });
471
+ return;
472
+ }
473
+ try {
474
+ resolve({ ok: true, value: JSON.parse(raw) as unknown });
475
+ return;
476
+ } catch {
477
+ const params = new URLSearchParams(raw);
478
+ const payload = params.get("payload") ?? params.get("data") ?? params.get("message");
479
+ if (payload) {
480
+ resolve({ ok: true, value: JSON.parse(payload) as unknown });
481
+ return;
482
+ }
483
+ throw new Error("invalid json");
484
+ }
485
+ } catch (err) {
486
+ resolve({ ok: false, error: err instanceof Error ? err.message : String(err) });
487
+ }
488
+ });
489
+ req.on("error", (err) => {
490
+ resolve({ ok: false, error: err instanceof Error ? err.message : String(err) });
491
+ });
492
+ });
493
+ }
494
+
495
+ function asRecord(value: unknown): Record<string, unknown> | null {
496
+ return value && typeof value === "object" && !Array.isArray(value)
497
+ ? (value as Record<string, unknown>)
498
+ : null;
499
+ }
500
+
501
+ function readString(record: Record<string, unknown> | null, key: string): string | undefined {
502
+ if (!record) return undefined;
503
+ const value = record[key];
504
+ return typeof value === "string" ? value : undefined;
505
+ }
506
+
507
+ function readNumber(record: Record<string, unknown> | null, key: string): number | undefined {
508
+ if (!record) return undefined;
509
+ const value = record[key];
510
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
511
+ }
512
+
513
+ function readBoolean(record: Record<string, unknown> | null, key: string): boolean | undefined {
514
+ if (!record) return undefined;
515
+ const value = record[key];
516
+ return typeof value === "boolean" ? value : undefined;
517
+ }
518
+
519
+ function extractAttachments(message: Record<string, unknown>): BlueBubblesAttachment[] {
520
+ const raw = message["attachments"];
521
+ if (!Array.isArray(raw)) return [];
522
+ const out: BlueBubblesAttachment[] = [];
523
+ for (const entry of raw) {
524
+ const record = asRecord(entry);
525
+ if (!record) continue;
526
+ out.push({
527
+ guid: readString(record, "guid"),
528
+ uti: readString(record, "uti"),
529
+ mimeType: readString(record, "mimeType") ?? readString(record, "mime_type"),
530
+ transferName: readString(record, "transferName") ?? readString(record, "transfer_name"),
531
+ totalBytes: readNumberLike(record, "totalBytes") ?? readNumberLike(record, "total_bytes"),
532
+ height: readNumberLike(record, "height"),
533
+ width: readNumberLike(record, "width"),
534
+ originalROWID: readNumberLike(record, "originalROWID") ?? readNumberLike(record, "rowid"),
535
+ });
536
+ }
537
+ return out;
538
+ }
539
+
540
+ function buildAttachmentPlaceholder(attachments: BlueBubblesAttachment[]): string {
541
+ if (attachments.length === 0) return "";
542
+ const mimeTypes = attachments.map((entry) => entry.mimeType ?? "");
543
+ const allImages = mimeTypes.every((entry) => entry.startsWith("image/"));
544
+ const allVideos = mimeTypes.every((entry) => entry.startsWith("video/"));
545
+ const allAudio = mimeTypes.every((entry) => entry.startsWith("audio/"));
546
+ const tag = allImages
547
+ ? "<media:image>"
548
+ : allVideos
549
+ ? "<media:video>"
550
+ : allAudio
551
+ ? "<media:audio>"
552
+ : "<media:attachment>";
553
+ const label = allImages ? "image" : allVideos ? "video" : allAudio ? "audio" : "file";
554
+ const suffix = attachments.length === 1 ? label : `${label}s`;
555
+ return `${tag} (${attachments.length} ${suffix})`;
556
+ }
557
+
558
+ function buildMessagePlaceholder(message: NormalizedWebhookMessage): string {
559
+ const attachmentPlaceholder = buildAttachmentPlaceholder(message.attachments ?? []);
560
+ if (attachmentPlaceholder) return attachmentPlaceholder;
561
+ if (message.balloonBundleId) return "<media:sticker>";
562
+ return "";
563
+ }
564
+
565
+ // Returns inline reply tag like "[[reply_to:4]]" for prepending to message body
566
+ function formatReplyTag(message: {
567
+ replyToId?: string;
568
+ replyToShortId?: string;
569
+ }): string | null {
570
+ // Prefer short ID
571
+ const rawId = message.replyToShortId || message.replyToId;
572
+ if (!rawId) return null;
573
+ return `[[reply_to:${rawId}]]`;
574
+ }
575
+
576
+ function readNumberLike(record: Record<string, unknown> | null, key: string): number | undefined {
577
+ if (!record) return undefined;
578
+ const value = record[key];
579
+ if (typeof value === "number" && Number.isFinite(value)) return value;
580
+ if (typeof value === "string") {
581
+ const parsed = Number.parseFloat(value);
582
+ if (Number.isFinite(parsed)) return parsed;
583
+ }
584
+ return undefined;
585
+ }
586
+
587
+ function extractReplyMetadata(message: Record<string, unknown>): {
588
+ replyToId?: string;
589
+ replyToBody?: string;
590
+ replyToSender?: string;
591
+ } {
592
+ const replyRaw =
593
+ message["replyTo"] ??
594
+ message["reply_to"] ??
595
+ message["replyToMessage"] ??
596
+ message["reply_to_message"] ??
597
+ message["repliedMessage"] ??
598
+ message["quotedMessage"] ??
599
+ message["associatedMessage"] ??
600
+ message["reply"];
601
+ const replyRecord = asRecord(replyRaw);
602
+ const replyHandle = asRecord(replyRecord?.["handle"]) ?? asRecord(replyRecord?.["sender"]) ?? null;
603
+ const replySenderRaw =
604
+ readString(replyHandle, "address") ??
605
+ readString(replyHandle, "handle") ??
606
+ readString(replyHandle, "id") ??
607
+ readString(replyRecord, "senderId") ??
608
+ readString(replyRecord, "sender") ??
609
+ readString(replyRecord, "from");
610
+ const normalizedSender = replySenderRaw
611
+ ? normalizeBlueBubblesHandle(replySenderRaw) || replySenderRaw.trim()
612
+ : undefined;
613
+
614
+ const replyToBody =
615
+ readString(replyRecord, "text") ??
616
+ readString(replyRecord, "body") ??
617
+ readString(replyRecord, "message") ??
618
+ readString(replyRecord, "subject") ??
619
+ undefined;
620
+
621
+ const directReplyId =
622
+ readString(message, "replyToMessageGuid") ??
623
+ readString(message, "replyToGuid") ??
624
+ readString(message, "replyGuid") ??
625
+ readString(message, "selectedMessageGuid") ??
626
+ readString(message, "selectedMessageId") ??
627
+ readString(message, "replyToMessageId") ??
628
+ readString(message, "replyId") ??
629
+ readString(replyRecord, "guid") ??
630
+ readString(replyRecord, "id") ??
631
+ readString(replyRecord, "messageId");
632
+
633
+ const associatedType =
634
+ readNumberLike(message, "associatedMessageType") ??
635
+ readNumberLike(message, "associated_message_type");
636
+ const associatedGuid =
637
+ readString(message, "associatedMessageGuid") ??
638
+ readString(message, "associated_message_guid") ??
639
+ readString(message, "associatedMessageId");
640
+ const isReactionAssociation =
641
+ typeof associatedType === "number" && REACTION_TYPE_MAP.has(associatedType);
642
+
643
+ const replyToId = directReplyId ?? (!isReactionAssociation ? associatedGuid : undefined);
644
+ const threadOriginatorGuid = readString(message, "threadOriginatorGuid");
645
+ const messageGuid = readString(message, "guid");
646
+ const fallbackReplyId =
647
+ !replyToId && threadOriginatorGuid && threadOriginatorGuid !== messageGuid
648
+ ? threadOriginatorGuid
649
+ : undefined;
650
+
651
+ return {
652
+ replyToId: (replyToId ?? fallbackReplyId)?.trim() || undefined,
653
+ replyToBody: replyToBody?.trim() || undefined,
654
+ replyToSender: normalizedSender || undefined,
655
+ };
656
+ }
657
+
658
+ function readFirstChatRecord(message: Record<string, unknown>): Record<string, unknown> | null {
659
+ const chats = message["chats"];
660
+ if (!Array.isArray(chats) || chats.length === 0) return null;
661
+ const first = chats[0];
662
+ return asRecord(first);
663
+ }
664
+
665
+ function normalizeParticipantEntry(entry: unknown): BlueBubblesParticipant | null {
666
+ if (typeof entry === "string" || typeof entry === "number") {
667
+ const raw = String(entry).trim();
668
+ if (!raw) return null;
669
+ const normalized = normalizeBlueBubblesHandle(raw) || raw;
670
+ return normalized ? { id: normalized } : null;
671
+ }
672
+ const record = asRecord(entry);
673
+ if (!record) return null;
674
+ const nestedHandle =
675
+ asRecord(record["handle"]) ?? asRecord(record["sender"]) ?? asRecord(record["contact"]) ?? null;
676
+ const idRaw =
677
+ readString(record, "address") ??
678
+ readString(record, "handle") ??
679
+ readString(record, "id") ??
680
+ readString(record, "phoneNumber") ??
681
+ readString(record, "phone_number") ??
682
+ readString(record, "email") ??
683
+ readString(nestedHandle, "address") ??
684
+ readString(nestedHandle, "handle") ??
685
+ readString(nestedHandle, "id");
686
+ const nameRaw =
687
+ readString(record, "displayName") ??
688
+ readString(record, "name") ??
689
+ readString(record, "title") ??
690
+ readString(nestedHandle, "displayName") ??
691
+ readString(nestedHandle, "name");
692
+ const normalizedId = idRaw ? normalizeBlueBubblesHandle(idRaw) || idRaw.trim() : "";
693
+ if (!normalizedId) return null;
694
+ const name = nameRaw?.trim() || undefined;
695
+ return { id: normalizedId, name };
696
+ }
697
+
698
+ function normalizeParticipantList(raw: unknown): BlueBubblesParticipant[] {
699
+ if (!Array.isArray(raw) || raw.length === 0) return [];
700
+ const seen = new Set<string>();
701
+ const output: BlueBubblesParticipant[] = [];
702
+ for (const entry of raw) {
703
+ const normalized = normalizeParticipantEntry(entry);
704
+ if (!normalized?.id) continue;
705
+ const key = normalized.id.toLowerCase();
706
+ if (seen.has(key)) continue;
707
+ seen.add(key);
708
+ output.push(normalized);
709
+ }
710
+ return output;
711
+ }
712
+
713
+ function formatGroupMembers(params: {
714
+ participants?: BlueBubblesParticipant[];
715
+ fallback?: BlueBubblesParticipant;
716
+ }): string | undefined {
717
+ const seen = new Set<string>();
718
+ const ordered: BlueBubblesParticipant[] = [];
719
+ for (const entry of params.participants ?? []) {
720
+ if (!entry?.id) continue;
721
+ const key = entry.id.toLowerCase();
722
+ if (seen.has(key)) continue;
723
+ seen.add(key);
724
+ ordered.push(entry);
725
+ }
726
+ if (ordered.length === 0 && params.fallback?.id) {
727
+ ordered.push(params.fallback);
728
+ }
729
+ if (ordered.length === 0) return undefined;
730
+ return ordered
731
+ .map((entry) => (entry.name ? `${entry.name} (${entry.id})` : entry.id))
732
+ .join(", ");
733
+ }
734
+
735
+ function resolveGroupFlagFromChatGuid(chatGuid?: string | null): boolean | undefined {
736
+ const guid = chatGuid?.trim();
737
+ if (!guid) return undefined;
738
+ const parts = guid.split(";");
739
+ if (parts.length >= 3) {
740
+ if (parts[1] === "+") return true;
741
+ if (parts[1] === "-") return false;
742
+ }
743
+ if (guid.includes(";+;")) return true;
744
+ if (guid.includes(";-;")) return false;
745
+ return undefined;
746
+ }
747
+
748
+ function extractChatIdentifierFromChatGuid(chatGuid?: string | null): string | undefined {
749
+ const guid = chatGuid?.trim();
750
+ if (!guid) return undefined;
751
+ const parts = guid.split(";");
752
+ if (parts.length < 3) return undefined;
753
+ const identifier = parts[2]?.trim();
754
+ return identifier || undefined;
755
+ }
756
+
757
+ function formatGroupAllowlistEntry(params: {
758
+ chatGuid?: string;
759
+ chatId?: number;
760
+ chatIdentifier?: string;
761
+ }): string | null {
762
+ const guid = params.chatGuid?.trim();
763
+ if (guid) return `chat_guid:${guid}`;
764
+ const chatId = params.chatId;
765
+ if (typeof chatId === "number" && Number.isFinite(chatId)) return `chat_id:${chatId}`;
766
+ const identifier = params.chatIdentifier?.trim();
767
+ if (identifier) return `chat_identifier:${identifier}`;
768
+ return null;
769
+ }
770
+
771
+ type BlueBubblesParticipant = {
772
+ id: string;
773
+ name?: string;
774
+ };
775
+
776
+ type NormalizedWebhookMessage = {
777
+ text: string;
778
+ senderId: string;
779
+ senderName?: string;
780
+ messageId?: string;
781
+ timestamp?: number;
782
+ isGroup: boolean;
783
+ chatId?: number;
784
+ chatGuid?: string;
785
+ chatIdentifier?: string;
786
+ chatName?: string;
787
+ fromMe?: boolean;
788
+ attachments?: BlueBubblesAttachment[];
789
+ balloonBundleId?: string;
790
+ associatedMessageGuid?: string;
791
+ associatedMessageType?: number;
792
+ associatedMessageEmoji?: string;
793
+ isTapback?: boolean;
794
+ participants?: BlueBubblesParticipant[];
795
+ replyToId?: string;
796
+ replyToBody?: string;
797
+ replyToSender?: string;
798
+ };
799
+
800
+ type NormalizedWebhookReaction = {
801
+ action: "added" | "removed";
802
+ emoji: string;
803
+ senderId: string;
804
+ senderName?: string;
805
+ messageId: string;
806
+ timestamp?: number;
807
+ isGroup: boolean;
808
+ chatId?: number;
809
+ chatGuid?: string;
810
+ chatIdentifier?: string;
811
+ chatName?: string;
812
+ fromMe?: boolean;
813
+ };
814
+
815
+ const REACTION_TYPE_MAP = new Map<number, { emoji: string; action: "added" | "removed" }>([
816
+ [2000, { emoji: "❤️", action: "added" }],
817
+ [2001, { emoji: "👍", action: "added" }],
818
+ [2002, { emoji: "👎", action: "added" }],
819
+ [2003, { emoji: "😂", action: "added" }],
820
+ [2004, { emoji: "‼️", action: "added" }],
821
+ [2005, { emoji: "❓", action: "added" }],
822
+ [3000, { emoji: "❤️", action: "removed" }],
823
+ [3001, { emoji: "👍", action: "removed" }],
824
+ [3002, { emoji: "👎", action: "removed" }],
825
+ [3003, { emoji: "😂", action: "removed" }],
826
+ [3004, { emoji: "‼️", action: "removed" }],
827
+ [3005, { emoji: "❓", action: "removed" }],
828
+ ]);
829
+
830
+ // Maps tapback text patterns (e.g., "Loved", "Liked") to emoji + action
831
+ const TAPBACK_TEXT_MAP = new Map<string, { emoji: string; action: "added" | "removed" }>([
832
+ ["loved", { emoji: "❤️", action: "added" }],
833
+ ["liked", { emoji: "👍", action: "added" }],
834
+ ["disliked", { emoji: "👎", action: "added" }],
835
+ ["laughed at", { emoji: "😂", action: "added" }],
836
+ ["emphasized", { emoji: "‼️", action: "added" }],
837
+ ["questioned", { emoji: "❓", action: "added" }],
838
+ // Removal patterns (e.g., "Removed a heart from")
839
+ ["removed a heart from", { emoji: "❤️", action: "removed" }],
840
+ ["removed a like from", { emoji: "👍", action: "removed" }],
841
+ ["removed a dislike from", { emoji: "👎", action: "removed" }],
842
+ ["removed a laugh from", { emoji: "😂", action: "removed" }],
843
+ ["removed an emphasis from", { emoji: "‼️", action: "removed" }],
844
+ ["removed a question from", { emoji: "❓", action: "removed" }],
845
+ ]);
846
+
847
+ const TAPBACK_EMOJI_REGEX =
848
+ /(?:\p{Regional_Indicator}{2})|(?:[0-9#*]\uFE0F?\u20E3)|(?:\p{Extended_Pictographic}(?:\uFE0F|\uFE0E)?(?:\p{Emoji_Modifier})?(?:\u200D\p{Extended_Pictographic}(?:\uFE0F|\uFE0E)?(?:\p{Emoji_Modifier})?)*)/u;
849
+
850
+ function extractFirstEmoji(text: string): string | null {
851
+ const match = text.match(TAPBACK_EMOJI_REGEX);
852
+ return match ? match[0] : null;
853
+ }
854
+
855
+ function extractQuotedTapbackText(text: string): string | null {
856
+ const match = text.match(/[“"]([^”"]+)[”"]/s);
857
+ return match ? match[1] : null;
858
+ }
859
+
860
+ function isTapbackAssociatedType(type: number | undefined): boolean {
861
+ return typeof type === "number" && Number.isFinite(type) && type >= 2000 && type < 4000;
862
+ }
863
+
864
+ function resolveTapbackActionHint(type: number | undefined): "added" | "removed" | undefined {
865
+ if (typeof type !== "number" || !Number.isFinite(type)) return undefined;
866
+ if (type >= 3000 && type < 4000) return "removed";
867
+ if (type >= 2000 && type < 3000) return "added";
868
+ return undefined;
869
+ }
870
+
871
+ function resolveTapbackContext(message: NormalizedWebhookMessage): {
872
+ emojiHint?: string;
873
+ actionHint?: "added" | "removed";
874
+ replyToId?: string;
875
+ } | null {
876
+ const associatedType = message.associatedMessageType;
877
+ const hasTapbackType = isTapbackAssociatedType(associatedType);
878
+ const hasTapbackMarker = Boolean(message.associatedMessageEmoji) || Boolean(message.isTapback);
879
+ if (!hasTapbackType && !hasTapbackMarker) return null;
880
+ const replyToId = message.associatedMessageGuid?.trim() || message.replyToId?.trim() || undefined;
881
+ const actionHint = resolveTapbackActionHint(associatedType);
882
+ const emojiHint =
883
+ message.associatedMessageEmoji?.trim() || REACTION_TYPE_MAP.get(associatedType ?? -1)?.emoji;
884
+ return { emojiHint, actionHint, replyToId };
885
+ }
886
+
887
+ // Detects tapback text patterns like 'Loved "message"' and converts to structured format
888
+ function parseTapbackText(params: {
889
+ text: string;
890
+ emojiHint?: string;
891
+ actionHint?: "added" | "removed";
892
+ requireQuoted?: boolean;
893
+ }): {
894
+ emoji: string;
895
+ action: "added" | "removed";
896
+ quotedText: string;
897
+ } | null {
898
+ const trimmed = params.text.trim();
899
+ const lower = trimmed.toLowerCase();
900
+ if (!trimmed) return null;
901
+
902
+ for (const [pattern, { emoji, action }] of TAPBACK_TEXT_MAP) {
903
+ if (lower.startsWith(pattern)) {
904
+ // Extract quoted text if present (e.g., 'Loved "hello"' -> "hello")
905
+ const afterPattern = trimmed.slice(pattern.length).trim();
906
+ if (params.requireQuoted) {
907
+ const strictMatch = afterPattern.match(/^[“"](.+)[”"]$/s);
908
+ if (!strictMatch) return null;
909
+ return { emoji, action, quotedText: strictMatch[1] };
910
+ }
911
+ const quotedText =
912
+ extractQuotedTapbackText(afterPattern) ?? extractQuotedTapbackText(trimmed) ?? afterPattern;
913
+ return { emoji, action, quotedText };
914
+ }
915
+ }
916
+
917
+ if (lower.startsWith("reacted")) {
918
+ const emoji = extractFirstEmoji(trimmed) ?? params.emojiHint;
919
+ if (!emoji) return null;
920
+ const quotedText = extractQuotedTapbackText(trimmed);
921
+ if (params.requireQuoted && !quotedText) return null;
922
+ const fallback = trimmed.slice("reacted".length).trim();
923
+ return { emoji, action: params.actionHint ?? "added", quotedText: quotedText ?? fallback };
924
+ }
925
+
926
+ if (lower.startsWith("removed")) {
927
+ const emoji = extractFirstEmoji(trimmed) ?? params.emojiHint;
928
+ if (!emoji) return null;
929
+ const quotedText = extractQuotedTapbackText(trimmed);
930
+ if (params.requireQuoted && !quotedText) return null;
931
+ const fallback = trimmed.slice("removed".length).trim();
932
+ return { emoji, action: params.actionHint ?? "removed", quotedText: quotedText ?? fallback };
933
+ }
934
+ return null;
935
+ }
936
+
937
+ function maskSecret(value: string): string {
938
+ if (value.length <= 6) return "***";
939
+ return `${value.slice(0, 2)}***${value.slice(-2)}`;
940
+ }
941
+
942
+ function resolveBlueBubblesAckReaction(params: {
943
+ cfg: OpenClawConfig;
944
+ agentId: string;
945
+ core: BlueBubblesCoreRuntime;
946
+ runtime: BlueBubblesRuntimeEnv;
947
+ }): string | null {
948
+ const raw = resolveAckReaction(params.cfg, params.agentId).trim();
949
+ if (!raw) return null;
950
+ try {
951
+ normalizeBlueBubblesReactionInput(raw);
952
+ return raw;
953
+ } catch {
954
+ const key = raw.toLowerCase();
955
+ if (!invalidAckReactions.has(key)) {
956
+ invalidAckReactions.add(key);
957
+ logVerbose(
958
+ params.core,
959
+ params.runtime,
960
+ `ack reaction skipped (unsupported for BlueBubbles): ${raw}`,
961
+ );
962
+ }
963
+ return null;
964
+ }
965
+ }
966
+
967
+ function extractMessagePayload(payload: Record<string, unknown>): Record<string, unknown> | null {
968
+ const dataRaw = payload.data ?? payload.payload ?? payload.event;
969
+ const data =
970
+ asRecord(dataRaw) ??
971
+ (typeof dataRaw === "string" ? (asRecord(JSON.parse(dataRaw)) ?? null) : null);
972
+ const messageRaw = payload.message ?? data?.message ?? data;
973
+ const message =
974
+ asRecord(messageRaw) ??
975
+ (typeof messageRaw === "string" ? (asRecord(JSON.parse(messageRaw)) ?? null) : null);
976
+ if (!message) return null;
977
+ return message;
978
+ }
979
+
980
+ function normalizeWebhookMessage(payload: Record<string, unknown>): NormalizedWebhookMessage | null {
981
+ const message = extractMessagePayload(payload);
982
+ if (!message) return null;
983
+
984
+ const text =
985
+ readString(message, "text") ??
986
+ readString(message, "body") ??
987
+ readString(message, "subject") ??
988
+ "";
989
+
990
+ const handleValue = message.handle ?? message.sender;
991
+ const handle =
992
+ asRecord(handleValue) ??
993
+ (typeof handleValue === "string" ? { address: handleValue } : null);
994
+ const senderId =
995
+ readString(handle, "address") ??
996
+ readString(handle, "handle") ??
997
+ readString(handle, "id") ??
998
+ readString(message, "senderId") ??
999
+ readString(message, "sender") ??
1000
+ readString(message, "from") ??
1001
+ "";
1002
+
1003
+ const senderName =
1004
+ readString(handle, "displayName") ??
1005
+ readString(handle, "name") ??
1006
+ readString(message, "senderName") ??
1007
+ undefined;
1008
+
1009
+ const chat = asRecord(message.chat) ?? asRecord(message.conversation) ?? null;
1010
+ const chatFromList = readFirstChatRecord(message);
1011
+ const chatGuid =
1012
+ readString(message, "chatGuid") ??
1013
+ readString(message, "chat_guid") ??
1014
+ readString(chat, "chatGuid") ??
1015
+ readString(chat, "chat_guid") ??
1016
+ readString(chat, "guid") ??
1017
+ readString(chatFromList, "chatGuid") ??
1018
+ readString(chatFromList, "chat_guid") ??
1019
+ readString(chatFromList, "guid");
1020
+ const chatIdentifier =
1021
+ readString(message, "chatIdentifier") ??
1022
+ readString(message, "chat_identifier") ??
1023
+ readString(chat, "chatIdentifier") ??
1024
+ readString(chat, "chat_identifier") ??
1025
+ readString(chat, "identifier") ??
1026
+ readString(chatFromList, "chatIdentifier") ??
1027
+ readString(chatFromList, "chat_identifier") ??
1028
+ readString(chatFromList, "identifier") ??
1029
+ extractChatIdentifierFromChatGuid(chatGuid);
1030
+ const chatId =
1031
+ readNumberLike(message, "chatId") ??
1032
+ readNumberLike(message, "chat_id") ??
1033
+ readNumberLike(chat, "chatId") ??
1034
+ readNumberLike(chat, "chat_id") ??
1035
+ readNumberLike(chat, "id") ??
1036
+ readNumberLike(chatFromList, "chatId") ??
1037
+ readNumberLike(chatFromList, "chat_id") ??
1038
+ readNumberLike(chatFromList, "id");
1039
+ const chatName =
1040
+ readString(message, "chatName") ??
1041
+ readString(chat, "displayName") ??
1042
+ readString(chat, "name") ??
1043
+ readString(chatFromList, "displayName") ??
1044
+ readString(chatFromList, "name") ??
1045
+ undefined;
1046
+
1047
+ const chatParticipants = chat ? chat["participants"] : undefined;
1048
+ const messageParticipants = message["participants"];
1049
+ const chatsParticipants = chatFromList ? chatFromList["participants"] : undefined;
1050
+ const participants = Array.isArray(chatParticipants)
1051
+ ? chatParticipants
1052
+ : Array.isArray(messageParticipants)
1053
+ ? messageParticipants
1054
+ : Array.isArray(chatsParticipants)
1055
+ ? chatsParticipants
1056
+ : [];
1057
+ const normalizedParticipants = normalizeParticipantList(participants);
1058
+ const participantsCount = participants.length;
1059
+ const groupFromChatGuid = resolveGroupFlagFromChatGuid(chatGuid);
1060
+ const explicitIsGroup =
1061
+ readBoolean(message, "isGroup") ??
1062
+ readBoolean(message, "is_group") ??
1063
+ readBoolean(chat, "isGroup") ??
1064
+ readBoolean(message, "group");
1065
+ const isGroup =
1066
+ typeof groupFromChatGuid === "boolean"
1067
+ ? groupFromChatGuid
1068
+ : explicitIsGroup ?? (participantsCount > 2 ? true : false);
1069
+
1070
+ const fromMe = readBoolean(message, "isFromMe") ?? readBoolean(message, "is_from_me");
1071
+ const messageId =
1072
+ readString(message, "guid") ??
1073
+ readString(message, "id") ??
1074
+ readString(message, "messageId") ??
1075
+ undefined;
1076
+ const balloonBundleId = readString(message, "balloonBundleId");
1077
+ const associatedMessageGuid =
1078
+ readString(message, "associatedMessageGuid") ??
1079
+ readString(message, "associated_message_guid") ??
1080
+ readString(message, "associatedMessageId") ??
1081
+ undefined;
1082
+ const associatedMessageType =
1083
+ readNumberLike(message, "associatedMessageType") ??
1084
+ readNumberLike(message, "associated_message_type");
1085
+ const associatedMessageEmoji =
1086
+ readString(message, "associatedMessageEmoji") ??
1087
+ readString(message, "associated_message_emoji") ??
1088
+ readString(message, "reactionEmoji") ??
1089
+ readString(message, "reaction_emoji") ??
1090
+ undefined;
1091
+ const isTapback =
1092
+ readBoolean(message, "isTapback") ??
1093
+ readBoolean(message, "is_tapback") ??
1094
+ readBoolean(message, "tapback") ??
1095
+ undefined;
1096
+
1097
+ const timestampRaw =
1098
+ readNumber(message, "date") ??
1099
+ readNumber(message, "dateCreated") ??
1100
+ readNumber(message, "timestamp");
1101
+ const timestamp =
1102
+ typeof timestampRaw === "number"
1103
+ ? timestampRaw > 1_000_000_000_000
1104
+ ? timestampRaw
1105
+ : timestampRaw * 1000
1106
+ : undefined;
1107
+
1108
+ const normalizedSender = normalizeBlueBubblesHandle(senderId);
1109
+ if (!normalizedSender) return null;
1110
+ const replyMetadata = extractReplyMetadata(message);
1111
+
1112
+ return {
1113
+ text,
1114
+ senderId: normalizedSender,
1115
+ senderName,
1116
+ messageId,
1117
+ timestamp,
1118
+ isGroup,
1119
+ chatId,
1120
+ chatGuid,
1121
+ chatIdentifier,
1122
+ chatName,
1123
+ fromMe,
1124
+ attachments: extractAttachments(message),
1125
+ balloonBundleId,
1126
+ associatedMessageGuid,
1127
+ associatedMessageType,
1128
+ associatedMessageEmoji,
1129
+ isTapback,
1130
+ participants: normalizedParticipants,
1131
+ replyToId: replyMetadata.replyToId,
1132
+ replyToBody: replyMetadata.replyToBody,
1133
+ replyToSender: replyMetadata.replyToSender,
1134
+ };
1135
+ }
1136
+
1137
+ function normalizeWebhookReaction(payload: Record<string, unknown>): NormalizedWebhookReaction | null {
1138
+ const message = extractMessagePayload(payload);
1139
+ if (!message) return null;
1140
+
1141
+ const associatedGuid =
1142
+ readString(message, "associatedMessageGuid") ??
1143
+ readString(message, "associated_message_guid") ??
1144
+ readString(message, "associatedMessageId");
1145
+ const associatedType =
1146
+ readNumberLike(message, "associatedMessageType") ??
1147
+ readNumberLike(message, "associated_message_type");
1148
+ if (!associatedGuid || associatedType === undefined) return null;
1149
+
1150
+ const mapping = REACTION_TYPE_MAP.get(associatedType);
1151
+ const associatedEmoji =
1152
+ readString(message, "associatedMessageEmoji") ??
1153
+ readString(message, "associated_message_emoji") ??
1154
+ readString(message, "reactionEmoji") ??
1155
+ readString(message, "reaction_emoji");
1156
+ const emoji = (associatedEmoji?.trim() || mapping?.emoji) ?? `reaction:${associatedType}`;
1157
+ const action = mapping?.action ?? resolveTapbackActionHint(associatedType) ?? "added";
1158
+
1159
+ const handleValue = message.handle ?? message.sender;
1160
+ const handle =
1161
+ asRecord(handleValue) ??
1162
+ (typeof handleValue === "string" ? { address: handleValue } : null);
1163
+ const senderId =
1164
+ readString(handle, "address") ??
1165
+ readString(handle, "handle") ??
1166
+ readString(handle, "id") ??
1167
+ readString(message, "senderId") ??
1168
+ readString(message, "sender") ??
1169
+ readString(message, "from") ??
1170
+ "";
1171
+ const senderName =
1172
+ readString(handle, "displayName") ??
1173
+ readString(handle, "name") ??
1174
+ readString(message, "senderName") ??
1175
+ undefined;
1176
+
1177
+ const chat = asRecord(message.chat) ?? asRecord(message.conversation) ?? null;
1178
+ const chatFromList = readFirstChatRecord(message);
1179
+ const chatGuid =
1180
+ readString(message, "chatGuid") ??
1181
+ readString(message, "chat_guid") ??
1182
+ readString(chat, "chatGuid") ??
1183
+ readString(chat, "chat_guid") ??
1184
+ readString(chat, "guid") ??
1185
+ readString(chatFromList, "chatGuid") ??
1186
+ readString(chatFromList, "chat_guid") ??
1187
+ readString(chatFromList, "guid");
1188
+ const chatIdentifier =
1189
+ readString(message, "chatIdentifier") ??
1190
+ readString(message, "chat_identifier") ??
1191
+ readString(chat, "chatIdentifier") ??
1192
+ readString(chat, "chat_identifier") ??
1193
+ readString(chat, "identifier") ??
1194
+ readString(chatFromList, "chatIdentifier") ??
1195
+ readString(chatFromList, "chat_identifier") ??
1196
+ readString(chatFromList, "identifier") ??
1197
+ extractChatIdentifierFromChatGuid(chatGuid);
1198
+ const chatId =
1199
+ readNumberLike(message, "chatId") ??
1200
+ readNumberLike(message, "chat_id") ??
1201
+ readNumberLike(chat, "chatId") ??
1202
+ readNumberLike(chat, "chat_id") ??
1203
+ readNumberLike(chat, "id") ??
1204
+ readNumberLike(chatFromList, "chatId") ??
1205
+ readNumberLike(chatFromList, "chat_id") ??
1206
+ readNumberLike(chatFromList, "id");
1207
+ const chatName =
1208
+ readString(message, "chatName") ??
1209
+ readString(chat, "displayName") ??
1210
+ readString(chat, "name") ??
1211
+ readString(chatFromList, "displayName") ??
1212
+ readString(chatFromList, "name") ??
1213
+ undefined;
1214
+
1215
+ const chatParticipants = chat ? chat["participants"] : undefined;
1216
+ const messageParticipants = message["participants"];
1217
+ const chatsParticipants = chatFromList ? chatFromList["participants"] : undefined;
1218
+ const participants = Array.isArray(chatParticipants)
1219
+ ? chatParticipants
1220
+ : Array.isArray(messageParticipants)
1221
+ ? messageParticipants
1222
+ : Array.isArray(chatsParticipants)
1223
+ ? chatsParticipants
1224
+ : [];
1225
+ const participantsCount = participants.length;
1226
+ const groupFromChatGuid = resolveGroupFlagFromChatGuid(chatGuid);
1227
+ const explicitIsGroup =
1228
+ readBoolean(message, "isGroup") ??
1229
+ readBoolean(message, "is_group") ??
1230
+ readBoolean(chat, "isGroup") ??
1231
+ readBoolean(message, "group");
1232
+ const isGroup =
1233
+ typeof groupFromChatGuid === "boolean"
1234
+ ? groupFromChatGuid
1235
+ : explicitIsGroup ?? (participantsCount > 2 ? true : false);
1236
+
1237
+ const fromMe = readBoolean(message, "isFromMe") ?? readBoolean(message, "is_from_me");
1238
+ const timestampRaw =
1239
+ readNumberLike(message, "date") ??
1240
+ readNumberLike(message, "dateCreated") ??
1241
+ readNumberLike(message, "timestamp");
1242
+ const timestamp =
1243
+ typeof timestampRaw === "number"
1244
+ ? timestampRaw > 1_000_000_000_000
1245
+ ? timestampRaw
1246
+ : timestampRaw * 1000
1247
+ : undefined;
1248
+
1249
+ const normalizedSender = normalizeBlueBubblesHandle(senderId);
1250
+ if (!normalizedSender) return null;
1251
+
1252
+ return {
1253
+ action,
1254
+ emoji,
1255
+ senderId: normalizedSender,
1256
+ senderName,
1257
+ messageId: associatedGuid,
1258
+ timestamp,
1259
+ isGroup,
1260
+ chatId,
1261
+ chatGuid,
1262
+ chatIdentifier,
1263
+ chatName,
1264
+ fromMe,
1265
+ };
1266
+ }
1267
+
1268
+ export async function handleBlueBubblesWebhookRequest(
1269
+ req: IncomingMessage,
1270
+ res: ServerResponse,
1271
+ ): Promise<boolean> {
1272
+ const url = new URL(req.url ?? "/", "http://localhost");
1273
+ const path = normalizeWebhookPath(url.pathname);
1274
+ const targets = webhookTargets.get(path);
1275
+ if (!targets || targets.length === 0) return false;
1276
+
1277
+ if (req.method !== "POST") {
1278
+ res.statusCode = 405;
1279
+ res.setHeader("Allow", "POST");
1280
+ res.end("Method Not Allowed");
1281
+ return true;
1282
+ }
1283
+
1284
+ const body = await readJsonBody(req, 1024 * 1024);
1285
+ if (!body.ok) {
1286
+ res.statusCode = body.error === "payload too large" ? 413 : 400;
1287
+ res.end(body.error ?? "invalid payload");
1288
+ console.warn(`[bluebubbles] webhook rejected: ${body.error ?? "invalid payload"}`);
1289
+ return true;
1290
+ }
1291
+
1292
+ const payload = asRecord(body.value) ?? {};
1293
+ const firstTarget = targets[0];
1294
+ if (firstTarget) {
1295
+ logVerbose(
1296
+ firstTarget.core,
1297
+ firstTarget.runtime,
1298
+ `webhook received path=${path} keys=${Object.keys(payload).join(",") || "none"}`,
1299
+ );
1300
+ }
1301
+ const eventTypeRaw = payload.type;
1302
+ const eventType = typeof eventTypeRaw === "string" ? eventTypeRaw.trim() : "";
1303
+ const allowedEventTypes = new Set([
1304
+ "new-message",
1305
+ "updated-message",
1306
+ "message-reaction",
1307
+ "reaction",
1308
+ ]);
1309
+ if (eventType && !allowedEventTypes.has(eventType)) {
1310
+ res.statusCode = 200;
1311
+ res.end("ok");
1312
+ if (firstTarget) {
1313
+ logVerbose(firstTarget.core, firstTarget.runtime, `webhook ignored type=${eventType}`);
1314
+ }
1315
+ return true;
1316
+ }
1317
+ const reaction = normalizeWebhookReaction(payload);
1318
+ if (
1319
+ (eventType === "updated-message" ||
1320
+ eventType === "message-reaction" ||
1321
+ eventType === "reaction") &&
1322
+ !reaction
1323
+ ) {
1324
+ res.statusCode = 200;
1325
+ res.end("ok");
1326
+ if (firstTarget) {
1327
+ logVerbose(
1328
+ firstTarget.core,
1329
+ firstTarget.runtime,
1330
+ `webhook ignored ${eventType || "event"} without reaction`,
1331
+ );
1332
+ }
1333
+ return true;
1334
+ }
1335
+ const message = reaction ? null : normalizeWebhookMessage(payload);
1336
+ if (!message && !reaction) {
1337
+ res.statusCode = 400;
1338
+ res.end("invalid payload");
1339
+ console.warn("[bluebubbles] webhook rejected: unable to parse message payload");
1340
+ return true;
1341
+ }
1342
+
1343
+ const matching = targets.filter((target) => {
1344
+ const token = target.account.config.password?.trim();
1345
+ if (!token) return true;
1346
+ const guidParam = url.searchParams.get("guid") ?? url.searchParams.get("password");
1347
+ const headerToken =
1348
+ req.headers["x-guid"] ??
1349
+ req.headers["x-password"] ??
1350
+ req.headers["x-bluebubbles-guid"] ??
1351
+ req.headers["authorization"];
1352
+ const guid =
1353
+ (Array.isArray(headerToken) ? headerToken[0] : headerToken) ?? guidParam ?? "";
1354
+ if (guid && guid.trim() === token) return true;
1355
+ const remote = req.socket?.remoteAddress ?? "";
1356
+ if (remote === "127.0.0.1" || remote === "::1" || remote === "::ffff:127.0.0.1") {
1357
+ return true;
1358
+ }
1359
+ return false;
1360
+ });
1361
+
1362
+ if (matching.length === 0) {
1363
+ res.statusCode = 401;
1364
+ res.end("unauthorized");
1365
+ console.warn(
1366
+ `[bluebubbles] webhook rejected: unauthorized guid=${maskSecret(url.searchParams.get("guid") ?? url.searchParams.get("password") ?? "")}`,
1367
+ );
1368
+ return true;
1369
+ }
1370
+
1371
+ for (const target of matching) {
1372
+ target.statusSink?.({ lastInboundAt: Date.now() });
1373
+ if (reaction) {
1374
+ processReaction(reaction, target).catch((err) => {
1375
+ target.runtime.error?.(
1376
+ `[${target.account.accountId}] BlueBubbles reaction failed: ${String(err)}`,
1377
+ );
1378
+ });
1379
+ } else if (message) {
1380
+ // Route messages through debouncer to coalesce rapid-fire events
1381
+ // (e.g., text message + URL balloon arriving as separate webhooks)
1382
+ const debouncer = getOrCreateDebouncer(target);
1383
+ debouncer.enqueue({ message, target }).catch((err) => {
1384
+ target.runtime.error?.(
1385
+ `[${target.account.accountId}] BlueBubbles webhook failed: ${String(err)}`,
1386
+ );
1387
+ });
1388
+ }
1389
+ }
1390
+
1391
+ res.statusCode = 200;
1392
+ res.end("ok");
1393
+ if (reaction) {
1394
+ if (firstTarget) {
1395
+ logVerbose(
1396
+ firstTarget.core,
1397
+ firstTarget.runtime,
1398
+ `webhook accepted reaction sender=${reaction.senderId} msg=${reaction.messageId} action=${reaction.action}`,
1399
+ );
1400
+ }
1401
+ } else if (message) {
1402
+ if (firstTarget) {
1403
+ logVerbose(
1404
+ firstTarget.core,
1405
+ firstTarget.runtime,
1406
+ `webhook accepted sender=${message.senderId} group=${message.isGroup} chatGuid=${message.chatGuid ?? ""} chatId=${message.chatId ?? ""}`,
1407
+ );
1408
+ }
1409
+ }
1410
+ return true;
1411
+ }
1412
+
1413
+ async function processMessage(
1414
+ message: NormalizedWebhookMessage,
1415
+ target: WebhookTarget,
1416
+ ): Promise<void> {
1417
+ const { account, config, runtime, core, statusSink } = target;
1418
+
1419
+ const groupFlag = resolveGroupFlagFromChatGuid(message.chatGuid);
1420
+ const isGroup = typeof groupFlag === "boolean" ? groupFlag : message.isGroup;
1421
+
1422
+ const text = message.text.trim();
1423
+ const attachments = message.attachments ?? [];
1424
+ const placeholder = buildMessagePlaceholder(message);
1425
+ // Check if text is a tapback pattern (e.g., 'Loved "hello"') and transform to emoji format
1426
+ // For tapbacks, we'll append [[reply_to:N]] at the end; for regular messages, prepend it
1427
+ const tapbackContext = resolveTapbackContext(message);
1428
+ const tapbackParsed = parseTapbackText({
1429
+ text,
1430
+ emojiHint: tapbackContext?.emojiHint,
1431
+ actionHint: tapbackContext?.actionHint,
1432
+ requireQuoted: !tapbackContext,
1433
+ });
1434
+ const isTapbackMessage = Boolean(tapbackParsed);
1435
+ const rawBody = tapbackParsed
1436
+ ? tapbackParsed.action === "removed"
1437
+ ? `removed ${tapbackParsed.emoji} reaction`
1438
+ : `reacted with ${tapbackParsed.emoji}`
1439
+ : text || placeholder;
1440
+
1441
+ const cacheMessageId = message.messageId?.trim();
1442
+ let messageShortId: string | undefined;
1443
+ const cacheInboundMessage = () => {
1444
+ if (!cacheMessageId) return;
1445
+ const cacheEntry = rememberBlueBubblesReplyCache({
1446
+ accountId: account.accountId,
1447
+ messageId: cacheMessageId,
1448
+ chatGuid: message.chatGuid,
1449
+ chatIdentifier: message.chatIdentifier,
1450
+ chatId: message.chatId,
1451
+ senderLabel: message.fromMe ? "me" : message.senderId,
1452
+ body: rawBody,
1453
+ timestamp: message.timestamp ?? Date.now(),
1454
+ });
1455
+ messageShortId = cacheEntry.shortId;
1456
+ };
1457
+
1458
+ if (message.fromMe) {
1459
+ // Cache from-me messages so reply context can resolve sender/body.
1460
+ cacheInboundMessage();
1461
+ return;
1462
+ }
1463
+
1464
+ if (!rawBody) {
1465
+ logVerbose(core, runtime, `drop: empty text sender=${message.senderId}`);
1466
+ return;
1467
+ }
1468
+ logVerbose(
1469
+ core,
1470
+ runtime,
1471
+ `msg sender=${message.senderId} group=${isGroup} textLen=${text.length} attachments=${attachments.length} chatGuid=${message.chatGuid ?? ""} chatId=${message.chatId ?? ""}`,
1472
+ );
1473
+
1474
+ const dmPolicy = account.config.dmPolicy ?? "pairing";
1475
+ const groupPolicy = account.config.groupPolicy ?? "allowlist";
1476
+ const configAllowFrom = (account.config.allowFrom ?? []).map((entry) => String(entry));
1477
+ const configGroupAllowFrom = (account.config.groupAllowFrom ?? []).map((entry) => String(entry));
1478
+ const storeAllowFrom = await core.channel.pairing
1479
+ .readAllowFromStore("bluebubbles")
1480
+ .catch(() => []);
1481
+ const effectiveAllowFrom = [...configAllowFrom, ...storeAllowFrom]
1482
+ .map((entry) => String(entry).trim())
1483
+ .filter(Boolean);
1484
+ const effectiveGroupAllowFrom = [
1485
+ ...(configGroupAllowFrom.length > 0 ? configGroupAllowFrom : configAllowFrom),
1486
+ ...storeAllowFrom,
1487
+ ]
1488
+ .map((entry) => String(entry).trim())
1489
+ .filter(Boolean);
1490
+ const groupAllowEntry = formatGroupAllowlistEntry({
1491
+ chatGuid: message.chatGuid,
1492
+ chatId: message.chatId ?? undefined,
1493
+ chatIdentifier: message.chatIdentifier ?? undefined,
1494
+ });
1495
+ const groupName = message.chatName?.trim() || undefined;
1496
+
1497
+ if (isGroup) {
1498
+ if (groupPolicy === "disabled") {
1499
+ logVerbose(core, runtime, "Blocked BlueBubbles group message (groupPolicy=disabled)");
1500
+ logGroupAllowlistHint({
1501
+ runtime,
1502
+ reason: "groupPolicy=disabled",
1503
+ entry: groupAllowEntry,
1504
+ chatName: groupName,
1505
+ accountId: account.accountId,
1506
+ });
1507
+ return;
1508
+ }
1509
+ if (groupPolicy === "allowlist") {
1510
+ if (effectiveGroupAllowFrom.length === 0) {
1511
+ logVerbose(core, runtime, "Blocked BlueBubbles group message (no allowlist)");
1512
+ logGroupAllowlistHint({
1513
+ runtime,
1514
+ reason: "groupPolicy=allowlist (empty allowlist)",
1515
+ entry: groupAllowEntry,
1516
+ chatName: groupName,
1517
+ accountId: account.accountId,
1518
+ });
1519
+ return;
1520
+ }
1521
+ const allowed = isAllowedBlueBubblesSender({
1522
+ allowFrom: effectiveGroupAllowFrom,
1523
+ sender: message.senderId,
1524
+ chatId: message.chatId ?? undefined,
1525
+ chatGuid: message.chatGuid ?? undefined,
1526
+ chatIdentifier: message.chatIdentifier ?? undefined,
1527
+ });
1528
+ if (!allowed) {
1529
+ logVerbose(
1530
+ core,
1531
+ runtime,
1532
+ `Blocked BlueBubbles sender ${message.senderId} (not in groupAllowFrom)`,
1533
+ );
1534
+ logVerbose(
1535
+ core,
1536
+ runtime,
1537
+ `drop: group sender not allowed sender=${message.senderId} allowFrom=${effectiveGroupAllowFrom.join(",")}`,
1538
+ );
1539
+ logGroupAllowlistHint({
1540
+ runtime,
1541
+ reason: "groupPolicy=allowlist (not allowlisted)",
1542
+ entry: groupAllowEntry,
1543
+ chatName: groupName,
1544
+ accountId: account.accountId,
1545
+ });
1546
+ return;
1547
+ }
1548
+ }
1549
+ } else {
1550
+ if (dmPolicy === "disabled") {
1551
+ logVerbose(core, runtime, `Blocked BlueBubbles DM from ${message.senderId}`);
1552
+ logVerbose(core, runtime, `drop: dmPolicy disabled sender=${message.senderId}`);
1553
+ return;
1554
+ }
1555
+ if (dmPolicy !== "open") {
1556
+ const allowed = isAllowedBlueBubblesSender({
1557
+ allowFrom: effectiveAllowFrom,
1558
+ sender: message.senderId,
1559
+ chatId: message.chatId ?? undefined,
1560
+ chatGuid: message.chatGuid ?? undefined,
1561
+ chatIdentifier: message.chatIdentifier ?? undefined,
1562
+ });
1563
+ if (!allowed) {
1564
+ if (dmPolicy === "pairing") {
1565
+ const { code, created } = await core.channel.pairing.upsertPairingRequest({
1566
+ channel: "bluebubbles",
1567
+ id: message.senderId,
1568
+ meta: { name: message.senderName },
1569
+ });
1570
+ runtime.log?.(
1571
+ `[bluebubbles] pairing request sender=${message.senderId} created=${created}`,
1572
+ );
1573
+ if (created) {
1574
+ logVerbose(core, runtime, `bluebubbles pairing request sender=${message.senderId}`);
1575
+ try {
1576
+ await sendMessageBlueBubbles(
1577
+ message.senderId,
1578
+ core.channel.pairing.buildPairingReply({
1579
+ channel: "bluebubbles",
1580
+ idLine: `Your BlueBubbles sender id: ${message.senderId}`,
1581
+ code,
1582
+ }),
1583
+ { cfg: config, accountId: account.accountId },
1584
+ );
1585
+ statusSink?.({ lastOutboundAt: Date.now() });
1586
+ } catch (err) {
1587
+ logVerbose(
1588
+ core,
1589
+ runtime,
1590
+ `bluebubbles pairing reply failed for ${message.senderId}: ${String(err)}`,
1591
+ );
1592
+ runtime.error?.(
1593
+ `[bluebubbles] pairing reply failed sender=${message.senderId}: ${String(err)}`,
1594
+ );
1595
+ }
1596
+ }
1597
+ } else {
1598
+ logVerbose(
1599
+ core,
1600
+ runtime,
1601
+ `Blocked unauthorized BlueBubbles sender ${message.senderId} (dmPolicy=${dmPolicy})`,
1602
+ );
1603
+ logVerbose(
1604
+ core,
1605
+ runtime,
1606
+ `drop: dm sender not allowed sender=${message.senderId} allowFrom=${effectiveAllowFrom.join(",")}`,
1607
+ );
1608
+ }
1609
+ return;
1610
+ }
1611
+ }
1612
+ }
1613
+
1614
+ const chatId = message.chatId ?? undefined;
1615
+ const chatGuid = message.chatGuid ?? undefined;
1616
+ const chatIdentifier = message.chatIdentifier ?? undefined;
1617
+ const peerId = isGroup
1618
+ ? chatGuid ?? chatIdentifier ?? (chatId ? String(chatId) : "group")
1619
+ : message.senderId;
1620
+
1621
+ const route = core.channel.routing.resolveAgentRoute({
1622
+ cfg: config,
1623
+ channel: "bluebubbles",
1624
+ accountId: account.accountId,
1625
+ peer: {
1626
+ kind: isGroup ? "group" : "dm",
1627
+ id: peerId,
1628
+ },
1629
+ });
1630
+
1631
+ // Mention gating for group chats (parity with iMessage/WhatsApp)
1632
+ const messageText = text;
1633
+ const mentionRegexes = core.channel.mentions.buildMentionRegexes(config, route.agentId);
1634
+ const wasMentioned = isGroup
1635
+ ? core.channel.mentions.matchesMentionPatterns(messageText, mentionRegexes)
1636
+ : true;
1637
+ const canDetectMention = mentionRegexes.length > 0;
1638
+ const requireMention = core.channel.groups.resolveRequireMention({
1639
+ cfg: config,
1640
+ channel: "bluebubbles",
1641
+ groupId: peerId,
1642
+ accountId: account.accountId,
1643
+ });
1644
+
1645
+ // Command gating (parity with iMessage/WhatsApp)
1646
+ const useAccessGroups = config.commands?.useAccessGroups !== false;
1647
+ const hasControlCmd = core.channel.text.hasControlCommand(messageText, config);
1648
+ const ownerAllowedForCommands =
1649
+ effectiveAllowFrom.length > 0
1650
+ ? isAllowedBlueBubblesSender({
1651
+ allowFrom: effectiveAllowFrom,
1652
+ sender: message.senderId,
1653
+ chatId: message.chatId ?? undefined,
1654
+ chatGuid: message.chatGuid ?? undefined,
1655
+ chatIdentifier: message.chatIdentifier ?? undefined,
1656
+ })
1657
+ : false;
1658
+ const groupAllowedForCommands =
1659
+ effectiveGroupAllowFrom.length > 0
1660
+ ? isAllowedBlueBubblesSender({
1661
+ allowFrom: effectiveGroupAllowFrom,
1662
+ sender: message.senderId,
1663
+ chatId: message.chatId ?? undefined,
1664
+ chatGuid: message.chatGuid ?? undefined,
1665
+ chatIdentifier: message.chatIdentifier ?? undefined,
1666
+ })
1667
+ : false;
1668
+ const dmAuthorized = dmPolicy === "open" || ownerAllowedForCommands;
1669
+ const commandGate = resolveControlCommandGate({
1670
+ useAccessGroups,
1671
+ authorizers: [
1672
+ { configured: effectiveAllowFrom.length > 0, allowed: ownerAllowedForCommands },
1673
+ { configured: effectiveGroupAllowFrom.length > 0, allowed: groupAllowedForCommands },
1674
+ ],
1675
+ allowTextCommands: true,
1676
+ hasControlCommand: hasControlCmd,
1677
+ });
1678
+ const commandAuthorized = isGroup ? commandGate.commandAuthorized : dmAuthorized;
1679
+
1680
+ // Block control commands from unauthorized senders in groups
1681
+ if (isGroup && commandGate.shouldBlock) {
1682
+ logInboundDrop({
1683
+ log: (msg) => logVerbose(core, runtime, msg),
1684
+ channel: "bluebubbles",
1685
+ reason: "control command (unauthorized)",
1686
+ target: message.senderId,
1687
+ });
1688
+ return;
1689
+ }
1690
+
1691
+ // Allow control commands to bypass mention gating when authorized (parity with iMessage)
1692
+ const shouldBypassMention =
1693
+ isGroup &&
1694
+ requireMention &&
1695
+ !wasMentioned &&
1696
+ commandAuthorized &&
1697
+ hasControlCmd;
1698
+ const effectiveWasMentioned = wasMentioned || shouldBypassMention;
1699
+
1700
+ // Skip group messages that require mention but weren't mentioned
1701
+ if (isGroup && requireMention && canDetectMention && !wasMentioned && !shouldBypassMention) {
1702
+ logVerbose(core, runtime, `bluebubbles: skipping group message (no mention)`);
1703
+ return;
1704
+ }
1705
+
1706
+ // Cache allowed inbound messages so later replies can resolve sender/body without
1707
+ // surfacing dropped content (allowlist/mention/command gating).
1708
+ cacheInboundMessage();
1709
+
1710
+ const baseUrl = account.config.serverUrl?.trim();
1711
+ const password = account.config.password?.trim();
1712
+ const maxBytes =
1713
+ account.config.mediaMaxMb && account.config.mediaMaxMb > 0
1714
+ ? account.config.mediaMaxMb * 1024 * 1024
1715
+ : 8 * 1024 * 1024;
1716
+
1717
+ let mediaUrls: string[] = [];
1718
+ let mediaPaths: string[] = [];
1719
+ let mediaTypes: string[] = [];
1720
+ if (attachments.length > 0) {
1721
+ if (!baseUrl || !password) {
1722
+ logVerbose(core, runtime, "attachment download skipped (missing serverUrl/password)");
1723
+ } else {
1724
+ for (const attachment of attachments) {
1725
+ if (!attachment.guid) continue;
1726
+ if (attachment.totalBytes && attachment.totalBytes > maxBytes) {
1727
+ logVerbose(
1728
+ core,
1729
+ runtime,
1730
+ `attachment too large guid=${attachment.guid} bytes=${attachment.totalBytes}`,
1731
+ );
1732
+ continue;
1733
+ }
1734
+ try {
1735
+ const downloaded = await downloadBlueBubblesAttachment(attachment, {
1736
+ cfg: config,
1737
+ accountId: account.accountId,
1738
+ maxBytes,
1739
+ });
1740
+ const saved = await core.channel.media.saveMediaBuffer(
1741
+ downloaded.buffer,
1742
+ downloaded.contentType,
1743
+ "inbound",
1744
+ maxBytes,
1745
+ );
1746
+ mediaPaths.push(saved.path);
1747
+ mediaUrls.push(saved.path);
1748
+ if (saved.contentType) {
1749
+ mediaTypes.push(saved.contentType);
1750
+ }
1751
+ } catch (err) {
1752
+ logVerbose(
1753
+ core,
1754
+ runtime,
1755
+ `attachment download failed guid=${attachment.guid} err=${String(err)}`,
1756
+ );
1757
+ }
1758
+ }
1759
+ }
1760
+ }
1761
+ let replyToId = message.replyToId;
1762
+ let replyToBody = message.replyToBody;
1763
+ let replyToSender = message.replyToSender;
1764
+ let replyToShortId: string | undefined;
1765
+
1766
+ if (isTapbackMessage && tapbackContext?.replyToId) {
1767
+ replyToId = tapbackContext.replyToId;
1768
+ }
1769
+
1770
+ if (replyToId) {
1771
+ const cached = resolveReplyContextFromCache({
1772
+ accountId: account.accountId,
1773
+ replyToId,
1774
+ chatGuid: message.chatGuid,
1775
+ chatIdentifier: message.chatIdentifier,
1776
+ chatId: message.chatId,
1777
+ });
1778
+ if (cached) {
1779
+ if (!replyToBody && cached.body) replyToBody = cached.body;
1780
+ if (!replyToSender && cached.senderLabel) replyToSender = cached.senderLabel;
1781
+ replyToShortId = cached.shortId;
1782
+ if (core.logging.shouldLogVerbose()) {
1783
+ const preview = (cached.body ?? "").replace(/\s+/g, " ").slice(0, 120);
1784
+ logVerbose(
1785
+ core,
1786
+ runtime,
1787
+ `reply-context cache hit replyToId=${replyToId} sender=${replyToSender ?? ""} body="${preview}"`,
1788
+ );
1789
+ }
1790
+ }
1791
+ }
1792
+
1793
+ // If no cached short ID, try to get one from the UUID directly
1794
+ if (replyToId && !replyToShortId) {
1795
+ replyToShortId = getShortIdForUuid(replyToId);
1796
+ }
1797
+
1798
+ // Use inline [[reply_to:N]] tag format
1799
+ // For tapbacks/reactions: append at end (e.g., "reacted with ❤️ [[reply_to:4]]")
1800
+ // For regular replies: prepend at start (e.g., "[[reply_to:4]] Awesome")
1801
+ const replyTag = formatReplyTag({ replyToId, replyToShortId });
1802
+ const baseBody = replyTag
1803
+ ? isTapbackMessage
1804
+ ? `${rawBody} ${replyTag}`
1805
+ : `${replyTag} ${rawBody}`
1806
+ : rawBody;
1807
+ const fromLabel = isGroup ? undefined : message.senderName || `user:${message.senderId}`;
1808
+ const groupSubject = isGroup ? message.chatName?.trim() || undefined : undefined;
1809
+ const groupMembers = isGroup
1810
+ ? formatGroupMembers({
1811
+ participants: message.participants,
1812
+ fallback: message.senderId ? { id: message.senderId, name: message.senderName } : undefined,
1813
+ })
1814
+ : undefined;
1815
+ const storePath = core.channel.session.resolveStorePath(config.session?.store, {
1816
+ agentId: route.agentId,
1817
+ });
1818
+ const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(config);
1819
+ const previousTimestamp = core.channel.session.readSessionUpdatedAt({
1820
+ storePath,
1821
+ sessionKey: route.sessionKey,
1822
+ });
1823
+ const body = core.channel.reply.formatAgentEnvelope({
1824
+ channel: "BlueBubbles",
1825
+ from: fromLabel,
1826
+ timestamp: message.timestamp,
1827
+ previousTimestamp,
1828
+ envelope: envelopeOptions,
1829
+ body: baseBody,
1830
+ });
1831
+ let chatGuidForActions = chatGuid;
1832
+ if (!chatGuidForActions && baseUrl && password) {
1833
+ const target =
1834
+ isGroup && (chatId || chatIdentifier)
1835
+ ? chatId
1836
+ ? ({ kind: "chat_id", chatId } as const)
1837
+ : ({ kind: "chat_identifier", chatIdentifier: chatIdentifier ?? "" } as const)
1838
+ : ({ kind: "handle", address: message.senderId } as const);
1839
+ if (target.kind !== "chat_identifier" || target.chatIdentifier) {
1840
+ chatGuidForActions =
1841
+ (await resolveChatGuidForTarget({
1842
+ baseUrl,
1843
+ password,
1844
+ target,
1845
+ })) ?? undefined;
1846
+ }
1847
+ }
1848
+
1849
+ const ackReactionScope = config.messages?.ackReactionScope ?? "group-mentions";
1850
+ const removeAckAfterReply = config.messages?.removeAckAfterReply ?? false;
1851
+ const ackReactionValue = resolveBlueBubblesAckReaction({
1852
+ cfg: config,
1853
+ agentId: route.agentId,
1854
+ core,
1855
+ runtime,
1856
+ });
1857
+ const shouldAckReaction = () =>
1858
+ Boolean(
1859
+ ackReactionValue &&
1860
+ core.channel.reactions.shouldAckReaction({
1861
+ scope: ackReactionScope,
1862
+ isDirect: !isGroup,
1863
+ isGroup,
1864
+ isMentionableGroup: isGroup,
1865
+ requireMention: Boolean(requireMention),
1866
+ canDetectMention,
1867
+ effectiveWasMentioned,
1868
+ shouldBypassMention,
1869
+ }),
1870
+ );
1871
+ const ackMessageId = message.messageId?.trim() || "";
1872
+ const ackReactionPromise =
1873
+ shouldAckReaction() && ackMessageId && chatGuidForActions && ackReactionValue
1874
+ ? sendBlueBubblesReaction({
1875
+ chatGuid: chatGuidForActions,
1876
+ messageGuid: ackMessageId,
1877
+ emoji: ackReactionValue,
1878
+ opts: { cfg: config, accountId: account.accountId },
1879
+ }).then(
1880
+ () => true,
1881
+ (err) => {
1882
+ logVerbose(
1883
+ core,
1884
+ runtime,
1885
+ `ack reaction failed chatGuid=${chatGuidForActions} msg=${ackMessageId}: ${String(err)}`,
1886
+ );
1887
+ return false;
1888
+ },
1889
+ )
1890
+ : null;
1891
+
1892
+ // Respect sendReadReceipts config (parity with WhatsApp)
1893
+ const sendReadReceipts = account.config.sendReadReceipts !== false;
1894
+ if (chatGuidForActions && baseUrl && password && sendReadReceipts) {
1895
+ try {
1896
+ await markBlueBubblesChatRead(chatGuidForActions, {
1897
+ cfg: config,
1898
+ accountId: account.accountId,
1899
+ });
1900
+ logVerbose(core, runtime, `marked read chatGuid=${chatGuidForActions}`);
1901
+ } catch (err) {
1902
+ runtime.error?.(`[bluebubbles] mark read failed: ${String(err)}`);
1903
+ }
1904
+ } else if (!sendReadReceipts) {
1905
+ logVerbose(core, runtime, "mark read skipped (sendReadReceipts=false)");
1906
+ } else {
1907
+ logVerbose(core, runtime, "mark read skipped (missing chatGuid or credentials)");
1908
+ }
1909
+
1910
+ const outboundTarget = isGroup
1911
+ ? formatBlueBubblesChatTarget({
1912
+ chatId,
1913
+ chatGuid: chatGuidForActions ?? chatGuid,
1914
+ chatIdentifier,
1915
+ }) || peerId
1916
+ : chatGuidForActions
1917
+ ? formatBlueBubblesChatTarget({ chatGuid: chatGuidForActions })
1918
+ : message.senderId;
1919
+
1920
+ const maybeEnqueueOutboundMessageId = (messageId?: string, snippet?: string) => {
1921
+ const trimmed = messageId?.trim();
1922
+ if (!trimmed || trimmed === "ok" || trimmed === "unknown") return;
1923
+ // Cache outbound message to get short ID
1924
+ const cacheEntry = rememberBlueBubblesReplyCache({
1925
+ accountId: account.accountId,
1926
+ messageId: trimmed,
1927
+ chatGuid: chatGuidForActions ?? chatGuid,
1928
+ chatIdentifier,
1929
+ chatId,
1930
+ senderLabel: "me",
1931
+ body: snippet ?? "",
1932
+ timestamp: Date.now(),
1933
+ });
1934
+ const displayId = cacheEntry.shortId || trimmed;
1935
+ const preview = snippet ? ` "${snippet.slice(0, 12)}${snippet.length > 12 ? "…" : ""}"` : "";
1936
+ core.system.enqueueSystemEvent(`Assistant sent${preview} [message_id:${displayId}]`, {
1937
+ sessionKey: route.sessionKey,
1938
+ contextKey: `bluebubbles:outbound:${outboundTarget}:${trimmed}`,
1939
+ });
1940
+ };
1941
+
1942
+ const ctxPayload = {
1943
+ Body: body,
1944
+ BodyForAgent: body,
1945
+ RawBody: rawBody,
1946
+ CommandBody: rawBody,
1947
+ BodyForCommands: rawBody,
1948
+ MediaUrl: mediaUrls[0],
1949
+ MediaUrls: mediaUrls.length > 0 ? mediaUrls : undefined,
1950
+ MediaPath: mediaPaths[0],
1951
+ MediaPaths: mediaPaths.length > 0 ? mediaPaths : undefined,
1952
+ MediaType: mediaTypes[0],
1953
+ MediaTypes: mediaTypes.length > 0 ? mediaTypes : undefined,
1954
+ From: isGroup ? `group:${peerId}` : `bluebubbles:${message.senderId}`,
1955
+ To: `bluebubbles:${outboundTarget}`,
1956
+ SessionKey: route.sessionKey,
1957
+ AccountId: route.accountId,
1958
+ ChatType: isGroup ? "group" : "direct",
1959
+ ConversationLabel: fromLabel,
1960
+ // Use short ID for token savings (agent can use this to reference the message)
1961
+ ReplyToId: replyToShortId || replyToId,
1962
+ ReplyToIdFull: replyToId,
1963
+ ReplyToBody: replyToBody,
1964
+ ReplyToSender: replyToSender,
1965
+ GroupSubject: groupSubject,
1966
+ GroupMembers: groupMembers,
1967
+ SenderName: message.senderName || undefined,
1968
+ SenderId: message.senderId,
1969
+ Provider: "bluebubbles",
1970
+ Surface: "bluebubbles",
1971
+ // Use short ID for token savings (agent can use this to reference the message)
1972
+ MessageSid: messageShortId || message.messageId,
1973
+ MessageSidFull: message.messageId,
1974
+ Timestamp: message.timestamp,
1975
+ OriginatingChannel: "bluebubbles",
1976
+ OriginatingTo: `bluebubbles:${outboundTarget}`,
1977
+ WasMentioned: effectiveWasMentioned,
1978
+ CommandAuthorized: commandAuthorized,
1979
+ };
1980
+
1981
+ let sentMessage = false;
1982
+ try {
1983
+ await core.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
1984
+ ctx: ctxPayload,
1985
+ cfg: config,
1986
+ dispatcherOptions: {
1987
+ deliver: async (payload) => {
1988
+ const rawReplyToId = typeof payload.replyToId === "string" ? payload.replyToId.trim() : "";
1989
+ // Resolve short ID (e.g., "5") to full UUID
1990
+ const replyToMessageGuid = rawReplyToId
1991
+ ? resolveBlueBubblesMessageId(rawReplyToId, { requireKnownShortId: true })
1992
+ : "";
1993
+ const mediaList = payload.mediaUrls?.length
1994
+ ? payload.mediaUrls
1995
+ : payload.mediaUrl
1996
+ ? [payload.mediaUrl]
1997
+ : [];
1998
+ if (mediaList.length > 0) {
1999
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
2000
+ cfg: config,
2001
+ channel: "bluebubbles",
2002
+ accountId: account.accountId,
2003
+ });
2004
+ const text = core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode);
2005
+ let first = true;
2006
+ for (const mediaUrl of mediaList) {
2007
+ const caption = first ? text : undefined;
2008
+ first = false;
2009
+ const result = await sendBlueBubblesMedia({
2010
+ cfg: config,
2011
+ to: outboundTarget,
2012
+ mediaUrl,
2013
+ caption: caption ?? undefined,
2014
+ replyToId: replyToMessageGuid || null,
2015
+ accountId: account.accountId,
2016
+ });
2017
+ const cachedBody = (caption ?? "").trim() || "<media:attachment>";
2018
+ maybeEnqueueOutboundMessageId(result.messageId, cachedBody);
2019
+ sentMessage = true;
2020
+ statusSink?.({ lastOutboundAt: Date.now() });
2021
+ }
2022
+ return;
2023
+ }
2024
+
2025
+ const textLimit =
2026
+ account.config.textChunkLimit && account.config.textChunkLimit > 0
2027
+ ? account.config.textChunkLimit
2028
+ : DEFAULT_TEXT_LIMIT;
2029
+ const chunkMode = account.config.chunkMode ?? "length";
2030
+ const tableMode = core.channel.text.resolveMarkdownTableMode({
2031
+ cfg: config,
2032
+ channel: "bluebubbles",
2033
+ accountId: account.accountId,
2034
+ });
2035
+ const text = core.channel.text.convertMarkdownTables(payload.text ?? "", tableMode);
2036
+ const chunks =
2037
+ chunkMode === "newline"
2038
+ ? core.channel.text.chunkTextWithMode(text, textLimit, chunkMode)
2039
+ : core.channel.text.chunkMarkdownText(text, textLimit);
2040
+ if (!chunks.length && text) chunks.push(text);
2041
+ if (!chunks.length) return;
2042
+ for (let i = 0; i < chunks.length; i++) {
2043
+ const chunk = chunks[i];
2044
+ const result = await sendMessageBlueBubbles(outboundTarget, chunk, {
2045
+ cfg: config,
2046
+ accountId: account.accountId,
2047
+ replyToMessageGuid: replyToMessageGuid || undefined,
2048
+ });
2049
+ maybeEnqueueOutboundMessageId(result.messageId, chunk);
2050
+ sentMessage = true;
2051
+ statusSink?.({ lastOutboundAt: Date.now() });
2052
+ // In newline mode, restart typing after each chunk if more chunks remain
2053
+ // Small delay allows the Apple API to finish clearing the typing state from message send
2054
+ if (chunkMode === "newline" && i < chunks.length - 1 && chatGuidForActions) {
2055
+ await new Promise((r) => setTimeout(r, 150));
2056
+ sendBlueBubblesTyping(chatGuidForActions, true, {
2057
+ cfg: config,
2058
+ accountId: account.accountId,
2059
+ }).catch(() => {
2060
+ // Ignore typing errors
2061
+ });
2062
+ }
2063
+ }
2064
+ },
2065
+ onReplyStart: async () => {
2066
+ if (!chatGuidForActions) return;
2067
+ if (!baseUrl || !password) return;
2068
+ logVerbose(core, runtime, `typing start chatGuid=${chatGuidForActions}`);
2069
+ try {
2070
+ await sendBlueBubblesTyping(chatGuidForActions, true, {
2071
+ cfg: config,
2072
+ accountId: account.accountId,
2073
+ });
2074
+ } catch (err) {
2075
+ runtime.error?.(`[bluebubbles] typing start failed: ${String(err)}`);
2076
+ }
2077
+ },
2078
+ onIdle: async () => {
2079
+ if (!chatGuidForActions) return;
2080
+ if (!baseUrl || !password) return;
2081
+ try {
2082
+ await sendBlueBubblesTyping(chatGuidForActions, false, {
2083
+ cfg: config,
2084
+ accountId: account.accountId,
2085
+ });
2086
+ } catch (err) {
2087
+ logVerbose(core, runtime, `typing stop failed: ${String(err)}`);
2088
+ }
2089
+ },
2090
+ onError: (err, info) => {
2091
+ runtime.error?.(`BlueBubbles ${info.kind} reply failed: ${String(err)}`);
2092
+ },
2093
+ },
2094
+ replyOptions: {
2095
+ disableBlockStreaming:
2096
+ typeof account.config.blockStreaming === "boolean"
2097
+ ? !account.config.blockStreaming
2098
+ : undefined,
2099
+ },
2100
+ });
2101
+ } finally {
2102
+ if (sentMessage && chatGuidForActions && ackMessageId) {
2103
+ core.channel.reactions.removeAckReactionAfterReply({
2104
+ removeAfterReply: removeAckAfterReply,
2105
+ ackReactionPromise,
2106
+ ackReactionValue: ackReactionValue ?? null,
2107
+ remove: () =>
2108
+ sendBlueBubblesReaction({
2109
+ chatGuid: chatGuidForActions,
2110
+ messageGuid: ackMessageId,
2111
+ emoji: ackReactionValue ?? "",
2112
+ remove: true,
2113
+ opts: { cfg: config, accountId: account.accountId },
2114
+ }),
2115
+ onError: (err) => {
2116
+ logAckFailure({
2117
+ log: (msg) => logVerbose(core, runtime, msg),
2118
+ channel: "bluebubbles",
2119
+ target: `${chatGuidForActions}/${ackMessageId}`,
2120
+ error: err,
2121
+ });
2122
+ },
2123
+ });
2124
+ }
2125
+ if (chatGuidForActions && baseUrl && password && !sentMessage) {
2126
+ // Stop typing indicator when no message was sent (e.g., NO_REPLY)
2127
+ sendBlueBubblesTyping(chatGuidForActions, false, {
2128
+ cfg: config,
2129
+ accountId: account.accountId,
2130
+ }).catch((err) => {
2131
+ logTypingFailure({
2132
+ log: (msg) => logVerbose(core, runtime, msg),
2133
+ channel: "bluebubbles",
2134
+ action: "stop",
2135
+ target: chatGuidForActions,
2136
+ error: err,
2137
+ });
2138
+ });
2139
+ }
2140
+ }
2141
+ }
2142
+
2143
+ async function processReaction(
2144
+ reaction: NormalizedWebhookReaction,
2145
+ target: WebhookTarget,
2146
+ ): Promise<void> {
2147
+ const { account, config, runtime, core } = target;
2148
+ if (reaction.fromMe) return;
2149
+
2150
+ const dmPolicy = account.config.dmPolicy ?? "pairing";
2151
+ const groupPolicy = account.config.groupPolicy ?? "allowlist";
2152
+ const configAllowFrom = (account.config.allowFrom ?? []).map((entry) => String(entry));
2153
+ const configGroupAllowFrom = (account.config.groupAllowFrom ?? []).map((entry) => String(entry));
2154
+ const storeAllowFrom = await core.channel.pairing
2155
+ .readAllowFromStore("bluebubbles")
2156
+ .catch(() => []);
2157
+ const effectiveAllowFrom = [...configAllowFrom, ...storeAllowFrom]
2158
+ .map((entry) => String(entry).trim())
2159
+ .filter(Boolean);
2160
+ const effectiveGroupAllowFrom = [
2161
+ ...(configGroupAllowFrom.length > 0 ? configGroupAllowFrom : configAllowFrom),
2162
+ ...storeAllowFrom,
2163
+ ]
2164
+ .map((entry) => String(entry).trim())
2165
+ .filter(Boolean);
2166
+
2167
+ if (reaction.isGroup) {
2168
+ if (groupPolicy === "disabled") return;
2169
+ if (groupPolicy === "allowlist") {
2170
+ if (effectiveGroupAllowFrom.length === 0) return;
2171
+ const allowed = isAllowedBlueBubblesSender({
2172
+ allowFrom: effectiveGroupAllowFrom,
2173
+ sender: reaction.senderId,
2174
+ chatId: reaction.chatId ?? undefined,
2175
+ chatGuid: reaction.chatGuid ?? undefined,
2176
+ chatIdentifier: reaction.chatIdentifier ?? undefined,
2177
+ });
2178
+ if (!allowed) return;
2179
+ }
2180
+ } else {
2181
+ if (dmPolicy === "disabled") return;
2182
+ if (dmPolicy !== "open") {
2183
+ const allowed = isAllowedBlueBubblesSender({
2184
+ allowFrom: effectiveAllowFrom,
2185
+ sender: reaction.senderId,
2186
+ chatId: reaction.chatId ?? undefined,
2187
+ chatGuid: reaction.chatGuid ?? undefined,
2188
+ chatIdentifier: reaction.chatIdentifier ?? undefined,
2189
+ });
2190
+ if (!allowed) return;
2191
+ }
2192
+ }
2193
+
2194
+ const chatId = reaction.chatId ?? undefined;
2195
+ const chatGuid = reaction.chatGuid ?? undefined;
2196
+ const chatIdentifier = reaction.chatIdentifier ?? undefined;
2197
+ const peerId = reaction.isGroup
2198
+ ? chatGuid ?? chatIdentifier ?? (chatId ? String(chatId) : "group")
2199
+ : reaction.senderId;
2200
+
2201
+ const route = core.channel.routing.resolveAgentRoute({
2202
+ cfg: config,
2203
+ channel: "bluebubbles",
2204
+ accountId: account.accountId,
2205
+ peer: {
2206
+ kind: reaction.isGroup ? "group" : "dm",
2207
+ id: peerId,
2208
+ },
2209
+ });
2210
+
2211
+ const senderLabel = reaction.senderName || reaction.senderId;
2212
+ const chatLabel = reaction.isGroup ? ` in group:${peerId}` : "";
2213
+ // Use short ID for token savings
2214
+ const messageDisplayId = getShortIdForUuid(reaction.messageId) || reaction.messageId;
2215
+ // Format: "Tyler reacted with ❤️ [[reply_to:5]]" or "Tyler removed ❤️ reaction [[reply_to:5]]"
2216
+ const text =
2217
+ reaction.action === "removed"
2218
+ ? `${senderLabel} removed ${reaction.emoji} reaction [[reply_to:${messageDisplayId}]]${chatLabel}`
2219
+ : `${senderLabel} reacted with ${reaction.emoji} [[reply_to:${messageDisplayId}]]${chatLabel}`;
2220
+ core.system.enqueueSystemEvent(text, {
2221
+ sessionKey: route.sessionKey,
2222
+ contextKey: `bluebubbles:reaction:${reaction.action}:${peerId}:${reaction.messageId}:${reaction.senderId}:${reaction.emoji}`,
2223
+ });
2224
+ logVerbose(core, runtime, `reaction event enqueued: ${text}`);
2225
+ }
2226
+
2227
+ export async function monitorBlueBubblesProvider(
2228
+ options: BlueBubblesMonitorOptions,
2229
+ ): Promise<void> {
2230
+ const { account, config, runtime, abortSignal, statusSink } = options;
2231
+ const core = getBlueBubblesRuntime();
2232
+ const path = options.webhookPath?.trim() || DEFAULT_WEBHOOK_PATH;
2233
+
2234
+ // Fetch and cache server info (for macOS version detection in action gating)
2235
+ const serverInfo = await fetchBlueBubblesServerInfo({
2236
+ baseUrl: account.baseUrl,
2237
+ password: account.config.password,
2238
+ accountId: account.accountId,
2239
+ timeoutMs: 5000,
2240
+ }).catch(() => null);
2241
+ if (serverInfo?.os_version) {
2242
+ runtime.log?.(`[${account.accountId}] BlueBubbles server macOS ${serverInfo.os_version}`);
2243
+ }
2244
+
2245
+ const unregister = registerBlueBubblesWebhookTarget({
2246
+ account,
2247
+ config,
2248
+ runtime,
2249
+ core,
2250
+ path,
2251
+ statusSink,
2252
+ });
2253
+
2254
+ return await new Promise((resolve) => {
2255
+ const stop = () => {
2256
+ unregister();
2257
+ resolve();
2258
+ };
2259
+
2260
+ if (abortSignal?.aborted) {
2261
+ stop();
2262
+ return;
2263
+ }
2264
+
2265
+ abortSignal?.addEventListener("abort", stop, { once: true });
2266
+ runtime.log?.(
2267
+ `[${account.accountId}] BlueBubbles webhook listening on ${normalizeWebhookPath(path)}`,
2268
+ );
2269
+ });
2270
+ }
2271
+
2272
+ export function resolveWebhookPathFromConfig(config?: BlueBubblesAccountConfig): string {
2273
+ const raw = config?.webhookPath?.trim();
2274
+ if (raw) return normalizeWebhookPath(raw);
2275
+ return DEFAULT_WEBHOOK_PATH;
2276
+ }