@openclaw/sms 2026.7.2-beta.7 → 2026.8.1-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.
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import { defineBundledChannelEntry } from "openclaw/plugin-sdk/channel-entry-con
3
3
  var sms_default = defineBundledChannelEntry({
4
4
  id: "sms",
5
5
  name: "SMS",
6
- description: "Twilio SMS channel plugin for OpenClaw text messages.",
6
+ description: "Twilio SMS/MMS channel plugin for OpenClaw messages.",
7
7
  importMetaUrl: import.meta.url,
8
8
  plugin: {
9
9
  specifier: "./channel-plugin-api.js",
@@ -0,0 +1,404 @@
1
+ import { t as getSmsRuntime } from "./runtime-BBlPgBIF.js";
2
+ import { n as TWILIO_MMS_MAX_BYTES } from "./twilio-QS1jkUGH.js";
3
+ import { resolveExpiresAtMsFromDurationMs } from "openclaw/plugin-sdk/number-runtime";
4
+ import { createHash } from "node:crypto";
5
+ import { formatInboundMediaUnavailableText, toInboundMediaFactsWithMetadata } from "openclaw/plugin-sdk/channel-inbound";
6
+ import { collectErrorGraphCandidates } from "openclaw/plugin-sdk/error-runtime";
7
+ import { SsrFBlockedError, safeEqualSecret } from "openclaw/plugin-sdk/security-runtime";
8
+ import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
9
+ import { MediaFetchError, unlinkIfExists } from "openclaw/plugin-sdk/media-runtime";
10
+ import { createHostedOutboundMediaStore } from "openclaw/plugin-sdk/outbound-media";
11
+ import { isTransientNetworkError } from "openclaw/plugin-sdk/retry-runtime";
12
+ //#region extensions/sms/src/media.ts
13
+ const TWILIO_API_HOSTNAME = "api.twilio.com";
14
+ const TWILIO_MEDIA_PATH_RE = /^\/2010-04-01\/Accounts\/([^/]+)\/Messages\/([^/]+)\/Media\/(ME[0-9a-fA-F]{32})$/u;
15
+ const TWILIO_MEDIA_TOTAL_TIMEOUT_MS = 6e4;
16
+ const TWILIO_MEDIA_RESPONSE_HEADER_TIMEOUT_MS = 3e4;
17
+ const TWILIO_MEDIA_READ_IDLE_TIMEOUT_MS = 3e4;
18
+ const TWILIO_MEDIA_BATCH_TIMEOUT_MS = 4 * 6e4;
19
+ const TWILIO_MEDIA_RETRY = {
20
+ attempts: 2,
21
+ minDelayMs: 500,
22
+ maxDelayMs: 2e3,
23
+ jitter: .2
24
+ };
25
+ const TWILIO_MMS_IMAGE_MAX_BYTES = 5e6;
26
+ const TWILIO_MMS_OTHER_MAX_BYTES = 5e5;
27
+ const TWILIO_MMS_LARGE_MEDIA_TYPES = /* @__PURE__ */ new Set([
28
+ "image/gif",
29
+ "image/jpeg",
30
+ "image/jpg",
31
+ "image/png"
32
+ ]);
33
+ const TWILIO_MMS_MEDIA_ONLY_TYPES = /* @__PURE__ */ new Set(["application/vcard"]);
34
+ const TWILIO_MMS_EXTENSION_BY_TYPE = {
35
+ "application/pdf": ".pdf",
36
+ "application/vcard": ".vcf",
37
+ "audio/3gpp": ".3gp",
38
+ "audio/3gpp2": ".3g2",
39
+ "audio/ac3": ".ac3",
40
+ "audio/amr": ".amr",
41
+ "audio/amr-nb": ".amr",
42
+ "audio/basic": ".au",
43
+ "audio/l24": ".l24",
44
+ "audio/mp3": ".mp3",
45
+ "audio/mp4": ".m4a",
46
+ "audio/mpeg": ".mp3",
47
+ "audio/ogg": ".ogg",
48
+ "audio/vnd.rn-realaudio": ".ra",
49
+ "audio/vnd.wave": ".wav",
50
+ "audio/webm": ".webm",
51
+ "image/bmp": ".bmp",
52
+ "image/gif": ".gif",
53
+ "image/heic": ".heic",
54
+ "image/heif": ".heif",
55
+ "image/jpeg": ".jpg",
56
+ "image/jpg": ".jpg",
57
+ "image/png": ".png",
58
+ "image/tiff": ".tiff",
59
+ "text/calendar": ".ics",
60
+ "text/csv": ".csv",
61
+ "text/directory": ".vcf",
62
+ "text/richtext": ".rtx",
63
+ "text/rtf": ".rtf",
64
+ "text/vcard": ".vcf",
65
+ "text/x-vcard": ".vcf",
66
+ "video/3gpp": ".3gp",
67
+ "video/3gpp-tt": ".3gp",
68
+ "video/3gpp2": ".3g2",
69
+ "video/h261": ".h261",
70
+ "video/h263": ".h263",
71
+ "video/h263-1998": ".h263",
72
+ "video/h263-2000": ".h263",
73
+ "video/h264": ".h264",
74
+ "video/h265": ".h265",
75
+ "video/mp4": ".mp4",
76
+ "video/mpeg": ".mpg",
77
+ "video/mpeg4": ".mp4",
78
+ "video/quicktime": ".mov",
79
+ "video/webm": ".webm"
80
+ };
81
+ const SMS_OUTBOUND_MEDIA_TTL_MS = 10 * 6e4;
82
+ const SMS_OUTBOUND_MEDIA_ID_RE = /^[a-f0-9]{24}$/;
83
+ const SMS_OUTBOUND_MEDIA_TOKEN_PARAM_PREFIX = "__openclaw_mms_token";
84
+ const SMS_OUTBOUND_MEDIA_NAMESPACE = "hosted-outbound-media";
85
+ const SMS_OUTBOUND_MEDIA_CHUNKS_NAMESPACE = "hosted-outbound-media-chunks";
86
+ const SMS_OUTBOUND_MEDIA_MAX_ENTRIES = 64;
87
+ const SMS_OUTBOUND_MEDIA_MAX_CHUNK_ROWS = SMS_OUTBOUND_MEDIA_MAX_ENTRIES * 160;
88
+ const hostedSmsMediaStores = /* @__PURE__ */ new Map();
89
+ let hostedSmsMediaRuntime;
90
+ function normalizeBasePath(path) {
91
+ const withLeadingSlash = path.trim().startsWith("/") ? path.trim() : `/${path.trim()}`;
92
+ return withLeadingSlash === "/" ? "" : withLeadingSlash.replace(/\/+$/u, "");
93
+ }
94
+ function normalizeExactPath(path) {
95
+ return normalizeBasePath(path) || "/";
96
+ }
97
+ function toHostedStoreRoutePath(path) {
98
+ const normalized = normalizeExactPath(path);
99
+ return normalized === "/" ? normalized : `${normalized}/`;
100
+ }
101
+ function resolveSmsHostedMediaRoute(params) {
102
+ if (!params.publicWebhookUrl.trim()) throw new Error("MMS send requires channels.sms.publicWebhookUrl.");
103
+ const publicWebhookUrl = new URL(params.publicWebhookUrl);
104
+ if (publicWebhookUrl.protocol !== "https:" || !publicWebhookUrl.hostname) throw new Error("MMS send requires an HTTPS publicWebhookUrl with a hostname.");
105
+ if (publicWebhookUrl.username || publicWebhookUrl.password) throw new Error("MMS send requires a publicWebhookUrl without embedded HTTP authentication.");
106
+ return {
107
+ localRoutePath: toHostedStoreRoutePath(params.webhookPath),
108
+ publicBaseUrl: publicWebhookUrl.origin,
109
+ publicRoutePath: normalizeExactPath(publicWebhookUrl.pathname),
110
+ publicSearch: publicWebhookUrl.search
111
+ };
112
+ }
113
+ function createHostedSmsMediaStore(runtime, accountId) {
114
+ const accountScope = createHash("sha256").update(accountId).digest("hex").slice(0, 16);
115
+ return createHostedOutboundMediaStore({
116
+ metadataStore: runtime.state.openKeyedStore({
117
+ namespace: `${SMS_OUTBOUND_MEDIA_NAMESPACE}-${accountScope}`,
118
+ maxEntries: SMS_OUTBOUND_MEDIA_MAX_ENTRIES,
119
+ overflowPolicy: "reject-new"
120
+ }),
121
+ chunkStore: runtime.state.openKeyedStore({
122
+ namespace: `${SMS_OUTBOUND_MEDIA_CHUNKS_NAMESPACE}-${accountScope}`,
123
+ maxEntries: SMS_OUTBOUND_MEDIA_MAX_CHUNK_ROWS,
124
+ overflowPolicy: "reject-new"
125
+ }),
126
+ ttlMs: SMS_OUTBOUND_MEDIA_TTL_MS,
127
+ maxEntries: SMS_OUTBOUND_MEDIA_MAX_ENTRIES,
128
+ maxChunkRows: SMS_OUTBOUND_MEDIA_MAX_CHUNK_ROWS,
129
+ overflowPolicy: "reject-new",
130
+ resolveExpiresAtMs: (ttlMs) => resolveExpiresAtMsFromDurationMs(ttlMs)
131
+ });
132
+ }
133
+ function getHostedSmsMediaStore(accountId) {
134
+ const runtime = getSmsRuntime();
135
+ if (hostedSmsMediaRuntime !== runtime) {
136
+ hostedSmsMediaRuntime = runtime;
137
+ hostedSmsMediaStores.clear();
138
+ }
139
+ const existing = hostedSmsMediaStores.get(accountId);
140
+ if (existing) return existing;
141
+ const created = createHostedSmsMediaStore(runtime, accountId);
142
+ hostedSmsMediaStores.set(accountId, created);
143
+ return created;
144
+ }
145
+ function createHostedSmsMediaCleanup(store, id) {
146
+ let cleanup;
147
+ return async () => {
148
+ const activeCleanup = cleanup ?? store.delete(id);
149
+ cleanup = activeCleanup;
150
+ try {
151
+ await activeCleanup;
152
+ } catch (error) {
153
+ if (cleanup === activeCleanup) cleanup = void 0;
154
+ throw error;
155
+ }
156
+ };
157
+ }
158
+ async function prepareHostedSmsMedia(params) {
159
+ const route = resolveSmsHostedMediaRoute({
160
+ webhookPath: params.account.webhookPath,
161
+ publicWebhookUrl: params.account.publicWebhookUrl
162
+ });
163
+ const store = getHostedSmsMediaStore(params.account.accountId);
164
+ const captionByteLength = params.captionByteLength ?? 0;
165
+ if (!Number.isSafeInteger(captionByteLength) || captionByteLength < 0) throw new Error("MMS caption byte length must be a non-negative integer.");
166
+ const aggregateMediaBudget = TWILIO_MMS_IMAGE_MAX_BYTES - captionByteLength - 1;
167
+ if (aggregateMediaBudget < 1) throw new Error("Twilio MMS caption leaves no room for an attachment below 5,000,000 bytes.");
168
+ const mediaAccess = (() => {
169
+ const localRoots = params.mediaAccess?.localRoots ?? params.mediaLocalRoots;
170
+ const readFile = params.mediaAccess?.readFile ?? params.mediaReadFile;
171
+ const workspaceDir = params.mediaAccess?.workspaceDir;
172
+ if (!localRoots && !readFile && !workspaceDir) return;
173
+ return {
174
+ ...localRoots ? { localRoots } : {},
175
+ ...readFile ? { readFile } : {},
176
+ ...workspaceDir ? { workspaceDir } : {}
177
+ };
178
+ })();
179
+ const stagedUrl = new URL(await store.prepareUrl({
180
+ mediaUrl: params.mediaUrl,
181
+ routePath: route.localRoutePath,
182
+ publicBaseUrl: route.publicBaseUrl,
183
+ maxBytes: aggregateMediaBudget,
184
+ mediaAccess
185
+ }));
186
+ const id = stagedUrl.pathname.split("/").at(-1) ?? "";
187
+ const token = stagedUrl.searchParams.get("token");
188
+ if (!SMS_OUTBOUND_MEDIA_ID_RE.test(id) || !token) throw new Error("Hosted MMS media URL could not be prepared.");
189
+ const cleanup = createHostedSmsMediaCleanup(store, id);
190
+ const entry = await store.read(id);
191
+ if (!entry) throw new Error("Hosted MMS media expired before it could be sent.");
192
+ const contentType = entry.metadata.contentType?.split(";", 1)[0]?.trim().toLowerCase();
193
+ if (!contentType || !TWILIO_MMS_EXTENSION_BY_TYPE[contentType]) {
194
+ await cleanup();
195
+ throw new Error(`Twilio MMS does not support media type ${contentType || "unknown content type"}.`);
196
+ }
197
+ if (captionByteLength > 0 && TWILIO_MMS_MEDIA_ONLY_TYPES.has(contentType)) {
198
+ await cleanup();
199
+ throw new Error(`Twilio MMS media type ${contentType} must be sent without a caption.`);
200
+ }
201
+ const maxBytes = TWILIO_MMS_LARGE_MEDIA_TYPES.has(contentType) ? TWILIO_MMS_IMAGE_MAX_BYTES : TWILIO_MMS_OTHER_MAX_BYTES;
202
+ if (entry.metadata.byteLength > maxBytes) {
203
+ await cleanup();
204
+ throw new Error(`Twilio MMS media exceeds the ${maxBytes.toLocaleString("en-US")} byte limit for ${contentType || "unknown content type"}.`);
205
+ }
206
+ if (entry.metadata.byteLength + captionByteLength >= TWILIO_MMS_IMAGE_MAX_BYTES) {
207
+ await cleanup();
208
+ throw new Error("Twilio MMS attachment and caption must total less than 5,000,000 bytes.");
209
+ }
210
+ const tokenParam = `${SMS_OUTBOUND_MEDIA_TOKEN_PARAM_PREFIX}_${id}`;
211
+ const querySeparator = route.publicSearch ? "&" : "?";
212
+ return {
213
+ url: `${route.publicBaseUrl}${route.publicRoutePath}${route.publicSearch}${querySeparator}${tokenParam}=${encodeURIComponent(token)}`,
214
+ cleanup
215
+ };
216
+ }
217
+ function requireTwilioMediaUrl(rawUrl, identity) {
218
+ const url = new URL(rawUrl);
219
+ if (url.protocol !== "https:" || url.hostname !== TWILIO_API_HOSTNAME || url.port || url.username || url.password) throw new Error("Twilio MMS media URL must use https://api.twilio.com.");
220
+ const match = TWILIO_MEDIA_PATH_RE.exec(url.pathname);
221
+ if (!match || match[1] !== identity.accountSid || match[2] !== identity.messageSid) throw new Error("Twilio MMS media URL does not match the inbound message.");
222
+ return url.toString();
223
+ }
224
+ function inboundMediaUnavailableBody(body, count) {
225
+ return formatInboundMediaUnavailableText({
226
+ body,
227
+ notice: `[${count} Twilio MMS attachment${count === 1 ? "" : "s"} unavailable]`
228
+ });
229
+ }
230
+ function inboundMediaFileName(contentType, index) {
231
+ return `mms-${index + 1}${extensionForMime(contentType) ?? ".bin"}`;
232
+ }
233
+ function createInboundMediaCleanup(paths) {
234
+ let cleanup;
235
+ return async () => {
236
+ cleanup ??= Promise.all(paths.map(async (filePath) => await unlinkIfExists(filePath))).then(() => void 0);
237
+ await cleanup;
238
+ };
239
+ }
240
+ function nestedSmsMediaErrorCandidates(candidate) {
241
+ const nested = [
242
+ candidate.cause,
243
+ candidate.reason,
244
+ candidate.original,
245
+ candidate.error,
246
+ candidate.data
247
+ ];
248
+ if (Array.isArray(candidate.errors)) nested.push(...candidate.errors);
249
+ return nested;
250
+ }
251
+ function isRetryableSmsInboundMediaError(error) {
252
+ if (!(error instanceof MediaFetchError)) return false;
253
+ if (error.code === "http_error") return error.status === 408 || error.status === 429 || typeof error.status === "number" && error.status >= 500;
254
+ if (error.code !== "fetch_failed") return false;
255
+ if (collectErrorGraphCandidates(error.cause, nestedSmsMediaErrorCandidates).some((candidate) => candidate instanceof SsrFBlockedError)) return false;
256
+ return isTransientNetworkError(error.cause);
257
+ }
258
+ async function materializeSmsInboundMedia(params) {
259
+ const savedPaths = [];
260
+ const cleanup = createInboundMediaCleanup(savedPaths);
261
+ const declaredUnavailableCount = params.msg.unavailableMediaCount ?? 0;
262
+ if (params.msg.media.length === 0) return {
263
+ body: declaredUnavailableCount > 0 ? inboundMediaUnavailableBody(params.msg.body, declaredUnavailableCount) : params.msg.body,
264
+ media: [],
265
+ cleanup
266
+ };
267
+ const callbackAccountSid = params.msg.accountSid;
268
+ if (!callbackAccountSid || callbackAccountSid !== params.account.accountSid) {
269
+ params.log?.warn?.(`Refused Twilio MMS attachments for ${params.msg.messageSid}: webhook account mismatch`);
270
+ return {
271
+ body: inboundMediaUnavailableBody(params.msg.body, declaredUnavailableCount + params.msg.media.length),
272
+ media: [],
273
+ cleanup
274
+ };
275
+ }
276
+ let remainingBytes = TWILIO_MMS_MAX_BYTES;
277
+ let unavailableCount = declaredUnavailableCount;
278
+ const batchTimeoutSignal = AbortSignal.timeout(TWILIO_MEDIA_BATCH_TIMEOUT_MS);
279
+ const abortSignal = params.abortSignal ? AbortSignal.any([params.abortSignal, batchTimeoutSignal]) : batchTimeoutSignal;
280
+ const savedMedia = [];
281
+ try {
282
+ for (const [index, media] of params.msg.media.entries()) {
283
+ abortSignal.throwIfAborted();
284
+ if (remainingBytes <= 0) {
285
+ unavailableCount += 1;
286
+ continue;
287
+ }
288
+ try {
289
+ const saved = await params.mediaRuntime.media.saveRemoteMedia({
290
+ url: requireTwilioMediaUrl(media.url, {
291
+ accountSid: callbackAccountSid,
292
+ messageSid: params.msg.messageSid
293
+ }),
294
+ requestInit: {
295
+ headers: { authorization: `Basic ${Buffer.from(`${params.account.accountSid}:${params.account.authToken}`).toString("base64")}` },
296
+ signal: abortSignal
297
+ },
298
+ filePathHint: inboundMediaFileName(media.contentType, index),
299
+ fallbackContentType: media.contentType,
300
+ maxBytes: remainingBytes,
301
+ ssrfPolicy: { hostnameAllowlist: [TWILIO_API_HOSTNAME] },
302
+ timeoutMs: TWILIO_MEDIA_TOTAL_TIMEOUT_MS,
303
+ responseHeaderTimeoutMs: TWILIO_MEDIA_RESPONSE_HEADER_TIMEOUT_MS,
304
+ readIdleTimeoutMs: TWILIO_MEDIA_READ_IDLE_TIMEOUT_MS,
305
+ retry: TWILIO_MEDIA_RETRY
306
+ });
307
+ remainingBytes -= saved.size;
308
+ savedPaths.push(saved.path);
309
+ savedMedia.push({
310
+ path: saved.path,
311
+ contentType: saved.contentType ?? media.contentType,
312
+ messageId: params.msg.messageSid
313
+ });
314
+ } catch (error) {
315
+ abortSignal.throwIfAborted();
316
+ if (isRetryableSmsInboundMediaError(error)) throw error;
317
+ unavailableCount += 1;
318
+ params.log?.warn?.(`Failed to download Twilio MMS attachment ${index + 1} for ${params.msg.messageSid}`);
319
+ }
320
+ }
321
+ return {
322
+ body: unavailableCount > 0 ? inboundMediaUnavailableBody(params.msg.body, unavailableCount) : params.msg.body,
323
+ media: await toInboundMediaFactsWithMetadata(savedMedia),
324
+ cleanup
325
+ };
326
+ } catch (error) {
327
+ await cleanup();
328
+ throw error;
329
+ }
330
+ }
331
+ function hostedSmsMediaFileName(id, contentType) {
332
+ const normalizedContentType = contentType?.split(";", 1)[0]?.trim().toLowerCase();
333
+ const extension = normalizedContentType ? TWILIO_MMS_EXTENSION_BY_TYPE[normalizedContentType] : void 0;
334
+ return extension ? `mms-${id.slice(0, 10)}${extension}` : void 0;
335
+ }
336
+ async function tryHandleHostedSmsMediaRequest(req, res, accountId = "default") {
337
+ let url;
338
+ try {
339
+ url = new URL(req.url ?? "/", "http://localhost");
340
+ } catch {
341
+ return false;
342
+ }
343
+ const tokenCandidates = [...url.searchParams.entries()].filter(([key]) => key.startsWith(`${SMS_OUTBOUND_MEDIA_TOKEN_PARAM_PREFIX}_`)).map(([key, token]) => ({
344
+ id: key.slice(21),
345
+ token
346
+ })).filter((candidate) => SMS_OUTBOUND_MEDIA_ID_RE.test(candidate.id));
347
+ if (tokenCandidates.length === 0) return false;
348
+ if (tokenCandidates.length !== 1) {
349
+ res.statusCode = 400;
350
+ res.end("Bad Request");
351
+ return true;
352
+ }
353
+ const method = req.method ?? "GET";
354
+ if (method !== "GET" && method !== "HEAD") {
355
+ res.statusCode = 405;
356
+ res.setHeader("Allow", "GET, HEAD");
357
+ res.end("Method Not Allowed");
358
+ return true;
359
+ }
360
+ const routePath = toHostedStoreRoutePath(url.pathname);
361
+ const store = getHostedSmsMediaStore(accountId);
362
+ const candidate = tokenCandidates[0];
363
+ if (!candidate) return false;
364
+ const metadata = await store.readMetadata(candidate.id);
365
+ if (!metadata || metadata.routePath !== routePath) {
366
+ res.statusCode = 404;
367
+ res.end("Not Found");
368
+ return true;
369
+ }
370
+ if (!safeEqualSecret(candidate.token, metadata.token)) {
371
+ res.statusCode = 401;
372
+ res.end("Unauthorized");
373
+ return true;
374
+ }
375
+ let servedMetadata = metadata;
376
+ let body;
377
+ if (method === "GET") {
378
+ const entry = await store.read(candidate.id);
379
+ if (!entry || entry.metadata.routePath !== routePath || !safeEqualSecret(candidate.token, entry.metadata.token)) {
380
+ res.statusCode = 404;
381
+ res.end("Not Found");
382
+ return true;
383
+ }
384
+ servedMetadata = entry.metadata;
385
+ body = entry.buffer;
386
+ }
387
+ const contentType = servedMetadata.contentType ?? "application/octet-stream";
388
+ const fileName = hostedSmsMediaFileName(candidate.id, contentType);
389
+ if (!fileName) {
390
+ res.statusCode = 415;
391
+ res.end("Unsupported Media Type");
392
+ return true;
393
+ }
394
+ res.statusCode = 200;
395
+ res.setHeader("Content-Type", contentType);
396
+ res.setHeader("Content-Length", String(servedMetadata.byteLength));
397
+ res.setHeader("Content-Disposition", `inline; filename="${fileName}"`);
398
+ res.setHeader("Cache-Control", "no-store");
399
+ res.setHeader("X-Content-Type-Options", "nosniff");
400
+ res.end(body);
401
+ return true;
402
+ }
403
+ //#endregion
404
+ export { materializeSmsInboundMedia, prepareHostedSmsMedia, tryHandleHostedSmsMediaRequest };