@openclaw/sms 2026.10.10 → 2026.11.5-beta.1

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.
@@ -1,5 +1,5 @@
1
1
  import { t as getSmsRuntime } from "./.setup/runtime-A8rnEOmw.mjs";
2
- import { C as normalizeSmsAllowFrom, S as looksLikeSmsPhoneNumber, _ as isSmsAccountConfigured, a as listTwilioIncomingPhoneNumbers, b as resolveSmsAccount, c as resolveTwilioInboundSender, d as respondTwiml, f as retrieveTwilioMessagingService, g as inspectSmsAccount, h as assertSmsCredentialOwnerAvailable, i as buildTwilioInboundMessage, l as resolveTwilioMessageSid, m as verifyTwilioSignature, o as listTwilioMessages, p as sendSmsViaTwilio, r as TWIML_CONTENT_TYPE, s as readTwilioWebhookForm, t as TWILIO_MESSAGE_BODY_MAX_LENGTH, u as resolveTwilioWebhookSignatureUrl, v as listSmsAccountIds, w as normalizeSmsPhoneNumber, x as resolveTwilioStatusCallbackUrl, y as resolveDefaultSmsAccountId } from "./.setup/twilio-DlIKNs5E.mjs";
2
+ import { C as normalizeSmsAllowFrom, S as looksLikeSmsPhoneNumber, _ as isSmsAccountConfigured, a as listTwilioIncomingPhoneNumbers, b as resolveSmsAccount, c as resolveTwilioInboundSender, d as respondTwiml, f as retrieveTwilioMessagingService, g as inspectSmsAccount, h as assertSmsCredentialOwnerAvailable, i as buildTwilioInboundMessage, l as resolveTwilioMessageSid, m as verifyTwilioSignature, o as listTwilioMessages, p as sendSmsViaTwilio, r as TWIML_CONTENT_TYPE, s as readTwilioWebhookForm, t as TWILIO_MESSAGE_BODY_MAX_LENGTH, u as resolveTwilioWebhookSignatureUrl, v as listSmsAccountIds, w as normalizeSmsPhoneNumber, x as resolveTwilioStatusCallbackUrl, y as resolveDefaultSmsAccountId } from "./.setup/twilio-07yIWayE.mjs";
3
3
  import { n as collectRuntimeConfigAssignments, r as secretTargetRegistryEntries } from "./.setup/secret-contract-BTxRnkG1.mjs";
4
4
  import { DEFAULT_ACCOUNT_ID } from "openclaw/plugin-sdk/account-id";
5
5
  import { createHybridChannelConfigAdapter, createScopedDmSecurityResolver } from "openclaw/plugin-sdk/channel-config-helpers";
@@ -16,8 +16,7 @@ import { buildSecretInputSchema } from "openclaw/plugin-sdk/secret-input";
16
16
  import { AllowFromListSchema, DmPolicySchema, buildChannelConfigSchema, buildMultiAccountChannelSchema, requireOpenAllowFrom } from "openclaw/plugin-sdk/channel-config-schema";
17
17
  import { requireChannelOpenAllowFrom } from "openclaw/plugin-sdk/extension-shared";
18
18
  import { z } from "zod";
