@openclaw/sms 2026.11.3 → 2026.11.5-beta.2

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-BBlPgBIF.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-BvmfwtSb.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-BzT4FTeC.mjs";
3
3
  import { n as collectRuntimeConfigAssignments, r as secretTargetRegistryEntries } from "./.setup/secret-contract-B2P_lFGm.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";
@@ -137,20 +136,14 @@ function normalizeDeliveryStatus(rawStatus) {
137
136
  function resolveDeliveryStatus(form) {
138
137
  return normalizeDeliveryStatus(firstTrimmed(form, "MessageStatus") || firstTrimmed(form, "SmsStatus"));
139
138
  }
140
- function hashAccountSid(accountSid) {
141
- return createHash("sha256").update(accountSid).digest("hex");
142
- }
143
139
  function fingerprintObservation(params) {
144
- return createHash("sha256").update(JSON.stringify([
140
+ return sha256Hex(JSON.stringify([
145
141
  params.source,
146
142
  params.messageSid,
147
143
  params.status,
148
144
  params.errorCode ?? "",
149
145
  params.rawDlrDoneDate ?? ""
150
- ])).digest("hex");
151
- }
152
- function deliveryRecordKey(params) {
153
- return createHash("sha256").update(`${params.accountId}\n${params.accountSidHash}\n${params.messageSid}`).digest("hex");
146
+ ]));
154
147
  }
155
148
  function openDeliveryStore() {
156
149
  const runtime = getSmsRuntime();
@@ -168,30 +161,6 @@ function openDeliveryStore() {
168
161
  function isTwilioDeliveryStatusForm(form) {
169
162
  return Boolean(resolveDeliveryStatus(form));
170
163
  }
171
- function parseSmsDeliveryObservation(form, nowMs = Date.now()) {
172
- const messageSid = resolveTwilioMessageSid(form);
173
- const status = resolveDeliveryStatus(form);
174
- if (!messageSid || !status) return null;
175
- const errorCode = firstTrimmed(form, "ErrorCode");
176
- const rawDlrDoneDate = firstTrimmed(form, "RawDlrDoneDate");
177
- return {
178
- messageSid,
179
- observation: {
180
- source: "callback",
181
- fingerprint: fingerprintObservation({
182
- source: "callback",
183
- messageSid,
184
- status,
185
- ...errorCode ? { errorCode } : {},
186
- ...rawDlrDoneDate ? { rawDlrDoneDate } : {}
187
- }),
188
- status,
189
- observedAt: nowMs,
190
- ...errorCode ? { errorCode } : {},
191
- ...rawDlrDoneDate ? { rawDlrDoneDate } : {}
192
- }
193
- };
194
- }
195
164
  function reduceDeliveryStatus(current, observation) {
196
165
  if (current?.status === "conflicted") return {
197
166
  status: current.status,
@@ -223,39 +192,32 @@ function reduceDeliveryStatus(current, observation) {
223
192
  ...selected === current && current.conflict ? { conflict: true } : {}
224
193
  };
225
194
  }
226
- function mergeSmsDeliveryObservation(params) {
227
- if (params.current?.observations.some((existing) => existing.fingerprint === params.observation.fingerprint)) return;
228
- const reduced = reduceDeliveryStatus(params.current, params.observation);
229
- return {
230
- accountId: params.accountId,
231
- accountSidHash: params.accountSidHash,
232
- messageSid: params.messageSid,
233
- status: reduced.status,
234
- firstObservedAt: params.current?.firstObservedAt ?? params.observation.observedAt,
235
- lastObservedAt: params.observation.observedAt,
236
- ...reduced.errorCode ? { errorCode: reduced.errorCode } : {},
237
- ...reduced.conflict ? { conflict: true } : {},
238
- observations: [...params.current?.observations ?? [], params.observation].slice(-20)
239
- };
240
- }
241
195
  async function recordSmsDeliveryObservation(params) {
242
196
  if (!params.store.observe || !params.store.compareAndApply) throw new Error("SMS delivery observations require plugin state comparisons.");
243
197
  const accountId = params.account.accountId;
244
- const accountSidHash = hashAccountSid(params.account.accountSid);
245
- const key = deliveryRecordKey({
246
- accountId,
247
- accountSidHash,
248
- messageSid: params.messageSid
249
- });
198
+ const accountSidHash = sha256Hex(params.account.accountSid);
199
+ const key = sha256Hex(`${accountId}\n${accountSidHash}\n${params.messageSid}`);
250
200
  let observed = await params.store.observe(key);
251
- while (true) {
252
- const next = mergeSmsDeliveryObservation({
201
+ function mergeSmsDeliveryObservation() {
202
+ const messageSid = params.messageSid;
203
+ const current = observed.value;
204
+ const observation = params.observation;
205
+ if (current?.observations.some((existing) => existing.fingerprint === observation.fingerprint)) return;
206
+ const reduced = reduceDeliveryStatus(current, observation);
207
+ return {
253
208
  accountId,
254
209
  accountSidHash,
255
- messageSid: params.messageSid,
256
- current: observed.value,
257
- observation: params.observation
258
- });
210
+ messageSid,
211
+ status: reduced.status,
212
+ firstObservedAt: current?.firstObservedAt ?? observation.observedAt,
213
+ lastObservedAt: observation.observedAt,
214
+ ...reduced.errorCode ? { errorCode: reduced.errorCode } : {},
215
+ ...reduced.conflict ? { conflict: true } : {},
216
+ observations: [...current?.observations ?? [], observation].slice(-20)
217
+ };
218
+ }
219
+ while (true) {
220
+ const next = mergeSmsDeliveryObservation();
259
221
  const result = await params.store.compareAndApply(key, observed.comparison, next ? {
260
222
  operation: "update",
261
223
  action: "set",
@@ -276,14 +238,32 @@ async function recordSmsDeliveryObservation(params) {
276
238
  };
277
239
  }
278
240
  }
279
- function createSmsDeliveryRecorder(store = openDeliveryStore()) {
241
+ function createSmsDeliveryRecorder() {
242
+ const store = openDeliveryStore();
280
243
  return { async record({ account, form }) {
281
- const parsed = parseSmsDeliveryObservation(form);
282
- if (!parsed) throw new Error("Invalid Twilio delivery status callback.");
244
+ const nowMs = Date.now();
245
+ const messageSid = resolveTwilioMessageSid(form);
246
+ const status = resolveDeliveryStatus(form);
247
+ if (!messageSid || !status) throw new Error("Invalid Twilio delivery status callback.");
248
+ const errorCode = firstTrimmed(form, "ErrorCode");
249
+ const rawDlrDoneDate = firstTrimmed(form, "RawDlrDoneDate");
283
250
  return await recordSmsDeliveryObservation({
284
251
  account,
285
- messageSid: parsed.messageSid,
286
- observation: parsed.observation,
252
+ messageSid,
253
+ observation: {
254
+ source: "callback",
255
+ fingerprint: fingerprintObservation({
256
+ source: "callback",
257
+ messageSid,
258
+ status,
259
+ ...errorCode ? { errorCode } : {},
260
+ ...rawDlrDoneDate ? { rawDlrDoneDate } : {}
261
+ }),
262
+ status,
263
+ observedAt: nowMs,
264
+ ...errorCode ? { errorCode } : {},
265
+ ...rawDlrDoneDate ? { rawDlrDoneDate } : {}
266
+ },
287
267
  store
288
268
  });
289
269
  } };
@@ -303,15 +283,15 @@ async function recordInitialSmsDeliveryResult(params) {
303
283
  status
304
284
  }),
305
285
  status,
306
- observedAt: params.nowMs ?? Date.now()
286
+ observedAt: Date.now()
307
287
  },
308
- store: params.store ?? openDeliveryStore()
288
+ store: openDeliveryStore()
309
289
  });
310
290
  }
311
- async function listRecentSmsDeliveryRecords(account, limit = 1, store = openDeliveryStore()) {
312
- if (limit <= 0) return [];
313
- const accountSidHash = hashAccountSid(account.accountSid);
314
- 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);
291
+ async function listRecentSmsDeliveryRecords(account) {
292
+ const store = openDeliveryStore();
293
+ const accountSidHash = sha256Hex(account.accountSid);
294
+ 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);
315
295
  }
316
296
  //#endregion
317
297
  //#region extensions/sms/src/send.ts
@@ -446,7 +426,7 @@ async function prepareSmsMediaAttempt(params) {
446
426
  });
447
427
  let hostedMedia;
448
428
  try {
449
- const { prepareHostedSmsMedia } = await import("./.setup/media-BIjSnGTm.mjs");
429
+ const { prepareHostedSmsMedia } = await import("./.setup/media-_9qy6Xis.mjs");
450
430
  assertSmsCredentialOwnerAvailable(params.account);
451
431
  const prepared = await prepareHostedSmsMedia({
452
432
  account: params.account,
@@ -479,85 +459,74 @@ async function sendPreparedSmsMediaAttempt(params) {
479
459
  //#endregion
480
460
  //#region extensions/sms/src/inbound.ts
481
461
  const CHANNEL_ID$2 = "sms";
482
- async function authorizeSmsSender(params) {
483
- const commandRequested = params.channelRuntime.commands.shouldComputeCommandAuthorized(params.rawBody, params.cfg);
484
- return await params.channelRuntime.inbound.ingress.resolveStable({
485
- channelId: CHANNEL_ID$2,
486
- accountId: params.account.accountId,
487
- cfg: params.cfg,
488
- identity: {
489
- key: "phone",
490
- entryIdPrefix: "sms-entry"
491
- },
492
- readStoreAllowFrom: async () => await params.channelRuntime.pairing.readAllowFromStore({
493
- channel: CHANNEL_ID$2,
494
- accountId: params.account.accountId
495
- }),
496
- subject: { stableId: params.from },
497
- conversation: {
498
- kind: "direct",
499
- id: params.from
500
- },
501
- contextBinding: params.contextBinding,
502
- event: { mayPair: true },
503
- dmPolicy: params.account.dmPolicy,
504
- allowFrom: params.account.allowFrom,
505
- command: commandRequested ? {
506
- cfg: params.cfg,
507
- modeWhenAccessGroupsOff: "configured"
508
- } : void 0
509
- });
510
- }
511
- async function issueSmsPairingChallenge(params) {
512
- await createChannelPairingChallengeIssuer({
513
- channel: CHANNEL_ID$2,
514
- accountId: params.account.accountId,
515
- upsertPairingRequest: async (input) => await params.channelRuntime.pairing.upsertPairingRequest({
516
- channel: CHANNEL_ID$2,
517
- accountId: params.account.accountId,
518
- ...input
519
- })
520
- })({
521
- senderId: params.from,
522
- senderIdLine: `Your SMS phone number: ${params.from}`,
523
- sendPairingReply: async (text) => {
524
- await sendSmsTextChunks({
525
- account: params.account,
526
- to: params.from,
527
- text
528
- });
529
- },
530
- onCreated: () => {
531
- params.log?.info?.(`SMS pairing request created for ${params.from}`);
532
- },
533
- onReplyError: (err) => {
534
- params.log?.warn?.(`SMS pairing reply failed for ${params.from}: ${String(err)}`);
535
- }
536
- });
537
- }
538
462
  async function dispatchSmsInboundEvent(params) {
539
463
  const from = normalizeSmsPhoneNumber(params.msg.from);
540
- let auth = await authorizeSmsSender({
541
- cfg: params.cfg,
542
- account: params.account,
543
- channelRuntime: params.channelRuntime,
544
- from,
545
- rawBody: params.msg.body
546
- });
464
+ async function authorizeSmsSender(contextBinding) {
465
+ const { cfg, account, channelRuntime } = params;
466
+ const rawBody = params.msg.body;
467
+ const commandRequested = channelRuntime.commands.shouldComputeCommandAuthorized(rawBody, cfg);
468
+ return await channelRuntime.inbound.ingress.resolveStable({
469
+ channelId: CHANNEL_ID$2,
470
+ accountId: account.accountId,
471
+ cfg,
472
+ identity: {
473
+ key: "phone",
474
+ entryIdPrefix: "sms-entry"
475
+ },
476
+ readStoreAllowFrom: async () => await channelRuntime.pairing.readAllowFromStore({
477
+ channel: CHANNEL_ID$2,
478
+ accountId: account.accountId
479
+ }),
480
+ subject: { stableId: from },
481
+ conversation: {
482
+ kind: "direct",
483
+ id: from
484
+ },
485
+ contextBinding,
486
+ event: { mayPair: true },
487
+ dmPolicy: account.dmPolicy,
488
+ allowFrom: account.allowFrom,
489
+ command: commandRequested ? {
490
+ cfg,
491
+ modeWhenAccessGroupsOff: "configured"
492
+ } : void 0
493
+ });
494
+ }
495
+ let auth = await authorizeSmsSender();
547
496
  if (!auth.senderAccess.allowed) {
548
497
  if (auth.senderAccess.decision === "pairing") {
549
- await issueSmsPairingChallenge({
550
- account: params.account,
551
- channelRuntime: params.channelRuntime,
552
- from,
553
- log: params.log
498
+ const { account, channelRuntime, log } = params;
499
+ await createChannelPairingChallengeIssuer({
500
+ channel: CHANNEL_ID$2,
501
+ accountId: account.accountId,
502
+ upsertPairingRequest: async (input) => await channelRuntime.pairing.upsertPairingRequest({
503
+ channel: CHANNEL_ID$2,
504
+ accountId: account.accountId,
505
+ ...input
506
+ })
507
+ })({
508
+ senderId: from,
509
+ senderIdLine: `Your SMS phone number: ${from}`,
510
+ sendPairingReply: async (text) => {
511
+ await sendSmsTextChunks({
512
+ account,
513
+ to: from,
514
+ text
515
+ });
516
+ },
517
+ onCreated: () => {
518
+ log?.info?.(`SMS pairing request created for ${from}`);
519
+ },
520
+ onReplyError: (err) => {
521
+ log?.warn?.(`SMS pairing reply failed for ${from}: ${String(err)}`);
522
+ }
554
523
  });
555
524
  return;
556
525
  }
557
526
  params.log?.warn?.(`SMS sender ${from} is not authorized`);
558
527
  return;
559
528
  }
560
- const materialized = params.msg.media.length > 0 || (params.msg.unavailableMediaCount ?? 0) > 0 ? await (await import("./.setup/media-BIjSnGTm.mjs")).materializeSmsInboundMedia({
529
+ const materialized = params.msg.media.length > 0 || (params.msg.unavailableMediaCount ?? 0) > 0 ? await (await import("./.setup/media-_9qy6Xis.mjs")).materializeSmsInboundMedia({
561
530
  account: params.account,
562
531
  msg: params.msg,
563
532
  mediaRuntime: params.channelRuntime,
@@ -604,17 +573,10 @@ async function dispatchSmsInboundEvent(params) {
604
573
  });
605
574
  const sessionKey = route.sessionKey;
606
575
  auth = await authorizeSmsSender({
607
- cfg: params.cfg,
608
- account: params.account,
609
- channelRuntime: params.channelRuntime,
610
- from,
611
- rawBody: params.msg.body,
612
- contextBinding: {
613
- agentId: route.agentId,
614
- sessionKey,
615
- messageId: params.msg.messageSid,
616
- inboundEventKind: "user_request"
617
- }
576
+ agentId: route.agentId,
577
+ sessionKey,
578
+ messageId: params.msg.messageSid,
579
+ inboundEventKind: "user_request"
618
580
  });
619
581
  if (!auth.senderAccess.allowed) {
620
582
  params.log?.warn?.(`SMS sender ${from} authorization changed before dispatch`);
@@ -1035,65 +997,6 @@ function collectSmsStartupWarnings(account) {
1035
997
  if (account.dmPolicy === "open" && !account.allowFrom.includes("*")) warnings.push("- SMS: dmPolicy=open should set allowFrom=[\"*\"] or explicit sender numbers.");
1036
998
  return warnings;
1037
999
  }
1038
- async function registerSmsWebhookRoute(params) {
1039
- const webhookPath = normalizeWebhookPath(params.account.webhookPath);
1040
- const currentRoute = activeRoutePaths.get(webhookPath);
1041
- 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}.`);
1042
- const predecessorStop = currentRoute ? stopSmsWebhookRoute(webhookPath, currentRoute) : pendingRouteStops.get(webhookPath) ?? Promise.resolve();
1043
- const ingress = createSmsIngressSpool({
1044
- cfg: params.cfg,
1045
- account: params.account,
1046
- channelRuntime: params.channelRuntime,
1047
- ...params.log ? { log: params.log } : {}
1048
- });
1049
- let unregisterRoute;
1050
- try {
1051
- const webhookHandler = createSmsWebhookHandler({
1052
- ...params,
1053
- ingress
1054
- });
1055
- unregisterRoute = registerPluginHttpRoute({
1056
- path: webhookPath,
1057
- auth: "plugin",
1058
- pluginId: CHANNEL_ID$1,
1059
- accountId: params.account.accountId,
1060
- throwOnFailure: true,
1061
- log: (msg) => params.log?.info?.(msg),
1062
- handler: async (req, res) => {
1063
- const { tryHandleHostedSmsMediaRequest } = await import("./.setup/media-BIjSnGTm.mjs");
1064
- if (await tryHandleHostedSmsMediaRequest(req, res, params.account.accountId)) return true;
1065
- return await webhookHandler(req, res);
1066
- }
1067
- });
1068
- } catch (error) {
1069
- await Promise.allSettled([predecessorStop, ingress.stop()]);
1070
- throw error;
1071
- }
1072
- const route = {
1073
- accountId: params.account.accountId,
1074
- ingress,
1075
- unregisterRoute,
1076
- ready: Promise.resolve()
1077
- };
1078
- activeRoutePaths.set(webhookPath, route);
1079
- route.ready = predecessorStop.then(() => {
1080
- if (activeRoutePaths.get(webhookPath) === route && !route.stopTask) ingress.start();
1081
- });
1082
- const unregister = () => stopSmsWebhookRoute(webhookPath, route);
1083
- const readinessAbort = new AbortController();
1084
- const lifecycle = waitUntilAbort(AbortSignal.any([params.abortSignal, readinessAbort.signal]), unregister);
1085
- try {
1086
- await route.ready;
1087
- } catch (error) {
1088
- readinessAbort.abort();
1089
- await Promise.allSettled([lifecycle]);
1090
- throw error;
1091
- }
1092
- return {
1093
- lifecycle,
1094
- isActive: () => activeRoutePaths.get(webhookPath) === route
1095
- };
1096
- }
1097
1000
  async function startSmsGatewayAccount(params) {
1098
1001
  params.statusSink?.({ lifecycle: "starting" });
1099
1002
  if (!params.account.enabled) {
@@ -1111,7 +1014,66 @@ async function startSmsGatewayAccount(params) {
1111
1014
  return waitUntilAbort(params.abortSignal);
1112
1015
  }
1113
1016
  for (const warning of warnings) params.log?.warn?.(warning);
1114
- const registration = await registerSmsWebhookRoute(params);
1017
+ async function registerSmsWebhookRoute() {
1018
+ const webhookPath = normalizeWebhookPath(params.account.webhookPath);
1019
+ const currentRoute = activeRoutePaths.get(webhookPath);
1020
+ 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}.`);
1021
+ const predecessorStop = currentRoute ? stopSmsWebhookRoute(webhookPath, currentRoute) : pendingRouteStops.get(webhookPath) ?? Promise.resolve();
1022
+ const ingress = createSmsIngressSpool({
1023
+ cfg: params.cfg,
1024
+ account: params.account,
1025
+ channelRuntime: params.channelRuntime,
1026
+ ...params.log ? { log: params.log } : {}
1027
+ });
1028
+ let unregisterRoute;
1029
+ try {
1030
+ const webhookHandler = createSmsWebhookHandler({
1031
+ ...params,
1032
+ ingress
1033
+ });
1034
+ unregisterRoute = registerPluginHttpRoute({
1035
+ path: webhookPath,
1036
+ auth: "plugin",
1037
+ pluginId: CHANNEL_ID$1,
1038
+ accountId: params.account.accountId,
1039
+ throwOnFailure: true,
1040
+ log: (msg) => params.log?.info?.(msg),
1041
+ handler: async (req, res) => {
1042
+ const { tryHandleHostedSmsMediaRequest } = await import("./.setup/media-_9qy6Xis.mjs");
1043
+ if (await tryHandleHostedSmsMediaRequest(req, res, params.account.accountId)) return true;
1044
+ return await webhookHandler(req, res);
1045
+ }
1046
+ });
1047
+ } catch (error) {
1048
+ await Promise.allSettled([predecessorStop, ingress.stop()]);
1049
+ throw error;
1050
+ }
1051
+ const route = {
1052
+ accountId: params.account.accountId,
1053
+ ingress,
1054
+ unregisterRoute,
1055
+ ready: Promise.resolve()
1056
+ };
1057
+ activeRoutePaths.set(webhookPath, route);
1058
+ route.ready = predecessorStop.then(() => {
1059
+ if (activeRoutePaths.get(webhookPath) === route && !route.stopTask) ingress.start();
1060
+ });
1061
+ const unregister = () => stopSmsWebhookRoute(webhookPath, route);
1062
+ const readinessAbort = new AbortController();
1063
+ const lifecycle = waitUntilAbort(AbortSignal.any([params.abortSignal, readinessAbort.signal]), unregister);
1064
+ try {
1065
+ await route.ready;
1066
+ } catch (error) {
1067
+ readinessAbort.abort();
1068
+ await Promise.allSettled([lifecycle]);
1069
+ throw error;
1070
+ }
1071
+ return {
1072
+ lifecycle,
1073
+ isActive: () => activeRoutePaths.get(webhookPath) === route
1074
+ };
1075
+ }
1076
+ const registration = await registerSmsWebhookRoute();
1115
1077
  if (registration.isActive()) {
1116
1078
  params.log?.info?.(`Registered SMS webhook route ${params.account.webhookPath} for account ${params.account.accountId}`);
1117
1079
  params.statusSink?.(channelReadyPatch());
@@ -1128,23 +1090,35 @@ function resolveRemoteProbeTimeoutMs(timeoutMs) {
1128
1090
  const settleMarginMs = Math.min(100, Math.max(1, Math.floor(normalized / 10)));
1129
1091
  return Math.max(0, normalized - settleMarginMs);
1130
1092
  }
1131
- async function runRemoteProbe(params) {
1132
- try {
1133
- return {
1134
- kind: "value",
1135
- value: await withTimeout(Promise.resolve().then(params.run), params.timeoutMs, { message: `timed out after ${params.timeoutMs}ms` })
1136
- };
1137
- } catch (error) {
1138
- return {
1139
- kind: "error",
1140
- error: `${params.label} failed: ${formatErrorMessage(error)}`
1141
- };
1142
- }
1093
+ function formatRemoteProbeFailure(label, error, timeoutMs) {
1094
+ return `${label} failed: ${error instanceof Error && error.name === "TimeoutError" ? `timed out after ${timeoutMs}ms` : formatErrorMessage(error)}`;
1143
1095
  }
1144
1096
  function addTailscaleHint(account, hints) {
1145
1097
  if (!(URL.parse(account.publicWebhookUrl)?.hostname)?.endsWith(".ts.net")) return;
1146
1098
  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}`);
1147
1099
  }
1100
+ function compareWebhook(summary, url, prefix) {
1101
+ if (!url) return {
1102
+ status: `${prefix}missing`,
1103
+ ...summary
1104
+ };
1105
+ const configured = {
1106
+ ...summary,
1107
+ configuredUrl: url
1108
+ };
1109
+ if (summary.configuredMethod && summary.configuredMethod !== "POST") return {
1110
+ status: `${prefix}method-mismatch`,
1111
+ ...configured
1112
+ };
1113
+ if (url !== summary.expectedUrl) return {
1114
+ status: `${prefix}url-mismatch`,
1115
+ ...configured
1116
+ };
1117
+ return {
1118
+ status: `${prefix}matches`,
1119
+ ...configured
1120
+ };
1121
+ }
1148
1122
  function compareTwilioWebhook(account, phoneNumber) {
1149
1123
  if (!account.fromNumber) return {
1150
1124
  status: "skipped",
@@ -1154,63 +1128,26 @@ function compareTwilioWebhook(account, phoneNumber) {
1154
1128
  status: "number-not-found",
1155
1129
  expectedNumber: account.fromNumber
1156
1130
  };
1157
- const summary = {
1131
+ const probe = compareWebhook({
1158
1132
  phoneNumber: phoneNumber.phoneNumber || account.fromNumber,
1159
1133
  expectedUrl: account.publicWebhookUrl,
1160
1134
  configuredMethod: phoneNumber.smsMethod.toUpperCase()
1161
- };
1162
- if (!phoneNumber.smsUrl) return {
1163
- status: "missing",
1164
- ...summary
1165
- };
1166
- const configured = {
1167
- ...summary,
1168
- configuredUrl: phoneNumber.smsUrl
1169
- };
1170
- if (summary.configuredMethod && summary.configuredMethod !== "POST") return {
1171
- status: "method-mismatch",
1172
- ...configured
1173
- };
1174
- if (phoneNumber.smsUrl !== account.publicWebhookUrl) return {
1175
- status: "url-mismatch",
1176
- ...configured
1177
- };
1178
- return {
1179
- status: "matches",
1180
- ...configured,
1135
+ }, phoneNumber.smsUrl, "");
1136
+ return probe.status === "matches" ? {
1137
+ ...probe,
1181
1138
  voiceUrl: phoneNumber.voiceUrl
1182
- };
1139
+ } : probe;
1183
1140
  }
1184
1141
  function compareTwilioMessagingService(account, service) {
1185
1142
  if (service.useInboundWebhookOnNumber) return {
1186
1143
  status: "unavailable",
1187
1144
  reason: "Twilio Messaging Service defers inbound webhooks to sender phone numbers; configure fromNumber or disable defer-to-sender before checking."
1188
1145
  };
1189
- const summary = {
1146
+ return compareWebhook({
1190
1147
  serviceSid: service.sid || account.messagingServiceSid,
1191
1148
  expectedUrl: account.publicWebhookUrl,
1192
1149
  configuredMethod: service.inboundMethod.toUpperCase()
1193
- };
1194
- if (!service.inboundRequestUrl) return {
1195
- status: "messaging-service-missing",
1196
- ...summary
1197
- };
1198
- const configured = {
1199
- ...summary,
1200
- configuredUrl: service.inboundRequestUrl
1201
- };
1202
- if (summary.configuredMethod && summary.configuredMethod !== "POST") return {
1203
- status: "messaging-service-method-mismatch",
1204
- ...configured
1205
- };
1206
- if (service.inboundRequestUrl !== account.publicWebhookUrl) return {
1207
- status: "messaging-service-url-mismatch",
1208
- ...configured
1209
- };
1210
- return {
1211
- status: "messaging-service-matches",
1212
- ...configured
1213
- };
1150
+ }, service.inboundRequestUrl, "messaging-service-");
1214
1151
  }
1215
1152
  function recentInboundSummary(messages) {
1216
1153
  const message = messages[0];
@@ -1265,45 +1202,29 @@ async function probeSmsAccount(params) {
1265
1202
  else {
1266
1203
  const requestOptions = () => ({
1267
1204
  account: params.account,
1268
- fetchImpl: params.options?.fetchImpl,
1269
1205
  timeoutMs: remoteTimeoutMs
1270
1206
  });
1271
- const webhookTask = params.account.fromNumber || params.account.messagingServiceSid ? runRemoteProbe({
1272
- label: "Twilio webhook check",
1273
- timeoutMs: remoteTimeoutMs,
1274
- run: params.account.fromNumber ? async () => compareTwilioWebhook(params.account, (await listTwilioIncomingPhoneNumbers({
1275
- ...requestOptions(),
1276
- phoneNumber: params.account.fromNumber
1277
- }))[0]) : async () => compareTwilioMessagingService(params.account, await retrieveTwilioMessagingService({
1278
- ...requestOptions(),
1279
- serviceSid: params.account.messagingServiceSid
1280
- }))
1281
- }) : Promise.resolve({
1282
- kind: "value",
1283
- value: {
1284
- status: "unavailable",
1285
- reason: "Twilio SMS check requires fromNumber or messagingServiceSid."
1286
- }
1287
- });
1288
- const messageTask = params.account.fromNumber ? runRemoteProbe({
1289
- label: "Twilio message history check",
1290
- timeoutMs: remoteTimeoutMs,
1291
- run: async () => await listTwilioMessages({
1292
- ...requestOptions(),
1293
- to: params.account.fromNumber,
1294
- pageSize: 3
1295
- })
1296
- }) : Promise.resolve({
1297
- kind: "value",
1298
- value: []
1207
+ const webhookTask = params.account.fromNumber ? listTwilioIncomingPhoneNumbers({
1208
+ ...requestOptions(),
1209
+ phoneNumber: params.account.fromNumber
1210
+ }).then(([number]) => compareTwilioWebhook(params.account, number)) : params.account.messagingServiceSid ? retrieveTwilioMessagingService({
1211
+ ...requestOptions(),
1212
+ serviceSid: params.account.messagingServiceSid
1213
+ }).then((service) => compareTwilioMessagingService(params.account, service)) : Promise.resolve({
1214
+ status: "unavailable",
1215
+ reason: "Twilio SMS check requires fromNumber or messagingServiceSid."
1299
1216
  });
1300
- const [webhookOutcome, messageOutcome] = await Promise.all([webhookTask, messageTask]);
1301
- webhook = webhookOutcome.kind === "value" ? webhookOutcome.value : {
1217
+ const messageTask = params.account.fromNumber ? listTwilioMessages({
1218
+ ...requestOptions(),
1219
+ to: params.account.fromNumber
1220
+ }) : Promise.resolve([]);
1221
+ const [webhookOutcome, messageOutcome] = await Promise.allSettled([webhookTask, messageTask]);
1222
+ webhook = webhookOutcome.status === "fulfilled" ? webhookOutcome.value : {
1302
1223
  status: "unavailable",
1303
- reason: webhookOutcome.error
1224
+ reason: formatRemoteProbeFailure("Twilio webhook check", webhookOutcome.reason, remoteTimeoutMs)
1304
1225
  };
1305
- if (messageOutcome.kind === "value") messages = messageOutcome.value;
1306
- else messageHistoryError = messageOutcome.error;
1226
+ if (messageOutcome.status === "fulfilled") messages = messageOutcome.value;
1227
+ else messageHistoryError = formatRemoteProbeFailure("Twilio message history check", messageOutcome.reason, remoteTimeoutMs);
1307
1228
  }
1308
1229
  const recentInbound = recentInboundSummary(messages);
1309
1230
  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.");
@@ -1402,45 +1323,6 @@ const collectSmsOpenDmFindings = createConditionalWarningCollector.findings({
1402
1323
  severity: "critical",
1403
1324
  title: "SMS security warning"
1404
1325
  });
1405
- function applySmsAccountConfig(params) {
1406
- const patch = {};
1407
- for (const key of [
1408
- "accountSid",
1409
- "authToken",
1410
- "fromNumber",
1411
- "messagingServiceSid",
1412
- "defaultTo",
1413
- "webhookPath",
1414
- "publicWebhookUrl",
1415
- "dmPolicy",
1416
- "allowFrom"
1417
- ]) if (params.input[key] !== void 0) patch[key] = params.input[key];
1418
- const channels = { ...params.cfg.channels };
1419
- const current = { ...channels[CHANNEL_ID] };
1420
- if (params.accountId === DEFAULT_ACCOUNT_ID) {
1421
- channels[CHANNEL_ID] = {
1422
- ...current,
1423
- ...patch
1424
- };
1425
- return {
1426
- ...params.cfg,
1427
- channels
1428
- };
1429
- }
1430
- const accounts = { ...current.accounts };
1431
- accounts[params.accountId] = {
1432
- ...accounts[params.accountId],
1433
- ...patch
1434
- };
1435
- channels[CHANNEL_ID] = {
1436
- ...current,
1437
- accounts
1438
- };
1439
- return {
1440
- ...params.cfg,
1441
- channels
1442
- };
1443
- }
1444
1326
  const smsSetupContract = defineChannelSetupContract({
1445
1327
  fields: {
1446
1328
  accountSid: {
@@ -1515,11 +1397,46 @@ const smsSetupContract = defineChannelSetupContract({
1515
1397
  }
1516
1398
  }
1517
1399
  },
1518
- adapter: { applyAccountConfig: applySmsAccountConfig }
1400
+ adapter: { applyAccountConfig: (params) => {
1401
+ const patch = {};
1402
+ for (const key of [
1403
+ "accountSid",
1404
+ "authToken",
1405
+ "fromNumber",
1406
+ "messagingServiceSid",
1407
+ "defaultTo",
1408
+ "webhookPath",
1409
+ "publicWebhookUrl",
1410
+ "dmPolicy",
1411
+ "allowFrom"
1412
+ ]) if (params.input[key] !== void 0) patch[key] = params.input[key];
1413
+ const channels = { ...params.cfg.channels };
1414
+ const current = { ...channels[CHANNEL_ID] };
1415
+ if (params.accountId === DEFAULT_ACCOUNT_ID) {
1416
+ channels[CHANNEL_ID] = {
1417
+ ...current,
1418
+ ...patch
1419
+ };
1420
+ return {
1421
+ ...params.cfg,
1422
+ channels
1423
+ };
1424
+ }
1425
+ const accounts = { ...current.accounts };
1426
+ accounts[params.accountId] = {
1427
+ ...accounts[params.accountId],
1428
+ ...patch
1429
+ };
1430
+ channels[CHANNEL_ID] = {
1431
+ ...current,
1432
+ accounts
1433
+ };
1434
+ return {
1435
+ ...params.cfg,
1436
+ channels
1437
+ };
1438
+ } }
1519
1439
  });
1520
- function resolveSmsTextChunkLimit(params) {
1521
- return resolveSmsAccount(params.cfg, params.accountId).textChunkLimit || params.fallbackLimit || 1500;
1522
- }
1523
1440
  async function sendSmsText(ctx) {
1524
1441
  const account = resolveSmsAccount(ctx.cfg, ctx.accountId);
1525
1442
  const to = normalizeSmsPhoneNumber(ctx.to) || account.defaultTo;
@@ -1606,24 +1523,6 @@ const smsMessageAdapter = defineChannelMessageAdapter({
1606
1523
  media: sendPreparedSmsAttachment
1607
1524
  }
1608
1525
  });
1609
- function resolveSmsOutboundSessionRoute(params) {
1610
- const to = normalizeSmsPhoneNumber(params.resolvedTarget?.to ?? params.target);
1611
- if (!looksLikeSmsPhoneNumber(to)) return null;
1612
- return buildChannelOutboundSessionRoute({
1613
- cfg: params.cfg,
1614
- agentId: params.agentId,
1615
- channel: CHANNEL_ID,
1616
- accountId: params.accountId,
1617
- recipientSessionExact: true,
1618
- peer: {
1619
- kind: "direct",
1620
- id: to
1621
- },
1622
- chatType: "direct",
1623
- from: `sms:${to}`,
1624
- to: `sms:${to}`
1625
- });
1626
- }
1627
1526
  const smsPlugin = createChatChannelPlugin({
1628
1527
  base: {
1629
1528
  id: CHANNEL_ID,
@@ -1667,7 +1566,24 @@ const smsPlugin = createChatChannelPlugin({
1667
1566
  targetPrefixes: ["twilio-sms"],
1668
1567
  normalizeTarget: normalizeSmsPhoneNumber,
1669
1568
  inferTargetChatType: ({ to }) => looksLikeSmsPhoneNumber(to) ? "direct" : void 0,
1670
- resolveOutboundSessionRoute: resolveSmsOutboundSessionRoute,
1569
+ resolveOutboundSessionRoute: (params) => {
1570
+ const to = normalizeSmsPhoneNumber(params.resolvedTarget?.to ?? params.target);
1571
+ if (!looksLikeSmsPhoneNumber(to)) return null;
1572
+ return buildChannelOutboundSessionRoute({
1573
+ cfg: params.cfg,
1574
+ agentId: params.agentId,
1575
+ channel: CHANNEL_ID,
1576
+ accountId: params.accountId,
1577
+ recipientSessionExact: true,
1578
+ peer: {
1579
+ kind: "direct",
1580
+ id: to
1581
+ },
1582
+ chatType: "direct",
1583
+ from: `sms:${to}`,
1584
+ to: `sms:${to}`
1585
+ });
1586
+ },
1671
1587
  targetResolver: {
1672
1588
  looksLikeId: looksLikeSmsPhoneNumber,
1673
1589
  hint: "<+15551234567>"
@@ -1683,7 +1599,7 @@ const smsPlugin = createChatChannelPlugin({
1683
1599
  accountId: ctx.account.accountId,
1684
1600
  setStatus: ctx.setStatus
1685
1601
  });
1686
- return await startSmsGatewayAccount({
1602
+ await startSmsGatewayAccount({
1687
1603
  cfg: ctx.cfg,
1688
1604
  account: ctx.account,
1689
1605
  channelRuntime: ctx.channelRuntime,
@@ -1752,7 +1668,7 @@ const smsPlugin = createChatChannelPlugin({
1752
1668
  chunker: chunkTextForOutbound,
1753
1669
  chunkerMode: "text",
1754
1670
  textChunkLimit: 1500,
1755
- resolveEffectiveTextChunkLimit: resolveSmsTextChunkLimit,
1671
+ resolveEffectiveTextChunkLimit: ({ cfg, accountId }) => resolveSmsAccount(cfg, accountId).textChunkLimit,
1756
1672
  resolveTarget: ({ cfg, to, accountId }) => {
1757
1673
  const explicit = normalizeSmsPhoneNumber(to ?? "");
1758
1674
  if (explicit) return {