@openclaw/sms 2026.7.2-beta.7 → 2026.8.1-beta.3

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,45 +1,32 @@
1
1
  import { t as getSmsRuntime } from "./runtime-BBlPgBIF.js";
2
+ import { _ as normalizeSmsAllowFrom, a as listTwilioMessages, c as resolveTwilioMessageSid, d as retrieveTwilioMessagingService, f as sendSmsViaTwilio, g as looksLikeSmsPhoneNumber, h as resolveTwilioStatusCallbackUrl, i as listTwilioIncomingPhoneNumbers, l as resolveTwilioWebhookSignatureUrl, m as parseSmsPublicWebhookUrl, o as readTwilioWebhookForm, p as verifyTwilioSignature, r as buildTwilioInboundMessage, s as resolveTwilioInboundSender, t as TWILIO_MESSAGE_BODY_MAX_LENGTH, u as respondTwiml, v as normalizeSmsPhoneNumber } from "./twilio-QS1jkUGH.js";
2
3
  import { n as collectRuntimeConfigAssignments, r as secretTargetRegistryEntries } from "./secret-contract-Cp0f-YPc.js";
3
4
  import { DEFAULT_ACCOUNT_ID, normalizeOptionalAccountId } from "openclaw/plugin-sdk/account-id";
4
5
  import { createHybridChannelConfigAdapter, createScopedDmSecurityResolver } from "openclaw/plugin-sdk/channel-config-helpers";
5
6
  import { buildChannelOutboundSessionRoute, createChatChannelPlugin } from "openclaw/plugin-sdk/channel-core";