19
- import { createHash } from "node:crypto";
20
- import { withTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
19
+ import { sha256Hex } from "openclaw/plugin-sdk/node-crypto-runtime";
21
20
  import { createFixedWindowRateLimiter, isRequestBodyLimitError, registerPluginHttpRoute, resolveRequestClientIp } from "openclaw/plugin-sdk/webhook-ingress";
22
21
  import { channelBlockedPatch, channelReadyPatch, channelStoppedPatch } from "openclaw/plugin-sdk/gateway-runtime";
23
22
  import { createWebhookInFlightLimiter, runDetachedWebhookWork, sendHttpRequestRejection } from "openclaw/plugin-sdk/webhook-request-guards";
@@ -136,20 +135,14 @@ function normalizeDeliveryStatus(rawStatus) {
136
135
  function resolveDeliveryStatus(form) {
137
136
  return normalizeDeliveryStatus(firstTrimmed(form, "MessageStatus") || firstTrimmed(form, "SmsStatus"));
138
137
  }
139
- function hashAccountSid(accountSid) {
140
- return createHash("sha256").update(accountSid).digest("hex");
141
- }
142
138
  function fingerprintObservation(params) {
143
- return createHash("sha256").update(JSON.stringify([
139
+ return sha256Hex(JSON.stringify([
144
140
  params.source,
145
141
  params.messageSid,
146
142
  params.status,
147
143
  params.errorCode ?? "",
148
144
  params.rawDlrDoneDate ?? ""
149
- ])).digest("hex");
150
- }
151
- function deliveryRecordKey(params) {
152
- return createHash("sha256").update(`${params.accountId}\n${params.accountSidHash}\n${params.messageSid}`).digest("hex");
145
+ ]));
153
146
  }
154
147
  function openDeliveryStore() {
155
148
  const runtime = getSmsRuntime();
@@ -167,30 +160,6 @@ function openDeliveryStore() {
167
160
  function isTwilioDeliveryStatusForm(form) {
168
161
  return Boolean(resolveDeliveryStatus(form));
169
162
  }
170
- function parseSmsDeliveryObservation(form, nowMs = Date.now()) {
171
- const messageSid = resolveTwilioMessageSid(form);
172
- const status = resolveDeliveryStatus(form);
173
- if (!messageSid || !status) return null;
174
- const errorCode = firstTrimmed(form, "ErrorCode");
175
- const rawDlrDoneDate = firstTrimmed(form, "RawDlrDoneDate");
176
- return {
177
- messageSid,
178
- observation: {
179
- source: "callback",
180
- fingerprint: fingerprintObservation({
181
- source: "callback",
182
- messageSid,
183
- status,
184
- ...errorCode ? { errorCode } : {},
185
- ...rawDlrDoneDate ? { rawDlrDoneDate } : {}
186
- }),
187
- status,
188
- observedAt: nowMs,
189
- ...errorCode ? { errorCode } : {},
190
- ...rawDlrDoneDate ? { rawDlrDoneDate } : {}
191
- }
192
- };
193
- }
194
163
  function reduceDeliveryStatus(current, observation) {
195
164
  if (current?.status === "conflicted") return {
196
165
  status: current.status,
@@ -222,39 +191,32 @@ function reduceDeliveryStatus(current, observation) {
222
191
  ...selected === current && current.conflict ? { conflict: true } : {}
223
192
  };
224
193
  }
225
- function mergeSmsDeliveryObservation(params) {
226
- if (params.current?.observations.some((existing) => existing.fingerprint === params.observation.fingerprint)) return;
227
- const reduced = reduceDeliveryStatus(params.current, params.observation);
228
- return {
229
- accountId: params.accountId,
230
- accountSidHash: params.accountSidHash,
231
- messageSid: params.messageSid,
232
- status: reduced.status,
233
- firstObservedAt: params.current?.firstObservedAt ?? params.observation.observedAt,
234
- lastObservedAt: params.observation.observedAt,
235
- ...reduced.errorCode ? { errorCode: reduced.errorCode } : {},
236
- ...reduced.conflict ? { conflict: true } : {},
237
- observations: [...params.current?.observations ?? [], params.observation].slice(-20)
238
- };
239
- }
240
194
  async function recordSmsDeliveryObservation(params) {
241
195
  if (!params.store.observe || !params.store.compareAndApply) throw new Error("SMS delivery observations require plugin state comparisons.");
242
196
  const accountId = params.account.accountId;
243
- const accountSidHash = hashAccountSid(params.account.accountSid);
244
- const key = deliveryRecordKey({
245
- accountId,
246
- accountSidHash,
247
- messageSid: params.messageSid
248
- });
197
+ const accountSidHash = sha256Hex(params.account.accountSid);
198
+ const key = sha256Hex(`${accountId}\n${accountSidHash}\n${params.messageSid}`);
249
199
  let observed = await params.store.observe(key);
250
- while (true) {
251
- const next = mergeSmsDeliveryObservation({
200
+ function mergeSmsDeliveryObservation() {
201
+ const messageSid = params.messageSid;
202
+ const current = observed.value;
203
+ const observation = params.observation;
204
+ if (current?.observations.some((existing) => existing.fingerprint === observation.fingerprint)) return;
205
+ const reduced = reduceDeliveryStatus(current, observation);
206
+ return {
252
207
  accountId,
253
208
  accountSidHash,
254
- messageSid: params.messageSid,
255
- current: observed.value,
256
- observation: params.observation
257
- });
209
+ messageSid,
210
+ status: reduced.status,
211
+ firstObservedAt: current?.firstObservedAt ?? observation.observedAt,
212
+ lastObservedAt: observation.observedAt,
213
+ ...reduced.errorCode ? { errorCode: reduced.errorCode } : {},
214
+ ...reduced.conflict ? { conflict: true } : {},
215
+ observations: [...current?.observations ?? [], observation].slice(-20)
216
+ };
217
+ }
218
+ while (true) {
219
+ const next = mergeSmsDeliveryObservation();
258
220
  const result = await params.store.compareAndApply(key, observed.comparison, next ? {
259
221
  operation: "update",
260
222
  action: "set",
@@ -275,14 +237,32 @@ async function recordSmsDeliveryObservation(params) {
275
237
  };
276
238
  }
277
239
  }
278
- function createSmsDeliveryRecorder(store = openDeliveryStore()) {
240
+ function createSmsDeliveryRecorder() {
241
+ const store = openDeliveryStore();
279
242
  return { async record({ account, form }) {
280
- const parsed = parseSmsDeliveryObservation(form);
281
- if (!parsed) throw new Error("Invalid Twilio delivery status callback.");
243
+ const nowMs = Date.now();
244
+ const messageSid = resolveTwilioMessageSid(form);
245
+ const status = resolveDeliveryStatus(form);
246
+ if (!messageSid || !status) throw new Error("Invalid Twilio delivery status callback.");
247
+ const errorCode = firstTrimmed(form, "ErrorCode");
248
+ const rawDlrDoneDate = firstTrimmed(form, "RawDlrDoneDate");
282
249
  return await recordSmsDeliveryObservation({
283
250
  account,
284
- messageSid: parsed.messageSid,
285
- observation: parsed.observation,
251
+ messageSid,
252
+ observation: {
253
+ source: "callback",
254
+ fingerprint: fingerprintObservation({
255
+ source: "callback",
256
+ messageSid,
257
+ status,
258
+ ...errorCode ? { errorCode } : {},
259
+ ...rawDlrDoneDate ? { rawDlrDoneDate } : {}
260
+ }),
261
+ status,
262
+ observedAt: nowMs,
263
+ ...errorCode ? { errorCode } : {},
264
+ ...rawDlrDoneDate ? { rawDlrDoneDate } : {}
265
+ },
286
266
  store
287
267
  });
288
268
  } };
@@ -302,15 +282,15 @@ async function recordInitialSmsDeliveryResult(params) {
302
282
  status
303
283
  }),
304
284
  status,
305
- observedAt: params.nowMs ?? Date.now()
285
+ observedAt: Date.now()
306
286
  },
307
- store: params.store ?? openDeliveryStore()
287
+ store: openDeliveryStore()
308
288
  });
309
289
  }
310
- async function listRecentSmsDeliveryRecords(account, limit = 1, store = openDeliveryStore()) {
311
- if (limit <= 0) return [];
312
- const accountSidHash = hashAccountSid(account.accountSid);
313
- return (await store.entries()).map((entry) => entry.value).filter((record) => record.accountId === account.accountId && record.accountSidHash === accountSidHash).toSorted((left, right) => right.lastObservedAt - left.lastObservedAt).slice(0, limit);
290
+ async function listRecentSmsDeliveryRecords(account) {
291
+ const store = openDeliveryStore();
292
+ const accountSidHash = sha256Hex(account.accountSid);
293
+ return (await store.entries()).map((entry) => entry.value).filter((record) => record.accountId === account.accountId && record.accountSidHash === accountSidHash).toSorted((left, right) => right.lastObservedAt - left.lastObservedAt).slice(0, 1);
314
294
  }
315
295
  // extensions/sms/src/send.ts
316
296
  const SMS_ASSISTANT_TRANSCRIPT_ROLE_PREFIX = "[assistant-authored transcript] ";
@@ -444,7 +424,7 @@ async function prepareSmsMediaAttempt(params) {
444
424
  });
445
425
  let hostedMedia;
446
426
  try {
447
- const { prepareHostedSmsMedia } = await import("./.setup/media-CXXQruyp.mjs");
427
+ const { prepareHostedSmsMedia } = await import("./.setup/media-BF6-nsm2.mjs");
448
428
  assertSmsCredentialOwnerAvailable(params.account);
449
429
  const prepared = await prepareHostedSmsMedia({
450
430
  account: params.account,
@@ -476,85 +456,74 @@ async function sendPreparedSmsMediaAttempt(params) {
476
456
  }
477
457
  // extensions/sms/src/inbound.ts
478
458
  const CHANNEL_ID$2 = "sms";
479
- async function authorizeSmsSender(params) {
480
- const commandRequested = params.channelRuntime.commands.shouldComputeCommandAuthorized(params.rawBody, params.cfg);
481
- return await params.channelRuntime.inbound.ingress.resolveStable({
482
- channelId: CHANNEL_ID$2,
483
- accountId: params.account.accountId,
484
- cfg: params.cfg,
485
- identity: {
486
- key: "phone",
487
- entryIdPrefix: "sms-entry"
488
- },
489
- readStoreAllowFrom: async () => await params.channelRuntime.pairing.readAllowFromStore({
490
- channel: CHANNEL_ID$2,
491
- accountId: params.account.accountId
492
- }),
493
- subject: { stableId: params.from },
494
- conversation: {
495
- kind: "direct",
496
- id: params.from
497
- },
498
- contextBinding: params.contextBinding,
499
- event: { mayPair: true },
500
- dmPolicy: params.account.dmPolicy,
501
- allowFrom: params.account.allowFrom,
502
- command: commandRequested ? {
503
- cfg: params.cfg,
504
- modeWhenAccessGroupsOff: "configured"
505
- } : void 0
506
- });
507
- }
508
- async function issueSmsPairingChallenge(params) {
509
- await createChannelPairingChallengeIssuer({
510
- channel: CHANNEL_ID$2,
511
- accountId: params.account.accountId,
512
- upsertPairingRequest: async (input) => await params.channelRuntime.pairing.upsertPairingRequest({
513
- channel: CHANNEL_ID$2,
514
- accountId: params.account.accountId,
515
- ...input
516
- })
517
- })({
518
- senderId: params.from,
519
- senderIdLine: `Your SMS phone number: ${params.from}`,
520
- sendPairingReply: async (text) => {
521
- await sendSmsTextChunks({
522
- account: params.account,
523
- to: params.from,
524
- text
525
- });
526
- },
527
- onCreated: () => {
528
- params.log?.info?.(`SMS pairing request created for ${params.from}`);
529
- },
530
- onReplyError: (err) => {
531
- params.log?.warn?.(`SMS pairing reply failed for ${params.from}: ${String(err)}`);
532
- }
533
- });
534
- }
535
459
  async function dispatchSmsInboundEvent(params) {
536
460
  const from = normalizeSmsPhoneNumber(params.msg.from);
537
- let auth = await authorizeSmsSender({
538
- cfg: params.cfg,
539
- account: params.account,
540
- channelRuntime: params.channelRuntime,
541
- from,
542
- rawBody: params.msg.body
543
- });
461
+ async function authorizeSmsSender(contextBinding) {
462
+ const { cfg, account, channelRuntime } = params;
463
+ const rawBody = params.msg.body;
464
+ const commandRequested = channelRuntime.commands.shouldComputeCommandAuthorized(rawBody, cfg);
465
+ return await channelRuntime.inbound.ingress.resolveStable({
466
+ channelId: CHANNEL_ID$2,
467
+ accountId: account.accountId,
468
+ cfg,
469
+ identity: {
470
+ key: "phone",
471
+ entryIdPrefix: "sms-entry"
472
+ },
473
+ readStoreAllowFrom: async () => await channelRuntime.pairing.readAllowFromStore({
474
+ channel: CHANNEL_ID$2,
475
+ accountId: account.accountId
476
+ }),
477
+ subject: { stableId: from },
478
+ conversation: {
479
+ kind: "direct",
480
+ id: from
481
+ },
482
+ contextBinding,
483
+ event: { mayPair: true },
484
+ dmPolicy: account.dmPolicy,
485
+ allowFrom: account.allowFrom,
486
+ command: commandRequested ? {
487
+ cfg,
488
+ modeWhenAccessGroupsOff: "configured"
489
+ } : void 0
490
+ });
491
+ }
492
+ let auth = await authorizeSmsSender();
544
493
  if (!auth.senderAccess.allowed) {
545
494
  if (auth.senderAccess.decision === "pairing") {
546
- await issueSmsPairingChallenge({
547
- account: params.account,
548
- channelRuntime: params.channelRuntime,
549
- from,
550
- log: params.log
495
+ const { account, channelRuntime, log } = params;
496
+ await createChannelPairingChallengeIssuer({
497
+ channel: CHANNEL_ID$2,
498
+ accountId: account.accountId,
499
+ upsertPairingRequest: async (input) => await channelRuntime.pairing.upsertPairingRequest({
500
+ channel: CHANNEL_ID$2,
501
+ accountId: account.accountId,
502
+ ...input
503
+ })
504
+ })({
505
+ senderId: from,
506
+ senderIdLine: `Your SMS phone number: ${from}`,
507
+ sendPairingReply: async (text) => {
508
+ await sendSmsTextChunks({
509
+ account,
510
+ to: from,
511
+ text
512
+ });
513
+ },
514
+ onCreated: () => {
515
+ log?.info?.(`SMS pairing request created for ${from}`);
516
+ },
517
+ onReplyError: (err) => {
518
+ log?.warn?.(`SMS pairing reply failed for ${from}: ${String(err)}`);
519
+ }
551
520
  });
552
521
  return;
553
522
  }
554
523
  params.log?.warn?.(`SMS sender ${from} is not authorized`);
555
524
  return;
556
525
  }
557
- const materialized = params.msg.media.length > 0 || (params.msg.unavailableMediaCount ?? 0) > 0 ? await (await import("./.setup/media-CXXQruyp.mjs")).materializeSmsInboundMedia({
526
+ const materialized = params.msg.media.length > 0 || (params.msg.unavailableMediaCount ?? 0) > 0 ? await (await import("./.setup/media-BF6-nsm2.mjs")).materializeSmsInboundMedia({
558
527
  account: params.account,
559
528
  msg: params.msg,
560
529
  mediaRuntime: params.channelRuntime,
@@ -601,17 +570,10 @@ async function dispatchSmsInboundEvent(params) {
601
570
  });
602
571
  const sessionKey = route.sessionKey;
603
572
  auth = await authorizeSmsSender({
604
- cfg: params.cfg,
605
- account: params.account,
606
- channelRuntime: params.channelRuntime,
607
- from,
608
- rawBody: params.msg.body,
609
- contextBinding: {
610
- agentId: route.agentId,
611
- sessionKey,
612
- messageId: params.msg.messageSid,
613
- inboundEventKind: "user_request"
614
- }
573
+ agentId: route.agentId,
574
+ sessionKey,
575
+ messageId: params.msg.messageSid,
576
+ inboundEventKind: "user_request"
615
577
  });
616
578
  if (!auth.senderAccess.allowed) {
617
579
  params.log?.warn?.(`SMS sender ${from} authorization changed before dispatch`);
@@ -1029,65 +991,6 @@ function collectSmsStartupWarnings(account) {
1029
991
  if (account.dmPolicy === "open" && !account.allowFrom.includes("*")) warnings.push("- SMS: dmPolicy=open should set allowFrom=[\"*\"] or explicit sender numbers.");
1030
992
  return warnings;
1031
993
  }
1032
- async function registerSmsWebhookRoute(params) {
1033
- const webhookPath = normalizeWebhookPath(params.account.webhookPath);
1034
- const currentRoute = activeRoutePaths.get(webhookPath);
1035
- if (currentRoute && currentRoute.accountId !== params.account.accountId) throw new Error(`SMS webhook path ${webhookPath} is already registered by account ${currentRoute.accountId}; configure a distinct webhookPath for account ${params.account.accountId}.`);
1036
- const predecessorStop = currentRoute ? stopSmsWebhookRoute(webhookPath, currentRoute) : pendingRouteStops.get(webhookPath) ?? Promise.resolve();
1037
- const ingress = createSmsIngressSpool({
1038
- cfg: params.cfg,
1039
- account: params.account,
1040
- channelRuntime: params.channelRuntime,
1041
- ...params.log ? { log: params.log } : {}
1042
- });
1043
- let unregisterRoute;
1044
- try {
1045
- const webhookHandler = createSmsWebhookHandler({
1046
- ...params,
1047
- ingress
1048
- });
1049
- unregisterRoute = registerPluginHttpRoute({
1050
- path: webhookPath,
1051
- auth: "plugin",
1052
- pluginId: CHANNEL_ID$1,
1053
- accountId: params.account.accountId,
1054
- throwOnFailure: true,
1055
- log: (msg) => params.log?.info?.(msg),
1056
- handler: async (req, res) => {
1057
- const { tryHandleHostedSmsMediaRequest } = await import("./.setup/media-CXXQruyp.mjs");
1058
- if (await tryHandleHostedSmsMediaRequest(req, res, params.account.accountId)) return true;
1059
- return await webhookHandler(req, res);
1060
- }
1061
- });
1062
- } catch (error) {
1063
- await Promise.allSettled([predecessorStop, ingress.stop()]);
1064
- throw error;
1065
- }
1066
- const route = {
1067
- accountId: params.account.accountId,
1068
- ingress,
1069
- unregisterRoute,
1070
- ready: Promise.resolve()
1071
- };
1072
- activeRoutePaths.set(webhookPath, route);
1073
- route.ready = predecessorStop.then(() => {
1074
- if (activeRoutePaths.get(webhookPath) === route && !route.stopTask) ingress.start();
1075
- });
1076
- const unregister = () => stopSmsWebhookRoute(webhookPath, route);
1077
- const readinessAbort = new AbortController();
1078
- const lifecycle = waitUntilAbort(AbortSignal.any([params.abortSignal, readinessAbort.signal]), unregister);
1079
- try {
1080
- await route.ready;
1081
- } catch (error) {
1082
- readinessAbort.abort();
1083
- await Promise.allSettled([lifecycle]);
1084
- throw error;
1085
- }
1086
- return {
1087
- lifecycle,
1088
- isActive: () => activeRoutePaths.get(webhookPath) === route
1089
- };
1090
- }
1091
994
  async function startSmsGatewayAccount(params) {
1092
995
  params.statusSink?.({ lifecycle: "starting" });
1093
996
  if (!params.account.enabled) {
@@ -1105,7 +1008,66 @@ async function startSmsGatewayAccount(params) {
1105
1008
  return waitUntilAbort(params.abortSignal);
1106
1009
  }
1107
1010
  for (const warning of warnings) params.log?.warn?.(warning);
1108
- const registration = await registerSmsWebhookRoute(params);
1011
+ async function registerSmsWebhookRoute() {
1012
+ const webhookPath = normalizeWebhookPath(params.account.webhookPath);
1013
+ const currentRoute = activeRoutePaths.get(webhookPath);
1014
+ if (currentRoute && currentRoute.accountId !== params.account.accountId) throw new Error(`SMS webhook path ${webhookPath} is already registered by account ${currentRoute.accountId}; configure a distinct webhookPath for account ${params.account.accountId}.`);
1015
+ const predecessorStop = currentRoute ? stopSmsWebhookRoute(webhookPath, currentRoute) : pendingRouteStops.get(webhookPath) ?? Promise.resolve();
1016
+ const ingress = createSmsIngressSpool({
1017
+ cfg: params.cfg,
1018
+ account: params.account,
1019
+ channelRuntime: params.channelRuntime,
1020
+ ...params.log ? { log: params.log } : {}
1021
+ });
1022
+ let unregisterRoute;
1023
+ try {
1024
+ const webhookHandler = createSmsWebhookHandler({
1025
+ ...params,
1026
+ ingress
1027
+ });
1028
+ unregisterRoute = registerPluginHttpRoute({
1029
+ path: webhookPath,
1030
+ auth: "plugin",
1031
+ pluginId: CHANNEL_ID$1,
1032
+ accountId: params.account.accountId,
1033
+ throwOnFailure: true,
1034
+ log: (msg) => params.log?.info?.(msg),
1035
+ handler: async (req, res) => {
1036
+ const { tryHandleHostedSmsMediaRequest } = await import("./.setup/media-BF6-nsm2.mjs");
1037
+ if (await tryHandleHostedSmsMediaRequest(req, res, params.account.accountId)) return true;
1038
+ return await webhookHandler(req, res);
1039
+ }
1040
+ });
1041
+ } catch (error) {
1042
+ await Promise.allSettled([predecessorStop, ingress.stop()]);
1043
+ throw error;
1044
+ }
1045
+ const route = {
1046
+ accountId: params.account.accountId,
1047
+ ingress,
1048
+ unregisterRoute,
1049
+ ready: Promise.resolve()
1050
+ };
1051
+ activeRoutePaths.set(webhookPath, route);
1052
+ route.ready = predecessorStop.then(() => {
1053
+ if (activeRoutePaths.get(webhookPath) === route && !route.stopTask) ingress.start();
1054
+ });
1055
+ const unregister = () => stopSmsWebhookRoute(webhookPath, route);
1056
+ const readinessAbort = new AbortController();
1057
+ const lifecycle = waitUntilAbort(AbortSignal.any([params.abortSignal, readinessAbort.signal]), unregister);
1058
+ try {
1059
+ await route.ready;
1060
+ } catch (error) {
1061
+ readinessAbort.abort();
1062
+ await Promise.allSettled([lifecycle]);
1063
+ throw error;
1064
+ }
1065
+ return {
1066
+ lifecycle,
1067
+ isActive: () => activeRoutePaths.get(webhookPath) === route
1068
+ };
1069
+ }
1070
+ const registration = await registerSmsWebhookRoute();
1109
1071
  if (registration.isActive()) {
1110
1072
  params.log?.info?.(`Registered SMS webhook route ${params.account.webhookPath} for account ${params.account.accountId}`);
1111
1073
  params.statusSink?.(channelReadyPatch());
@@ -1121,23 +1083,35 @@ function resolveRemoteProbeTimeoutMs(timeoutMs) {
1121
1083
  const settleMarginMs = Math.min(100, Math.max(1, Math.floor(normalized / 10)));
1122
1084
  return Math.max(0, normalized - settleMarginMs);
1123
1085
  }
1124
- async function runRemoteProbe(params) {
1125
- try {
1126
- return {
1127
- kind: "value",
1128
- value: await withTimeout(Promise.resolve().then(params.run), params.timeoutMs, { message: `timed out after ${params.timeoutMs}ms` })
1129
- };
1130
- } catch (error) {
1131
- return {
1132
- kind: "error",
1133
- error: `${params.label} failed: ${formatErrorMessage(error)}`
1134
- };
1135
- }
1086
+ function formatRemoteProbeFailure(label, error, timeoutMs) {
1087
+ return `${label} failed: ${error instanceof Error && error.name === "TimeoutError" ? `timed out after ${timeoutMs}ms` : formatErrorMessage(error)}`;
1136
1088
  }
1137
1089
  function addTailscaleHint(account, hints) {
1138
1090
  if (!(URL.parse(account.publicWebhookUrl)?.hostname)?.endsWith(".ts.net")) return;
1139
1091
  hints.push(`Tailscale Funnel must expose the exact SMS path: tailscale funnel --bg --set-path ${account.webhookPath} http://127.0.0.1:<gateway-port>${account.webhookPath}`);
1140
1092
  }
1093
+ function compareWebhook(summary, url, prefix) {
1094
+ if (!url) return {
1095
+ status: `${prefix}missing`,
1096
+ ...summary
1097
+ };
1098
+ const configured = {
1099
+ ...summary,
1100
+ configuredUrl: url
1101
+ };
1102
+ if (summary.configuredMethod && summary.configuredMethod !== "POST") return {
1103
+ status: `${prefix}method-mismatch`,
1104
+ ...configured
1105
+ };
1106
+ if (url !== summary.expectedUrl) return {
1107
+ status: `${prefix}url-mismatch`,
1108
+ ...configured
1109
+ };
1110
+ return {
1111
+ status: `${prefix}matches`,
1112
+ ...configured
1113
+ };
1114
+ }
1141
1115
  function compareTwilioWebhook(account, phoneNumber) {
1142
1116
  if (!account.fromNumber) return {
1143
1117
  status: "skipped",
@@ -1147,63 +1121,26 @@ function compareTwilioWebhook(account, phoneNumber) {
1147
1121
  status: "number-not-found",
1148
1122
  expectedNumber: account.fromNumber
1149
1123
  };
1150
- const summary = {
1124
+ const probe = compareWebhook({
1151
1125
  phoneNumber: phoneNumber.phoneNumber || account.fromNumber,
1152
1126
  expectedUrl: account.publicWebhookUrl,
1153
1127
  configuredMethod: phoneNumber.smsMethod.toUpperCase()
1154
- };
1155
- if (!phoneNumber.smsUrl) return {
1156
- status: "missing",
1157
- ...summary
1158
- };
1159
- const configured = {
1160
- ...summary,
1161
- configuredUrl: phoneNumber.smsUrl
1162
- };
1163
- if (summary.configuredMethod && summary.configuredMethod !== "POST") return {
1164
- status: "method-mismatch",
1165
- ...configured
1166
- };
1167
- if (phoneNumber.smsUrl !== account.publicWebhookUrl) return {
1168
- status: "url-mismatch",
1169
- ...configured
1170
- };
1171
- return {
1172
- status: "matches",
1173
- ...configured,
1128
+ }, phoneNumber.smsUrl, "");
1129
+ return probe.status === "matches" ? {
1130
+ ...probe,
1174
1131
  voiceUrl: phoneNumber.voiceUrl
1175
- };
1132
+ } : probe;
1176
1133
  }
1177
1134
  function compareTwilioMessagingService(account, service) {
1178
1135
  if (service.useInboundWebhookOnNumber) return {
1179
1136
  status: "unavailable",
1180
1137
  reason: "Twilio Messaging Service defers inbound webhooks to sender phone numbers; configure fromNumber or disable defer-to-sender before checking."
1181
1138
  };
1182
- const summary = {
1139
+ return compareWebhook({
1183
1140
  serviceSid: service.sid || account.messagingServiceSid,
1184
1141
  expectedUrl: account.publicWebhookUrl,
1185
1142
  configuredMethod: service.inboundMethod.toUpperCase()
1186
- };
1187
- if (!service.inboundRequestUrl) return {
1188
- status: "messaging-service-missing",
1189
- ...summary
1190
- };
1191
- const configured = {
1192
- ...summary,
1193
- configuredUrl: service.inboundRequestUrl
1194
- };
1195
- if (summary.configuredMethod && summary.configuredMethod !== "POST") return {
1196
- status: "messaging-service-method-mismatch",
1197
- ...configured
1198
- };
1199
- if (service.inboundRequestUrl !== account.publicWebhookUrl) return {
1200
- status: "messaging-service-url-mismatch",
1201
- ...configured
1202
- };
1203
- return {
1204
- status: "messaging-service-matches",
1205
- ...configured
1206
- };
1143
+ }, service.inboundRequestUrl, "messaging-service-");
1207
1144
  }
1208
1145
  function recentInboundSummary(messages) {
1209
1146
  const message = messages[0];
@@ -1258,45 +1195,29 @@ async function probeSmsAccount(params) {
1258
1195
  else {
1259
1196
  const requestOptions = () => ({
1260
1197
  account: params.account,
1261
- fetchImpl: params.options?.fetchImpl,
1262
1198
  timeoutMs: remoteTimeoutMs
1263
1199
  });
1264
- const webhookTask = params.account.fromNumber || params.account.messagingServiceSid ? runRemoteProbe({
1265
- label: "Twilio webhook check",
1266
- timeoutMs: remoteTimeoutMs,
1267
- run: params.account.fromNumber ? async () => compareTwilioWebhook(params.account, (await listTwilioIncomingPhoneNumbers({
1268
- ...requestOptions(),
1269
- phoneNumber: params.account.fromNumber
1270
- }))[0]) : async () => compareTwilioMessagingService(params.account, await retrieveTwilioMessagingService({
1271
- ...requestOptions(),
1272
- serviceSid: params.account.messagingServiceSid
1273
- }))
1274
- }) : Promise.resolve({
1275
- kind: "value",
1276
- value: {
1277
- status: "unavailable",
1278
- reason: "Twilio SMS check requires fromNumber or messagingServiceSid."
1279
- }
1280
- });
1281
- const messageTask = params.account.fromNumber ? runRemoteProbe({
1282
- label: "Twilio message history check",
1283
- timeoutMs: remoteTimeoutMs,
1284
- run: async () => await listTwilioMessages({
1285
- ...requestOptions(),
1286
- to: params.account.fromNumber,
1287
- pageSize: 3
1288
- })
1289
- }) : Promise.resolve({
1290
- kind: "value",
1291
- value: []
1200
+ const webhookTask = params.account.fromNumber ? listTwilioIncomingPhoneNumbers({
1201
+ ...requestOptions(),
1202
+ phoneNumber: params.account.fromNumber
1203
+ }).then(([number]) => compareTwilioWebhook(params.account, number)) : params.account.messagingServiceSid ? retrieveTwilioMessagingService({
1204
+ ...requestOptions(),
1205
+ serviceSid: params.account.messagingServiceSid
1206
+ }).then((service) => compareTwilioMessagingService(params.account, service)) : Promise.resolve({
1207
+ status: "unavailable",
1208
+ reason: "Twilio SMS check requires fromNumber or messagingServiceSid."
1292
1209
  });
1293
- const [webhookOutcome, messageOutcome] = await Promise.all([webhookTask, messageTask]);
1294
- webhook = webhookOutcome.kind === "value" ? webhookOutcome.value : {
1210
+ const messageTask = params.account.fromNumber ? listTwilioMessages({
1211
+ ...requestOptions(),
1212
+ to: params.account.fromNumber
1213
+ }) : Promise.resolve([]);
1214
+ const [webhookOutcome, messageOutcome] = await Promise.allSettled([webhookTask, messageTask]);
1215
+ webhook = webhookOutcome.status === "fulfilled" ? webhookOutcome.value : {
1295
1216
  status: "unavailable",
1296
- reason: webhookOutcome.error
1217
+ reason: formatRemoteProbeFailure("Twilio webhook check", webhookOutcome.reason, remoteTimeoutMs)
1297
1218
  };
1298
- if (messageOutcome.kind === "value") messages = messageOutcome.value;
1299
- else messageHistoryError = messageOutcome.error;
1219
+ if (messageOutcome.status === "fulfilled") messages = messageOutcome.value;
1220
+ else messageHistoryError = formatRemoteProbeFailure("Twilio message history check", messageOutcome.reason, remoteTimeoutMs);
1300
1221
  }
1301
1222
  const recentInbound = recentInboundSummary(messages);
1302
1223
  if (recentInbound?.errorCode === TWILIO_ERROR_WEBHOOK_REACHABILITY) hints.push("Twilio error 11200 means Twilio could not reach the SMS webhook. Check the public URL, tunnel/Funnel route, and Twilio Messaging webhook method.");
@@ -1394,45 +1315,6 @@ const collectSmsOpenDmFindings = createConditionalWarningCollector.findings({
1394
1315
  severity: "critical",
1395
1316
  title: "SMS security warning"
1396
1317
  });
1397
- function applySmsAccountConfig(params) {
1398
- const patch = {};
1399
- for (const key of [
1400
- "accountSid",
1401
- "authToken",
1402
- "fromNumber",
1403
- "messagingServiceSid",
1404
- "defaultTo",
1405
- "webhookPath",
1406
- "publicWebhookUrl",
1407
- "dmPolicy",
1408
- "allowFrom"
1409
- ]) if (params.input[key] !== void 0) patch[key] = params.input[key];
1410
- const channels = { ...params.cfg.channels };
1411
- const current = { ...channels[CHANNEL_ID] };
1412
- if (params.accountId === DEFAULT_ACCOUNT_ID) {
1413
- channels[CHANNEL_ID] = {
1414
- ...current,
1415
- ...patch
1416
- };
1417
- return {
1418
- ...params.cfg,
1419
- channels
1420
- };
1421
- }
1422
- const accounts = { ...current.accounts };
1423
- accounts[params.accountId] = {
1424
- ...accounts[params.accountId],
1425
- ...patch
1426
- };
1427
- channels[CHANNEL_ID] = {
1428
- ...current,
1429
- accounts
1430
- };
1431
- return {
1432
- ...params.cfg,
1433
- channels
1434
- };
1435
- }
1436
1318
  const smsSetupContract = defineChannelSetupContract({
1437
1319
  fields: {
1438
1320
  accountSid: {
@@ -1507,11 +1389,46 @@ const smsSetupContract = defineChannelSetupContract({
1507
1389
  }
1508
1390
  }
1509
1391
  },
1510
- adapter: { applyAccountConfig: applySmsAccountConfig }
1392
+ adapter: { applyAccountConfig: (params) => {
1393
+ const patch = {};
1394
+ for (const key of [
1395
+ "accountSid",
1396
+ "authToken",
1397
+ "fromNumber",
1398
+ "messagingServiceSid",
1399
+ "defaultTo",
1400
+ "webhookPath",
1401
+ "publicWebhookUrl",
1402
+ "dmPolicy",
1403
+ "allowFrom"
1404
+ ]) if (params.input[key] !== void 0) patch[key] = params.input[key];
1405
+ const channels = { ...params.cfg.channels };
1406
+ const current = { ...channels[CHANNEL_ID] };
1407
+ if (params.accountId === DEFAULT_ACCOUNT_ID) {
1408
+ channels[CHANNEL_ID] = {
1409
+ ...current,
1410
+ ...patch
1411
+ };
1412
+ return {
1413
+ ...params.cfg,
1414
+ channels
1415
+ };
1416
+ }
1417
+ const accounts = { ...current.accounts };
1418
+ accounts[params.accountId] = {
1419
+ ...accounts[params.accountId],
1420
+ ...patch
1421
+ };
1422
+ channels[CHANNEL_ID] = {
1423
+ ...current,
1424
+ accounts
1425
+ };
1426
+ return {
1427
+ ...params.cfg,
1428
+ channels
1429
+ };
1430
+ } }
1511
1431
  });
1512
- function resolveSmsTextChunkLimit(params) {
1513
- return resolveSmsAccount(params.cfg, params.accountId).textChunkLimit || params.fallbackLimit || 1500;
1514
- }
1515
1432
  async function sendSmsText(ctx) {
1516
1433
  const account = resolveSmsAccount(ctx.cfg, ctx.accountId);
1517
1434
  const to = normalizeSmsPhoneNumber(ctx.to) || account.defaultTo;
@@ -1598,24 +1515,6 @@ const smsMessageAdapter = defineChannelMessageAdapter({
1598
1515
  media: sendPreparedSmsAttachment
1599
1516
  }
1600
1517
  });
1601
- function resolveSmsOutboundSessionRoute(params) {
1602
- const to = normalizeSmsPhoneNumber(params.resolvedTarget?.to ?? params.target);
1603
- if (!looksLikeSmsPhoneNumber(to)) return null;
1604
- return buildChannelOutboundSessionRoute({
1605
- cfg: params.cfg,
1606
- agentId: params.agentId,
1607
- channel: CHANNEL_ID,
1608
- accountId: params.accountId,
1609
- recipientSessionExact: true,
1610
- peer: {
1611
- kind: "direct",
1612
- id: to
1613
- },
1614
- chatType: "direct",
1615
- from: `sms:${to}`,
1616
- to: `sms:${to}`
1617
- });
1618
- }
1619
1518
  const smsPlugin = createChatChannelPlugin({
1620
1519
  base: {
1621
1520
  id: CHANNEL_ID,
@@ -1659,7 +1558,24 @@ const smsPlugin = createChatChannelPlugin({
1659
1558
  targetPrefixes: ["twilio-sms"],
1660
1559
  normalizeTarget: normalizeSmsPhoneNumber,
1661
1560
  inferTargetChatType: ({ to }) => looksLikeSmsPhoneNumber(to) ? "direct" : void 0,
1662
- resolveOutboundSessionRoute: resolveSmsOutboundSessionRoute,
1561
+ resolveOutboundSessionRoute: (params) => {
1562
+ const to = normalizeSmsPhoneNumber(params.resolvedTarget?.to ?? params.target);
1563
+ if (!looksLikeSmsPhoneNumber(to)) return null;
1564
+ return buildChannelOutboundSessionRoute({
1565
+ cfg: params.cfg,
1566
+ agentId: params.agentId,
1567
+ channel: CHANNEL_ID,
1568
+ accountId: params.accountId,
1569
+ recipientSessionExact: true,
1570
+ peer: {
1571
+ kind: "direct",
1572
+ id: to
1573
+ },
1574
+ chatType: "direct",
1575
+ from: `sms:${to}`,
1576
+ to: `sms:${to}`
1577
+ });
1578
+ },
1663
1579
  targetResolver: {
1664
1580
  looksLikeId: looksLikeSmsPhoneNumber,
1665
1581
  hint: "<+15551234567>"
@@ -1675,7 +1591,7 @@ const smsPlugin = createChatChannelPlugin({
1675
1591
  accountId: ctx.account.accountId,
1676
1592
  setStatus: ctx.setStatus
1677
1593
  });
1678
- return await startSmsGatewayAccount({
1594
+ await startSmsGatewayAccount({
1679
1595
  cfg: ctx.cfg,
1680
1596
  account: ctx.account,
1681
1597
  channelRuntime: ctx.channelRuntime,
@@ -1744,7 +1660,7 @@ const smsPlugin = createChatChannelPlugin({
1744
1660
  chunker: chunkTextForOutbound,
1745
1661
  chunkerMode: "text",
1746
1662
  textChunkLimit: 1500,
1747
- resolveEffectiveTextChunkLimit: resolveSmsTextChunkLimit,
1663
+ resolveEffectiveTextChunkLimit: ({ cfg, accountId }) => resolveSmsAccount(cfg, accountId).textChunkLimit,
1748
1664
  resolveTarget: ({ cfg, to, accountId }) => {
1749
1665
  const explicit = normalizeSmsPhoneNumber(to ?? "");
1750
1666
  if (explicit) return {