@openclaw/sms 2026.7.2-beta.2 → 2026.7.2-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/api.js CHANGED
@@ -1,8 +1,2 @@
1
- import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
2
- //#region extensions/sms/src/runtime.ts
3
- const { setRuntime: setSmsRuntime, getRuntime: getSmsRuntime } = createPluginRuntimeStore({
4
- pluginId: "sms",
5
- errorMessage: "SMS runtime not initialized - plugin not registered"
6
- });
7
- //#endregion
1
+ import { n as setSmsRuntime, t as getSmsRuntime } from "./runtime-BBlPgBIF.js";
8
2
  export { getSmsRuntime, setSmsRuntime };
@@ -1,13 +1,15 @@
1
+ import { t as getSmsRuntime } from "./runtime-BBlPgBIF.js";
1
2
  import { n as collectRuntimeConfigAssignments, r as secretTargetRegistryEntries } from "./secret-contract-Cp0f-YPc.js";
2
3
  import { DEFAULT_ACCOUNT_ID, normalizeOptionalAccountId } from "openclaw/plugin-sdk/account-id";
3
4
  import { createHybridChannelConfigAdapter, createScopedDmSecurityResolver } from "openclaw/plugin-sdk/channel-config-helpers";
4
5
  import { buildChannelOutboundSessionRoute, createChatChannelPlugin } from "openclaw/plugin-sdk/channel-core";