6
- import { bindIngressLifecycleToReplyOptions, createChannelIngressMonitor, createMessageReceiptFromOutboundResults, defineChannelMessageAdapter, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
7
+ import { bindIngressLifecycleToReplyOptions, createAccountStatusSink, createChannelIngressMonitor, createMessageReceiptFromOutboundResults, defineChannelMessageAdapter, waitUntilAbort } from "openclaw/plugin-sdk/channel-outbound";
7
8
  import { createConditionalWarningCollector } from "openclaw/plugin-sdk/channel-policy";
8
9
  import { defineChannelSetupContract } from "openclaw/plugin-sdk/channel-setup";
9
10
  import { createEmptyChannelDirectoryAdapter } from "openclaw/plugin-sdk/directory-runtime";
10
- import { normalizeStringEntries } from "openclaw/plugin-sdk/string-coerce-runtime";
11
+ import { createComputedAccountStatusAdapter, createDefaultChannelRuntimeState } from "openclaw/plugin-sdk/status-helpers";
12
+ import { isRecord, normalizeStringEntries } from "openclaw/plugin-sdk/string-coerce-runtime";
11
13
  import { chunkTextForOutbound, renderMarkdownIRChunksWithinLimit, sanitizeAssistantVisibleText, stripMarkdown } from "openclaw/plugin-sdk/text-chunking";
12
14
  import { createAccountListHelpers } from "openclaw/plugin-sdk/account-helpers";
13
15
  import { DEFAULT_ACCOUNT_ID as DEFAULT_ACCOUNT_ID$1, hasConfiguredAccountValue, resolveAccountEntry } from "openclaw/plugin-sdk/account-resolution";
14
- import { parseStrictInteger } from "openclaw/plugin-sdk/number-runtime";
16
+ import { parseStrictPositiveInteger } from "openclaw/plugin-sdk/number-runtime";
15
17
  import { buildSecretInputSchema, hasConfiguredSecretInput, normalizeResolvedSecretInputString } from "openclaw/plugin-sdk/secret-input";
16
18
  import { AllowFromListSchema, DmPolicySchema, buildChannelConfigSchema, buildMultiAccountChannelSchema, requireOpenAllowFrom } from "openclaw/plugin-sdk/channel-config-schema";
17
19
  import { requireChannelOpenAllowFrom } from "openclaw/plugin-sdk/extension-shared";
18
20
  import { z } from "zod";
19
- import { createFixedWindowRateLimiter, readRequestBodyWithLimit, registerPluginHttpRoute, resolveRequestClientIp } from "openclaw/plugin-sdk/webhook-ingress";
21
+ import { createHash } from "node:crypto";
22
+ import { channelBlockedPatch, channelReadyPatch, channelStoppedPatch } from "openclaw/plugin-sdk/gateway-runtime";
23
+ import { createFixedWindowRateLimiter, isRequestBodyLimitError, registerPluginHttpRoute, resolveRequestClientIp } from "openclaw/plugin-sdk/webhook-ingress";
20
24
  import { runDetachedWebhookWork } from "openclaw/plugin-sdk/webhook-request-guards";
21
25
  import { resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
22
26
  import { createChannelPairingChallengeIssuer } from "openclaw/plugin-sdk/channel-pairing";
23
- import { createHmac } from "node:crypto";
24
- import * as querystring from "node:querystring";
25
- import { readResponseTextPrefix, readResponseWithLimit } from "openclaw/plugin-sdk/response-limit-runtime";
26
- import { safeEqualSecret } from "openclaw/plugin-sdk/security-runtime";
27
- import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
28
- //#region extensions/sms/src/phone.ts
29
- function normalizeSmsPhoneNumber(raw) {
30
- const trimmed = raw.trim().replace(/^(?:sms|twilio-sms):/i, "").trim();
31
- if (!trimmed) return "";
32
- return (trimmed.startsWith("+") ? trimmed : `+${trimmed}`).replace(/[^\d+]/g, "");
33
- }
34
- function looksLikeSmsPhoneNumber(raw) {
35
- const normalized = normalizeSmsPhoneNumber(raw);
36
- return /^\+[1-9]\d{6,14}$/.test(normalized);
37
- }
38
- function normalizeSmsAllowFrom(raw) {
39
- if (raw.trim() === "*") return "*";
40
- return normalizeSmsPhoneNumber(raw).toLowerCase();
41
- }
42
- //#endregion
27
+ import { createChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
28
+ import { PlatformMessageNotDispatchedError, formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
29
+ import { withTimeout } from "openclaw/plugin-sdk/text-utility-runtime";
43
30
  //#region extensions/sms/src/accounts.ts
44
31
  const CHANNEL_ID$3 = "sms";
45
32
  const DEFAULT_WEBHOOK_PATH = "/webhooks/sms";
@@ -53,7 +40,7 @@ function parseList(raw) {
53
40
  }
54
41
  function parseTextChunkLimit(raw) {
55
42
  if (typeof raw === "number" && Number.isSafeInteger(raw) && raw > 0) return raw;
56
- if (typeof raw === "string" && /^\d+$/.test(raw.trim())) return parseStrictInteger(raw.trim()) ?? DEFAULT_TEXT_CHUNK_LIMIT;
43
+ if (typeof raw === "string" && /^\d+$/.test(raw.trim())) return parseStrictPositiveInteger(raw.trim()) ?? DEFAULT_TEXT_CHUNK_LIMIT;
57
44
  return DEFAULT_TEXT_CHUNK_LIMIT;
58
45
  }
59
46
  function firstNonBlankEnv(...values) {
@@ -121,7 +108,7 @@ function inspectSmsAccount(cfg, accountId) {
121
108
  configured,
122
109
  tokenStatus: account.authToken ? "available" : "missing",
123
110
  webhookPath: account.webhookPath,
124
- signatureValidation: account.dangerouslyDisableSignatureValidation || account.publicWebhookUrl ? "configured" : "missing-public-url"
111
+ signatureValidation: account.dangerouslyDisableSignatureValidation ? "configured" : !account.publicWebhookUrl ? "missing-public-url" : parseSmsPublicWebhookUrl(account.publicWebhookUrl) ? "configured" : "invalid-public-url"
125
112
  };
126
113
  }
127
114
  function isSmsAccountConfigured(account) {
@@ -133,6 +120,7 @@ const SecretInputSchema = buildSecretInputSchema();
133
120
  const SmsChannelConfigSchema = buildChannelConfigSchema(buildMultiAccountChannelSchema(z.object({
134
121
  name: z.string().optional(),
135
122
  enabled: z.boolean().optional(),
123
+ configWrites: z.boolean().optional(),
136
124
  accountSid: z.string().optional(),
137
125
  authToken: SecretInputSchema.optional(),
138
126
  fromNumber: z.string().optional(),
@@ -158,7 +146,7 @@ const SmsChannelConfigSchema = buildChannelConfigSchema(buildMultiAccountChannel
158
146
  }), { uiHints: {
159
147
  "": {
160
148
  label: "SMS",
161
- help: "Twilio SMS channel configuration for inbound webhooks and outbound text replies."
149
+ help: "Twilio SMS/MMS channel configuration for inbound webhooks and outbound replies."
162
150
  },
163
151
  accountSid: {
164
152
  label: "Twilio Account SID",
@@ -170,7 +158,7 @@ const SmsChannelConfigSchema = buildChannelConfigSchema(buildMultiAccountChannel
170
158
  },
171
159
  fromNumber: {
172
160
  label: "SMS From Number",
173
- help: "Twilio SMS-capable phone number in E.164 format, for example +15551234567.",
161
+ help: "Twilio SMS-capable phone number in E.164 format; outbound attachments also require MMS capability.",
174
162
  presentation: "phone-number"
175
163
  },
176
164
  messagingServiceSid: {
@@ -184,7 +172,7 @@ const SmsChannelConfigSchema = buildChannelConfigSchema(buildMultiAccountChannel
184
172
  },
185
173
  publicWebhookUrl: {
186
174
  label: "SMS Public Webhook URL",
187
- help: "Public URL configured in Twilio for incoming messages. Must match Twilio's signed URL exactly."
175
+ help: "Public URL configured in Twilio for incoming messages. Must match Twilio's signed URL exactly; outbound MMS also requires this same path to be reachable over HTTPS."
188
176
  },
189
177
  webhookPath: {
190
178
  label: "SMS Webhook Path",
@@ -208,339 +196,273 @@ const SmsChannelConfigSchema = buildChannelConfigSchema(buildMultiAccountChannel
208
196
  }
209
197
  } });
210
198
  //#endregion
211
- //#region extensions/sms/src/twilio.ts
212
- const TWILIO_ACCOUNTS_URL = "https://api.twilio.com/2010-04-01/Accounts";
213
- const TWILIO_MESSAGING_URL = "https://messaging.twilio.com/v1";
214
- const TWILIO_API_HOSTNAME = "api.twilio.com";
215
- const TWILIO_MESSAGING_HOSTNAME = "messaging.twilio.com";
216
- const TWILIO_API_TIMEOUT_MS = 3e4;
217
- const TWILIO_API_SUCCESS_BODY_LIMIT_BYTES = 1 * 1024 * 1024;
218
- const TWILIO_API_ERROR_BODY_LIMIT_BYTES = 8 * 1024;
219
- const TRUNCATED_RESPONSE_SUFFIX = "... [truncated]";
220
- const WEBHOOK_BODY_LIMIT_BYTES = 32 * 1024;
221
- const WEBHOOK_BODY_TIMEOUT_MS = 5e3;
222
- const TWILIO_CHANNEL_ADDRESS_RE = /^([a-z][a-z0-9-]*):(.*)$/i;
223
- function firstString(value) {
224
- if (Array.isArray(value)) return firstString(value[0]);
225
- return typeof value === "string" ? value : "";
226
- }
227
- function firstTrimmedString(value) {
228
- return firstString(value).trim();
229
- }
230
- function firstStringish(value) {
231
- const first = Array.isArray(value) ? value[0] : value;
232
- if (typeof first === "string") return first;
233
- return typeof first === "number" ? String(first) : "";
234
- }
235
- function parseTwilioApiError(text) {
236
- try {
237
- const parsed = JSON.parse(text);
238
- if (!parsed || typeof parsed !== "object") return {};
239
- const record = parsed;
240
- return {
241
- code: typeof record.code === "number" ? record.code : void 0,
242
- message: typeof record.message === "string" ? record.message : void 0
243
- };
244
- } catch {
245
- return {};
246
- }
247
- }
248
- function parseTwilioSuccessPayload(text) {
249
- if (!text.trim()) return {};
250
- try {
251
- const parsed = JSON.parse(text);
252
- if (!parsed || typeof parsed !== "object") throw new Error("Twilio SMS send returned malformed JSON.");
253
- const record = parsed;
254
- return {
255
- sid: typeof record.sid === "string" ? record.sid : void 0,
256
- to: typeof record.to === "string" ? record.to : void 0,
257
- from: typeof record.from === "string" ? record.from : void 0,
258
- status: typeof record.status === "string" ? record.status : void 0
259
- };
260
- } catch (cause) {
261
- if (cause instanceof Error && cause.message === "Twilio SMS send returned malformed JSON.") throw cause;
262
- throw new Error("Twilio SMS send returned malformed JSON.", { cause });
199
+ //#region extensions/sms/src/delivery-observations.ts
200
+ const DELIVERY_NAMESPACE = "twilio-delivery-observations-v1";
201
+ const DELIVERY_RETENTION_MS = 720 * 60 * 60 * 1e3;
202
+ const DELIVERY_MAX_MESSAGES = 5e3;
203
+ const DELIVERY_STATUS_RANK = {
204
+ accepted: 10,
205
+ scheduled: 20,
206
+ queued: 30,
207
+ sending: 40,
208
+ sent: 50
209
+ };
210
+ const TERMINAL_DELIVERY_STATUSES = /* @__PURE__ */ new Set([
211
+ "delivered",
212
+ "undelivered",
213
+ "failed",
214
+ "canceled"
215
+ ]);
216
+ const INBOUND_MESSAGE_STATUSES = /* @__PURE__ */ new Set(["receiving", "received"]);
217
+ let deliveryStore;
218
+ let deliveryStoreRuntime;
219
+ function firstTrimmed(form, key) {
220
+ return form[key]?.trim() ?? "";
221
+ }
222
+ function resolveMessageSid(form) {
223
+ return firstTrimmed(form, "MessageSid") || firstTrimmed(form, "SmsSid") || firstTrimmed(form, "SmsMessageSid");
224
+ }
225
+ function normalizeDeliveryStatus(rawStatus) {
226
+ const status = rawStatus.trim().toLowerCase();
227
+ return INBOUND_MESSAGE_STATUSES.has(status) ? "" : status;
228
+ }
229
+ function resolveDeliveryStatus(form) {
230
+ return normalizeDeliveryStatus(firstTrimmed(form, "MessageStatus") || firstTrimmed(form, "SmsStatus"));
231
+ }
232
+ function hashAccountSid(accountSid) {
233
+ return createHash("sha256").update(accountSid).digest("hex");
234
+ }
235
+ function fingerprintObservation(params) {
236
+ return createHash("sha256").update(JSON.stringify([
237
+ params.source,
238
+ params.messageSid,
239
+ params.status,
240
+ params.errorCode ?? "",
241
+ params.rawDlrDoneDate ?? ""
242
+ ])).digest("hex");
243
+ }
244
+ function deliveryRecordKey(params) {
245
+ return createHash("sha256").update(`${params.accountId}\n${params.accountSidHash}\n${params.messageSid}`).digest("hex");
246
+ }
247
+ function openDeliveryStore() {
248
+ const runtime = getSmsRuntime();
249
+ if (!deliveryStore || deliveryStoreRuntime !== runtime) {
250
+ deliveryStoreRuntime = runtime;
251
+ deliveryStore = runtime.state.openKeyedStore({
252
+ namespace: DELIVERY_NAMESPACE,
253
+ maxEntries: DELIVERY_MAX_MESSAGES,
254
+ overflowPolicy: "evict-oldest",
255
+ defaultTtlMs: DELIVERY_RETENTION_MS
256
+ });
263
257
  }
258
+ return deliveryStore;
264
259
  }
265
- function requestSearch(req) {
266
- try {
267
- return new URL(req.url ?? "/", "http://localhost").search;
268
- } catch {
269
- return "";
270
- }
260
+ function isTwilioDeliveryStatusForm(form) {
261
+ return Boolean(resolveDeliveryStatus(form));
271
262
  }
272
- function stripUrlFragment(url) {
273
- const hashIndex = url.indexOf("#");
274
- return hashIndex === -1 ? url : url.slice(0, hashIndex);
275
- }
276
- function resolveTwilioWebhookSignatureUrl(params) {
277
- const signatureBaseUrl = stripUrlFragment(params.publicWebhookUrl);
278
- if (signatureBaseUrl.includes("?")) return signatureBaseUrl;
279
- const search = requestSearch(params.req);
280
- if (!search) return signatureBaseUrl;
281
- return `${signatureBaseUrl}${search}`;
282
- }
283
- var TwilioSmsApiError = class extends Error {
284
- constructor(httpStatus, responseText, operation = "send") {
285
- const parsed = parseTwilioApiError(responseText);
286
- const detail = parsed.message ?? (responseText || "unknown");
287
- super(`Twilio SMS ${operation} failed (${httpStatus}): ${detail}`);
288
- this.name = "TwilioSmsApiError";
289
- this.httpStatus = httpStatus;
290
- this.responseText = responseText;
291
- this.twilioCode = parsed.code;
292
- }
293
- };
294
- function parseTwilioFormBody(body) {
295
- const parsed = querystring.parse(body);
296
- const out = {};
297
- for (const [key, value] of Object.entries(parsed)) out[key] = firstString(value);
298
- return out;
299
- }
300
- function computeTwilioSignature(params) {
301
- const data = params.url + Object.keys(params.form).toSorted().map((key) => `${key}${params.form[key] ?? ""}`).join("");
302
- return createHmac("sha1", params.authToken).update(data).digest("base64");
303
- }
304
- function verifyTwilioSignature(params) {
305
- if (!params.signature || !params.url || !params.authToken) return false;
306
- return safeEqualSecret(params.signature, computeTwilioSignature({
307
- url: params.url,
308
- authToken: params.authToken,
309
- form: params.form
310
- }));
311
- }
312
- function parseTwilioInboundFrom(raw) {
313
- const trimmed = raw.trim();
314
- if (!trimmed) return null;
315
- const channelAddress = trimmed.match(TWILIO_CHANNEL_ADDRESS_RE);
316
- const kind = channelAddress?.[1]?.toLowerCase();
317
- if (kind && kind !== "rcs") return null;
318
- const phoneNumber = normalizeSmsPhoneNumber(channelAddress?.[2] ?? trimmed);
319
- if (!looksLikeSmsPhoneNumber(phoneNumber)) return null;
320
- return phoneNumber;
321
- }
322
- function resolveTwilioInboundSender(form) {
323
- return parseTwilioInboundFrom(firstTrimmedString(form.From)) ?? "";
324
- }
325
- function buildTwilioInboundMessage(form) {
326
- const from = resolveTwilioInboundSender(form);
327
- const to = firstTrimmedString(form.To);
328
- const body = firstString(form.Body);
329
- const accountSid = firstTrimmedString(form.AccountSid);
330
- const messageSid = resolveTwilioMessageSid(form);
331
- if (!from || !to || !body || !messageSid) return null;
263
+ function parseSmsDeliveryObservation(form, nowMs = Date.now()) {
264
+ const messageSid = resolveMessageSid(form);
265
+ const status = resolveDeliveryStatus(form);
266
+ if (!messageSid || !status) return null;
267
+ const errorCode = firstTrimmed(form, "ErrorCode");
268
+ const rawDlrDoneDate = firstTrimmed(form, "RawDlrDoneDate");
332
269
  return {
333
- accountSid,
334
- from,
335
- to,
336
- body,
337
- messageSid
270
+ messageSid,
271
+ observation: {
272
+ source: "callback",
273
+ fingerprint: fingerprintObservation({
274
+ source: "callback",
275
+ messageSid,
276
+ status,
277
+ ...errorCode ? { errorCode } : {},
278
+ ...rawDlrDoneDate ? { rawDlrDoneDate } : {}
279
+ }),
280
+ status,
281
+ observedAt: nowMs,
282
+ ...errorCode ? { errorCode } : {},
283
+ ...rawDlrDoneDate ? { rawDlrDoneDate } : {}
284
+ }
338
285
  };
339
286
  }
340
- function resolveTwilioMessageSid(form) {
341
- return firstTrimmedString(form.MessageSid) || firstTrimmedString(form.SmsSid) || firstTrimmedString(form.SmsMessageSid);
342
- }
343
- async function readTwilioWebhookForm(req) {
344
- return parseTwilioFormBody(await readRequestBodyWithLimit(req, {
345
- maxBytes: WEBHOOK_BODY_LIMIT_BYTES,
346
- timeoutMs: WEBHOOK_BODY_TIMEOUT_MS
347
- }));
348
- }
349
- function respondTwiml(res, statusCode, body = "") {
350
- res.statusCode = statusCode;
351
- res.setHeader("content-type", "text/xml; charset=utf-8");
352
- res.end(body || "<Response></Response>");
353
- }
354
- function twilioApiUrl(accountSid, path, query) {
355
- const normalizedPath = path.startsWith("/") ? path : `/${path}`;
356
- const url = new URL(`${TWILIO_ACCOUNTS_URL}/${encodeURIComponent(accountSid)}${normalizedPath}`);
357
- if (query) url.search = query.toString();
358
- return url.toString();
359
- }
360
- function twilioMessagingUrl(path, query) {
361
- const normalizedPath = path.startsWith("/") ? path : `/${path}`;
362
- const url = new URL(`${TWILIO_MESSAGING_URL}${normalizedPath}`);
363
- if (query) url.search = query.toString();
364
- return url.toString();
365
- }
366
- function basicAuthHeader(account) {
367
- return `Basic ${Buffer.from(`${account.accountSid}:${account.authToken}`).toString("base64")}`;
368
- }
369
- function appendTruncatedResponseSuffix(text) {
370
- return `${text.trimEnd()}${TRUNCATED_RESPONSE_SUFFIX}`;
371
- }
372
- async function readTwilioApiResponseText(response) {
373
- const maxBytes = response.ok ? TWILIO_API_SUCCESS_BODY_LIMIT_BYTES : TWILIO_API_ERROR_BODY_LIMIT_BYTES;
374
- if (!response.ok) {
375
- const prefix = await readResponseTextPrefix(response, maxBytes);
376
- return prefix.truncated ? appendTruncatedResponseSuffix(prefix.text) : prefix.text;
377
- }
378
- const body = await readResponseWithLimit(response, maxBytes, { onOverflow: ({ size, maxBytes: limit }) => /* @__PURE__ */ new Error(`Twilio SMS API response body too large: ${size} bytes (limit: ${limit} bytes)`) });
379
- return new TextDecoder().decode(body);
380
- }
381
- function normalizeRequestHeaders(headers) {
382
- if (!headers) return {};
383
- if (headers instanceof Headers) return Object.fromEntries(headers.entries());
384
- if (Array.isArray(headers)) return Object.fromEntries(headers.map(([key, value]) => [key, value]));
385
- return Object.fromEntries(Object.entries(headers));
386
- }
387
- async function requestTwilioApi(params) {
388
- const init = {
389
- ...params.init,
390
- headers: {
391
- ...normalizeRequestHeaders(params.init?.headers),
392
- authorization: basicAuthHeader(params.account)
393
- }
287
+ function reduceDeliveryStatus(current, observation) {
288
+ if (!current) return {
289
+ status: observation.status,
290
+ ...observation.errorCode ? { errorCode: observation.errorCode } : {}
394
291
  };
395
- if (params.fetchImpl) {
396
- const response = await params.fetchImpl(params.url, init);
292
+ if (current.status === "conflicted") return {
293
+ status: current.status,
294
+ ...current.errorCode ? { errorCode: current.errorCode } : {},
295
+ conflict: true
296
+ };
297
+ if (current.status === observation.status) {
298
+ const errorCode = current.errorCode ?? observation.errorCode;
397
299
  return {
398
- ok: response.ok,
399
- status: response.status,
400
- text: await readTwilioApiResponseText(response)
300
+ status: current.status,
301
+ ...errorCode ? { errorCode } : {},
302
+ ...current.conflict ? { conflict: true } : {}
401
303
  };
402
304
  }
403
- const guarded = await fetchWithSsrFGuard({
404
- url: params.url,
405
- init,
406
- auditContext: "sms-twilio-api",
407
- policy: { allowedHostnames: [params.allowedHostname] },
408
- requireHttps: true,
409
- timeoutMs: params.timeoutMs ?? TWILIO_API_TIMEOUT_MS
410
- });
411
- try {
305
+ const currentTerminal = TERMINAL_DELIVERY_STATUSES.has(current.status);
306
+ const nextTerminal = TERMINAL_DELIVERY_STATUSES.has(observation.status);
307
+ if (currentTerminal && nextTerminal && current.status !== observation.status) {
308
+ const errorCode = observation.errorCode ?? current.errorCode;
412
309
  return {
413
- ok: guarded.response.ok,
414
- status: guarded.response.status,
415
- text: await readTwilioApiResponseText(guarded.response)
310
+ status: "conflicted",
311
+ ...errorCode ? { errorCode } : {},
312
+ conflict: true
416
313
  };
417
- } finally {
418
- await guarded.release();
419
314
  }
420
- }
421
- function parseTwilioIncomingPhoneNumber(record) {
315
+ if (currentTerminal) return {
316
+ status: current.status,
317
+ ...current.errorCode ? { errorCode: current.errorCode } : {},
318
+ ...current.conflict ? { conflict: true } : {}
319
+ };
320
+ if (nextTerminal) return {
321
+ status: observation.status,
322
+ ...observation.errorCode ? { errorCode: observation.errorCode } : {}
323
+ };
324
+ const currentRank = DELIVERY_STATUS_RANK[current.status] ?? -1;
325
+ if ((DELIVERY_STATUS_RANK[observation.status] ?? -1) > currentRank) return {
326
+ status: observation.status,
327
+ ...observation.errorCode ? { errorCode: observation.errorCode } : {}
328
+ };
422
329
  return {
423
- sid: firstTrimmedString(record.sid),
424
- phoneNumber: firstTrimmedString(record.phone_number ?? record.phoneNumber),
425
- smsUrl: firstTrimmedString(record.sms_url ?? record.smsUrl),
426
- smsMethod: firstTrimmedString(record.sms_method ?? record.smsMethod),
427
- voiceUrl: firstTrimmedString(record.voice_url ?? record.voiceUrl)
330
+ status: current.status,
331
+ ...current.errorCode ? { errorCode: current.errorCode } : {},
332
+ ...current.conflict ? { conflict: true } : {}
428
333
  };
429
334
  }
430
- function parseTwilioMessageLogEntry(record) {
335
+ function mergeSmsDeliveryObservation(params) {
336
+ if (params.current?.observations.some((existing) => existing.fingerprint === params.observation.fingerprint)) return;
337
+ const reduced = reduceDeliveryStatus(params.current, params.observation);
431
338
  return {
432
- sid: firstTrimmedString(record.sid),
433
- direction: firstTrimmedString(record.direction),
434
- status: firstTrimmedString(record.status),
435
- to: firstTrimmedString(record.to),
436
- from: firstTrimmedString(record.from),
437
- errorCode: firstStringish(record.error_code ?? record.errorCode).trim(),
438
- body: firstString(record.body),
439
- dateCreated: firstTrimmedString(record.date_created ?? record.dateCreated),
440
- dateSent: firstTrimmedString(record.date_sent ?? record.dateSent)
339
+ accountId: params.accountId,
340
+ accountSidHash: params.accountSidHash,
341
+ messageSid: params.messageSid,
342
+ status: reduced.status,
343
+ firstObservedAt: params.current?.firstObservedAt ?? params.observation.observedAt,
344
+ lastObservedAt: params.observation.observedAt,
345
+ ...reduced.errorCode ? { errorCode: reduced.errorCode } : {},
346
+ ...reduced.conflict ? { conflict: true } : {},
347
+ observations: [...params.current?.observations ?? [], params.observation].slice(-20)
441
348
  };
442
349
  }
443
- function parseTwilioMessagingService(record) {
350
+ async function recordSmsDeliveryObservation(params) {
351
+ if (!params.store.update) throw new Error("SMS delivery observations require atomic plugin state updates.");
352
+ const accountSidHash = hashAccountSid(params.account.accountSid);
353
+ const key = deliveryRecordKey({
354
+ accountId: params.account.accountId,
355
+ accountSidHash,
356
+ messageSid: params.messageSid
357
+ });
358
+ let record;
359
+ let duplicate = false;
360
+ await params.store.update(key, (current) => {
361
+ const next = mergeSmsDeliveryObservation({
362
+ accountId: params.account.accountId,
363
+ accountSidHash,
364
+ messageSid: params.messageSid,
365
+ current,
366
+ observation: params.observation
367
+ });
368
+ if (!next) {
369
+ duplicate = true;
370
+ record = current;
371
+ return;
372
+ }
373
+ record = next;
374
+ return next;
375
+ });
376
+ if (!record) throw new Error("SMS delivery observation was not persisted.");
444
377
  return {
445
- sid: firstTrimmedString(record.sid),
446
- inboundRequestUrl: firstTrimmedString(record.inbound_request_url ?? record.inboundRequestUrl),
447
- inboundMethod: firstTrimmedString(record.inbound_method ?? record.inboundMethod),
448
- useInboundWebhookOnNumber: Boolean(record.use_inbound_webhook_on_number ?? record.useInboundWebhookOnNumber)
378
+ duplicate,
379
+ record
449
380
  };
450
381
  }
451
- function parseTwilioListPayload(text, key, parseEntry) {
452
- if (!text.trim()) return [];
453
- let parsed;
454
- try {
455
- parsed = JSON.parse(text);
456
- } catch {
457
- return [];
458
- }
459
- if (!parsed || typeof parsed !== "object") return [];
460
- const items = parsed[key];
461
- if (!Array.isArray(items)) return [];
462
- return items.filter((item) => Boolean(item && typeof item === "object" && !Array.isArray(item))).map(parseEntry);
463
- }
464
- async function listTwilioIncomingPhoneNumbers(params) {
465
- const query = new URLSearchParams();
466
- if (params.phoneNumber) query.set("PhoneNumber", params.phoneNumber);
467
- const response = await requestTwilioApi({
468
- account: params.account,
469
- url: twilioApiUrl(params.account.accountSid, "/IncomingPhoneNumbers.json", query),
470
- allowedHostname: TWILIO_API_HOSTNAME,
471
- fetchImpl: params.fetchImpl,
472
- timeoutMs: params.timeoutMs
473
- });
474
- if (!response.ok) throw new TwilioSmsApiError(response.status, response.text, "phone-number lookup");
475
- return parseTwilioListPayload(response.text, "incoming_phone_numbers", parseTwilioIncomingPhoneNumber);
382
+ function createSmsDeliveryRecorder(store = openDeliveryStore()) {
383
+ return { async record({ account, form }) {
384
+ const parsed = parseSmsDeliveryObservation(form);
385
+ if (!parsed) throw new Error("Invalid Twilio delivery status callback.");
386
+ return await recordSmsDeliveryObservation({
387
+ account,
388
+ messageSid: parsed.messageSid,
389
+ observation: parsed.observation,
390
+ store
391
+ });
392
+ } };
476
393
  }
477
- async function retrieveTwilioMessagingService(params) {
478
- const response = await requestTwilioApi({
394
+ async function recordInitialSmsDeliveryResult(params) {
395
+ const messageSid = params.result.sid.trim();
396
+ const status = normalizeDeliveryStatus(params.result.status ?? "");
397
+ if (!messageSid || !status) return null;
398
+ return await recordSmsDeliveryObservation({
479
399
  account: params.account,
480
- url: twilioMessagingUrl(`/Services/${encodeURIComponent(params.serviceSid)}`),
481
- allowedHostname: TWILIO_MESSAGING_HOSTNAME,
482
- fetchImpl: params.fetchImpl,
483
- timeoutMs: params.timeoutMs
484
- });
485
- if (!response.ok) throw new TwilioSmsApiError(response.status, response.text, "messaging-service lookup");
486
- let parsed;
487
- try {
488
- parsed = JSON.parse(response.text);
489
- } catch {
490
- throw new Error("Twilio Messaging Service lookup returned malformed JSON.");
491
- }
492
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Twilio Messaging Service lookup returned malformed JSON.");
493
- return parseTwilioMessagingService(parsed);
494
- }
495
- async function listTwilioMessages(params) {
496
- const query = new URLSearchParams();
497
- if (params.to) query.set("To", params.to);
498
- if (params.from) query.set("From", params.from);
499
- query.set("PageSize", String(params.pageSize ?? 5));
500
- const response = await requestTwilioApi({
501
- account: params.account,
502
- url: twilioApiUrl(params.account.accountSid, "/Messages.json", query),
503
- allowedHostname: TWILIO_API_HOSTNAME,
504
- fetchImpl: params.fetchImpl,
505
- timeoutMs: params.timeoutMs
400
+ messageSid,
401
+ observation: {
402
+ source: "api-response",
403
+ fingerprint: fingerprintObservation({
404
+ source: "api-response",
405
+ messageSid,
406
+ status
407
+ }),
408
+ status,
409
+ observedAt: params.nowMs ?? Date.now()
410
+ },
411
+ store: params.store ?? openDeliveryStore()
506
412
  });
507
- if (!response.ok) throw new TwilioSmsApiError(response.status, response.text, "message lookup");
508
- return parseTwilioListPayload(response.text, "messages", parseTwilioMessageLogEntry);
509
- }
510
- async function sendSmsViaTwilio(params) {
511
- if (!params.account.fromNumber && !params.account.messagingServiceSid) throw new Error("Twilio SMS send requires fromNumber or messagingServiceSid.");
512
- const body = new URLSearchParams({
513
- To: params.to,
514
- Body: params.text
413
+ }
414
+ async function listRecentSmsDeliveryRecords(account, limit = 1, store = openDeliveryStore()) {
415
+ if (limit <= 0) return [];
416
+ const accountSidHash = hashAccountSid(account.accountSid);
417
+ 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);
418
+ }
419
+ //#endregion
420
+ //#region extensions/sms/src/send.ts
421
+ const SMS_ASSISTANT_TRANSCRIPT_ROLE_PREFIX = "[assistant-authored transcript] ";
422
+ function createSmsMessageReceipt(params) {
423
+ const receipt = createMessageReceiptFromOutboundResults({
424
+ results: params.results.map((result) => ({
425
+ channel: "sms",
426
+ messageId: result.sid,
427
+ chatId: result.to,
428
+ toJid: result.to,
429
+ conversationId: result.to,
430
+ meta: {
431
+ ...result.from ? { from: result.from } : {},
432
+ ...result.status ? { status: result.status } : {}
433
+ }
434
+ })),
435
+ threadId: params.results[0]?.to,
436
+ kind: params.kind
515
437
  });
516
- if (params.account.fromNumber) body.set("From", params.account.fromNumber);
517
- else body.set("MessagingServiceSid", params.account.messagingServiceSid);
518
- const init = {
519
- method: "POST",
520
- headers: { "content-type": "application/x-www-form-urlencoded" },
521
- body
522
- };
523
- const response = await requestTwilioApi({
524
- account: params.account,
525
- url: twilioApiUrl(params.account.accountSid, "/Messages.json"),
526
- allowedHostname: TWILIO_API_HOSTNAME,
527
- init,
528
- fetchImpl: params.fetchImpl
438
+ if (params.kind === "media") receipt.parts = receipt.parts.map((part, index) => index === 0 ? part : {
439
+ ...part,
440
+ kind: "text"
529
441
  });
530
- if (!response.ok) throw new TwilioSmsApiError(response.status, response.text);
531
- const payload = parseTwilioSuccessPayload(response.text);
532
- const sid = payload.sid?.trim();
533
- if (!sid) throw new Error("Twilio SMS send response did not include a Message SID.");
442
+ return receipt;
443
+ }
444
+ function createSmsDeliveryProgressResult(result, kind) {
534
445
  return {
535
- sid,
536
- to: payload.to?.trim() || params.to,
537
- ...payload.from?.trim() ? { from: payload.from.trim() } : {},
538
- ...payload.status?.trim() ? { status: payload.status.trim() } : {}
446
+ channel: "sms",
447
+ messageId: result.sid,
448
+ chatId: result.to,
449
+ receipt: createSmsMessageReceipt({
450
+ results: [result],
451
+ kind
452
+ })
539
453
  };
540
454
  }
541
- //#endregion
542
- //#region extensions/sms/src/send.ts
543
- const SMS_ASSISTANT_TRANSCRIPT_ROLE_PREFIX = "[assistant-authored transcript] ";
455
+ function throwSmsPartialDeliveryError(error, results, kind) {
456
+ if (results.length === 0) throw error;
457
+ throw createChannelPartialDeliveryError(error, {
458
+ messageIds: results.map((result) => result.sid),
459
+ receipt: createSmsMessageReceipt({
460
+ results,
461
+ kind
462
+ }),
463
+ visibleReplySent: true
464
+ });
465
+ }
544
466
  function toSmsPlainText(text) {
545
467
  return stripMarkdown(sanitizeAssistantVisibleText(text), {
546
468
  assistantTranscriptRoleHeaders: true,
@@ -561,17 +483,132 @@ function chunkSmsPlainText(text, limit) {
561
483
  measureRendered: (rendered) => rendered.length
562
484
  }).map(({ rendered }) => rendered).filter(Boolean);
563
485
  }
564
- async function sendSmsTextChunks(params) {
486
+ function prepareSmsTextChunks(params) {
565
487
  const text = toSmsPlainText(params.text);
566
- if (!text) throw new Error("SMS send requires non-empty text.");
567
- const chunks = chunkSmsPlainText(text, params.account.textChunkLimit);
568
- const sendChunks = chunks.length ? chunks : [text];
488
+ if (!text) return [];
489
+ return chunkSmsPlainText(text, Math.min(params.configuredLimit, TWILIO_MESSAGE_BODY_MAX_LENGTH));
490
+ }
491
+ async function sendSmsProviderMessage(params) {
492
+ let platformDispatchStarted = false;
493
+ let result;
494
+ try {
495
+ result = await sendSmsViaTwilio({
496
+ account: params.account,
497
+ to: params.to,
498
+ ...params.text !== void 0 ? { text: params.text } : {},
499
+ ...params.mediaUrls !== void 0 ? { mediaUrls: params.mediaUrls } : {},
500
+ onPlatformSendDispatch: async () => {
501
+ await params.onPlatformSendDispatch?.();
502
+ platformDispatchStarted = true;
503
+ }
504
+ });
505
+ } catch (error) {
506
+ if (platformDispatchStarted || error instanceof PlatformMessageNotDispatchedError) throw error;
507
+ throw new PlatformMessageNotDispatchedError(`SMS send failed before Twilio dispatch: ${formatErrorMessage(error)}`, { cause: error });
508
+ }
509
+ await recordInitialDeliveryBestEffort(params.account, result);
510
+ return result;
511
+ }
512
+ function logInitialDeliveryPersistenceFailure(result, error) {
513
+ try {
514
+ getSmsRuntime().logging.getChildLogger({
515
+ plugin: "sms",
516
+ feature: "delivery-status"
517
+ }).warn("SMS delivery initial state could not be persisted.", {
518
+ messageSid: result.sid,
519
+ errorType: error instanceof Error ? error.name : typeof error
520
+ });
521
+ } catch {}
522
+ }
523
+ async function recordInitialDeliveryBestEffort(account, result) {
524
+ try {
525
+ await recordInitialSmsDeliveryResult({
526
+ account,
527
+ result
528
+ });
529
+ } catch (error) {
530
+ logInitialDeliveryPersistenceFailure(result, error);
531
+ }
532
+ }
533
+ async function sendSmsTextChunks(params) {
534
+ const chunks = prepareSmsTextChunks({
535
+ text: params.text,
536
+ configuredLimit: params.account.textChunkLimit
537
+ });
538
+ if (chunks.length === 0) throw new Error("SMS send requires non-empty text.");
569
539
  const results = [];
570
- for (const textLocal of sendChunks) results.push(await sendSmsViaTwilio({
571
- account: params.account,
572
- to: params.to,
573
- text: textLocal
574
- }));
540
+ try {
541
+ for (const text of chunks) {
542
+ const result = await sendSmsProviderMessage({
543
+ account: params.account,
544
+ to: params.to,
545
+ text,
546
+ onPlatformSendDispatch: params.onPlatformSendDispatch
547
+ });
548
+ results.push(result);
549
+ await params.onDeliveryResult?.(createSmsDeliveryProgressResult(result, "text"));
550
+ }
551
+ } catch (error) {
552
+ throwSmsPartialDeliveryError(error, results, "text");
553
+ }
554
+ return results;
555
+ }
556
+ async function prepareSmsMediaAttempt(params) {
557
+ if (!params.mediaUrl) throw new Error("MMS send requires mediaUrl.");
558
+ const [caption, ...remainingChunks] = prepareSmsTextChunks({
559
+ text: params.text,
560
+ configuredLimit: params.account.textChunkLimit
561
+ });
562
+ let hostedMedia;
563
+ try {
564
+ const { prepareHostedSmsMedia } = await import("./media-C_8jX0L8.js");
565
+ const prepared = await prepareHostedSmsMedia({
566
+ account: params.account,
567
+ mediaUrl: params.mediaUrl,
568
+ mediaAccess: params.mediaAccess,
569
+ mediaLocalRoots: params.mediaLocalRoots,
570
+ mediaReadFile: params.mediaReadFile,
571
+ captionByteLength: Buffer.byteLength(caption ?? "", "utf8")
572
+ });
573
+ hostedMedia = {
574
+ hostedMediaUrl: prepared.url,
575
+ cleanupHostedMedia: prepared.cleanup
576
+ };
577
+ } catch (error) {
578
+ if (error instanceof PlatformMessageNotDispatchedError) throw error;
579
+ throw new PlatformMessageNotDispatchedError(`SMS media preparation failed before Twilio dispatch: ${formatErrorMessage(error)}`, { cause: error });
580
+ }
581
+ return {
582
+ ...hostedMedia,
583
+ ...caption ? { caption } : {},
584
+ remainingChunks
585
+ };
586
+ }
587
+ async function sendPreparedSmsMediaAttempt(params) {
588
+ const results = [];
589
+ try {
590
+ const mediaResult = await sendSmsProviderMessage({
591
+ account: params.account,
592
+ to: params.to,
593
+ ...params.attempt.caption ? { text: params.attempt.caption } : {},
594
+ mediaUrls: [params.attempt.hostedMediaUrl],
595
+ onPlatformSendDispatch: params.onPlatformSendDispatch
596
+ });
597
+ results.push(mediaResult);
598
+ await params.onDeliveryResult?.(createSmsDeliveryProgressResult(mediaResult, "media"));
599
+ for (const text of params.attempt.remainingChunks) {
600
+ const result = await sendSmsProviderMessage({
601
+ account: params.account,
602
+ to: params.to,
603
+ text,
604
+ onPlatformSendDispatch: params.onPlatformSendDispatch
605
+ });
606
+ results.push(result);
607
+ await params.onDeliveryResult?.(createSmsDeliveryProgressResult(result, "text"));
608
+ }
609
+ } catch (error) {
610
+ throwSmsPartialDeliveryError(error, results, "media");
611
+ }
575
612
  return results;
576
613
  }
577
614
  //#endregion
@@ -594,8 +631,9 @@ async function authorizeSmsSender(params) {
594
631
  subject: { stableId: params.from },
595
632
  conversation: {
596
633
  kind: "direct",
597
- id: "direct"
634
+ id: params.from
598
635
  },
636
+ contextBinding: params.contextBinding,
599
637
  event: { mayPair: true },
600
638
  dmPolicy: params.account.dmPolicy,
601
639
  allowFrom: params.account.allowFrom,
@@ -634,7 +672,7 @@ async function issueSmsPairingChallenge(params) {
634
672
  }
635
673
  async function dispatchSmsInboundEvent(params) {
636
674
  const from = normalizeSmsPhoneNumber(params.msg.from);
637
- const auth = await authorizeSmsSender({
675
+ let auth = await authorizeSmsSender({
638
676
  cfg: params.cfg,
639
677
  account: params.account,
640
678
  channelRuntime: params.channelRuntime,
@@ -654,101 +692,162 @@ async function dispatchSmsInboundEvent(params) {
654
692
  params.log?.warn?.(`SMS sender ${from} is not authorized`);
655
693
  return;
656
694
  }
657
- const route = params.channelRuntime.routing.resolveAgentRoute({
658
- cfg: params.cfg,
659
- channel: CHANNEL_ID$2,
660
- accountId: params.account.accountId,
661
- peer: {
662
- kind: "direct",
663
- id: from
695
+ const materialized = params.msg.media.length > 0 || (params.msg.unavailableMediaCount ?? 0) > 0 ? await (await import("./media-C_8jX0L8.js")).materializeSmsInboundMedia({
696
+ account: params.account,
697
+ msg: params.msg,
698
+ mediaRuntime: params.channelRuntime,
699
+ abortSignal: params.turnAdoptionLifecycle?.abortSignal,
700
+ log: params.log
701
+ }) : {
702
+ body: params.msg.body,
703
+ media: [],
704
+ cleanup: async () => void 0
705
+ };
706
+ let adoptionState = "pending";
707
+ try {
708
+ const turnAdoptionLifecycle = materialized.media.length > 0 && params.turnAdoptionLifecycle ? {
709
+ ...params.turnAdoptionLifecycle,
710
+ onAdopted: async () => {
711
+ try {
712
+ await params.turnAdoptionLifecycle?.onAdopted();
713
+ adoptionState = "adopted";
714
+ } catch (error) {
715
+ await materialized.cleanup();
716
+ throw error;
717
+ }
718
+ },
719
+ onDeferred: () => {
720
+ const deferred = params.turnAdoptionLifecycle?.onDeferred?.();
721
+ if (deferred !== false) adoptionState = "deferred";
722
+ return deferred;
723
+ },
724
+ onAbandoned: () => {
725
+ adoptionState = "abandoned";
726
+ materialized.cleanup().then(() => params.turnAdoptionLifecycle?.onAbandoned?.()).catch((error) => {
727
+ params.log?.warn?.(`Failed to abandon Twilio MMS ingress ${params.msg.messageSid}: ${String(error)}`);
728
+ });
729
+ }
730
+ } : params.turnAdoptionLifecycle;
731
+ const route = params.channelRuntime.routing.resolveAgentRoute({
732
+ cfg: params.cfg,
733
+ channel: CHANNEL_ID$2,
734
+ accountId: params.account.accountId,
735
+ peer: {
736
+ kind: "direct",
737
+ id: from
738
+ }
739
+ });
740
+ const sessionKey = route.sessionKey;
741
+ auth = await authorizeSmsSender({
742
+ cfg: params.cfg,
743
+ account: params.account,
744
+ channelRuntime: params.channelRuntime,
745
+ from,
746
+ rawBody: params.msg.body,
747
+ contextBinding: {
748
+ agentId: route.agentId,
749
+ sessionKey,
750
+ messageId: params.msg.messageSid,
751
+ inboundEventKind: "user_request"
752
+ }
753
+ });
754
+ if (!auth.senderAccess.allowed) {
755
+ params.log?.warn?.(`SMS sender ${from} authorization changed before dispatch`);
756
+ return;
664
757
  }
665
- });
666
- const sessionKey = route.sessionKey;
667
- const commandRequested = auth.commandAccess.requested;
668
- const commandAuthorized = auth.commandAccess.authorized;
669
- const isTextCommand = params.channelRuntime.commands.isControlCommandMessage(params.msg.body, params.cfg);
670
- await params.channelRuntime.inbound.run({
671
- channel: CHANNEL_ID$2,
672
- accountId: params.account.accountId,
673
- raw: params.msg,
674
- ...params.turnAdoptionLifecycle ? { turnAdoptionLifecycle: params.turnAdoptionLifecycle } : {},
675
- adapter: {
676
- ingest: (msg) => ({
677
- id: msg.messageSid,
678
- timestamp: params.receivedAt,
679
- rawText: msg.body,
680
- textForAgent: msg.body,
681
- textForCommands: msg.body,
682
- raw: msg
683
- }),
684
- resolveTurn: async (input) => {
685
- const ctxPayload = params.channelRuntime.inbound.buildContext({
686
- channel: CHANNEL_ID$2,
687
- accountId: params.account.accountId,
688
- timestamp: input.timestamp,
689
- from: `sms:${from}`,
690
- sender: {
691
- id: from,
692
- name: from
693
- },
694
- conversation: {
695
- kind: "direct",
696
- id: from,
697
- label: from
698
- },
699
- route: {
700
- agentId: route.agentId,
758
+ const commandRequested = auth.commandAccess.requested;
759
+ const commandAuthorized = auth.commandAccess.authorized;
760
+ const isTextCommand = params.channelRuntime.commands.isControlCommandMessage(params.msg.body, params.cfg);
761
+ await params.channelRuntime.inbound.run({
762
+ channel: CHANNEL_ID$2,
763
+ accountId: params.account.accountId,
764
+ raw: params.msg,
765
+ ...turnAdoptionLifecycle ? { turnAdoptionLifecycle } : {},
766
+ adapter: {
767
+ ingest: (msg) => ({
768
+ id: msg.messageSid,
769
+ timestamp: params.receivedAt,
770
+ rawText: msg.body,
771
+ textForAgent: materialized.body,
772
+ textForCommands: msg.body,
773
+ raw: msg
774
+ }),
775
+ resolveTurn: async (input) => {
776
+ const ctxPayload = params.channelRuntime.inbound.buildContext({
777
+ channelIngress: auth,
778
+ channel: CHANNEL_ID$2,
701
779
  accountId: params.account.accountId,
702
- routeSessionKey: sessionKey,
703
- dispatchSessionKey: sessionKey
704
- },
705
- reply: { to: `sms:${from}` },
706
- message: {
707
- rawBody: input.rawText,
708
- commandBody: input.textForCommands,
709
- bodyForAgent: input.textForAgent
710
- },
711
- access: commandRequested ? { commands: { authorized: commandAuthorized } } : void 0,
712
- command: isTextCommand ? {
713
- kind: "text-slash",
714
- body: input.textForCommands,
715
- authorized: commandAuthorized
716
- } : void 0,
717
- extra: {
718
- MessageSid: params.msg.messageSid,
719
- SenderE164: from,
720
- To: params.msg.to
721
- }
722
- });
723
- return {
724
- cfg: params.cfg,
725
- channel: CHANNEL_ID$2,
726
- accountId: params.account.accountId,
727
- route: {
728
- agentId: route.agentId,
729
- sessionKey
730
- },
731
- ctxPayload,
732
- delivery: {
733
- durable: () => ({ to: from }),
734
- deliver: async (payload) => {
735
- const text = payload.text;
736
- if (!text) return { visibleReplySent: false };
737
- await sendSmsTextChunks({
738
- account: params.account,
739
- to: from,
740
- text
741
- });
742
- return { visibleReplySent: true };
780
+ messageId: input.id,
781
+ timestamp: input.timestamp,
782
+ from: `sms:${from}`,
783
+ sender: {
784
+ id: from,
785
+ name: from
786
+ },
787
+ conversation: {
788
+ kind: "direct",
789
+ id: from,
790
+ label: from
791
+ },
792
+ route: {
793
+ agentId: route.agentId,
794
+ accountId: params.account.accountId,
795
+ routeSessionKey: sessionKey,
796
+ dispatchSessionKey: sessionKey
797
+ },
798
+ reply: { to: `sms:${from}` },
799
+ message: {
800
+ rawBody: input.rawText,
801
+ commandBody: input.textForCommands,
802
+ bodyForAgent: input.textForAgent
803
+ },
804
+ media: materialized.media,
805
+ access: commandRequested ? { commands: { authorized: commandAuthorized } } : void 0,
806
+ command: isTextCommand ? {
807
+ kind: "text-slash",
808
+ body: input.textForCommands,
809
+ authorized: commandAuthorized
810
+ } : void 0,
811
+ extra: {
812
+ MessageSid: params.msg.messageSid,
813
+ SenderE164: from,
814
+ To: params.msg.to
743
815
  }
744
- },
745
- dispatcherOptions: { onReplyStart: () => {
746
- params.log?.info?.(`SMS reply started for ${from}`);
747
- } }
748
- };
816
+ });
817
+ return {
818
+ cfg: params.cfg,
819
+ channel: CHANNEL_ID$2,
820
+ accountId: params.account.accountId,
821
+ route: {
822
+ agentId: route.agentId,
823
+ sessionKey
824
+ },
825
+ ctxPayload,
826
+ delivery: {
827
+ durable: () => ({ to: from }),
828
+ deliver: async (payload) => {
829
+ const text = payload.text;
830
+ if (!text) return { visibleReplySent: false };
831
+ await sendSmsTextChunks({
832
+ account: params.account,
833
+ to: from,
834
+ text
835
+ });
836
+ return { visibleReplySent: true };
837
+ }
838
+ },
839
+ dispatcherOptions: { onReplyStart: () => {
840
+ params.log?.info?.(`SMS reply started for ${from}`);
841
+ } }
842
+ };
843
+ }
749
844
  }
750
- }
751
- });
845
+ });
846
+ if (adoptionState === "pending" || adoptionState === "abandoned") await materialized.cleanup();
847
+ } catch (error) {
848
+ if (adoptionState === "pending" || adoptionState === "abandoned") await materialized.cleanup();
849
+ throw error;
850
+ }
752
851
  }
753
852
  //#endregion
754
853
  //#region extensions/sms/src/ingress-spool.ts
@@ -758,7 +857,20 @@ var SmsIngressPermanentError = class extends Error {};
758
857
  function parseSmsIngressForm(form, account) {
759
858
  const message = buildTwilioInboundMessage(form);
760
859
  if (!message) throw new SmsIngressPermanentError("SMS ingress payload is invalid.");
761
- if (message.accountSid && message.accountSid !== account.accountSid) throw new SmsIngressPermanentError("SMS ingress payload has an invalid Twilio account.");
860
+ if (!message.accountSid || message.accountSid !== account.accountSid) throw new SmsIngressPermanentError("SMS ingress payload has an invalid Twilio account.");
861
+ if (/^rcs:/iu.test(message.to)) {
862
+ if (!message.body) throw new SmsIngressPermanentError("SMS ingress payload is invalid.");
863
+ if (account.messagingServiceSid && message.messagingServiceSid !== account.messagingServiceSid) throw new SmsIngressPermanentError("SMS ingress payload has an invalid Twilio Messaging Service.");
864
+ const { unavailableMediaCount: _unavailableMediaCount, ...textMessage } = message;
865
+ return {
866
+ ...textMessage,
867
+ media: []
868
+ };
869
+ }
870
+ if (account.fromNumber) {
871
+ const recipient = normalizeSmsPhoneNumber(message.to);
872
+ if (!looksLikeSmsPhoneNumber(recipient) || recipient !== account.fromNumber) throw new SmsIngressPermanentError("SMS ingress payload has an invalid Twilio recipient.");
873
+ } else if (!message.messagingServiceSid || message.messagingServiceSid !== account.messagingServiceSid) throw new SmsIngressPermanentError("SMS ingress payload has an invalid Twilio Messaging Service.");
762
874
  return message;
763
875
  }
764
876
  function createSmsIngressSpool(params) {
@@ -843,7 +955,9 @@ function createSmsIngressSpool(params) {
843
955
  //#endregion
844
956
  //#region extensions/sms/src/webhook.ts
845
957
  const INVALID_REQUEST_MAX_REQUESTS = 300;
846
- const CALLBACK_DISPATCH_MAX_REQUESTS = 30;
958
+ const INBOUND_DISPATCH_MAX_REQUESTS = 30;
959
+ const DELIVERY_CALLBACK_MAX_REQUESTS = 3e3;
960
+ const DELIVERY_CALLBACK_WINDOW_MS = 6e4;
847
961
  const SMS_WEBHOOK_ACCEPTED_HEADER = "x-openclaw-delivery-accepted";
848
962
  const SMS_WEBHOOK_ACCEPTED_VALUE = "durable";
849
963
  const invalidRequestRateLimiter = createFixedWindowRateLimiter({
@@ -851,12 +965,12 @@ const invalidRequestRateLimiter = createFixedWindowRateLimiter({
851
965
  windowMs: 6e4,
852
966
  maxTrackedKeys: 5e3
853
967
  });
854
- const callbackDispatchRateLimiter = createFixedWindowRateLimiter({
855
- maxRequests: CALLBACK_DISPATCH_MAX_REQUESTS,
968
+ const inboundDispatchRateLimiter = createFixedWindowRateLimiter({
969
+ maxRequests: INBOUND_DISPATCH_MAX_REQUESTS,
856
970
  windowMs: 6e4,
857
971
  maxTrackedKeys: 5e3
858
972
  });
859
- const validatedAggregateRateLimiter = createFixedWindowRateLimiter({
973
+ const validatedInboundAggregateRateLimiter = createFixedWindowRateLimiter({
860
974
  maxRequests: 300,
861
975
  windowMs: 6e4,
862
976
  maxTrackedKeys: 1e3
@@ -880,6 +994,13 @@ function rejectInvalidRequestRateLimit(params) {
880
994
  return true;
881
995
  }
882
996
  function createSmsWebhookHandler(params) {
997
+ let deliveryRecorder = params.delivery;
998
+ const deliveryCallbackRateLimiter = createFixedWindowRateLimiter({
999
+ maxRequests: DELIVERY_CALLBACK_MAX_REQUESTS,
1000
+ windowMs: DELIVERY_CALLBACK_WINDOW_MS,
1001
+ maxTrackedKeys: 1
1002
+ });
1003
+ const deliveryCallbackKey = accountRouteRateLimitKey(params.account);
883
1004
  return async (req, res) => {
884
1005
  if (req.method !== "POST") {
885
1006
  respondTwiml(res, 405, "Method not allowed");
@@ -897,14 +1018,12 @@ function createSmsWebhookHandler(params) {
897
1018
  let form;
898
1019
  try {
899
1020
  form = await readTwilioWebhookForm(req);
900
- } catch {
901
- if (invalidRequestRateLimited) return rejectInvalidRequestRateLimit({
902
- key: clientAddressKey,
903
- log: params.log,
904
- res
905
- });
906
- respondTwiml(res, 400, "Invalid request body");
907
- return true;
1021
+ } catch (error) {
1022
+ if (isRequestBodyLimitError(error, "PAYLOAD_TOO_LARGE")) {
1023
+ respondTwiml(res, 413, "Payload too large");
1024
+ return true;
1025
+ }
1026
+ throw error;
908
1027
  }
909
1028
  if (!params.account.dangerouslyDisableSignatureValidation) {
910
1029
  if (!verifyTwilioSignature({
@@ -931,18 +1050,51 @@ function createSmsWebhookHandler(params) {
931
1050
  log: params.log,
932
1051
  res
933
1052
  });
1053
+ if (isTwilioDeliveryStatusForm(form)) {
1054
+ if (params.account.dangerouslyDisableSignatureValidation && inboundDispatchRateLimiter.isRateLimited(clientAddressKey)) {
1055
+ params.log?.warn?.("SMS webhook callback rate limit exceeded");
1056
+ respondTwiml(res, 429, "Rate limit exceeded");
1057
+ return true;
1058
+ }
1059
+ const messageSid = resolveTwilioMessageSid(form);
1060
+ if (!messageSid) {
1061
+ respondTwiml(res, 400, "Missing MessageSid");
1062
+ return true;
1063
+ }
1064
+ const callbackAccountSid = form.AccountSid;
1065
+ if (!callbackAccountSid || callbackAccountSid !== params.account.accountSid) {
1066
+ params.log?.warn?.(`SMS delivery callback ignored missing or mismatched account for message ${messageSid}`);
1067
+ respondTwiml(res, 200);
1068
+ return true;
1069
+ }
1070
+ if (deliveryCallbackRateLimiter.isRateLimited(deliveryCallbackKey)) {
1071
+ params.log?.warn?.("SMS delivery callback rate limit exceeded");
1072
+ respondTwiml(res, 503, "Service unavailable");
1073
+ return true;
1074
+ }
1075
+ deliveryRecorder ??= createSmsDeliveryRecorder();
1076
+ const verdict = await deliveryRecorder.record({
1077
+ account: params.account,
1078
+ form
1079
+ });
1080
+ if (verdict.duplicate) params.log?.info?.(`SMS delivery callback ignored duplicate for message ${messageSid}`);
1081
+ else params.log?.info?.(`SMS delivery observation ${verdict.record.status} recorded for message ${messageSid}`);
1082
+ res.setHeader(SMS_WEBHOOK_ACCEPTED_HEADER, SMS_WEBHOOK_ACCEPTED_VALUE);
1083
+ respondTwiml(res, 200);
1084
+ return true;
1085
+ }
934
1086
  const dispatchKey = params.account.dangerouslyDisableSignatureValidation ? clientAddressKey : rateLimitKey({
935
1087
  account: params.account,
936
1088
  subject: resolveTwilioInboundSender(form)
937
1089
  });
938
- if (callbackDispatchRateLimiter.isRateLimited(dispatchKey)) {
1090
+ if (inboundDispatchRateLimiter.isRateLimited(dispatchKey)) {
939
1091
  params.log?.warn?.("SMS webhook callback rate limit exceeded");
940
1092
  respondTwiml(res, 429, "Rate limit exceeded");
941
1093
  return true;
942
1094
  }
943
1095
  if (!params.account.dangerouslyDisableSignatureValidation) {
944
1096
  const aggregateKey = accountRouteRateLimitKey(params.account);
945
- if (validatedAggregateRateLimiter.isRateLimited(aggregateKey)) {
1097
+ if (validatedInboundAggregateRateLimiter.isRateLimited(aggregateKey)) {
946
1098
  params.log?.warn?.(`SMS webhook aggregate rate limit exceeded for ${aggregateKey}`);
947
1099
  respondTwiml(res, 429, "Rate limit exceeded");
948
1100
  return true;
@@ -994,6 +1146,7 @@ function collectSmsStartupWarnings(account) {
994
1146
  const warnings = [];
995
1147
  if (!account.accountSid || !account.authToken || !account.fromNumber && !account.messagingServiceSid) warnings.push("- SMS: accountSid, authToken, and fromNumber or messagingServiceSid are required.");
996
1148
  if (!account.publicWebhookUrl && !account.dangerouslyDisableSignatureValidation) warnings.push("- SMS: publicWebhookUrl is required for Twilio signature validation. Set dangerouslyDisableSignatureValidation=true only for local testing.");
1149
+ else if (account.publicWebhookUrl && !resolveTwilioStatusCallbackUrl(account.publicWebhookUrl)) warnings.push("- SMS: publicWebhookUrl must be a properly encoded absolute HTTP(S) URL with a valid hostname, no embedded credentials, and remain within OpenClaw's 4,000-character callback safety limit; OpenClaw will omit the per-message delivery callback until fixed.");
997
1150
  if (account.dmPolicy === "allowlist" && account.allowFrom.length === 0) warnings.push("- SMS: dmPolicy=allowlist with empty allowFrom rejects every sender.");
998
1151
  if (account.dmPolicy === "open" && !account.allowFrom.includes("*")) warnings.push("- SMS: dmPolicy=open should set allowFrom=[\"*\"] or explicit sender numbers.");
999
1152
  return warnings;
@@ -1011,16 +1164,22 @@ async function registerSmsWebhookRoute(params) {
1011
1164
  });
1012
1165
  let unregisterRoute;
1013
1166
  try {
1167
+ const webhookHandler = createSmsWebhookHandler({
1168
+ ...params,
1169
+ ingress
1170
+ });
1014
1171
  unregisterRoute = registerPluginHttpRoute({
1015
1172
  path: webhookPath,
1016
1173
  auth: "plugin",
1017
1174
  pluginId: CHANNEL_ID$1,
1018
1175
  accountId: params.account.accountId,
1176
+ throwOnFailure: true,
1019
1177
  log: (msg) => params.log?.info?.(msg),
1020
- handler: createSmsWebhookHandler({
1021
- ...params,
1022
- ingress
1023
- })
1178
+ handler: async (req, res) => {
1179
+ const { tryHandleHostedSmsMediaRequest } = await import("./media-C_8jX0L8.js");
1180
+ if (await tryHandleHostedSmsMediaRequest(req, res, params.account.accountId)) return true;
1181
+ return await webhookHandler(req, res);
1182
+ }
1024
1183
  });
1025
1184
  } catch (error) {
1026
1185
  await Promise.allSettled([predecessorStop, ingress.stop()]);
@@ -1052,23 +1211,52 @@ async function registerSmsWebhookRoute(params) {
1052
1211
  };
1053
1212
  }
1054
1213
  async function startSmsGatewayAccount(params) {
1214
+ params.statusSink?.({ lifecycle: "starting" });
1055
1215
  if (!params.account.enabled) {
1056
1216
  params.log?.info?.(`SMS account ${params.account.accountId} is disabled`);
1217
+ params.statusSink?.(channelStoppedPatch());
1057
1218
  return waitUntilAbort(params.abortSignal);
1058
1219
  }
1059
1220
  const warnings = collectSmsStartupWarnings(params.account);
1060
1221
  if (warnings.some((warning) => warning.includes("required"))) {
1061
1222
  for (const warning of warnings) params.log?.warn?.(warning);
1223
+ params.statusSink?.(channelBlockedPatch(warnings.join("; "), {
1224
+ running: true,
1225
+ connected: false
1226
+ }));
1062
1227
  return waitUntilAbort(params.abortSignal);
1063
1228
  }
1064
1229
  for (const warning of warnings) params.log?.warn?.(warning);
1065
1230
  const registration = await registerSmsWebhookRoute(params);
1066
- if (registration.isActive()) params.log?.info?.(`Registered SMS webhook route ${params.account.webhookPath} for account ${params.account.accountId}`);
1067
- return registration.lifecycle;
1231
+ if (registration.isActive()) {
1232
+ params.log?.info?.(`Registered SMS webhook route ${params.account.webhookPath} for account ${params.account.accountId}`);
1233
+ params.statusSink?.(channelReadyPatch());
1234
+ }
1235
+ return registration.lifecycle.finally(() => {
1236
+ params.statusSink?.(channelStoppedPatch());
1237
+ });
1068
1238
  }
1069
1239
  //#endregion
1070
1240
  //#region extensions/sms/src/status.ts
1071
1241
  const TWILIO_ERROR_WEBHOOK_REACHABILITY = "11200";
1242
+ function resolveRemoteProbeTimeoutMs(timeoutMs) {
1243
+ const normalized = Math.max(1, Math.floor(timeoutMs));
1244
+ const settleMarginMs = Math.min(100, Math.max(1, Math.floor(normalized / 10)));
1245
+ return Math.max(0, normalized - settleMarginMs);
1246
+ }
1247
+ async function runRemoteProbe(params) {
1248
+ try {
1249
+ return {
1250
+ kind: "value",
1251
+ value: await withTimeout(Promise.resolve().then(params.run), params.timeoutMs, { message: `timed out after ${params.timeoutMs}ms` })
1252
+ };
1253
+ } catch (error) {
1254
+ return {
1255
+ kind: "error",
1256
+ error: `${params.label} failed: ${formatErrorMessage(error)}`
1257
+ };
1258
+ }
1259
+ }
1072
1260
  function addTailscaleHint(account, hints) {
1073
1261
  let host;
1074
1262
  try {
@@ -1164,6 +1352,17 @@ function recentInboundSummary(messages) {
1164
1352
  dateSent: message.dateSent
1165
1353
  };
1166
1354
  }
1355
+ function recentOutboundSummary(records) {
1356
+ const record = records[0];
1357
+ if (!record) return;
1358
+ return {
1359
+ messageSid: record.messageSid,
1360
+ status: record.status,
1361
+ lastObservedAt: record.lastObservedAt,
1362
+ ...record.errorCode ? { errorCode: record.errorCode } : {},
1363
+ ...record.conflict ? { conflict: true } : {}
1364
+ };
1365
+ }
1167
1366
  function webhookError(probe) {
1168
1367
  switch (probe.status) {
1169
1368
  case "matches":
@@ -1182,34 +1381,76 @@ function webhookError(probe) {
1182
1381
  async function probeSmsAccount(params) {
1183
1382
  const hints = [];
1184
1383
  addTailscaleHint(params.account, hints);
1185
- const webhook = params.account.fromNumber ? compareTwilioWebhook(params.account, (await listTwilioIncomingPhoneNumbers({
1186
- account: params.account,
1187
- phoneNumber: params.account.fromNumber,
1188
- fetchImpl: params.options?.fetchImpl,
1189
- timeoutMs: params.timeoutMs
1190
- }))[0]) : params.account.messagingServiceSid ? compareTwilioMessagingService(params.account, await retrieveTwilioMessagingService({
1191
- account: params.account,
1192
- serviceSid: params.account.messagingServiceSid,
1193
- fetchImpl: params.options?.fetchImpl,
1194
- timeoutMs: params.timeoutMs
1195
- })) : {
1384
+ const recentOutbound = recentOutboundSummary(params.options?.deliveryRecords ?? []);
1385
+ const remoteTimeoutMs = resolveRemoteProbeTimeoutMs(params.timeoutMs);
1386
+ let webhook;
1387
+ let messageHistoryError;
1388
+ let messages = [];
1389
+ if (remoteTimeoutMs === 0) webhook = {
1196
1390
  status: "unavailable",
1197
- reason: "Twilio SMS probe requires fromNumber or messagingServiceSid."
1391
+ reason: "Twilio webhook probe skipped because the probe timeout is too short."
1198
1392
  };
1199
- const recentInbound = recentInboundSummary(params.account.fromNumber ? await listTwilioMessages({
1200
- account: params.account,
1201
- to: params.account.fromNumber,
1202
- pageSize: 3,
1203
- fetchImpl: params.options?.fetchImpl,
1204
- timeoutMs: params.timeoutMs
1205
- }) : []);
1393
+ else {
1394
+ const webhookTask = params.account.fromNumber ? runRemoteProbe({
1395
+ label: "Twilio webhook probe",
1396
+ timeoutMs: remoteTimeoutMs,
1397
+ run: async () => compareTwilioWebhook(params.account, (await listTwilioIncomingPhoneNumbers({
1398
+ account: params.account,
1399
+ phoneNumber: params.account.fromNumber,
1400
+ fetchImpl: params.options?.fetchImpl,
1401
+ timeoutMs: remoteTimeoutMs
1402
+ }))[0])
1403
+ }) : params.account.messagingServiceSid ? runRemoteProbe({
1404
+ label: "Twilio webhook probe",
1405
+ timeoutMs: remoteTimeoutMs,
1406
+ run: async () => compareTwilioMessagingService(params.account, await retrieveTwilioMessagingService({
1407
+ account: params.account,
1408
+ serviceSid: params.account.messagingServiceSid,
1409
+ fetchImpl: params.options?.fetchImpl,
1410
+ timeoutMs: remoteTimeoutMs
1411
+ }))
1412
+ }) : Promise.resolve({
1413
+ kind: "value",
1414
+ value: {
1415
+ status: "unavailable",
1416
+ reason: "Twilio SMS probe requires fromNumber or messagingServiceSid."
1417
+ }
1418
+ });
1419
+ const messageTask = params.account.fromNumber ? runRemoteProbe({
1420
+ label: "Twilio message history probe",
1421
+ timeoutMs: remoteTimeoutMs,
1422
+ run: async () => await listTwilioMessages({
1423
+ account: params.account,
1424
+ to: params.account.fromNumber,
1425
+ pageSize: 3,
1426
+ fetchImpl: params.options?.fetchImpl,
1427
+ timeoutMs: remoteTimeoutMs
1428
+ })
1429
+ }) : Promise.resolve({
1430
+ kind: "value",
1431
+ value: []
1432
+ });
1433
+ const [webhookOutcome, messageOutcome] = await Promise.all([webhookTask, messageTask]);
1434
+ webhook = webhookOutcome.kind === "value" ? webhookOutcome.value : {
1435
+ status: "unavailable",
1436
+ reason: webhookOutcome.error
1437
+ };
1438
+ if (messageOutcome.kind === "value") messages = messageOutcome.value;
1439
+ else messageHistoryError = messageOutcome.error;
1440
+ }
1441
+ const recentInbound = recentInboundSummary(messages);
1206
1442
  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.");
1207
- const error = webhookError(webhook) ?? (recentInbound?.errorCode === TWILIO_ERROR_WEBHOOK_REACHABILITY ? `Recent inbound SMS ${recentInbound.sid} has Twilio error 11200.` : void 0);
1443
+ const error = [
1444
+ webhookError(webhook),
1445
+ messageHistoryError,
1446
+ recentInbound?.errorCode === TWILIO_ERROR_WEBHOOK_REACHABILITY ? `Recent inbound SMS ${recentInbound.sid} has Twilio error 11200.` : void 0
1447
+ ].filter((value) => Boolean(value)).join(" ");
1208
1448
  return {
1209
1449
  ok: !error,
1210
1450
  ...error ? { error } : {},
1211
1451
  webhook,
1212
1452
  ...recentInbound ? { recentInbound } : {},
1453
+ ...recentOutbound ? { recentOutbound } : {},
1213
1454
  hints
1214
1455
  };
1215
1456
  }
@@ -1237,6 +1478,15 @@ function formatSmsProbeLines(probe) {
1237
1478
  tone: smsProbe.recentInbound.errorCode ? "warn" : "muted"
1238
1479
  });
1239
1480
  }
1481
+ if (smsProbe.recentOutbound?.messageSid) {
1482
+ const error = smsProbe.recentOutbound.errorCode ? ` error=${smsProbe.recentOutbound.errorCode}` : "";
1483
+ const status = smsProbe.recentOutbound.status || "unknown";
1484
+ const tone = status === "delivered" ? "success" : status === "failed" || status === "undelivered" || status === "canceled" || status === "conflicted" ? "error" : "muted";
1485
+ lines.push({
1486
+ text: `Recent outbound: ${status}${error}`,
1487
+ tone
1488
+ });
1489
+ }
1240
1490
  for (const hint of smsProbe.hints ?? []) lines.push({
1241
1491
  text: hint,
1242
1492
  tone: "warn"
@@ -1277,7 +1527,13 @@ const resolveSmsDmPolicy = createScopedDmSecurityResolver({
1277
1527
  approveHint: "openclaw pairing approve sms <code>",
1278
1528
  normalizeEntry: normalizeSmsAllowFrom
1279
1529
  });
1280
- const collectSmsSecurityWarnings = createConditionalWarningCollector((account) => account.dangerouslyDisableSignatureValidation && "- SMS: Twilio signature validation is disabled. Only use this for local testing.", (account) => account.dmPolicy === "open" && account.allowFrom.includes("*") && "- SMS: dmPolicy=\"open\" allows any phone number to message the bot.");
1530
+ const collectSmsSecurityWarnings = createConditionalWarningCollector((account) => account.dangerouslyDisableSignatureValidation && "- SMS: Twilio signature validation is disabled. Only use this for local testing.");
1531
+ const collectSmsOpenDmFindings = createConditionalWarningCollector.findings({
1532
+ collectWarnings: createConditionalWarningCollector((account) => account.dmPolicy === "open" && account.allowFrom.includes("*") && "- SMS: dmPolicy=\"open\" allows any phone number to message the bot."),
1533
+ checkId: "channels.sms.dm.open",
1534
+ severity: "critical",
1535
+ title: "SMS security warning"
1536
+ });
1281
1537
  function smsSetupPatch(input) {
1282
1538
  const patch = {};
1283
1539
  for (const key of [
@@ -1400,25 +1656,12 @@ const smsSetupContract = defineChannelSetupContract({
1400
1656
  function createSmsReceipt(params) {
1401
1657
  const first = params.results[0];
1402
1658
  if (!first) throw new Error("SMS send did not return a Twilio Message SID.");
1659
+ const receipt = createSmsMessageReceipt(params);
1403
1660
  return {
1404
1661
  channel: CHANNEL_ID,
1405
1662
  messageId: first.sid,
1406
1663
  chatId: first.to,
1407
- receipt: createMessageReceiptFromOutboundResults({
1408
- results: params.results.map((result) => ({
1409
- channel: CHANNEL_ID,
1410
- messageId: result.sid,
1411
- chatId: result.to,
1412
- toJid: result.to,
1413
- conversationId: result.to,
1414
- meta: {
1415
- ...result.from ? { from: result.from } : {},
1416
- ...result.status ? { status: result.status } : {}
1417
- }
1418
- })),
1419
- threadId: first.to,
1420
- kind: params.kind
1421
- })
1664
+ receipt
1422
1665
  };
1423
1666
  }
1424
1667
  function resolveSmsTextChunkLimit(params) {
@@ -1432,19 +1675,83 @@ async function sendSmsText(ctx) {
1432
1675
  results: await sendSmsTextChunks({
1433
1676
  account,
1434
1677
  to,
1435
- text: ctx.text
1678
+ text: ctx.text,
1679
+ onPlatformSendDispatch: ctx.onPlatformSendDispatch,
1680
+ onDeliveryResult: ctx.onDeliveryResult
1436
1681
  }),
1437
1682
  kind: "text"
1438
1683
  });
1439
1684
  }
1685
+ const preparedSmsAttachmentAttempts = /* @__PURE__ */ new WeakMap();
1686
+ function resolveSmsAttachmentAttemptToken(attemptToken) {
1687
+ if (!isRecord(attemptToken) || typeof attemptToken.platformDispatchStarted !== "boolean" || !isRecord(attemptToken.attempt) || typeof attemptToken.attempt.cleanupHostedMedia !== "function") return;
1688
+ return attemptToken;
1689
+ }
1690
+ async function prepareSmsAttachmentAttempt(ctx) {
1691
+ const account = resolveSmsAccount(ctx.cfg, ctx.accountId);
1692
+ const to = normalizeSmsPhoneNumber(ctx.to) || account.defaultTo;
1693
+ if (!looksLikeSmsPhoneNumber(to)) throw new Error(`Invalid SMS target: ${ctx.to}`);
1694
+ return {
1695
+ account,
1696
+ to,
1697
+ attempt: await prepareSmsMediaAttempt({
1698
+ account,
1699
+ text: ctx.text,
1700
+ mediaUrl: ctx.mediaUrl,
1701
+ mediaAccess: ctx.mediaAccess,
1702
+ mediaLocalRoots: ctx.mediaLocalRoots,
1703
+ mediaReadFile: ctx.mediaReadFile
1704
+ }),
1705
+ platformDispatchStarted: false
1706
+ };
1707
+ }
1708
+ function getOrPrepareSmsAttachmentAttempt(ctx) {
1709
+ const existing = preparedSmsAttachmentAttempts.get(ctx);
1710
+ if (existing) return existing;
1711
+ const created = prepareSmsAttachmentAttempt(ctx);
1712
+ preparedSmsAttachmentAttempts.set(ctx, created);
1713
+ return created;
1714
+ }
1715
+ async function sendPreparedSmsAttachment(ctx) {
1716
+ const preparation = preparedSmsAttachmentAttempts.get(ctx);
1717
+ preparedSmsAttachmentAttempts.delete(ctx);
1718
+ if (!preparation) throw new Error("SMS message lifecycle did not prepare the MMS attachment.");
1719
+ const prepared = await preparation;
1720
+ return createSmsReceipt({
1721
+ results: await sendPreparedSmsMediaAttempt({
1722
+ ...prepared,
1723
+ onPlatformSendDispatch: async () => {
1724
+ await ctx.onPlatformSendDispatch?.();
1725
+ prepared.platformDispatchStarted = true;
1726
+ },
1727
+ onDeliveryResult: ctx.onDeliveryResult
1728
+ }),
1729
+ kind: "media"
1730
+ });
1731
+ }
1440
1732
  const smsMessageAdapter = defineChannelMessageAdapter({
1441
1733
  id: CHANNEL_ID,
1442
1734
  durableFinal: { capabilities: {
1443
1735
  text: true,
1444
- media: false,
1736
+ media: true,
1445
1737
  messageSendingHooks: true
1446
1738
  } },
1447
- send: { text: async (ctx) => await sendSmsText(ctx) }
1739
+ send: {
1740
+ lifecycle: {
1741
+ beforeSendAttempt: async (ctx) => {
1742
+ if (ctx.kind !== "media") return;
1743
+ return await getOrPrepareSmsAttachmentAttempt(ctx);
1744
+ },
1745
+ afterSendFailure: async (ctx) => {
1746
+ if (ctx.kind !== "media") return;
1747
+ const attemptToken = resolveSmsAttachmentAttemptToken(ctx.attemptToken);
1748
+ if (!attemptToken || attemptToken.platformDispatchStarted) return;
1749
+ await attemptToken.attempt.cleanupHostedMedia();
1750
+ }
1751
+ },
1752
+ text: async (ctx) => await sendSmsText(ctx),
1753
+ media: async (ctx) => await sendPreparedSmsAttachment(ctx)
1754
+ }
1448
1755
  });
1449
1756
  function resolveSmsOutboundSessionRoute(params) {
1450
1757
  const to = normalizeSmsPhoneNumber(params.resolvedTarget?.to ?? params.target);
@@ -1471,15 +1778,15 @@ const smsPlugin = createChatChannelPlugin({
1471
1778
  id: CHANNEL_ID,
1472
1779
  label: "SMS",
1473
1780
  selectionLabel: "SMS (Twilio)",
1474
- detailLabel: "Twilio SMS",
1781
+ detailLabel: "Twilio SMS/MMS",
1475
1782
  docsPath: "/channels/sms",
1476
1783
  docsLabel: "sms",
1477
- blurb: "Twilio-backed SMS with inbound webhooks and outbound replies.",
1784
+ blurb: "Twilio-backed SMS/MMS with inbound webhooks and outbound replies.",
1478
1785
  order: 88
1479
1786
  },
1480
1787
  capabilities: {
1481
1788
  chatTypes: ["direct"],
1482
- media: false,
1789
+ media: true,
1483
1790
  threads: false,
1484
1791
  reactions: false,
1485
1792
  edit: false,
@@ -1490,11 +1797,6 @@ const smsPlugin = createChatChannelPlugin({
1490
1797
  },
1491
1798
  reload: { configPrefixes: [`channels.${CHANNEL_ID}`] },
1492
1799
  configSchema: SmsChannelConfigSchema,
1493
- setup: { applyAccountConfig: ({ cfg, accountId, input }) => applySmsAccountConfig({
1494
- cfg,
1495
- accountId,
1496
- input
1497
- }) },
1498
1800
  setupContract: smsSetupContract,
1499
1801
  config: {
1500
1802
  ...smsConfigAdapter,
@@ -1511,6 +1813,7 @@ const smsPlugin = createChatChannelPlugin({
1511
1813
  messaging: {
1512
1814
  targetPrefixes: ["twilio-sms"],
1513
1815
  normalizeTarget: (target) => normalizeSmsPhoneNumber(target),
1816
+ inferTargetChatType: ({ to }) => looksLikeSmsPhoneNumber(normalizeSmsPhoneNumber(to)) ? "direct" : void 0,
1514
1817
  resolveOutboundSessionRoute: (params) => resolveSmsOutboundSessionRoute(params),
1515
1818
  targetResolver: {
1516
1819
  looksLikeId: looksLikeSmsPhoneNumber,
@@ -1523,35 +1826,47 @@ const smsPlugin = createChatChannelPlugin({
1523
1826
  ctx.log?.warn?.("SMS channel runtime is not available; webhook route not started");
1524
1827
  return;
1525
1828
  }
1829
+ const statusSink = createAccountStatusSink({
1830
+ accountId: ctx.account.accountId,
1831
+ setStatus: ctx.setStatus
1832
+ });
1526
1833
  return await startSmsGatewayAccount({
1527
1834
  cfg: ctx.cfg,
1528
1835
  account: ctx.account,
1529
1836
  channelRuntime: ctx.channelRuntime,
1530
1837
  abortSignal: ctx.abortSignal,
1531
- log: ctx.log
1838
+ log: ctx.log,
1839
+ statusSink
1532
1840
  });
1533
1841
  } },
1534
- status: {
1535
- buildAccountSnapshot: ({ account }) => {
1842
+ status: createComputedAccountStatusAdapter({
1843
+ defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID),
1844
+ resolveAccountSnapshot: ({ account }) => {
1536
1845
  const configured = isSmsAccountConfigured(account);
1537
1846
  return {
1538
1847
  accountId: account.accountId,
1539
1848
  name: account.fromNumber || account.messagingServiceSid || "SMS",
1540
1849
  enabled: account.enabled,
1541
1850
  configured,
1542
- statusState: !account.enabled ? "disabled" : configured ? "configured" : "unconfigured"
1851
+ extra: { statusState: !account.enabled ? "disabled" : configured ? "configured" : "unconfigured" }
1543
1852
  };
1544
1853
  },
1545
- probeAccount: async ({ account, timeoutMs }) => await probeSmsAccount({
1546
- account,
1547
- timeoutMs
1548
- }),
1854
+ probeAccount: async ({ account, timeoutMs }) => {
1855
+ const startedAt = Date.now();
1856
+ const deliveryRecords = await listRecentSmsDeliveryRecords(account);
1857
+ const elapsedMs = Math.max(0, Date.now() - startedAt);
1858
+ return await probeSmsAccount({
1859
+ account,
1860
+ timeoutMs: Math.max(1, timeoutMs - elapsedMs),
1861
+ options: { deliveryRecords }
1862
+ });
1863
+ },
1549
1864
  formatCapabilitiesProbe: ({ probe }) => formatSmsProbeLines(probe),
1550
1865
  buildCapabilitiesDiagnostics: async ({ account }) => ({ lines: collectSmsStartupWarnings(account).map((text) => ({
1551
1866
  text,
1552
1867
  tone: "warn"
1553
1868
  })) })
1554
- },
1869
+ }),
1555
1870
  secrets: {
1556
1871
  secretTargetRegistryEntries,
1557
1872
  collectRuntimeConfigAssignments
@@ -1559,7 +1874,7 @@ const smsPlugin = createChatChannelPlugin({
1559
1874
  agentPrompt: { messageToolHints: () => [
1560
1875
  "",
1561
1876
  "### SMS Formatting",
1562
- "SMS is plain text only. Keep replies brief, avoid markdown tables, and split long details into short messages."
1877
+ "SMS text is plain text. MMS attachments are supported; keep captions brief and avoid markdown tables."
1563
1878
  ] },
1564
1879
  message: smsMessageAdapter
1565
1880
  },
@@ -1577,7 +1892,7 @@ const smsPlugin = createChatChannelPlugin({
1577
1892
  } },
1578
1893
  security: {
1579
1894
  resolveDmPolicy: resolveSmsDmPolicy,
1580
- collectWarnings: ({ account }) => collectSmsSecurityWarnings(account)
1895
+ collectWarnings: ({ account }) => [...collectSmsSecurityWarnings(account), ...collectSmsOpenDmFindings(account)]
1581
1896
  },
1582
1897
  outbound: {
1583
1898
  deliveryMode: "gateway",