@openclaw/signal 0.0.0 → 2026.6.11

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.
Files changed (49) hide show
  1. package/README.md +12 -2
  2. package/dist/accounts-hOCHbEhX.js +40 -0
  3. package/dist/api.js +16 -0
  4. package/dist/approval-handler.runtime-CeJI1wow.js +158 -0
  5. package/dist/approval-resolver-BR0MioAA.js +15 -0
  6. package/dist/channel-LmY2UpOt.js +619 -0
  7. package/dist/channel-config-api.js +2 -0
  8. package/dist/channel-entry.js +18 -0
  9. package/dist/channel-plugin-api.js +2 -0
  10. package/dist/channel.runtime-B0-YpkC4.js +65 -0
  11. package/dist/config-api-KS-qhQvD.js +2 -0
  12. package/dist/config-schema-BiojLEsX.js +27 -0
  13. package/dist/contract-api.js +3 -0
  14. package/dist/identity-B6O4k8xg.js +130 -0
  15. package/dist/index.js +18 -0
  16. package/dist/install-signal-cli-CXgTF3de.js +243 -0
  17. package/dist/message-actions-Bue0g2Kc.js +548 -0
  18. package/dist/monitor-CUhIKHJo.js +1404 -0
  19. package/dist/probe-BQ_Izoya.js +48 -0
  20. package/dist/reaction-runtime-api-C_PQ45D9.js +1074 -0
  21. package/dist/reaction-runtime-api.js +2 -0
  22. package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
  23. package/dist/runtime-api.js +18 -0
  24. package/dist/secret-contract-api.js +5 -0
  25. package/dist/send-CBlFUkY_.js +599 -0
  26. package/dist/send.runtime-CfaZd8X4.js +2 -0
  27. package/dist/setup-entry.js +11 -0
  28. package/node_modules/ws/LICENSE +20 -0
  29. package/node_modules/ws/README.md +548 -0
  30. package/node_modules/ws/browser.js +8 -0
  31. package/node_modules/ws/index.js +22 -0
  32. package/node_modules/ws/lib/buffer-util.js +131 -0
  33. package/node_modules/ws/lib/constants.js +19 -0
  34. package/node_modules/ws/lib/event-target.js +292 -0
  35. package/node_modules/ws/lib/extension.js +203 -0
  36. package/node_modules/ws/lib/limiter.js +55 -0
  37. package/node_modules/ws/lib/permessage-deflate.js +528 -0
  38. package/node_modules/ws/lib/receiver.js +760 -0
  39. package/node_modules/ws/lib/sender.js +607 -0
  40. package/node_modules/ws/lib/stream.js +161 -0
  41. package/node_modules/ws/lib/subprotocol.js +62 -0
  42. package/node_modules/ws/lib/validation.js +152 -0
  43. package/node_modules/ws/lib/websocket-server.js +562 -0
  44. package/node_modules/ws/lib/websocket.js +1407 -0
  45. package/node_modules/ws/package.json +70 -0
  46. package/node_modules/ws/wrapper.mjs +21 -0
  47. package/npm-shrinkwrap.json +36 -0
  48. package/openclaw.plugin.json +771 -0
  49. package/package.json +77 -7