5
- import { createMessageReceiptFromOutboundResults, defineChannelMessageAdapter, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
6
+ import { bindIngressLifecycleToReplyOptions, createChannelIngressMonitor, createMessageReceiptFromOutboundResults, defineChannelMessageAdapter, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
6
7
  import { createConditionalWarningCollector } from "openclaw/plugin-sdk/channel-policy";
8
+ import { defineChannelSetupContract } from "openclaw/plugin-sdk/channel-setup";
7
9
  import { createEmptyChannelDirectoryAdapter } from "openclaw/plugin-sdk/directory-runtime";
8
10
  import { normalizeStringEntries } from "openclaw/plugin-sdk/string-coerce-runtime";
9
11
  import { chunkTextForOutbound, renderMarkdownIRChunksWithinLimit, sanitizeAssistantVisibleText, stripMarkdown } from "openclaw/plugin-sdk/text-chunking";
10
- import { DEFAULT_ACCOUNT_ID as DEFAULT_ACCOUNT_ID$1, listCombinedAccountIds, resolveAccountEntry, resolveListedDefaultAccountId, resolveMergedAccountConfig } from "openclaw/plugin-sdk/account-resolution";
12
+ import { DEFAULT_ACCOUNT_ID as DEFAULT_ACCOUNT_ID$1, hasConfiguredAccountValue, listCombinedAccountIds, resolveAccountEntry, resolveListedDefaultAccountId, resolveMergedAccountConfig } from "openclaw/plugin-sdk/account-resolution";
11
13
  import { parseStrictInteger } from "openclaw/plugin-sdk/number-runtime";
12
14
  import { buildSecretInputSchema, hasConfiguredSecretInput, normalizeResolvedSecretInputString } from "openclaw/plugin-sdk/secret-input";
13
15
  import { AllowFromListSchema, DmPolicySchema, buildChannelConfigSchema, buildMultiAccountChannelSchema, requireOpenAllowFrom } from "openclaw/plugin-sdk/channel-config-schema";
@@ -22,10 +24,9 @@ import * as querystring from "node:querystring";
22
24
  import { readResponseTextPrefix, readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
23
25
  import { safeEqualSecret } from "openclaw/plugin-sdk/security-runtime";
24
26
  import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
25
- import { performance } from "node:perf_hooks";
26
27
  //#region extensions/sms/src/phone.ts
27
28
  function normalizeSmsPhoneNumber(raw) {
28
- const trimmed = raw.trim().replace(/^(?:sms|twilio-sms):/i, "");
29
+ const trimmed = raw.trim().replace(/^(?:sms|twilio-sms):/i, "").trim();
29
30
  if (!trimmed) return "";
30
31
  return (trimmed.startsWith("+") ? trimmed : `+${trimmed}`).replace(/[^\d+]/g, "");
31
32
  }
@@ -58,7 +59,16 @@ function firstNonBlankEnv(...values) {
58
59
  return values.find((value) => value?.trim());
59
60
  }
60
61
  function hasBaseAccount(channelCfg) {
61
- return Boolean(channelCfg?.accountSid || hasConfiguredSecretInput(channelCfg?.authToken) || channelCfg?.fromNumber || channelCfg?.messagingServiceSid || process.env.TWILIO_ACCOUNT_SID || process.env.TWILIO_AUTH_TOKEN || process.env.TWILIO_PHONE_NUMBER || process.env.TWILIO_SMS_FROM || process.env.TWILIO_MESSAGING_SERVICE_SID);
62
+ return [
63
+ channelCfg?.accountSid,
64
+ channelCfg?.fromNumber,
65
+ channelCfg?.messagingServiceSid,
66
+ process.env.TWILIO_ACCOUNT_SID,
67
+ process.env.TWILIO_AUTH_TOKEN,
68
+ process.env.TWILIO_PHONE_NUMBER,
69
+ process.env.TWILIO_SMS_FROM,
70
+ process.env.TWILIO_MESSAGING_SERVICE_SID
71
+ ].some((value) => hasConfiguredAccountValue(value)) || hasConfiguredSecretInput(channelCfg?.authToken);
62
72
  }
63
73
  function listSmsAccountIds(cfg) {
64
74
  const channelCfg = getChannelConfig(cfg);
@@ -173,7 +183,8 @@ const SmsChannelConfigSchema = buildChannelConfigSchema(buildMultiAccountChannel
173
183
  },
174
184
  fromNumber: {
175
185
  label: "SMS From Number",
176
- help: "Twilio SMS-capable phone number in E.164 format, for example +15551234567."
186
+ help: "Twilio SMS-capable phone number in E.164 format, for example +15551234567.",
187
+ presentation: "phone-number"
177
188
  },
178
189
  messagingServiceSid: {
179
190
  label: "Twilio Messaging Service SID",
@@ -181,7 +192,8 @@ const SmsChannelConfigSchema = buildChannelConfigSchema(buildMultiAccountChannel
181
192
  },
182
193
  defaultTo: {
183
194
  label: "SMS Default To Number",
184
- help: "Optional default outbound phone number used when a send flow omits an explicit SMS target."
195
+ help: "Optional default outbound phone number used when a send flow omits an explicit SMS target.",
196
+ presentation: "phone-number"
185
197
  },
186
198
  publicWebhookUrl: {
187
199
  label: "SMS Public Webhook URL",
@@ -197,8 +209,12 @@ const SmsChannelConfigSchema = buildChannelConfigSchema(buildMultiAccountChannel
197
209
  },
198
210
  allowFrom: {
199
211
  label: "SMS Allow From",
200
- help: "Allowed sender phone numbers in E.164 format, or * when dmPolicy is open."
212
+ help: "Allowed sender phone numbers in E.164 format, or * when dmPolicy is open.",
213
+ presentation: "phone-number"
201
214
  },
215
+ "accounts.*.fromNumber": { presentation: "phone-number" },
216
+ "accounts.*.defaultTo": { presentation: "phone-number" },
217
+ "accounts.*.allowFrom.*": { presentation: "phone-number" },
202
218
  textChunkLimit: {
203
219
  label: "SMS Text Chunk Limit",
204
220
  help: "Maximum characters per outbound SMS chunk before OpenClaw splits long replies."
@@ -316,12 +332,15 @@ function parseTwilioInboundFrom(raw) {
316
332
  if (!looksLikeSmsPhoneNumber(phoneNumber)) return null;
317
333
  return phoneNumber;
318
334
  }
335
+ function resolveTwilioInboundSender(form) {
336
+ return parseTwilioInboundFrom(firstTrimmedString(form.From)) ?? "";
337
+ }
319
338
  function buildTwilioInboundMessage(form) {
320
- const from = parseTwilioInboundFrom(firstTrimmedString(form.From));
339
+ const from = resolveTwilioInboundSender(form);
321
340
  const to = firstTrimmedString(form.To);
322
341
  const body = firstString(form.Body);
323
342
  const accountSid = firstTrimmedString(form.AccountSid);
324
- const messageSid = firstTrimmedString(form.MessageSid) || firstTrimmedString(form.SmsSid) || firstTrimmedString(form.SmsMessageSid);
343
+ const messageSid = resolveTwilioMessageSid(form);
325
344
  if (!from || !to || !body || !messageSid) return null;
326
345
  return {
327
346
  accountSid,
@@ -331,6 +350,9 @@ function buildTwilioInboundMessage(form) {
331
350
  messageSid
332
351
  };
333
352
  }
353
+ function resolveTwilioMessageSid(form) {
354
+ return firstTrimmedString(form.MessageSid) || firstTrimmedString(form.SmsSid) || firstTrimmedString(form.SmsMessageSid);
355
+ }
334
356
  async function readTwilioWebhookForm(req) {
335
357
  return parseTwilioFormBody(await readRequestBodyWithLimit(req, {
336
358
  maxBytes: WEBHOOK_BODY_LIMIT_BYTES,
@@ -569,6 +591,7 @@ async function sendSmsTextChunks(params) {
569
591
  //#region extensions/sms/src/inbound.ts
570
592
  const CHANNEL_ID$2 = "sms";
571
593
  async function authorizeSmsSender(params) {
594
+ const commandRequested = params.channelRuntime.commands.shouldComputeCommandAuthorized(params.rawBody, params.cfg);
572
595
  return await resolveStableChannelMessageIngress({
573
596
  channelId: CHANNEL_ID$2,
574
597
  accountId: params.account.accountId,
@@ -588,7 +611,11 @@ async function authorizeSmsSender(params) {
588
611
  },
589
612
  event: { mayPair: true },
590
613
  dmPolicy: params.account.dmPolicy,
591
- allowFrom: params.account.allowFrom
614
+ allowFrom: params.account.allowFrom,
615
+ command: commandRequested ? {
616
+ cfg: params.cfg,
617
+ modeWhenAccessGroupsOff: "configured"
618
+ } : void 0
592
619
  });
593
620
  }
594
621
  async function issueSmsPairingChallenge(params) {
@@ -624,7 +651,8 @@ async function dispatchSmsInboundEvent(params) {
624
651
  cfg: params.cfg,
625
652
  account: params.account,
626
653
  channelRuntime: params.channelRuntime,
627
- from
654
+ from,
655
+ rawBody: params.msg.body
628
656
  });
629
657
  if (!auth.senderAccess.allowed) {
630
658
  if (auth.senderAccess.decision === "pairing") {
@@ -649,14 +677,18 @@ async function dispatchSmsInboundEvent(params) {
649
677
  }
650
678
  });
651
679
  const sessionKey = route.sessionKey;
680
+ const commandRequested = auth.commandAccess.requested;
681
+ const commandAuthorized = auth.commandAccess.authorized;
682
+ const isTextCommand = params.channelRuntime.commands.isControlCommandMessage(params.msg.body, params.cfg);
652
683
  await params.channelRuntime.inbound.run({
653
684
  channel: CHANNEL_ID$2,
654
685
  accountId: params.account.accountId,
655
686
  raw: params.msg,
687
+ ...params.turnAdoptionLifecycle ? { turnAdoptionLifecycle: params.turnAdoptionLifecycle } : {},
656
688
  adapter: {
657
689
  ingest: (msg) => ({
658
690
  id: msg.messageSid,
659
- timestamp: Date.now(),
691
+ timestamp: params.receivedAt,
660
692
  rawText: msg.body,
661
693
  textForAgent: msg.body,
662
694
  textForCommands: msg.body,
@@ -689,22 +721,27 @@ async function dispatchSmsInboundEvent(params) {
689
721
  commandBody: input.textForCommands,
690
722
  bodyForAgent: input.textForAgent
691
723
  },
724
+ access: commandRequested ? { commands: { authorized: commandAuthorized } } : void 0,
725
+ command: isTextCommand ? {
726
+ kind: "text-slash",
727
+ body: input.textForCommands,
728
+ authorized: commandAuthorized
729
+ } : void 0,
692
730
  extra: {
693
731
  MessageSid: params.msg.messageSid,
732
+ SenderE164: from,
694
733
  To: params.msg.to
695
734
  }
696
735
  });
697
- const storePath = params.channelRuntime.session.resolveStorePath(params.cfg.session?.store, { agentId: route.agentId });
698
736
  return {
699
737
  cfg: params.cfg,
700
738
  channel: CHANNEL_ID$2,
701
739
  accountId: params.account.accountId,
702
- agentId: route.agentId,
703
- routeSessionKey: sessionKey,
704
- storePath,
740
+ route: {
741
+ agentId: route.agentId,
742
+ sessionKey
743
+ },
705
744
  ctxPayload,
706
- recordInboundSession: params.channelRuntime.session.recordInboundSession,
707
- dispatchReplyWithBufferedBlockDispatcher: params.channelRuntime.reply.dispatchReplyWithBufferedBlockDispatcher,
708
745
  delivery: {
709
746
  durable: () => ({ to: from }),
710
747
  deliver: async (payload) => {
@@ -727,34 +764,100 @@ async function dispatchSmsInboundEvent(params) {
727
764
  });
728
765
  }
729
766
  //#endregion
730
- //#region extensions/sms/src/webhook-replay-guard.ts
731
- const REPLAY_CACHE_TTL_MS = 10 * 6e4;
732
- const REPLAY_CACHE_MAX_KEYS = 1e4;
733
- function createSmsWebhookReplayGuard(options = {}) {
734
- const ttlMs = options.ttlMs ?? REPLAY_CACHE_TTL_MS;
735
- const maxKeys = options.maxKeys ?? REPLAY_CACHE_MAX_KEYS;
736
- const now = options.now ?? (() => performance.now());
737
- const entries = /* @__PURE__ */ new Map();
738
- const pruneExpired = (nowMs) => {
739
- for (const [key, expiresAt] of entries) {
740
- if (expiresAt > nowMs) break;
741
- entries.delete(key);
742
- }
743
- };
744
- return { remember: (messageSid) => {
745
- const nowMs = now();
746
- pruneExpired(nowMs);
747
- if (entries.has(messageSid)) return { kind: "replayed" };
748
- if (entries.size >= maxKeys) {
749
- const oldestExpiresAt = entries.values().next().value ?? nowMs;
767
+ //#region extensions/sms/src/ingress-spool.ts
768
+ const SMS_INGRESS_PAYLOAD_VERSION = 1;
769
+ const SMS_INGRESS_DRAIN_INTERVAL_MS = 500;
770
+ const SMS_COMPLETED_TTL_MS = 1440 * 60 * 1e3;
771
+ const SMS_COMPLETED_MAX_ENTRIES = 2e4;
772
+ const SMS_FAILED_TTL_MS = 720 * 60 * 60 * 1e3;
773
+ const SMS_FAILED_MAX_ENTRIES = 1e3;
774
+ var SmsIngressPermanentError = class extends Error {};
775
+ function parseSmsIngressForm(form, account) {
776
+ const message = buildTwilioInboundMessage(form);
777
+ if (!message) throw new SmsIngressPermanentError("SMS ingress payload is invalid.");
778
+ if (message.accountSid && message.accountSid !== account.accountSid) throw new SmsIngressPermanentError("SMS ingress payload has an invalid Twilio account.");
779
+ return message;
780
+ }
781
+ function createSmsIngressSpool(params) {
782
+ const queue = params.queue ?? getSmsRuntime().state.openChannelIngressQueue({ accountId: params.account.accountId });
783
+ const deliver = params.deliver ?? (async (message, lifecycle, receivedAt) => {
784
+ await dispatchSmsInboundEvent({
785
+ cfg: params.cfg,
786
+ account: params.account,
787
+ channelRuntime: params.channelRuntime,
788
+ msg: message,
789
+ receivedAt,
790
+ turnAdoptionLifecycle: lifecycle,
791
+ log: params.log
792
+ });
793
+ });
794
+ const monitor = createChannelIngressMonitor({
795
+ queue,
796
+ inspect: (form, context) => {
797
+ const eventId = resolveTwilioMessageSid(form);
798
+ if (!eventId) {
799
+ if (context.phase === "claim") throw new SmsIngressPermanentError("SMS ingress payload is invalid.");
800
+ throw new Error("SMS webhook is missing MessageSid.");
801
+ }
802
+ const sender = resolveTwilioInboundSender(form);
750
803
  return {
751
- kind: "saturated",
752
- retryAfterMs: Math.max(0, oldestExpiresAt - nowMs)
804
+ eventId,
805
+ laneKey: sender ? `sender:${sender}` : `event:${eventId}`
753
806
  };
754
- }
755
- entries.set(messageSid, nowMs + ttlMs);
756
- return { kind: "accepted" };
757
- } };
807
+ },
808
+ payload: {
809
+ version: SMS_INGRESS_PAYLOAD_VERSION,
810
+ serialize: (form) => form,
811
+ deserialize: (form) => form,
812
+ encode: ({ body }) => ({
813
+ version: SMS_INGRESS_PAYLOAD_VERSION,
814
+ form: body
815
+ }),
816
+ decode: (payload) => ({
817
+ version: payload.version,
818
+ body: payload.form
819
+ }),
820
+ createClaimError: (kind) => new SmsIngressPermanentError(kind === "invalid-version" ? "SMS ingress payload version is invalid." : "SMS ingress identity changed after durable admission.")
821
+ },
822
+ deliver: (_form, lifecycle, event) => deliver(parseSmsIngressForm(event.payload.form, params.account), bindIngressLifecycleToReplyOptions(lifecycle).turnAdoptionLifecycle, event.receivedAt),
823
+ pollIntervalMs: SMS_INGRESS_DRAIN_INTERVAL_MS,
824
+ retention: {
825
+ pruneIntervalMs: 0,
826
+ completedTtlMs: SMS_COMPLETED_TTL_MS,
827
+ completedMaxEntries: SMS_COMPLETED_MAX_ENTRIES,
828
+ failedTtlMs: SMS_FAILED_TTL_MS,
829
+ failedMaxEntries: SMS_FAILED_MAX_ENTRIES
830
+ },
831
+ appendRetryDelaysMs: [0],
832
+ waitForDeliveryIdleBeforeRepump: false,
833
+ waitForDeliveryIdleOnStop: false,
834
+ runPumpTask: runDetachedWebhookWork,
835
+ admissionMode: "durable-after-stop",
836
+ drain: {
837
+ onLog: (message) => params.log?.warn?.(message),
838
+ resolveNonRetryableFailure: (error) => error instanceof SmsIngressPermanentError ? {
839
+ reason: "invalid-payload",
840
+ message: error.message
841
+ } : null
842
+ },
843
+ ...params.abortSignal ? { abortSignal: params.abortSignal } : {},
844
+ createStoppedError: () => /* @__PURE__ */ new Error("SMS ingress stopped."),
845
+ onError: (error) => params.log?.error?.(`SMS ingress drain failed: ${error instanceof Error ? error.message : String(error)}`)
846
+ });
847
+ return {
848
+ enqueue: async (form) => {
849
+ const admitted = await monitor.admit(form);
850
+ if (admitted.kind === "ignored") throw new Error("SMS webhook admission was unexpectedly ignored.");
851
+ return {
852
+ kind: admitted.queueResult.kind,
853
+ duplicate: admitted.queueResult.duplicate
854
+ };
855
+ },
856
+ start: monitor.start,
857
+ pause: monitor.pause,
858
+ waitForIdle: monitor.waitForIdle,
859
+ stop: monitor.stop
860
+ };
758
861
  }
759
862
  //#endregion
760
863
  //#region extensions/sms/src/webhook.ts
@@ -770,15 +873,6 @@ const callbackDispatchRateLimiter = createFixedWindowRateLimiter({
770
873
  windowMs: 6e4,
771
874
  maxTrackedKeys: 5e3
772
875
  });
773
- const replayGuardsByAccount = /* @__PURE__ */ new Map();
774
- function resolveSmsWebhookReplayGuard(account) {
775
- const key = `${account.accountId}\0${account.accountSid}`;
776
- const existing = replayGuardsByAccount.get(key);
777
- if (existing) return existing;
778
- const created = createSmsWebhookReplayGuard();
779
- replayGuardsByAccount.set(key, created);
780
- return created;
781
- }
782
876
  function headerValue(value) {
783
877
  if (Array.isArray(value)) return value[0];
784
878
  return value;
@@ -795,7 +889,6 @@ function rejectInvalidRequestRateLimit(params) {
795
889
  return true;
796
890
  }
797
891
  function createSmsWebhookHandler(params) {
798
- const webhookReplayGuard = resolveSmsWebhookReplayGuard(params.account);
799
892
  return async (req, res) => {
800
893
  if (req.method !== "POST") {
801
894
  respondTwiml(res, 405, "Method not allowed");
@@ -842,26 +935,6 @@ function createSmsWebhookHandler(params) {
842
935
  return true;
843
936
  }
844
937
  }
845
- const msg = buildTwilioInboundMessage(form);
846
- if (!msg) {
847
- if (invalidRequestRateLimited) return rejectInvalidRequestRateLimit({
848
- key,
849
- log: params.log,
850
- res
851
- });
852
- respondTwiml(res, 400, "Missing SMS payload");
853
- return true;
854
- }
855
- if (msg.accountSid && msg.accountSid !== params.account.accountSid) {
856
- if (invalidRequestRateLimited) return rejectInvalidRequestRateLimit({
857
- key,
858
- log: params.log,
859
- res
860
- });
861
- params.log?.warn?.("SMS webhook rejected mismatched Twilio AccountSid");
862
- respondTwiml(res, 403, "Invalid account");
863
- return true;
864
- }
865
938
  if (invalidRequestRateLimited && params.account.dangerouslyDisableSignatureValidation) return rejectInvalidRequestRateLimit({
866
939
  key,
867
940
  log: params.log,
@@ -872,28 +945,12 @@ function createSmsWebhookHandler(params) {
872
945
  respondTwiml(res, 429, "Rate limit exceeded");
873
946
  return true;
874
947
  }
875
- const replayDecision = webhookReplayGuard.remember(msg.messageSid);
876
- if (replayDecision.kind === "replayed") {
877
- params.log?.warn?.(`SMS webhook ignored replayed message ${msg.messageSid}`);
878
- respondTwiml(res, 200);
948
+ const messageSid = resolveTwilioMessageSid(form);
949
+ if (!messageSid) {
950
+ respondTwiml(res, 400, "Missing MessageSid");
879
951
  return true;
880
952
  }
881
- if (replayDecision.kind === "saturated") {
882
- const retryAfterSeconds = Math.max(1, Math.ceil(replayDecision.retryAfterMs / 1e3));
883
- params.log?.warn?.("SMS webhook replay cache is full of unexpired message SIDs");
884
- res.setHeader("Retry-After", String(retryAfterSeconds));
885
- respondTwiml(res, 429, "Replay cache saturated");
886
- return true;
887
- }
888
- runDetachedWebhookWork(() => dispatchSmsInboundEvent({
889
- cfg: params.cfg,
890
- account: params.account,
891
- msg,
892
- channelRuntime: params.channelRuntime,
893
- log: params.log
894
- })).catch((err) => {
895
- params.log?.error?.(`SMS webhook dispatch failed: ${err instanceof Error ? err.message : String(err)}`);
896
- });
953
+ if ((await params.ingress.enqueue(form)).duplicate) params.log?.warn?.(`SMS webhook ignored replayed message ${messageSid}`);
897
954
  respondTwiml(res, 200);
898
955
  return true;
899
956
  };
@@ -901,15 +958,34 @@ function createSmsWebhookHandler(params) {
901
958
  //#endregion
902
959
  //#region extensions/sms/src/gateway.ts
903
960
  const CHANNEL_ID$1 = "sms";
904
- const activeRoutes = /* @__PURE__ */ new Map();
905
961
  const activeRoutePaths = /* @__PURE__ */ new Map();
906
- function routeKey(account) {
907
- return `${account.accountId}:${normalizeWebhookPath(account.webhookPath)}`;
908
- }
962
+ const pendingRouteStops = /* @__PURE__ */ new Map();
909
963
  function normalizeWebhookPath(path) {
910
964
  const trimmed = path.trim();
911
965
  return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
912
966
  }
967
+ function stopSmsWebhookRoute(webhookPath, route) {
968
+ if (route.stopTask) return route.stopTask;
969
+ const pauseTask = route.ingress.pause();
970
+ route.unregisterRoute();
971
+ if (activeRoutePaths.get(webhookPath) === route) activeRoutePaths.delete(webhookPath);
972
+ const previousStop = pendingRouteStops.get(webhookPath) ?? Promise.resolve();
973
+ const stopTask = Promise.all([
974
+ previousStop,
975
+ route.ready,
976
+ pauseTask
977
+ ]).then(() => route.ingress.stop(), async (error) => {
978
+ await Promise.allSettled([route.ingress.stop()]);
979
+ throw error;
980
+ });
981
+ route.stopTask = stopTask;
982
+ pendingRouteStops.set(webhookPath, stopTask);
983
+ const clear = () => {
984
+ if (pendingRouteStops.get(webhookPath) === stopTask) pendingRouteStops.delete(webhookPath);
985
+ };
986
+ stopTask.then(clear, clear);
987
+ return stopTask;
988
+ }
913
989
  function collectSmsStartupWarnings(account) {
914
990
  const warnings = [];
915
991
  if (!account.accountSid || !account.authToken || !account.fromNumber && !account.messagingServiceSid) warnings.push("- SMS: accountSid, authToken, and fromNumber or messagingServiceSid are required.");
@@ -918,27 +994,57 @@ function collectSmsStartupWarnings(account) {
918
994
  if (account.dmPolicy === "open" && !account.allowFrom.includes("*")) warnings.push("- SMS: dmPolicy=open should set allowFrom=[\"*\"] or explicit sender numbers.");
919
995
  return warnings;
920
996
  }
921
- function registerSmsWebhookRoute(params) {
922
- const key = routeKey(params.account);
997
+ async function registerSmsWebhookRoute(params) {
923
998
  const webhookPath = normalizeWebhookPath(params.account.webhookPath);
924
- const currentPathOwner = activeRoutePaths.get(webhookPath);
925
- if (currentPathOwner && currentPathOwner !== params.account.accountId) throw new Error(`SMS webhook path ${webhookPath} is already registered by account ${currentPathOwner}; configure a distinct webhookPath for account ${params.account.accountId}.`);
926
- activeRoutes.get(key)?.();
927
- activeRoutePaths.delete(webhookPath);
928
- const unregister = registerPluginHttpRoute({
929
- path: webhookPath,
930
- auth: "plugin",
931
- pluginId: CHANNEL_ID$1,
999
+ const currentRoute = activeRoutePaths.get(webhookPath);
1000
+ 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}.`);
1001
+ const predecessorStop = currentRoute ? stopSmsWebhookRoute(webhookPath, currentRoute) : pendingRouteStops.get(webhookPath) ?? Promise.resolve();
1002
+ const ingress = createSmsIngressSpool({
1003
+ cfg: params.cfg,
1004
+ account: params.account,
1005
+ channelRuntime: params.channelRuntime,
1006
+ ...params.log ? { log: params.log } : {}
1007
+ });
1008
+ let unregisterRoute;
1009
+ try {
1010
+ unregisterRoute = registerPluginHttpRoute({
1011
+ path: webhookPath,
1012
+ auth: "plugin",
1013
+ pluginId: CHANNEL_ID$1,
1014
+ accountId: params.account.accountId,
1015
+ log: (msg) => params.log?.info?.(msg),
1016
+ handler: createSmsWebhookHandler({
1017
+ ...params,
1018
+ ingress
1019
+ })
1020
+ });
1021
+ } catch (error) {
1022
+ await Promise.allSettled([predecessorStop, ingress.stop()]);
1023
+ throw error;
1024
+ }
1025
+ const route = {
932
1026
  accountId: params.account.accountId,
933
- log: (msg) => params.log?.info?.(msg),
934
- handler: createSmsWebhookHandler(params)
1027
+ ingress,
1028
+ unregisterRoute,
1029
+ ready: Promise.resolve()
1030
+ };
1031
+ activeRoutePaths.set(webhookPath, route);
1032
+ route.ready = predecessorStop.then(() => {
1033
+ if (activeRoutePaths.get(webhookPath) === route && !route.stopTask) ingress.start();
935
1034
  });
936
- activeRoutes.set(key, unregister);
937
- activeRoutePaths.set(webhookPath, params.account.accountId);
938
- return () => {
939
- unregister();
940
- activeRoutes.delete(key);
941
- if (activeRoutePaths.get(webhookPath) === params.account.accountId) activeRoutePaths.delete(webhookPath);
1035
+ const unregister = () => stopSmsWebhookRoute(webhookPath, route);
1036
+ const readinessAbort = new AbortController();
1037
+ const lifecycle = waitUntilAbort(AbortSignal.any([params.abortSignal, readinessAbort.signal]), unregister);
1038
+ try {
1039
+ await route.ready;
1040
+ } catch (error) {
1041
+ readinessAbort.abort();
1042
+ await Promise.allSettled([lifecycle]);
1043
+ throw error;
1044
+ }
1045
+ return {
1046
+ lifecycle,
1047
+ isActive: () => activeRoutePaths.get(webhookPath) === route
942
1048
  };
943
1049
  }
944
1050
  async function startSmsGatewayAccount(params) {
@@ -952,9 +1058,9 @@ async function startSmsGatewayAccount(params) {
952
1058
  return waitUntilAbort(params.abortSignal);
953
1059
  }
954
1060
  for (const warning of warnings) params.log?.warn?.(warning);
955
- const unregister = registerSmsWebhookRoute(params);
956
- params.log?.info?.(`Registered SMS webhook route ${params.account.webhookPath} for account ${params.account.accountId}`);
957
- return waitUntilAbort(params.abortSignal, unregister);
1061
+ const registration = await registerSmsWebhookRoute(params);
1062
+ if (registration.isActive()) params.log?.info?.(`Registered SMS webhook route ${params.account.webhookPath} for account ${params.account.accountId}`);
1063
+ return registration.lifecycle;
958
1064
  }
959
1065
  //#endregion
960
1066
  //#region extensions/sms/src/status.ts
@@ -1211,6 +1317,82 @@ function applySmsAccountConfig(params) {
1211
1317
  channels
1212
1318
  };
1213
1319
  }
1320
+ const smsSetupContract = defineChannelSetupContract({
1321
+ fields: {
1322
+ accountSid: {
1323
+ kind: "string",
1324
+ sensitive: true,
1325
+ cli: {
1326
+ flags: "--account-sid <sid>",
1327
+ description: "Twilio account SID"
1328
+ }
1329
+ },
1330
+ authToken: {
1331
+ kind: "string",
1332
+ sensitive: true,
1333
+ cli: {
1334
+ flags: "--auth-token <token>",
1335
+ description: "Twilio auth token"
1336
+ }
1337
+ },
1338
+ fromNumber: {
1339
+ kind: "string",
1340
+ cli: {
1341
+ flags: "--from-number <e164>",
1342
+ description: "Twilio sender phone number"
1343
+ }
1344
+ },
1345
+ messagingServiceSid: {
1346
+ kind: "string",
1347
+ cli: {
1348
+ flags: "--messaging-service-sid <sid>",
1349
+ description: "Twilio Messaging Service SID"
1350
+ }
1351
+ },
1352
+ defaultTo: {
1353
+ kind: "string",
1354
+ cli: {
1355
+ flags: "--default-to <e164>",
1356
+ description: "Default SMS recipient"
1357
+ }
1358
+ },
1359
+ webhookPath: {
1360
+ kind: "string",
1361
+ cli: {
1362
+ flags: "--webhook-path <path>",
1363
+ description: "SMS webhook path"
1364
+ }
1365
+ },
1366
+ publicWebhookUrl: {
1367
+ kind: "string",
1368
+ cli: {
1369
+ flags: "--public-webhook-url <url>",
1370
+ description: "Public SMS webhook URL"
1371
+ }
1372
+ },
1373
+ dmPolicy: {
1374
+ kind: "choice",
1375
+ choices: [
1376
+ "pairing",
1377
+ "allowlist",
1378
+ "open",
1379
+ "disabled"
1380
+ ],
1381
+ cli: {
1382
+ flags: "--dm-policy <policy>",
1383
+ description: "SMS DM policy"
1384
+ }
1385
+ },
1386
+ allowFrom: {
1387
+ kind: "string-list",
1388
+ cli: {
1389
+ flags: "--allow-from <numbers>",
1390
+ description: "Allowed SMS senders"
1391
+ }
1392
+ }
1393
+ },
1394
+ adapter: { applyAccountConfig: applySmsAccountConfig }
1395
+ });
1214
1396
  function createSmsReceipt(params) {
1215
1397
  const first = params.results[0];
1216
1398
  if (!first) throw new Error("SMS send did not return a Twilio Message SID.");
@@ -1304,7 +1486,12 @@ const smsPlugin = createChatChannelPlugin({
1304
1486
  },
1305
1487
  reload: { configPrefixes: [`channels.${CHANNEL_ID}`] },
1306
1488
  configSchema: SmsChannelConfigSchema,
1307
- setup: { applyAccountConfig: applySmsAccountConfig },
1489
+ setup: { applyAccountConfig: ({ cfg, accountId, input }) => applySmsAccountConfig({
1490
+ cfg,
1491
+ accountId,
1492
+ input
1493
+ }) },
1494
+ setupContract: smsSetupContract,
1308
1495
  config: {
1309
1496
  ...smsConfigAdapter,
1310
1497
  inspectAccount: inspectSmsAccount,
@@ -0,0 +1,8 @@
1
+ import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
2
+ //#region extensions/sms/src/runtime.ts
3
+ const { setRuntime: setSmsRuntime, getRuntime: getSmsRuntime } = createPluginRuntimeStore({
4
+ pluginId: "sms",
5
+ errorMessage: "SMS runtime not initialized - plugin not registered"
6
+ });
7
+ //#endregion
8
+ export { setSmsRuntime as n, getSmsRuntime as t };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@openclaw/sms",
3
- "version": "2026.7.2-beta.2",
3
+ "version": "2026.7.2-beta.4",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@openclaw/sms",
9
- "version": "2026.7.2-beta.2",
9
+ "version": "2026.7.2-beta.4",
10
10
  "dependencies": {
11
11
  "zod": "4.4.3"
12
12
  }
@@ -8,18 +8,6 @@
8
8
  "channels": [
9
9
  "sms"
10
10
  ],
11
- "channelEnvVars": {
12
- "sms": [
13
- "TWILIO_ACCOUNT_SID",
14
- "TWILIO_AUTH_TOKEN",
15
- "TWILIO_PHONE_NUMBER",
16
- "TWILIO_SMS_FROM",
17
- "TWILIO_MESSAGING_SERVICE_SID",
18
- "SMS_PUBLIC_WEBHOOK_URL",
19
- "SMS_WEBHOOK_PATH",
20
- "SMS_ALLOWED_USERS"
21
- ]
22
- },
23
11
  "configSchema": {
24
12
  "type": "object",
25
13
  "additionalProperties": false,
@@ -338,7 +326,8 @@
338
326
  },
339
327
  "fromNumber": {
340
328
  "label": "SMS From Number",
341
- "help": "Twilio SMS-capable phone number in E.164 format, for example +15551234567."
329
+ "help": "Twilio SMS-capable phone number in E.164 format, for example +15551234567.",
330
+ "presentation": "phone-number"
342
331
  },
343
332
  "messagingServiceSid": {
344
333
  "label": "Twilio Messaging Service SID",
@@ -346,7 +335,8 @@
346
335
  },
347
336
  "defaultTo": {
348
337
  "label": "SMS Default To Number",
349
- "help": "Optional default outbound phone number used when a send flow omits an explicit SMS target."
338
+ "help": "Optional default outbound phone number used when a send flow omits an explicit SMS target.",
339
+ "presentation": "phone-number"
350
340
  },
351
341
  "publicWebhookUrl": {
352
342
  "label": "SMS Public Webhook URL",
@@ -362,7 +352,17 @@
362
352
  },
363
353
  "allowFrom": {
364
354
  "label": "SMS Allow From",
365
- "help": "Allowed sender phone numbers in E.164 format, or * when dmPolicy is open."
355
+ "help": "Allowed sender phone numbers in E.164 format, or * when dmPolicy is open.",
356
+ "presentation": "phone-number"
357
+ },
358
+ "accounts.*.fromNumber": {
359
+ "presentation": "phone-number"
360
+ },
361
+ "accounts.*.defaultTo": {
362
+ "presentation": "phone-number"
363
+ },
364
+ "accounts.*.allowFrom.*": {
365
+ "presentation": "phone-number"
366
366
  },
367
367
  "textChunkLimit": {
368
368
  "label": "SMS Text Chunk Limit",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openclaw/sms",
3
- "version": "2026.7.2-beta.2",
3
+ "version": "2026.7.2-beta.4",
4
4
  "description": "OpenClaw SMS channel plugin for Twilio text messages.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,6 +16,20 @@
16
16
  ],
17
17
  "channel": {
18
18
  "id": "sms",
19
+ "configuredState": {
20
+ "env": {
21
+ "anyOf": [
22
+ "TWILIO_ACCOUNT_SID",
23
+ "TWILIO_AUTH_TOKEN",
24
+ "TWILIO_PHONE_NUMBER",
25
+ "TWILIO_SMS_FROM",
26
+ "TWILIO_MESSAGING_SERVICE_SID",
27
+ "SMS_PUBLIC_WEBHOOK_URL",
28
+ "SMS_WEBHOOK_PATH",
29
+ "SMS_ALLOWED_USERS"
30
+ ]
31
+ }
32
+ },
19
33
  "label": "SMS",
20
34
  "selectionLabel": "SMS (Twilio)",
21
35
  "detailLabel": "Twilio SMS",
@@ -23,13 +37,97 @@
23
37
  "docsLabel": "sms",
24
38
  "blurb": "Twilio-backed SMS with inbound webhooks and outbound replies.",
25
39
  "order": 88,
26
- "quickstartAllowFrom": true
40
+ "quickstartAllowFrom": true,
41
+ "setup": {
42
+ "fields": [
43
+ {
44
+ "key": "accountSid",
45
+ "kind": "string",
46
+ "sensitive": true,
47
+ "cli": {
48
+ "flags": "--account-sid <sid>",
49
+ "description": "Twilio account SID"
50
+ }
51
+ },
52
+ {
53
+ "key": "authToken",
54
+ "kind": "string",
55
+ "sensitive": true,
56
+ "cli": {
57
+ "flags": "--auth-token <token>",
58
+ "description": "Twilio auth token"
59
+ }
60
+ },
61
+ {
62
+ "key": "fromNumber",
63
+ "kind": "string",
64
+ "cli": {
65
+ "flags": "--from-number <e164>",
66
+ "description": "Twilio sender phone number"
67
+ }
68
+ },
69
+ {
70
+ "key": "messagingServiceSid",
71
+ "kind": "string",
72
+ "cli": {
73
+ "flags": "--messaging-service-sid <sid>",
74
+ "description": "Twilio Messaging Service SID"
75
+ }
76
+ },
77
+ {
78
+ "key": "defaultTo",
79
+ "kind": "string",
80
+ "cli": {
81
+ "flags": "--default-to <e164>",
82
+ "description": "Default SMS recipient"
83
+ }
84
+ },
85
+ {
86
+ "key": "webhookPath",
87
+ "kind": "string",
88
+ "cli": {
89
+ "flags": "--webhook-path <path>",
90
+ "description": "SMS webhook path"
91
+ }
92
+ },
93
+ {
94
+ "key": "publicWebhookUrl",
95
+ "kind": "string",
96
+ "cli": {
97
+ "flags": "--public-webhook-url <url>",
98
+ "description": "Public SMS webhook URL"
99
+ }
100
+ },
101
+ {
102
+ "key": "dmPolicy",
103
+ "kind": "choice",
104
+ "choices": [
105
+ "pairing",
106
+ "allowlist",
107
+ "open",
108
+ "disabled"
109
+ ],
110
+ "cli": {
111
+ "flags": "--dm-policy <policy>",
112
+ "description": "SMS DM policy"
113
+ }
114
+ },
115
+ {
116
+ "key": "allowFrom",
117
+ "kind": "string-list",
118
+ "cli": {
119
+ "flags": "--allow-from <numbers>",
120
+ "description": "Allowed SMS senders"
121
+ }
122
+ }
123
+ ]
124
+ }
27
125
  },
28
126
  "compat": {
29
- "pluginApi": ">=2026.7.2-beta.2"
127
+ "pluginApi": ">=2026.7.2-beta.4"
30
128
  },
31
129
  "build": {
32
- "openclawVersion": "2026.7.2-beta.2",
130
+ "openclawVersion": "2026.7.2-beta.4",
33
131
  "bundledDist": false
34
132
  },
35
133
  "install": {
@@ -54,7 +152,7 @@
54
152
  "README.md"
55
153
  ],
56
154
  "peerDependencies": {
57
- "openclaw": ">=2026.7.2-beta.2"
155
+ "openclaw": ">=2026.7.2-beta.4"
58
156
  },
59
157
  "peerDependenciesMeta": {
60
158
  "openclaw": {