@@ -0,0 +1,1404 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
+ import { i as resolveSignalAccount } from "./accounts-hOCHbEhX.js";
3
+ import { a as normalizeSignalAllowRecipient, c as resolveSignalSender, d as normalizeSignalMessagingTarget, i as isSignalSenderAllowed, l as looksLikeUuid, n as formatSignalSenderDisplay, o as resolveSignalPeerId, r as formatSignalSenderId, s as resolveSignalRecipient, t as formatSignalPairingIdLine } from "./identity-B6O4k8xg.js";
4
+ import { a as isSignalNativeApprovalHandlerConfigured } from "./message-actions-Bue0g2Kc.js";
5
+ import { a as signalRpcRequest, i as signalCheck, o as streamSignalEvents } from "./reaction-runtime-api-C_PQ45D9.js";
6
+ import { a as maybeResolveSignalApprovalReaction, n as sendReadReceiptSignal, r as sendTypingSignal, s as resolveSignalApprovalConversationKey, t as sendMessageSignal } from "./send-CBlFUkY_.js";
7
+ import { createChannelMessageReplyPipeline } from "openclaw/plugin-sdk/channel-outbound";
8
+ import { createChannelPairingChallengeIssuer } from "openclaw/plugin-sdk/channel-pairing";
9
+ import { detectMime, estimateBase64DecodedBytes, kindFromMime, saveMediaBuffer } from "openclaw/plugin-sdk/media-runtime";
10
+ import { resolveAgentRoute, resolveInboundLastRouteSessionKey } from "openclaw/plugin-sdk/routing";
11
+ import { normalizeOptionalString, normalizeStringEntries } from "openclaw/plugin-sdk/string-coerce-runtime";
12
+ import { CHANNEL_APPROVAL_NATIVE_RUNTIME_CONTEXT_CAPABILITY } from "openclaw/plugin-sdk/approval-handler-adapter-runtime";
13
+ import { normalizeE164 } from "openclaw/plugin-sdk/text-utility-runtime";
14
+ import path from "node:path";
15
+ import { resolveChannelGroupPolicy, resolveChannelGroupRequireMention } from "openclaw/plugin-sdk/channel-policy";
16
+ import { registerChannelRuntimeContext } from "openclaw/plugin-sdk/channel-runtime-context";
17
+ import { DEFAULT_GROUP_HISTORY_LIMIT, createChannelHistoryWindow } from "openclaw/plugin-sdk/reply-history";
18
+ import { deliverTextOrMediaReply, resolveSendableOutboundReplyParts } from "openclaw/plugin-sdk/reply-payload";
19
+ import { chunkTextWithMode, createReplyDispatcherWithTyping, dispatchInboundMessage, resolveChunkMode, resolveTextChunkLimit, settleReplyDispatcher } from "openclaw/plugin-sdk/reply-runtime";
20
+ import { getRuntimeConfig } from "openclaw/plugin-sdk/runtime-config-snapshot";
21
+ import { computeBackoff, createNonExitingRuntime, danger, logVerbose, shouldLogVerbose, sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
22
+ import { resolveAllowlistProviderRuntimeGroupPolicy, resolveDefaultGroupPolicy, warnMissingProviderGroupPolicyFallbackOnce } from "openclaw/plugin-sdk/runtime-group-policy";
23
+ import { waitForTransportReady } from "openclaw/plugin-sdk/transport-ready-runtime";
24
+ import { spawn } from "node:child_process";
25
+ import os from "node:os";
26
+ import { resolveHumanDelayConfig } from "openclaw/plugin-sdk/agent-runtime";
27
+ import { logTypingFailure } from "openclaw/plugin-sdk/channel-feedback";
28
+ import { buildChannelInboundEventContext, buildMentionRegexes, createChannelInboundDebouncer, filterChannelInboundQuoteContext, formatInboundEnvelope, formatInboundFromLabel, logInboundDrop, matchesMentionPatterns, resolveEnvelopeFormatOptions, resolveInboundMentionDecision, runChannelInboundEvent, shouldDebounceTextInbound } from "openclaw/plugin-sdk/channel-inbound";
29
+ import { hasControlCommand } from "openclaw/plugin-sdk/command-auth-native";
30
+ import { recordInboundSession, upsertChannelPairingRequest } from "openclaw/plugin-sdk/conversation-runtime";
31
+ import { createInternalHookEvent, fireAndForgetHook, toInternalMessageReceivedContext, triggerInternalHook } from "openclaw/plugin-sdk/hook-runtime";
32
+ import { resolvePinnedMainDmOwnerFromAllowlist } from "openclaw/plugin-sdk/security-runtime";
33
+ import { readSessionUpdatedAt, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
34
+ import { enqueueSystemEvent } from "openclaw/plugin-sdk/system-event-runtime";
35
+ import { createChannelIngressResolver, defineStableChannelIngressIdentity } from "openclaw/plugin-sdk/channel-ingress-runtime";
36
+ import { resolveChannelContextVisibilityMode } from "openclaw/plugin-sdk/context-visibility-runtime";
37
+ //#region extensions/signal/src/daemon.ts
38
+ function formatSignalDaemonExit(exit) {
39
+ return `signal daemon exited (source=${exit.source} code=${exit.code ?? "null"} signal=${exit.signal ?? "null"})`;
40
+ }
41
+ function isRecoverableSignalCliReceiveException(line) {
42
+ return /\breceive exception:\s+.*\binvalid PreKey message:\s+decryption failed\b/i.test(line);
43
+ }
44
+ function classifySignalCliLogLine(line) {
45
+ const trimmed = line.trim();
46
+ if (!trimmed) return null;
47
+ if (/\bERROR\b/.test(trimmed)) return "error";
48
+ if (isRecoverableSignalCliReceiveException(trimmed)) return "log";
49
+ if (/\b(FAILED|SEVERE|EXCEPTION)\b/i.test(trimmed)) return "error";
50
+ return "log";
51
+ }
52
+ function bindSignalCliOutput(params) {
53
+ params.stream?.on("data", (data) => {
54
+ for (const line of data.toString().split(/\r?\n/)) {
55
+ const kind = classifySignalCliLogLine(line);
56
+ if (kind === "log") params.log(`signal-cli: ${line.trim()}`);
57
+ else if (kind === "error") params.error(`signal-cli: ${line.trim()}`);
58
+ }
59
+ });
60
+ }
61
+ function resolveSignalCliConfigPath(raw) {
62
+ const value = raw.trim();
63
+ if (value === "~") return os.homedir();
64
+ if (value.startsWith("~/") || value.startsWith("~\\")) return path.join(os.homedir(), value.slice(2));
65
+ return value;
66
+ }
67
+ function buildDaemonArgs(opts) {
68
+ const args = [];
69
+ if (opts.configPath?.trim()) args.push("--config", resolveSignalCliConfigPath(opts.configPath));
70
+ if (opts.account) args.push("-a", opts.account);
71
+ args.push("daemon");
72
+ args.push("--http", `${opts.httpHost}:${opts.httpPort}`);
73
+ args.push("--no-receive-stdout");
74
+ if (opts.receiveMode) args.push("--receive-mode", opts.receiveMode);
75
+ if (opts.ignoreAttachments) args.push("--ignore-attachments");
76
+ if (opts.ignoreStories) args.push("--ignore-stories");
77
+ if (opts.sendReadReceipts) args.push("--send-read-receipts");
78
+ return args;
79
+ }
80
+ function spawnSignalDaemon(opts) {
81
+ const args = buildDaemonArgs(opts);
82
+ const child = spawn(opts.cliPath, args, { stdio: [
83
+ "ignore",
84
+ "pipe",
85
+ "pipe"
86
+ ] });
87
+ const log = opts.runtime?.log ?? (() => {});
88
+ const error = opts.runtime?.error ?? (() => {});
89
+ let exited = false;
90
+ let settledExit = false;
91
+ let resolveExit;
92
+ const exitedPromise = new Promise((resolve) => {
93
+ resolveExit = resolve;
94
+ });
95
+ const settleExit = (value) => {
96
+ if (settledExit) return;
97
+ settledExit = true;
98
+ exited = true;
99
+ resolveExit(value);
100
+ };
101
+ bindSignalCliOutput({
102
+ stream: child.stdout,
103
+ log,
104
+ error
105
+ });
106
+ bindSignalCliOutput({
107
+ stream: child.stderr,
108
+ log,
109
+ error
110
+ });
111
+ child.once("exit", (code, signal) => {
112
+ settleExit({
113
+ source: "process",
114
+ code: typeof code === "number" ? code : null,
115
+ signal: signal ?? null
116
+ });
117
+ error(formatSignalDaemonExit({
118
+ source: "process",
119
+ code: code ?? null,
120
+ signal: signal ?? null
121
+ }));
122
+ });
123
+ child.once("close", (code, signal) => {
124
+ settleExit({
125
+ source: "process",
126
+ code: typeof code === "number" ? code : null,
127
+ signal: signal ?? null
128
+ });
129
+ });
130
+ child.on("error", (err) => {
131
+ error(`signal-cli spawn error: ${String(err)}`);
132
+ settleExit({
133
+ source: "spawn-error",
134
+ code: null,
135
+ signal: null
136
+ });
137
+ });
138
+ return {
139
+ pid: child.pid ?? void 0,
140
+ exited: exitedPromise,
141
+ isExited: () => exited,
142
+ stop: () => {
143
+ if (!child.killed && !exited) child.kill("SIGTERM");
144
+ }
145
+ };
146
+ }
147
+ //#endregion
148
+ //#region extensions/signal/src/monitor/access-policy.ts
149
+ const SIGNAL_UUID_KIND = "plugin:signal-uuid";
150
+ const SIGNAL_GROUP_KIND = "plugin:signal-group";
151
+ function strippedSignalEntry(entry) {
152
+ const trimmed = entry.trim();
153
+ if (!trimmed) return null;
154
+ const signalStripped = trimmed.replace(/^signal:/i, "").trim();
155
+ return {
156
+ trimmed,
157
+ signalStripped,
158
+ lower: signalStripped.toLowerCase()
159
+ };
160
+ }
161
+ function normalizeSignalGroupEntry(entry) {
162
+ const parsed = strippedSignalEntry(entry);
163
+ if (!parsed) return null;
164
+ const { trimmed, signalStripped, lower } = parsed;
165
+ if (lower.startsWith("group:")) return signalStripped.slice(6).trim() || null;
166
+ return trimmed;
167
+ }
168
+ function normalizeSignalUuidEntry(entry) {
169
+ const parsed = strippedSignalEntry(entry);
170
+ if (!parsed) return null;
171
+ const { signalStripped, lower } = parsed;
172
+ if (lower.startsWith("uuid:")) return signalStripped.slice(5).trim() || null;
173
+ return looksLikeUuid(signalStripped) ? signalStripped : null;
174
+ }
175
+ function normalizeSignalPhoneEntry(entry) {
176
+ const parsed = strippedSignalEntry(entry);
177
+ if (!parsed) return null;
178
+ return normalizeSignalAllowRecipient(parsed.trimmed) ?? null;
179
+ }
180
+ const signalIngressIdentity = defineStableChannelIngressIdentity({
181
+ key: "stable",
182
+ normalizeEntry: () => null,
183
+ aliases: [
184
+ {
185
+ key: "phone",
186
+ kind: "phone",
187
+ normalizeEntry: normalizeSignalPhoneEntry,
188
+ normalizeSubject: (value) => value,
189
+ sensitivity: "pii"
190
+ },
191
+ {
192
+ key: "uuid",
193
+ kind: SIGNAL_UUID_KIND,
194
+ normalizeEntry: normalizeSignalUuidEntry,
195
+ normalizeSubject: (value) => value,
196
+ sensitivity: "pii"
197
+ },
198
+ {
199
+ key: "group",
200
+ kind: SIGNAL_GROUP_KIND,
201
+ normalizeEntry: normalizeSignalGroupEntry,
202
+ normalizeSubject: (value) => value
203
+ }
204
+ ],
205
+ isWildcardEntry: (entry) => entry.trim() === "*",
206
+ resolveEntryId({ entryIndex, fieldKey }) {
207
+ return `entry-${entryIndex + 1}:${fieldKey}`;
208
+ }
209
+ });
210
+ function signalSubjectInput(params) {
211
+ return {
212
+ stableId: formatSignalSenderId(params.sender),
213
+ aliases: {
214
+ phone: params.sender.kind === "phone" ? params.sender.e164 : void 0,
215
+ uuid: params.sender.kind === "uuid" ? params.sender.raw : void 0,
216
+ group: params.groupId
217
+ }
218
+ };
219
+ }
220
+ async function resolveSignalAccessState(params) {
221
+ const isGroup = params.isGroup ?? params.groupId != null;
222
+ const command = params.hasControlCommand === true ? {
223
+ allowTextCommands: true,
224
+ directGroupAllowFrom: "effective"
225
+ } : void 0;
226
+ return await createChannelIngressResolver({
227
+ channelId: "signal",
228
+ accountId: params.accountId,
229
+ identity: signalIngressIdentity,
230
+ cfg: params.cfg,
231
+ ...params.readStoreAllowFrom ? { readStoreAllowFrom: params.readStoreAllowFrom } : {},
232
+ useDefaultPairingStore: params.readStoreAllowFrom == null
233
+ }).message({
234
+ subject: signalSubjectInput({
235
+ sender: params.sender,
236
+ groupId: isGroup ? params.groupId : void 0
237
+ }),
238
+ conversation: {
239
+ kind: isGroup ? "group" : "direct",
240
+ id: isGroup ? params.groupId ?? "unknown" : params.sender.raw
241
+ },
242
+ ...isGroup ? { event: { mayPair: false } } : {},
243
+ dmPolicy: params.dmPolicy,
244
+ groupPolicy: params.groupPolicy,
245
+ policy: { groupAllowFromFallbackToAllowFrom: true },
246
+ allowFrom: params.allowFrom,
247
+ groupAllowFrom: params.groupAllowFrom,
248
+ command
249
+ });
250
+ }
251
+ async function handleSignalDirectMessageAccess(params) {
252
+ if (params.dmAccessDecision === "allow") return true;
253
+ if (params.dmAccessDecision === "block") {
254
+ if (params.dmPolicy !== "disabled") params.log(`Blocked signal sender ${params.senderDisplay} (dmPolicy=${params.dmPolicy})`);
255
+ return false;
256
+ }
257
+ if (params.dmPolicy === "pairing") await createChannelPairingChallengeIssuer({
258
+ channel: "signal",
259
+ upsertPairingRequest: async ({ id, meta }) => await upsertChannelPairingRequest({
260
+ channel: "signal",
261
+ id,
262
+ accountId: params.accountId,
263
+ meta
264
+ })
265
+ })({
266
+ senderId: params.senderId,
267
+ senderIdLine: params.senderIdLine,
268
+ meta: { name: params.senderName },
269
+ sendPairingReply: params.sendPairingReply,
270
+ onCreated: () => {
271
+ params.log(`signal pairing request sender=${params.senderId}`);
272
+ },
273
+ onReplyError: (err) => {
274
+ params.log(`signal pairing reply failed for ${params.senderId}: ${String(err)}`);
275
+ }
276
+ });
277
+ return false;
278
+ }
279
+ //#endregion
280
+ //#region extensions/signal/src/monitor/inbound-context.ts
281
+ function resolveSignalQuoteContext(params) {
282
+ const contextVisibilityMode = resolveChannelContextVisibilityMode({
283
+ cfg: params.cfg,
284
+ channel: "signal",
285
+ accountId: params.accountId
286
+ });
287
+ const quoteText = normalizeOptionalString(params.dataMessage?.quote?.text) ?? "";
288
+ const quoteSender = resolveSignalSender({
289
+ sourceNumber: params.dataMessage?.quote?.author ?? null,
290
+ sourceUuid: params.dataMessage?.quote?.authorUuid ?? null
291
+ });
292
+ const quoteSenderAllowed = !params.isGroup || params.effectiveGroupAllow.length === 0 ? true : quoteSender ? isSignalSenderAllowed(quoteSender, params.effectiveGroupAllow) : false;
293
+ const visibleQuote = filterChannelInboundQuoteContext(contextVisibilityMode, {
294
+ body: quoteText,
295
+ sender: quoteSender ? formatSignalSenderDisplay(quoteSender) : void 0,
296
+ senderAllowed: quoteSenderAllowed,
297
+ isQuote: true
298
+ });
299
+ return {
300
+ contextVisibilityMode,
301
+ decision: {
302
+ include: Boolean(visibleQuote),
303
+ reason: visibleQuote ? contextVisibilityMode === "all" ? "mode_all" : quoteSenderAllowed ? "sender_allowed" : "quote_override" : "blocked"
304
+ },
305
+ quoteSenderAllowed,
306
+ visibleQuoteText: visibleQuote?.body ?? "",
307
+ visibleQuoteSender: visibleQuote?.sender
308
+ };
309
+ }
310
+ //#endregion
311
+ //#region extensions/signal/src/monitor/mentions.ts
312
+ const OBJECT_REPLACEMENT = "";
313
+ function isValidMention(mention) {
314
+ if (!mention) return false;
315
+ if (!(mention.uuid || mention.number)) return false;
316
+ if (typeof mention.start !== "number" || Number.isNaN(mention.start)) return false;
317
+ if (typeof mention.length !== "number" || Number.isNaN(mention.length)) return false;
318
+ return mention.length > 0;
319
+ }
320
+ function clampBounds(start, length, textLength) {
321
+ const safeStart = Math.max(0, Math.trunc(start));
322
+ return {
323
+ start: safeStart,
324
+ end: Math.min(textLength, safeStart + Math.max(0, Math.trunc(length)))
325
+ };
326
+ }
327
+ function renderSignalMentions(message, mentions) {
328
+ if (!message || !mentions?.length) return message;
329
+ let normalized = message;
330
+ const candidates = mentions.filter(isValidMention).toSorted((a, b) => b.start - a.start);
331
+ for (const mention of candidates) {
332
+ const identifier = mention.uuid ?? mention.number;
333
+ if (!identifier) continue;
334
+ const { start, end } = clampBounds(mention.start, mention.length, normalized.length);
335
+ if (start >= end) continue;
336
+ if (!normalized.slice(start, end).includes(OBJECT_REPLACEMENT)) continue;
337
+ normalized = normalized.slice(0, start) + `@${identifier}` + normalized.slice(end);
338
+ }
339
+ return normalized;
340
+ }
341
+ //#endregion
342
+ //#region extensions/signal/src/monitor/event-handler.ts
343
+ function formatAttachmentKindCount(kind, count) {
344
+ if (kind === "attachment") return `${count} file${count > 1 ? "s" : ""}`;
345
+ return `${count} ${kind}${count > 1 ? "s" : ""}`;
346
+ }
347
+ function formatAttachmentSummaryPlaceholder(contentTypes) {
348
+ const kindCounts = /* @__PURE__ */ new Map();
349
+ for (const contentType of contentTypes) {
350
+ const kind = kindFromMime(contentType) ?? "attachment";
351
+ kindCounts.set(kind, (kindCounts.get(kind) ?? 0) + 1);
352
+ }
353
+ return `[${[...kindCounts.entries()].map(([kind, count]) => formatAttachmentKindCount(kind, count)).join(" + ")} attached]`;
354
+ }
355
+ function resolveSignalInboundRoute(params) {
356
+ return resolveAgentRoute({
357
+ cfg: params.cfg,
358
+ channel: "signal",
359
+ accountId: params.accountId,
360
+ peer: {
361
+ kind: params.isGroup ? "group" : "direct",
362
+ id: params.isGroup ? params.groupId ?? "unknown" : params.senderPeerId
363
+ }
364
+ });
365
+ }
366
+ function createSignalEventHandler(deps) {
367
+ async function handleSignalInboundMessage(entry) {
368
+ const fromLabel = formatInboundFromLabel({
369
+ isGroup: entry.isGroup,
370
+ groupLabel: entry.groupName ?? void 0,
371
+ groupId: entry.groupId ?? "unknown",
372
+ groupFallback: "Group",
373
+ directLabel: entry.senderName,
374
+ directId: entry.senderDisplay
375
+ });
376
+ const route = resolveSignalInboundRoute({
377
+ cfg: deps.cfg,
378
+ accountId: deps.accountId,
379
+ isGroup: entry.isGroup,
380
+ groupId: entry.groupId,
381
+ senderPeerId: entry.senderPeerId
382
+ });
383
+ const storePath = resolveStorePath(deps.cfg.session?.store, { agentId: route.agentId });
384
+ const envelopeOptions = resolveEnvelopeFormatOptions(deps.cfg);
385
+ const previousTimestamp = readSessionUpdatedAt({
386
+ storePath,
387
+ sessionKey: route.sessionKey
388
+ });
389
+ const body = formatInboundEnvelope({
390
+ channel: "Signal",
391
+ from: fromLabel,
392
+ timestamp: entry.timestamp ?? void 0,
393
+ body: entry.bodyText,
394
+ chatType: entry.isGroup ? "group" : "direct",
395
+ sender: {
396
+ name: entry.senderName,
397
+ id: entry.senderDisplay
398
+ },
399
+ previousTimestamp,
400
+ envelope: envelopeOptions
401
+ });
402
+ let combinedBody = body;
403
+ const historyKey = entry.isGroup ? entry.groupId ?? "unknown" : void 0;
404
+ if (entry.isGroup && historyKey) combinedBody = createChannelHistoryWindow({ historyMap: deps.groupHistories }).buildPendingContext({
405
+ historyKey,
406
+ limit: deps.historyLimit,
407
+ currentMessage: combinedBody,
408
+ formatEntry: (historyEntry) => formatInboundEnvelope({
409
+ channel: "Signal",
410
+ from: fromLabel,
411
+ timestamp: historyEntry.timestamp,
412
+ body: `${historyEntry.body}${historyEntry.messageId ? ` [id:${historyEntry.messageId}]` : ""}`,
413
+ chatType: "group",
414
+ senderLabel: historyEntry.sender,
415
+ envelope: envelopeOptions
416
+ })
417
+ });
418
+ const signalToRaw = entry.isGroup ? `group:${entry.groupId}` : `signal:${entry.senderRecipient}`;
419
+ const signalTo = normalizeSignalMessagingTarget(signalToRaw) ?? signalToRaw;
420
+ const inboundHistory = entry.isGroup && historyKey && deps.historyLimit > 0 ? createChannelHistoryWindow({ historyMap: deps.groupHistories }).buildInboundHistory({
421
+ historyKey,
422
+ limit: deps.historyLimit
423
+ }) : void 0;
424
+ const media = entry.mediaPaths && entry.mediaPaths.length > 0 ? entry.mediaPaths.map((path, index) => ({
425
+ path,
426
+ url: path,
427
+ contentType: entry.mediaTypes?.[index]
428
+ })) : entry.mediaPath ? [{
429
+ path: entry.mediaPath,
430
+ url: entry.mediaPath,
431
+ contentType: entry.mediaType
432
+ }] : void 0;
433
+ const ctxPayload = buildChannelInboundEventContext({
434
+ channel: "signal",
435
+ supplemental: { quote: entry.replyToBody ? {
436
+ body: entry.replyToBody,
437
+ sender: entry.replyToSender,
438
+ isQuote: entry.replyToIsQuote
439
+ } : void 0 },
440
+ messageId: entry.messageId,
441
+ timestamp: entry.timestamp ?? void 0,
442
+ from: entry.isGroup ? `group:${entry.groupId ?? "unknown"}` : `signal:${entry.senderRecipient}`,
443
+ sender: {
444
+ id: entry.senderDisplay,
445
+ name: entry.senderName
446
+ },
447
+ conversation: {
448
+ kind: entry.isGroup ? "group" : "direct",
449
+ id: entry.isGroup ? entry.groupId ?? "unknown" : entry.senderRecipient,
450
+ label: fromLabel
451
+ },
452
+ route: {
453
+ agentId: route.agentId,
454
+ accountId: route.accountId,
455
+ routeSessionKey: route.sessionKey
456
+ },
457
+ reply: { to: signalTo },
458
+ message: {
459
+ body: combinedBody,
460
+ bodyForAgent: entry.bodyText,
461
+ inboundHistory,
462
+ rawBody: entry.bodyText,
463
+ commandBody: entry.commandBody
464
+ },
465
+ access: {
466
+ ...entry.isGroup ? { mentions: {
467
+ canDetectMention: true,
468
+ wasMentioned: entry.wasMentioned === true
469
+ } } : {},
470
+ commands: { authorized: entry.commandAuthorized }
471
+ },
472
+ media,
473
+ extra: { GroupSubject: entry.isGroup ? entry.groupName ?? void 0 : void 0 }
474
+ });
475
+ if (shouldLogVerbose()) {
476
+ const preview = body.slice(0, 200).replace(/\\n/g, "\\\\n");
477
+ logVerbose(`signal inbound: from=${ctxPayload.From} len=${body.length} preview="${preview}"`);
478
+ }
479
+ const { onModelSelected, typingCallbacks, ...replyPipeline } = createChannelMessageReplyPipeline({
480
+ cfg: deps.cfg,
481
+ agentId: route.agentId,
482
+ channel: "signal",
483
+ accountId: route.accountId,
484
+ typing: {
485
+ start: async () => {
486
+ if (!ctxPayload.To) return;
487
+ await sendTypingSignal(ctxPayload.To, {
488
+ cfg: deps.cfg,
489
+ baseUrl: deps.baseUrl,
490
+ account: deps.account,
491
+ accountId: deps.accountId
492
+ });
493
+ },
494
+ onStartError: (err) => {
495
+ logTypingFailure({
496
+ log: logVerbose,
497
+ channel: "signal",
498
+ target: ctxPayload.To ?? void 0,
499
+ error: err
500
+ });
501
+ }
502
+ }
503
+ });
504
+ const { dispatcher, replyOptions, markDispatchIdle } = createReplyDispatcherWithTyping({
505
+ ...replyPipeline,
506
+ humanDelay: resolveHumanDelayConfig(deps.cfg, route.agentId),
507
+ typingCallbacks,
508
+ deliver: async (payload, _info) => {
509
+ await deps.deliverReplies({
510
+ cfg: deps.cfg,
511
+ replies: [payload],
512
+ target: ctxPayload.To,
513
+ baseUrl: deps.baseUrl,
514
+ account: deps.account,
515
+ accountId: deps.accountId,
516
+ runtime: deps.runtime,
517
+ maxBytes: deps.mediaMaxBytes,
518
+ textLimit: deps.textLimit
519
+ });
520
+ },
521
+ onError: (err, info) => {
522
+ deps.runtime.error?.(danger(`signal ${info.kind} reply failed: ${String(err)}`));
523
+ }
524
+ });
525
+ const inboundLastRouteSessionKey = resolveInboundLastRouteSessionKey({
526
+ route,
527
+ sessionKey: route.sessionKey
528
+ });
529
+ await runChannelInboundEvent({
530
+ channel: "signal",
531
+ accountId: route.accountId,
532
+ raw: entry,
533
+ adapter: {
534
+ ingest: () => ({
535
+ id: entry.messageId ?? `${entry.timestamp ?? Date.now()}`,
536
+ timestamp: entry.timestamp,
537
+ rawText: entry.bodyText,
538
+ raw: entry
539
+ }),
540
+ resolveTurn: () => ({
541
+ channel: "signal",
542
+ accountId: route.accountId,
543
+ routeSessionKey: route.sessionKey,
544
+ storePath,
545
+ ctxPayload,
546
+ recordInboundSession,
547
+ record: {
548
+ updateLastRoute: !entry.isGroup ? {
549
+ sessionKey: inboundLastRouteSessionKey,
550
+ channel: "signal",
551
+ to: entry.senderRecipient,
552
+ accountId: route.accountId,
553
+ mainDmOwnerPin: (() => {
554
+ if (inboundLastRouteSessionKey !== route.mainSessionKey) return;
555
+ const pinnedOwner = resolvePinnedMainDmOwnerFromAllowlist({
556
+ dmScope: deps.cfg.session?.dmScope,
557
+ allowFrom: deps.allowFrom,
558
+ normalizeEntry: normalizeSignalAllowRecipient
559
+ });
560
+ if (!pinnedOwner) return;
561
+ return {
562
+ ownerRecipient: pinnedOwner,
563
+ senderRecipient: entry.senderRecipient,
564
+ onSkip: ({ ownerRecipient, senderRecipient }) => {
565
+ logVerbose(`signal: skip main-session last route for ${senderRecipient} (pinned owner ${ownerRecipient})`);
566
+ }
567
+ };
568
+ })()
569
+ } : void 0,
570
+ onRecordError: (err) => {
571
+ logVerbose(`signal: failed updating session meta: ${String(err)}`);
572
+ }
573
+ },
574
+ history: {
575
+ isGroup: entry.isGroup,
576
+ historyKey,
577
+ historyMap: deps.groupHistories,
578
+ limit: deps.historyLimit
579
+ },
580
+ onPreDispatchFailure: () => settleReplyDispatcher({
581
+ dispatcher,
582
+ onSettled: () => markDispatchIdle()
583
+ }),
584
+ runDispatch: async () => {
585
+ try {
586
+ return await dispatchInboundMessage({
587
+ ctx: ctxPayload,
588
+ cfg: deps.cfg,
589
+ dispatcher,
590
+ replyOptions: {
591
+ ...replyOptions,
592
+ disableBlockStreaming: typeof deps.blockStreaming === "boolean" ? !deps.blockStreaming : void 0,
593
+ onModelSelected
594
+ }
595
+ });
596
+ } finally {
597
+ markDispatchIdle();
598
+ }
599
+ }
600
+ })
601
+ }
602
+ });
603
+ }
604
+ const { debouncer: inboundDebouncer } = createChannelInboundDebouncer({
605
+ cfg: deps.cfg,
606
+ channel: "signal",
607
+ buildKey: (entry) => {
608
+ const conversationId = entry.isGroup ? entry.groupId ?? "unknown" : entry.senderPeerId;
609
+ if (!conversationId || !entry.senderPeerId) return null;
610
+ return `signal:${deps.accountId}:${conversationId}:${entry.senderPeerId}`;
611
+ },
612
+ shouldDebounce: (entry) => {
613
+ return shouldDebounceTextInbound({
614
+ text: entry.bodyText,
615
+ cfg: deps.cfg,
616
+ hasMedia: Boolean(entry.mediaPath || entry.mediaType || entry.mediaPaths?.length)
617
+ });
618
+ },
619
+ onFlush: async (entries) => {
620
+ const last = entries.at(-1);
621
+ if (!last) return;
622
+ if (entries.length === 1) {
623
+ await handleSignalInboundMessage(last);
624
+ return;
625
+ }
626
+ const combinedText = entries.map((entry) => entry.bodyText).filter(Boolean).join("\\n");
627
+ if (!combinedText.trim()) return;
628
+ await handleSignalInboundMessage({
629
+ ...last,
630
+ bodyText: combinedText,
631
+ mediaPath: void 0,
632
+ mediaType: void 0,
633
+ mediaPaths: void 0,
634
+ mediaTypes: void 0
635
+ });
636
+ },
637
+ onError: (err) => {
638
+ deps.runtime.error?.(`signal debounce flush failed: ${String(err)}`);
639
+ }
640
+ });
641
+ async function handleReactionOnlyInbound(params) {
642
+ if (params.hasBodyContent) return false;
643
+ if (params.reaction.isRemove) return true;
644
+ const emojiLabel = normalizeOptionalString(params.reaction.emoji) ?? "emoji";
645
+ const senderName = params.envelope.sourceName ?? params.senderDisplay;
646
+ logVerbose(`signal reaction: ${emojiLabel} from ${senderName}`);
647
+ const groupId = params.reaction.groupInfo?.groupId ?? void 0;
648
+ const groupName = params.reaction.groupInfo?.groupName ?? void 0;
649
+ const isGroup = Boolean(groupId);
650
+ const messageId = params.reaction.targetSentTimestamp ? String(params.reaction.targetSentTimestamp) : "unknown";
651
+ const conversationKey = resolveSignalApprovalConversationKey(groupId ? `group:${groupId}` : `signal:${resolveSignalRecipient(params.sender)}`);
652
+ if (conversationKey && await maybeResolveSignalApprovalReaction({
653
+ cfg: deps.cfg,
654
+ accountId: deps.accountId,
655
+ conversationKey,
656
+ messageId,
657
+ reactionKey: emojiLabel,
658
+ actorId: formatSignalSenderId(params.sender),
659
+ targetAuthor: params.reaction.targetAuthor,
660
+ targetAuthorUuid: params.reaction.targetAuthorUuid,
661
+ logVerboseMessage: logVerbose
662
+ })) return true;
663
+ if (params.accessDecision.decision !== "allow") {
664
+ logVerbose(`Blocked signal reaction sender ${params.senderDisplay} (${params.accessDecision.reasonCode})`);
665
+ return true;
666
+ }
667
+ const targets = deps.resolveSignalReactionTargets(params.reaction);
668
+ if (!deps.shouldEmitSignalReactionNotification({
669
+ mode: deps.reactionMode,
670
+ account: deps.account,
671
+ targets,
672
+ sender: params.sender,
673
+ allowlist: deps.reactionAllowlist
674
+ })) return true;
675
+ const senderPeerId = resolveSignalPeerId(params.sender);
676
+ const route = resolveSignalInboundRoute({
677
+ cfg: deps.cfg,
678
+ accountId: deps.accountId,
679
+ isGroup,
680
+ groupId,
681
+ senderPeerId
682
+ });
683
+ const groupLabel = isGroup ? `${groupName ?? "Signal Group"} id:${groupId}` : void 0;
684
+ const text = deps.buildSignalReactionSystemEventText({
685
+ emojiLabel,
686
+ actorLabel: senderName,
687
+ messageId,
688
+ targetLabel: targets[0]?.display,
689
+ groupLabel
690
+ });
691
+ const contextKey = [
692
+ "signal",
693
+ "reaction",
694
+ "added",
695
+ messageId,
696
+ formatSignalSenderId(params.sender),
697
+ emojiLabel,
698
+ groupId ?? ""
699
+ ].filter(Boolean).join(":");
700
+ enqueueSystemEvent(text, {
701
+ sessionKey: route.sessionKey,
702
+ contextKey
703
+ });
704
+ return true;
705
+ }
706
+ return async (event) => {
707
+ if (event.event !== "receive" || !event.data) return;
708
+ let payload;
709
+ try {
710
+ payload = JSON.parse(event.data);
711
+ } catch (err) {
712
+ deps.runtime.error?.(`failed to parse event: ${String(err)}`);
713
+ return;
714
+ }
715
+ if (payload?.exception?.message) deps.runtime.error?.(`receive exception: ${payload.exception.message}`);
716
+ const envelope = payload?.envelope;
717
+ if (!envelope) return;
718
+ const sender = resolveSignalSender(envelope);
719
+ if (!sender) return;
720
+ const normalizedAccount = deps.account ? normalizeE164(deps.account) : void 0;
721
+ if (sender.kind === "phone" && normalizedAccount != null && sender.e164 === normalizedAccount || sender.kind === "uuid" && deps.accountUuid != null && sender.raw === deps.accountUuid) return;
722
+ if ("syncMessage" in envelope) return;
723
+ const dataMessage = envelope.dataMessage ?? envelope.editMessage?.dataMessage;
724
+ const reaction = deps.isSignalReactionMessage(envelope.reactionMessage) ? envelope.reactionMessage : deps.isSignalReactionMessage(dataMessage?.reaction) ? dataMessage?.reaction : null;
725
+ const messageText = renderSignalMentions(dataMessage?.message ?? "", dataMessage?.mentions).trim();
726
+ const groupId = dataMessage?.groupInfo?.groupId ?? reaction?.groupInfo?.groupId ?? void 0;
727
+ const isGroup = Boolean(groupId);
728
+ const hasControlCommandInMessage = hasControlCommand(messageText, deps.cfg);
729
+ const senderDisplay = formatSignalSenderDisplay(sender);
730
+ const { senderAccess, commandAccess } = await resolveSignalAccessState({
731
+ accountId: deps.accountId,
732
+ dmPolicy: deps.dmPolicy,
733
+ groupPolicy: deps.groupPolicy,
734
+ allowFrom: deps.allowFrom,
735
+ groupAllowFrom: deps.groupAllowFrom,
736
+ sender,
737
+ groupId,
738
+ isGroup,
739
+ cfg: deps.cfg,
740
+ hasControlCommand: hasControlCommandInMessage
741
+ });
742
+ const quoteText = normalizeOptionalString(dataMessage?.quote?.text) ?? "";
743
+ const { contextVisibilityMode, quoteSenderAllowed, visibleQuoteText, visibleQuoteSender } = resolveSignalQuoteContext({
744
+ cfg: deps.cfg,
745
+ accountId: deps.accountId,
746
+ isGroup,
747
+ dataMessage,
748
+ effectiveGroupAllow: senderAccess.effectiveGroupAllowFrom
749
+ });
750
+ if (quoteText && !visibleQuoteText && isGroup) logVerbose(`signal: drop quote context (mode=${contextVisibilityMode}, sender_allowed=${quoteSenderAllowed ? "yes" : "no"})`);
751
+ const hasBodyContent = Boolean(messageText || visibleQuoteText) || Boolean(!reaction && dataMessage?.attachments?.length);
752
+ if (reaction && await handleReactionOnlyInbound({
753
+ envelope,
754
+ sender,
755
+ senderDisplay,
756
+ reaction,
757
+ hasBodyContent,
758
+ accessDecision: senderAccess
759
+ })) return;
760
+ if (!dataMessage) return;
761
+ const senderRecipient = resolveSignalRecipient(sender);
762
+ const senderPeerId = resolveSignalPeerId(sender);
763
+ const senderAllowId = formatSignalSenderId(sender);
764
+ if (!senderRecipient) return;
765
+ const senderIdLine = formatSignalPairingIdLine(sender);
766
+ const groupName = dataMessage.groupInfo?.groupName ?? void 0;
767
+ if (!isGroup) {
768
+ if (!await handleSignalDirectMessageAccess({
769
+ dmPolicy: deps.dmPolicy,
770
+ dmAccessDecision: senderAccess.decision,
771
+ senderId: senderAllowId,
772
+ senderIdLine,
773
+ senderDisplay,
774
+ senderName: envelope.sourceName ?? void 0,
775
+ accountId: deps.accountId,
776
+ sendPairingReply: async (text) => {
777
+ await sendMessageSignal(`signal:${senderRecipient}`, text, {
778
+ cfg: deps.cfg,
779
+ baseUrl: deps.baseUrl,
780
+ account: deps.account,
781
+ maxBytes: deps.mediaMaxBytes,
782
+ accountId: deps.accountId
783
+ });
784
+ },
785
+ log: logVerbose
786
+ })) return;
787
+ }
788
+ if (isGroup) {
789
+ if (senderAccess.decision !== "allow") {
790
+ if (senderAccess.reasonCode === "group_policy_disabled") logVerbose("Blocked signal group message (groupPolicy: disabled)");
791
+ else if (senderAccess.reasonCode === "group_policy_empty_allowlist") logVerbose("Blocked signal group message (groupPolicy: allowlist, no groupAllowFrom)");
792
+ else logVerbose(`Blocked signal group sender ${senderDisplay} (not in groupAllowFrom)`);
793
+ return;
794
+ }
795
+ }
796
+ const commandAuthorized = commandAccess.authorized;
797
+ if (isGroup && commandAccess.shouldBlockControlCommand) {
798
+ logInboundDrop({
799
+ log: logVerbose,
800
+ channel: "signal",
801
+ reason: "control command (unauthorized)",
802
+ target: senderDisplay
803
+ });
804
+ return;
805
+ }
806
+ const route = resolveSignalInboundRoute({
807
+ cfg: deps.cfg,
808
+ accountId: deps.accountId,
809
+ isGroup,
810
+ groupId,
811
+ senderPeerId
812
+ });
813
+ const mentionRegexes = buildMentionRegexes(deps.cfg, route.agentId);
814
+ const wasMentioned = isGroup && matchesMentionPatterns(messageText, mentionRegexes);
815
+ const requireMention = isGroup && resolveChannelGroupRequireMention({
816
+ cfg: deps.cfg,
817
+ channel: "signal",
818
+ groupId,
819
+ accountId: deps.accountId,
820
+ configuredGroupDefaultsToNoMention: true
821
+ });
822
+ const canDetectMention = mentionRegexes.length > 0;
823
+ const mentionDecision = resolveInboundMentionDecision({
824
+ facts: {
825
+ canDetectMention,
826
+ wasMentioned,
827
+ hasAnyMention: false,
828
+ implicitMentionKinds: []
829
+ },
830
+ policy: {
831
+ isGroup,
832
+ requireMention,
833
+ allowTextCommands: true,
834
+ hasControlCommand: hasControlCommandInMessage,
835
+ commandAuthorized
836
+ }
837
+ });
838
+ const effectiveWasMentioned = mentionDecision.effectiveWasMentioned;
839
+ if (isGroup && requireMention && canDetectMention && mentionDecision.shouldSkip) {
840
+ logInboundDrop({
841
+ log: logVerbose,
842
+ channel: "signal",
843
+ reason: "no mention",
844
+ target: senderDisplay
845
+ });
846
+ const pendingPlaceholder = (() => {
847
+ if (!dataMessage.attachments?.length) return "";
848
+ if (deps.ignoreAttachments) return "<media:attachment>";
849
+ const attachmentTypes = (dataMessage.attachments ?? []).map((attachment) => typeof attachment?.contentType === "string" ? attachment.contentType : void 0);
850
+ if (attachmentTypes.length > 1) return formatAttachmentSummaryPlaceholder(attachmentTypes);
851
+ const firstContentType = dataMessage.attachments?.[0]?.contentType;
852
+ const pendingKind = kindFromMime(firstContentType ?? void 0);
853
+ return pendingKind ? `<media:${pendingKind}>` : "<media:attachment>";
854
+ })();
855
+ const pendingBodyText = messageText || pendingPlaceholder || visibleQuoteText;
856
+ const historyKey = groupId ?? "unknown";
857
+ createChannelHistoryWindow({ historyMap: deps.groupHistories }).record({
858
+ historyKey,
859
+ limit: deps.historyLimit,
860
+ entry: {
861
+ sender: envelope.sourceName ?? senderDisplay,
862
+ body: pendingBodyText,
863
+ timestamp: envelope.timestamp ?? void 0,
864
+ messageId: typeof envelope.timestamp === "number" ? String(envelope.timestamp) : void 0
865
+ }
866
+ });
867
+ const signalGroupPolicy = resolveChannelGroupPolicy({
868
+ cfg: deps.cfg,
869
+ channel: "signal",
870
+ groupId,
871
+ accountId: deps.accountId
872
+ });
873
+ if ((signalGroupPolicy.groupConfig?.ingest ?? signalGroupPolicy.defaultConfig?.ingest) === true) {
874
+ const canonicalGroupTarget = normalizeSignalMessagingTarget(`group:${groupId}`) ?? `group:${groupId}`;
875
+ fireAndForgetHook(triggerInternalHook(createInternalHookEvent("message", "received", route.sessionKey, toInternalMessageReceivedContext({
876
+ from: `group:${groupId}`,
877
+ to: canonicalGroupTarget,
878
+ content: pendingBodyText,
879
+ timestamp: envelope.timestamp ?? void 0,
880
+ channelId: "signal",
881
+ accountId: deps.accountId,
882
+ conversationId: canonicalGroupTarget,
883
+ messageId: typeof envelope.timestamp === "number" ? String(envelope.timestamp) : void 0,
884
+ senderId: senderDisplay,
885
+ senderName: envelope.sourceName ?? void 0,
886
+ provider: "signal",
887
+ surface: "signal",
888
+ originatingChannel: "signal",
889
+ originatingTo: canonicalGroupTarget,
890
+ isGroup: true,
891
+ groupId: canonicalGroupTarget
892
+ }))), "signal: mention-skip message hook failed");
893
+ }
894
+ return;
895
+ }
896
+ let mediaPath;
897
+ let mediaType;
898
+ const mediaPaths = [];
899
+ const mediaTypes = [];
900
+ let placeholder = "";
901
+ const attachments = dataMessage.attachments ?? [];
902
+ if (!deps.ignoreAttachments) for (const attachment of attachments) {
903
+ if (!attachment?.id) continue;
904
+ try {
905
+ const fetched = await deps.fetchAttachment({
906
+ baseUrl: deps.baseUrl,
907
+ account: deps.account,
908
+ attachment,
909
+ sender: senderRecipient,
910
+ groupId,
911
+ maxBytes: deps.mediaMaxBytes
912
+ });
913
+ if (fetched) {
914
+ mediaPaths.push(fetched.path);
915
+ mediaTypes.push(fetched.contentType ?? attachment.contentType ?? "application/octet-stream");
916
+ if (!mediaPath) {
917
+ mediaPath = fetched.path;
918
+ mediaType = fetched.contentType ?? attachment.contentType ?? void 0;
919
+ }
920
+ }
921
+ } catch (err) {
922
+ deps.runtime.error?.(danger(`attachment fetch failed: ${String(err)}`));
923
+ }
924
+ }
925
+ if (mediaPaths.length > 1) placeholder = formatAttachmentSummaryPlaceholder(mediaTypes);
926
+ else {
927
+ const kind = kindFromMime(mediaType ?? void 0);
928
+ if (kind) placeholder = `<media:${kind}>`;
929
+ else if (attachments.length) placeholder = "<media:attachment>";
930
+ }
931
+ const bodyText = messageText || placeholder || visibleQuoteText || "";
932
+ if (!bodyText) return;
933
+ const receiptTimestamp = typeof envelope.timestamp === "number" ? envelope.timestamp : typeof dataMessage.timestamp === "number" ? dataMessage.timestamp : void 0;
934
+ if (deps.sendReadReceipts && !deps.readReceiptsViaDaemon && !isGroup && receiptTimestamp) try {
935
+ await sendReadReceiptSignal(`signal:${senderRecipient}`, receiptTimestamp, {
936
+ cfg: deps.cfg,
937
+ baseUrl: deps.baseUrl,
938
+ account: deps.account,
939
+ accountId: deps.accountId
940
+ });
941
+ } catch (err) {
942
+ logVerbose(`signal read receipt failed for ${senderDisplay}: ${String(err)}`);
943
+ }
944
+ else if (deps.sendReadReceipts && !deps.readReceiptsViaDaemon && !isGroup && !receiptTimestamp) logVerbose(`signal read receipt skipped (missing timestamp) for ${senderDisplay}`);
945
+ const senderName = envelope.sourceName ?? senderDisplay;
946
+ const messageId = typeof envelope.timestamp === "number" ? String(envelope.timestamp) : void 0;
947
+ await inboundDebouncer.enqueue({
948
+ senderName,
949
+ senderDisplay,
950
+ senderRecipient,
951
+ senderPeerId,
952
+ groupId,
953
+ groupName,
954
+ isGroup,
955
+ bodyText,
956
+ commandBody: messageText,
957
+ timestamp: envelope.timestamp ?? void 0,
958
+ messageId,
959
+ mediaPath,
960
+ mediaType,
961
+ mediaPaths: mediaPaths.length > 0 ? mediaPaths : void 0,
962
+ mediaTypes: mediaTypes.length > 0 ? mediaTypes : void 0,
963
+ commandAuthorized,
964
+ wasMentioned: effectiveWasMentioned,
965
+ replyToBody: visibleQuoteText || void 0,
966
+ replyToSender: visibleQuoteSender,
967
+ replyToIsQuote: visibleQuoteText ? true : void 0
968
+ });
969
+ };
970
+ }
971
+ //#endregion
972
+ //#region extensions/signal/src/sse-reconnect.ts
973
+ const DEFAULT_RECONNECT_POLICY = {
974
+ initialMs: 1e3,
975
+ maxMs: 1e4,
976
+ factor: 2,
977
+ jitter: .2
978
+ };
979
+ async function runSignalSseLoop({ baseUrl, account, abortSignal, runtime, onEvent, timeoutMs, apiMode, policy }) {
980
+ const reconnectPolicy = {
981
+ ...DEFAULT_RECONNECT_POLICY,
982
+ ...policy
983
+ };
984
+ let reconnectAttempts = 0;
985
+ const logReconnectVerbose = (message) => {
986
+ if (!shouldLogVerbose()) return;
987
+ logVerbose(message);
988
+ };
989
+ for (;;) {
990
+ if (abortSignal?.aborted) break;
991
+ try {
992
+ await streamSignalEvents({
993
+ baseUrl,
994
+ account,
995
+ abortSignal,
996
+ timeoutMs,
997
+ apiMode,
998
+ onEvent: (event) => {
999
+ reconnectAttempts = 0;
1000
+ onEvent(event);
1001
+ },
1002
+ logger: {
1003
+ log: runtime.log,
1004
+ error: runtime.error
1005
+ }
1006
+ });
1007
+ if (abortSignal?.aborted) return;
1008
+ reconnectAttempts += 1;
1009
+ const delayMs = computeBackoff(reconnectPolicy, reconnectAttempts);
1010
+ logReconnectVerbose(`Signal stream ended, reconnecting in ${delayMs / 1e3}s...`);
1011
+ await sleepWithAbort(delayMs, abortSignal);
1012
+ } catch (err) {
1013
+ if (abortSignal?.aborted) return;
1014
+ runtime.error?.(`Signal stream error: ${String(err)}`);
1015
+ reconnectAttempts += 1;
1016
+ const delayMs = computeBackoff(reconnectPolicy, reconnectAttempts);
1017
+ runtime.log?.(`Signal connection lost, reconnecting in ${delayMs / 1e3}s...`);
1018
+ try {
1019
+ await sleepWithAbort(delayMs, abortSignal);
1020
+ } catch (sleepErr) {
1021
+ if (abortSignal?.aborted) return;
1022
+ throw sleepErr;
1023
+ }
1024
+ }
1025
+ }
1026
+ }
1027
+ //#endregion
1028
+ //#region extensions/signal/src/monitor.ts
1029
+ var monitor_exports = /* @__PURE__ */ __exportAll({ monitorSignalProvider: () => monitorSignalProvider });
1030
+ function resolveRuntime(opts) {
1031
+ return opts.runtime ?? createNonExitingRuntime();
1032
+ }
1033
+ function createSignalMonitorTaskRunner(runtime) {
1034
+ const inFlight = /* @__PURE__ */ new Set();
1035
+ return {
1036
+ runEventTask(task) {
1037
+ const trackedTask = Promise.resolve().then(task).catch((err) => runtime.error?.(`event handler failed: ${String(err)}`)).finally(() => inFlight.delete(trackedTask));
1038
+ inFlight.add(trackedTask);
1039
+ },
1040
+ async waitForIdle() {
1041
+ while (inFlight.size > 0) await Promise.allSettled(inFlight);
1042
+ }
1043
+ };
1044
+ }
1045
+ function mergeAbortSignals(a, b) {
1046
+ if (!a && !b) return {
1047
+ signal: void 0,
1048
+ dispose: () => {}
1049
+ };
1050
+ if (!a) return {
1051
+ signal: b,
1052
+ dispose: () => {}
1053
+ };
1054
+ if (!b) return {
1055
+ signal: a,
1056
+ dispose: () => {}
1057
+ };
1058
+ const controller = new AbortController();
1059
+ const abortFrom = (source) => {
1060
+ if (!controller.signal.aborted) controller.abort(source.reason);
1061
+ };
1062
+ if (a.aborted) {
1063
+ abortFrom(a);
1064
+ return {
1065
+ signal: controller.signal,
1066
+ dispose: () => {}
1067
+ };
1068
+ }
1069
+ if (b.aborted) {
1070
+ abortFrom(b);
1071
+ return {
1072
+ signal: controller.signal,
1073
+ dispose: () => {}
1074
+ };
1075
+ }
1076
+ const onAbortA = () => abortFrom(a);
1077
+ const onAbortB = () => abortFrom(b);
1078
+ a.addEventListener("abort", onAbortA, { once: true });
1079
+ b.addEventListener("abort", onAbortB, { once: true });
1080
+ return {
1081
+ signal: controller.signal,
1082
+ dispose: () => {
1083
+ a.removeEventListener("abort", onAbortA);
1084
+ b.removeEventListener("abort", onAbortB);
1085
+ }
1086
+ };
1087
+ }
1088
+ function createSignalDaemonLifecycle(params) {
1089
+ let daemonHandle = null;
1090
+ let daemonStopRequested = false;
1091
+ let daemonExitError;
1092
+ const daemonAbortController = new AbortController();
1093
+ const mergedAbort = mergeAbortSignals(params.abortSignal, daemonAbortController.signal);
1094
+ const stop = () => {
1095
+ daemonStopRequested = true;
1096
+ daemonHandle?.stop();
1097
+ };
1098
+ const attach = (handle) => {
1099
+ daemonHandle = handle;
1100
+ handle.exited.then((exit) => {
1101
+ if (daemonStopRequested || params.abortSignal?.aborted) return;
1102
+ daemonExitError = new Error(formatSignalDaemonExit(exit));
1103
+ if (!daemonAbortController.signal.aborted) daemonAbortController.abort(daemonExitError);
1104
+ });
1105
+ };
1106
+ const getExitError = () => daemonExitError;
1107
+ return {
1108
+ attach,
1109
+ stop,
1110
+ getExitError,
1111
+ abortSignal: mergedAbort.signal,
1112
+ dispose: mergedAbort.dispose
1113
+ };
1114
+ }
1115
+ function normalizeAllowList(raw) {
1116
+ return normalizeStringEntries(raw);
1117
+ }
1118
+ function resolveSignalReactionTargets(reaction) {
1119
+ const targets = [];
1120
+ const uuid = reaction.targetAuthorUuid?.trim();
1121
+ if (uuid) targets.push({
1122
+ kind: "uuid",
1123
+ id: uuid,
1124
+ display: `uuid:${uuid}`
1125
+ });
1126
+ const author = reaction.targetAuthor?.trim();
1127
+ if (author) {
1128
+ const normalized = normalizeE164(author);
1129
+ targets.push({
1130
+ kind: "phone",
1131
+ id: normalized,
1132
+ display: normalized
1133
+ });
1134
+ }
1135
+ return targets;
1136
+ }
1137
+ function isSignalReactionMessage(reaction) {
1138
+ if (!reaction) return false;
1139
+ const emoji = reaction.emoji?.trim();
1140
+ const timestamp = reaction.targetSentTimestamp;
1141
+ const hasTarget = Boolean(normalizeOptionalString(reaction.targetAuthor) || normalizeOptionalString(reaction.targetAuthorUuid));
1142
+ return Boolean(emoji && typeof timestamp === "number" && timestamp > 0 && hasTarget);
1143
+ }
1144
+ function shouldEmitSignalReactionNotification(params) {
1145
+ const { mode, account, targets, sender, allowlist } = params;
1146
+ const effectiveMode = mode ?? "own";
1147
+ if (effectiveMode === "off") return false;
1148
+ if (effectiveMode === "own") {
1149
+ const accountId = account?.trim();
1150
+ if (!accountId || !targets || targets.length === 0) return false;
1151
+ const normalizedAccount = normalizeE164(accountId);
1152
+ return targets.some((target) => {
1153
+ if (target.kind === "uuid") return accountId === target.id || accountId === `uuid:${target.id}`;
1154
+ return normalizedAccount === target.id;
1155
+ });
1156
+ }
1157
+ if (effectiveMode === "allowlist") {
1158
+ if (!sender || !allowlist || allowlist.length === 0) return false;
1159
+ return isSignalSenderAllowed(sender, allowlist);
1160
+ }
1161
+ return true;
1162
+ }
1163
+ function buildSignalReactionSystemEventText(params) {
1164
+ const base = `Signal reaction added: ${params.emojiLabel} by ${params.actorLabel} msg ${params.messageId}`;
1165
+ const withTarget = params.targetLabel ? `${base} from ${params.targetLabel}` : base;
1166
+ return params.groupLabel ? `${withTarget} in ${params.groupLabel}` : withTarget;
1167
+ }
1168
+ async function waitForSignalDaemonReady(params) {
1169
+ await (params.waitForTransportReadyFn ?? waitForTransportReady)({
1170
+ label: "signal daemon",
1171
+ timeoutMs: params.timeoutMs,
1172
+ logAfterMs: params.logAfterMs,
1173
+ logIntervalMs: params.logIntervalMs,
1174
+ pollIntervalMs: 150,
1175
+ abortSignal: params.abortSignal,
1176
+ runtime: params.runtime,
1177
+ check: async () => {
1178
+ const res = await signalCheck(params.baseUrl, 1e3);
1179
+ if (res.ok) return { ok: true };
1180
+ return {
1181
+ ok: false,
1182
+ error: res.error ?? (res.status ? `HTTP ${res.status}` : "unreachable")
1183
+ };
1184
+ }
1185
+ });
1186
+ }
1187
+ const SIGNAL_ATTACHMENT_RPC_RESPONSE_HEADROOM_BYTES = 64 * 1024;
1188
+ const SIGNAL_BASE64_OVERHEAD_NUMERATOR = 4;
1189
+ const SIGNAL_BASE64_OVERHEAD_DENOMINATOR = 3;
1190
+ function deriveSignalAttachmentRpcMaxResponseBytes(maxBytes) {
1191
+ if (!Number.isFinite(maxBytes) || maxBytes <= 0) return;
1192
+ return Math.ceil(maxBytes * SIGNAL_BASE64_OVERHEAD_NUMERATOR / SIGNAL_BASE64_OVERHEAD_DENOMINATOR) + SIGNAL_ATTACHMENT_RPC_RESPONSE_HEADROOM_BYTES;
1193
+ }
1194
+ async function fetchAttachment(params) {
1195
+ const { attachment } = params;
1196
+ if (!attachment?.id) return null;
1197
+ if (typeof attachment.size === "number" && attachment.size > params.maxBytes) throw new Error(`Signal attachment ${attachment.id} exceeds ${(params.maxBytes / (1024 * 1024)).toFixed(0)}MB limit`);
1198
+ const rpcParams = { id: attachment.id };
1199
+ if (params.account) rpcParams.account = params.account;
1200
+ if (params.groupId) rpcParams.groupId = params.groupId;
1201
+ else if (params.sender) rpcParams.recipient = params.sender;
1202
+ else return null;
1203
+ const result = await signalRpcRequest("getAttachment", rpcParams, {
1204
+ baseUrl: params.baseUrl,
1205
+ maxResponseBytes: deriveSignalAttachmentRpcMaxResponseBytes(params.maxBytes),
1206
+ apiMode: params.apiMode
1207
+ });
1208
+ if (!result?.data) return null;
1209
+ if (estimateBase64DecodedBytes(result.data) > params.maxBytes) throw new Error(`Signal attachment ${attachment.id} exceeds ${(params.maxBytes / (1024 * 1024)).toFixed(0)}MB limit`);
1210
+ const buffer = Buffer.from(result.data, "base64");
1211
+ const originalFilename = normalizeOptionalString(attachment.filename ?? void 0);
1212
+ const saved = await saveMediaBuffer(buffer, normalizeOptionalString(attachment.contentType ?? void 0) ?? await detectMime({
1213
+ buffer,
1214
+ filePath: originalFilename
1215
+ }), "inbound", params.maxBytes, originalFilename);
1216
+ return {
1217
+ path: saved.path,
1218
+ contentType: saved.contentType
1219
+ };
1220
+ }
1221
+ async function deliverReplies(params) {
1222
+ const { replies, target, baseUrl, account, accountId, runtime, maxBytes, textLimit, chunkMode } = params;
1223
+ for (const payload of replies) if (await deliverTextOrMediaReply({
1224
+ payload,
1225
+ text: resolveSendableOutboundReplyParts(payload).text,
1226
+ chunkText: (value) => chunkTextWithMode(value, textLimit, chunkMode),
1227
+ sendText: async (chunk) => {
1228
+ await sendMessageSignal(target, chunk, {
1229
+ cfg: params.cfg,
1230
+ baseUrl,
1231
+ account,
1232
+ maxBytes,
1233
+ accountId
1234
+ });
1235
+ },
1236
+ sendMedia: async ({ mediaUrl, caption }) => {
1237
+ await sendMessageSignal(target, caption ?? "", {
1238
+ cfg: params.cfg,
1239
+ baseUrl,
1240
+ account,
1241
+ mediaUrl,
1242
+ maxBytes,
1243
+ accountId
1244
+ });
1245
+ }
1246
+ }) !== "empty") runtime.log?.(`delivered reply to ${target}`);
1247
+ }
1248
+ async function monitorSignalProvider(opts = {}) {
1249
+ const runtime = resolveRuntime(opts);
1250
+ const cfg = opts.config ?? getRuntimeConfig();
1251
+ const accountInfo = resolveSignalAccount({
1252
+ cfg,
1253
+ accountId: opts.accountId
1254
+ });
1255
+ const historyLimit = Math.max(0, accountInfo.config.historyLimit ?? cfg.messages?.groupChat?.historyLimit ?? DEFAULT_GROUP_HISTORY_LIMIT);
1256
+ const groupHistories = /* @__PURE__ */ new Map();
1257
+ const textLimit = resolveTextChunkLimit(cfg, "signal", accountInfo.accountId);
1258
+ const chunkMode = resolveChunkMode(cfg, "signal", accountInfo.accountId);
1259
+ const baseUrl = normalizeOptionalString(opts.baseUrl) ?? accountInfo.baseUrl;
1260
+ const account = normalizeOptionalString(opts.account) ?? normalizeOptionalString(accountInfo.config.account);
1261
+ const dmPolicy = accountInfo.config.dmPolicy ?? "pairing";
1262
+ const allowFrom = normalizeAllowList(opts.allowFrom ?? accountInfo.config.allowFrom);
1263
+ const groupAllowFrom = normalizeAllowList(opts.groupAllowFrom ?? accountInfo.config.groupAllowFrom ?? (accountInfo.config.allowFrom && accountInfo.config.allowFrom.length > 0 ? accountInfo.config.allowFrom : []));
1264
+ const defaultGroupPolicy = resolveDefaultGroupPolicy(cfg);
1265
+ const { groupPolicy, providerMissingFallbackApplied } = resolveAllowlistProviderRuntimeGroupPolicy({
1266
+ providerConfigPresent: cfg.channels?.signal !== void 0,
1267
+ groupPolicy: accountInfo.config.groupPolicy,
1268
+ defaultGroupPolicy
1269
+ });
1270
+ warnMissingProviderGroupPolicyFallbackOnce({
1271
+ providerMissingFallbackApplied,
1272
+ providerKey: "signal",
1273
+ accountId: accountInfo.accountId,
1274
+ log: (message) => runtime.log?.(message)
1275
+ });
1276
+ const reactionMode = accountInfo.config.reactionNotifications ?? "own";
1277
+ const reactionAllowlist = normalizeAllowList(accountInfo.config.reactionAllowlist);
1278
+ const mediaMaxBytes = (opts.mediaMaxMb ?? accountInfo.config.mediaMaxMb ?? 8) * 1024 * 1024;
1279
+ const ignoreAttachments = opts.ignoreAttachments ?? accountInfo.config.ignoreAttachments ?? false;
1280
+ const sendReadReceipts = Boolean(opts.sendReadReceipts ?? accountInfo.config.sendReadReceipts);
1281
+ const waitForTransportReadyFn = opts.waitForTransportReady ?? waitForTransportReady;
1282
+ const autoStart = opts.autoStart ?? accountInfo.config.autoStart ?? !accountInfo.config.httpUrl;
1283
+ const configuredApiMode = cfg.channels?.signal?.apiMode ?? "auto";
1284
+ const startupTimeoutMs = Math.min(12e4, Math.max(1e3, opts.startupTimeoutMs ?? accountInfo.config.startupTimeoutMs ?? 3e4));
1285
+ const readReceiptsViaDaemon = autoStart && sendReadReceipts;
1286
+ const daemonLifecycle = createSignalDaemonLifecycle({ abortSignal: opts.abortSignal });
1287
+ const monitorTaskRunner = createSignalMonitorTaskRunner(runtime);
1288
+ let daemonHandle = null;
1289
+ if (autoStart && configuredApiMode === "container") throw new Error("channels.signal.autoStart=true is incompatible with channels.signal.apiMode=container");
1290
+ if (autoStart) {
1291
+ const cliPath = opts.cliPath ?? accountInfo.config.cliPath ?? "signal-cli";
1292
+ const configPath = normalizeOptionalString(opts.configPath) ?? normalizeOptionalString(accountInfo.config.configPath);
1293
+ const httpHost = opts.httpHost ?? accountInfo.config.httpHost ?? "127.0.0.1";
1294
+ const httpPort = opts.httpPort ?? accountInfo.config.httpPort ?? 8080;
1295
+ daemonHandle = spawnSignalDaemon({
1296
+ cliPath,
1297
+ ...configPath ? { configPath } : {},
1298
+ account,
1299
+ httpHost,
1300
+ httpPort,
1301
+ receiveMode: opts.receiveMode ?? accountInfo.config.receiveMode,
1302
+ ignoreAttachments: opts.ignoreAttachments ?? accountInfo.config.ignoreAttachments,
1303
+ ignoreStories: opts.ignoreStories ?? accountInfo.config.ignoreStories,
1304
+ sendReadReceipts,
1305
+ runtime
1306
+ });
1307
+ daemonLifecycle.attach(daemonHandle);
1308
+ }
1309
+ const onAbort = () => {
1310
+ daemonLifecycle.stop();
1311
+ };
1312
+ opts.abortSignal?.addEventListener("abort", onAbort, { once: true });
1313
+ try {
1314
+ if (daemonHandle) {
1315
+ await waitForSignalDaemonReady({
1316
+ baseUrl,
1317
+ abortSignal: daemonLifecycle.abortSignal,
1318
+ timeoutMs: startupTimeoutMs,
1319
+ logAfterMs: 1e4,
1320
+ logIntervalMs: 1e4,
1321
+ runtime,
1322
+ waitForTransportReadyFn
1323
+ });
1324
+ const daemonExitError = daemonLifecycle.getExitError();
1325
+ if (daemonExitError) throw daemonExitError;
1326
+ }
1327
+ registerChannelRuntimeContext({
1328
+ channelRuntime: opts.channelRuntime,
1329
+ channelId: "signal",
1330
+ accountId: accountInfo.accountId,
1331
+ capability: CHANNEL_APPROVAL_NATIVE_RUNTIME_CONTEXT_CAPABILITY,
1332
+ context: isSignalNativeApprovalHandlerConfigured({
1333
+ cfg,
1334
+ accountId: accountInfo.accountId
1335
+ }) ? {
1336
+ accountId: accountInfo.accountId,
1337
+ baseUrl,
1338
+ account,
1339
+ accountUuid: accountInfo.config.accountUuid
1340
+ } : null,
1341
+ abortSignal: opts.abortSignal
1342
+ });
1343
+ const handleEvent = createSignalEventHandler({
1344
+ runtime,
1345
+ cfg,
1346
+ baseUrl,
1347
+ account,
1348
+ accountUuid: accountInfo.config.accountUuid,
1349
+ accountId: accountInfo.accountId,
1350
+ blockStreaming: accountInfo.config.blockStreaming,
1351
+ historyLimit,
1352
+ groupHistories,
1353
+ textLimit,
1354
+ dmPolicy,
1355
+ allowFrom,
1356
+ groupAllowFrom,
1357
+ groupPolicy,
1358
+ reactionMode,
1359
+ reactionAllowlist,
1360
+ mediaMaxBytes,
1361
+ ignoreAttachments,
1362
+ sendReadReceipts,
1363
+ readReceiptsViaDaemon,
1364
+ fetchAttachment: (params) => fetchAttachment({
1365
+ ...params,
1366
+ apiMode: configuredApiMode
1367
+ }),
1368
+ deliverReplies: (params) => deliverReplies({
1369
+ ...params,
1370
+ cfg,
1371
+ chunkMode
1372
+ }),
1373
+ resolveSignalReactionTargets,
1374
+ isSignalReactionMessage,
1375
+ shouldEmitSignalReactionNotification,
1376
+ buildSignalReactionSystemEventText
1377
+ });
1378
+ await runSignalSseLoop({
1379
+ baseUrl,
1380
+ account,
1381
+ abortSignal: daemonLifecycle.abortSignal,
1382
+ runtime,
1383
+ timeoutMs: 0,
1384
+ apiMode: configuredApiMode,
1385
+ policy: opts.reconnectPolicy,
1386
+ onEvent: (event) => {
1387
+ monitorTaskRunner.runEventTask(() => handleEvent(event));
1388
+ }
1389
+ });
1390
+ const daemonExitError = daemonLifecycle.getExitError();
1391
+ if (daemonExitError) throw daemonExitError;
1392
+ } catch (err) {
1393
+ const daemonExitError = daemonLifecycle.getExitError();
1394
+ if (opts.abortSignal?.aborted && !daemonExitError) return;
1395
+ throw err;
1396
+ } finally {
1397
+ await monitorTaskRunner.waitForIdle();
1398
+ daemonLifecycle.dispose();
1399
+ opts.abortSignal?.removeEventListener("abort", onAbort);
1400
+ daemonLifecycle.stop();
1401
+ }
1402
+ }
1403
+ //#endregion
1404
+ export { monitor_exports as n, monitorSignalProvider as t };