@openclaw/sms 2026.7.2-beta.5 → 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.
@@ -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,115 +692,185 @@ 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
755
854
  const SMS_INGRESS_PAYLOAD_VERSION = 1;
756
855
  const SMS_INGRESS_DRAIN_INTERVAL_MS = 500;
757
- const SMS_COMPLETED_TTL_MS = 1440 * 60 * 1e3;
758
- const SMS_COMPLETED_MAX_ENTRIES = 2e4;
759
- const SMS_FAILED_TTL_MS = 720 * 60 * 60 * 1e3;
760
- const SMS_FAILED_MAX_ENTRIES = 1e3;
761
856
  var SmsIngressPermanentError = class extends Error {};
762
857
  function parseSmsIngressForm(form, account) {
763
858
  const message = buildTwilioInboundMessage(form);
764
859
  if (!message) throw new SmsIngressPermanentError("SMS ingress payload is invalid.");
765
- 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.");
766
874
  return message;
767
875
  }
768
876
  function createSmsIngressSpool(params) {
@@ -810,10 +918,8 @@ function createSmsIngressSpool(params) {
810
918
  pollIntervalMs: SMS_INGRESS_DRAIN_INTERVAL_MS,
811
919
  retention: {
812
920
  pruneIntervalMs: 0,
813
- completedTtlMs: SMS_COMPLETED_TTL_MS,
814
- completedMaxEntries: SMS_COMPLETED_MAX_ENTRIES,
815
- failedTtlMs: SMS_FAILED_TTL_MS,
816
- failedMaxEntries: SMS_FAILED_MAX_ENTRIES
921
+ completedTtlMs: 1440 * 60 * 1e3,
922
+ failedMaxEntries: 1e3
817
923
  },
818
924
  appendRetryDelaysMs: [0],
819
925
  waitForDeliveryIdleBeforeRepump: false,
@@ -849,17 +955,26 @@ function createSmsIngressSpool(params) {
849
955
  //#endregion
850
956
  //#region extensions/sms/src/webhook.ts
851
957
  const INVALID_REQUEST_MAX_REQUESTS = 300;
852
- 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;
961
+ const SMS_WEBHOOK_ACCEPTED_HEADER = "x-openclaw-delivery-accepted";
962
+ const SMS_WEBHOOK_ACCEPTED_VALUE = "durable";
853
963
  const invalidRequestRateLimiter = createFixedWindowRateLimiter({
854
964
  maxRequests: INVALID_REQUEST_MAX_REQUESTS,
855
965
  windowMs: 6e4,
856
966
  maxTrackedKeys: 5e3
857
967
  });
858
- const callbackDispatchRateLimiter = createFixedWindowRateLimiter({
859
- maxRequests: CALLBACK_DISPATCH_MAX_REQUESTS,
968
+ const inboundDispatchRateLimiter = createFixedWindowRateLimiter({
969
+ maxRequests: INBOUND_DISPATCH_MAX_REQUESTS,
860
970
  windowMs: 6e4,
861
971
  maxTrackedKeys: 5e3
862
972
  });
973
+ const validatedInboundAggregateRateLimiter = createFixedWindowRateLimiter({
974
+ maxRequests: 300,
975
+ windowMs: 6e4,
976
+ maxTrackedKeys: 1e3
977
+ });
863
978
  function headerValue(value) {
864
979
  if (Array.isArray(value)) return value[0];
865
980
  return value;
@@ -868,7 +983,10 @@ function resolvedClientAddress(params) {
868
983
  return resolveRequestClientIp(params.req, params.cfg.gateway?.trustedProxies, params.cfg.gateway?.allowRealIpFallback === true) ?? params.req.socket?.remoteAddress ?? "unknown";
869
984
  }
870
985
  function rateLimitKey(params) {
871
- return `${params.account.accountId}:${params.account.webhookPath}:${params.clientAddress}`;
986
+ return `${params.account.accountId}:${params.account.webhookPath}:${params.subject}`;
987
+ }
988
+ function accountRouteRateLimitKey(account) {
989
+ return `${account.accountId}:${account.webhookPath}`;
872
990
  }
873
991
  function rejectInvalidRequestRateLimit(params) {
874
992
  params.log?.warn?.(`SMS webhook invalid-request rate limit exceeded for ${params.key}`);
@@ -876,6 +994,13 @@ function rejectInvalidRequestRateLimit(params) {
876
994
  return true;
877
995
  }
878
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);
879
1004
  return async (req, res) => {
880
1005
  if (req.method !== "POST") {
881
1006
  respondTwiml(res, 405, "Method not allowed");
@@ -885,22 +1010,20 @@ function createSmsWebhookHandler(params) {
885
1010
  cfg: params.cfg,
886
1011
  req
887
1012
  });
888
- const key = rateLimitKey({
1013
+ const clientAddressKey = rateLimitKey({
889
1014
  account: params.account,
890
- clientAddress
1015
+ subject: clientAddress
891
1016
  });
892
- const invalidRequestRateLimited = invalidRequestRateLimiter.isRateLimited(key);
1017
+ const invalidRequestRateLimited = invalidRequestRateLimiter.isRateLimited(clientAddressKey);
893
1018
  let form;
894
1019
  try {
895
1020
  form = await readTwilioWebhookForm(req);
896
- } catch {
897
- if (invalidRequestRateLimited) return rejectInvalidRequestRateLimit({
898
- key,
899
- log: params.log,
900
- res
901
- });
902
- respondTwiml(res, 400, "Invalid request body");
903
- 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;
904
1027
  }
905
1028
  if (!params.account.dangerouslyDisableSignatureValidation) {
906
1029
  if (!verifyTwilioSignature({
@@ -913,7 +1036,7 @@ function createSmsWebhookHandler(params) {
913
1036
  form
914
1037
  })) {
915
1038
  if (invalidRequestRateLimited) return rejectInvalidRequestRateLimit({
916
- key,
1039
+ key: clientAddressKey,
917
1040
  log: params.log,
918
1041
  res
919
1042
  });
@@ -923,21 +1046,67 @@ function createSmsWebhookHandler(params) {
923
1046
  }
924
1047
  }
925
1048
  if (invalidRequestRateLimited && params.account.dangerouslyDisableSignatureValidation) return rejectInvalidRequestRateLimit({
926
- key,
1049
+ key: clientAddressKey,
927
1050
  log: params.log,
928
1051
  res
929
1052
  });
930
- if (callbackDispatchRateLimiter.isRateLimited(key)) {
931
- params.log?.warn?.(`SMS webhook rate limit exceeded for ${key}`);
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
+ }
1086
+ const dispatchKey = params.account.dangerouslyDisableSignatureValidation ? clientAddressKey : rateLimitKey({
1087
+ account: params.account,
1088
+ subject: resolveTwilioInboundSender(form)
1089
+ });
1090
+ if (inboundDispatchRateLimiter.isRateLimited(dispatchKey)) {
1091
+ params.log?.warn?.("SMS webhook callback rate limit exceeded");
932
1092
  respondTwiml(res, 429, "Rate limit exceeded");
933
1093
  return true;
934
1094
  }
1095
+ if (!params.account.dangerouslyDisableSignatureValidation) {
1096
+ const aggregateKey = accountRouteRateLimitKey(params.account);
1097
+ if (validatedInboundAggregateRateLimiter.isRateLimited(aggregateKey)) {
1098
+ params.log?.warn?.(`SMS webhook aggregate rate limit exceeded for ${aggregateKey}`);
1099
+ respondTwiml(res, 429, "Rate limit exceeded");
1100
+ return true;
1101
+ }
1102
+ }
935
1103
  const messageSid = resolveTwilioMessageSid(form);
936
1104
  if (!messageSid) {
937
1105
  respondTwiml(res, 400, "Missing MessageSid");
938
1106
  return true;
939
1107
  }
940
1108
  if ((await params.ingress.enqueue(form)).duplicate) params.log?.warn?.(`SMS webhook ignored replayed message ${messageSid}`);
1109
+ res.setHeader(SMS_WEBHOOK_ACCEPTED_HEADER, SMS_WEBHOOK_ACCEPTED_VALUE);
941
1110
  respondTwiml(res, 200);
942
1111
  return true;
943
1112
  };
@@ -977,6 +1146,7 @@ function collectSmsStartupWarnings(account) {
977
1146
  const warnings = [];
978
1147
  if (!account.accountSid || !account.authToken || !account.fromNumber && !account.messagingServiceSid) warnings.push("- SMS: accountSid, authToken, and fromNumber or messagingServiceSid are required.");
979
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.");
980
1150
  if (account.dmPolicy === "allowlist" && account.allowFrom.length === 0) warnings.push("- SMS: dmPolicy=allowlist with empty allowFrom rejects every sender.");
981
1151
  if (account.dmPolicy === "open" && !account.allowFrom.includes("*")) warnings.push("- SMS: dmPolicy=open should set allowFrom=[\"*\"] or explicit sender numbers.");
982
1152
  return warnings;
@@ -994,16 +1164,22 @@ async function registerSmsWebhookRoute(params) {
994
1164
  });
995
1165
  let unregisterRoute;
996
1166
  try {
1167
+ const webhookHandler = createSmsWebhookHandler({
1168
+ ...params,
1169
+ ingress
1170
+ });
997
1171
  unregisterRoute = registerPluginHttpRoute({
998
1172
  path: webhookPath,
999
1173
  auth: "plugin",
1000
1174
  pluginId: CHANNEL_ID$1,
1001
1175
  accountId: params.account.accountId,
1176
+ throwOnFailure: true,
1002
1177
  log: (msg) => params.log?.info?.(msg),
1003
- handler: createSmsWebhookHandler({
1004
- ...params,
1005
- ingress
1006
- })
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
+ }
1007
1183
  });
1008
1184
  } catch (error) {
1009
1185
  await Promise.allSettled([predecessorStop, ingress.stop()]);
@@ -1035,23 +1211,52 @@ async function registerSmsWebhookRoute(params) {
1035
1211
  };
1036
1212
  }
1037
1213
  async function startSmsGatewayAccount(params) {
1214
+ params.statusSink?.({ lifecycle: "starting" });
1038
1215
  if (!params.account.enabled) {
1039
1216
  params.log?.info?.(`SMS account ${params.account.accountId} is disabled`);
1217
+ params.statusSink?.(channelStoppedPatch());
1040
1218
  return waitUntilAbort(params.abortSignal);
1041
1219
  }
1042
1220
  const warnings = collectSmsStartupWarnings(params.account);
1043
1221
  if (warnings.some((warning) => warning.includes("required"))) {
1044
1222
  for (const warning of warnings) params.log?.warn?.(warning);
1223
+ params.statusSink?.(channelBlockedPatch(warnings.join("; "), {
1224
+ running: true,
1225
+ connected: false
1226
+ }));
1045
1227
  return waitUntilAbort(params.abortSignal);
1046
1228
  }
1047
1229
  for (const warning of warnings) params.log?.warn?.(warning);
1048
1230
  const registration = await registerSmsWebhookRoute(params);
1049
- if (registration.isActive()) params.log?.info?.(`Registered SMS webhook route ${params.account.webhookPath} for account ${params.account.accountId}`);
1050
- 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
+ });
1051
1238
  }
1052
1239
  //#endregion
1053
1240
  //#region extensions/sms/src/status.ts
1054
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
+ }
1055
1260
  function addTailscaleHint(account, hints) {
1056
1261
  let host;
1057
1262
  try {
@@ -1147,6 +1352,17 @@ function recentInboundSummary(messages) {
1147
1352
  dateSent: message.dateSent
1148
1353
  };
1149
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
+ }
1150
1366
  function webhookError(probe) {
1151
1367
  switch (probe.status) {
1152
1368
  case "matches":
@@ -1165,34 +1381,76 @@ function webhookError(probe) {
1165
1381
  async function probeSmsAccount(params) {
1166
1382
  const hints = [];
1167
1383
  addTailscaleHint(params.account, hints);
1168
- const webhook = params.account.fromNumber ? compareTwilioWebhook(params.account, (await listTwilioIncomingPhoneNumbers({
1169
- account: params.account,
1170
- phoneNumber: params.account.fromNumber,
1171
- fetchImpl: params.options?.fetchImpl,
1172
- timeoutMs: params.timeoutMs
1173
- }))[0]) : params.account.messagingServiceSid ? compareTwilioMessagingService(params.account, await retrieveTwilioMessagingService({
1174
- account: params.account,
1175
- serviceSid: params.account.messagingServiceSid,
1176
- fetchImpl: params.options?.fetchImpl,
1177
- timeoutMs: params.timeoutMs
1178
- })) : {
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 = {
1179
1390
  status: "unavailable",
1180
- reason: "Twilio SMS probe requires fromNumber or messagingServiceSid."
1391
+ reason: "Twilio webhook probe skipped because the probe timeout is too short."
1181
1392
  };
1182
- const recentInbound = recentInboundSummary(params.account.fromNumber ? await listTwilioMessages({
1183
- account: params.account,
1184
- to: params.account.fromNumber,
1185
- pageSize: 3,
1186
- fetchImpl: params.options?.fetchImpl,
1187
- timeoutMs: params.timeoutMs
1188
- }) : []);
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);
1189
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.");
1190
- 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(" ");
1191
1448
  return {
1192
1449
  ok: !error,
1193
1450
  ...error ? { error } : {},
1194
1451
  webhook,
1195
1452
  ...recentInbound ? { recentInbound } : {},
1453
+ ...recentOutbound ? { recentOutbound } : {},
1196
1454
  hints
1197
1455
  };
1198
1456
  }
@@ -1220,6 +1478,15 @@ function formatSmsProbeLines(probe) {
1220
1478
  tone: smsProbe.recentInbound.errorCode ? "warn" : "muted"
1221
1479
  });
1222
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
+ }
1223
1490
  for (const hint of smsProbe.hints ?? []) lines.push({
1224
1491
  text: hint,
1225
1492
  tone: "warn"
@@ -1383,25 +1650,12 @@ const smsSetupContract = defineChannelSetupContract({
1383
1650
  function createSmsReceipt(params) {
1384
1651
  const first = params.results[0];
1385
1652
  if (!first) throw new Error("SMS send did not return a Twilio Message SID.");
1653
+ const receipt = createSmsMessageReceipt(params);
1386
1654
  return {
1387
1655
  channel: CHANNEL_ID,
1388
1656
  messageId: first.sid,
1389
1657
  chatId: first.to,
1390
- receipt: createMessageReceiptFromOutboundResults({
1391
- results: params.results.map((result) => ({
1392
- channel: CHANNEL_ID,
1393
- messageId: result.sid,
1394
- chatId: result.to,
1395
- toJid: result.to,
1396
- conversationId: result.to,
1397
- meta: {
1398
- ...result.from ? { from: result.from } : {},
1399
- ...result.status ? { status: result.status } : {}
1400
- }
1401
- })),
1402
- threadId: first.to,
1403
- kind: params.kind
1404
- })
1658
+ receipt
1405
1659
  };
1406
1660
  }
1407
1661
  function resolveSmsTextChunkLimit(params) {
@@ -1415,19 +1669,83 @@ async function sendSmsText(ctx) {
1415
1669
  results: await sendSmsTextChunks({
1416
1670
  account,
1417
1671
  to,
1418
- text: ctx.text
1672
+ text: ctx.text,
1673
+ onPlatformSendDispatch: ctx.onPlatformSendDispatch,
1674
+ onDeliveryResult: ctx.onDeliveryResult
1419
1675
  }),
1420
1676
  kind: "text"
1421
1677
  });
1422
1678
  }
1679
+ const preparedSmsAttachmentAttempts = /* @__PURE__ */ new WeakMap();
1680
+ function resolveSmsAttachmentAttemptToken(attemptToken) {
1681
+ if (!isRecord(attemptToken) || typeof attemptToken.platformDispatchStarted !== "boolean" || !isRecord(attemptToken.attempt) || typeof attemptToken.attempt.cleanupHostedMedia !== "function") return;
1682
+ return attemptToken;
1683
+ }
1684
+ async function prepareSmsAttachmentAttempt(ctx) {
1685
+ const account = resolveSmsAccount(ctx.cfg, ctx.accountId);
1686
+ const to = normalizeSmsPhoneNumber(ctx.to) || account.defaultTo;
1687
+ if (!looksLikeSmsPhoneNumber(to)) throw new Error(`Invalid SMS target: ${ctx.to}`);
1688
+ return {
1689
+ account,
1690
+ to,
1691
+ attempt: await prepareSmsMediaAttempt({
1692
+ account,
1693
+ text: ctx.text,
1694
+ mediaUrl: ctx.mediaUrl,
1695
+ mediaAccess: ctx.mediaAccess,
1696
+ mediaLocalRoots: ctx.mediaLocalRoots,
1697
+ mediaReadFile: ctx.mediaReadFile
1698
+ }),
1699
+ platformDispatchStarted: false
1700
+ };
1701
+ }
1702
+ function getOrPrepareSmsAttachmentAttempt(ctx) {
1703
+ const existing = preparedSmsAttachmentAttempts.get(ctx);
1704
+ if (existing) return existing;
1705
+ const created = prepareSmsAttachmentAttempt(ctx);
1706
+ preparedSmsAttachmentAttempts.set(ctx, created);
1707
+ return created;
1708
+ }
1709
+ async function sendPreparedSmsAttachment(ctx) {
1710
+ const preparation = preparedSmsAttachmentAttempts.get(ctx);
1711
+ preparedSmsAttachmentAttempts.delete(ctx);
1712
+ if (!preparation) throw new Error("SMS message lifecycle did not prepare the MMS attachment.");
1713
+ const prepared = await preparation;
1714
+ return createSmsReceipt({
1715
+ results: await sendPreparedSmsMediaAttempt({
1716
+ ...prepared,
1717
+ onPlatformSendDispatch: async () => {
1718
+ await ctx.onPlatformSendDispatch?.();
1719
+ prepared.platformDispatchStarted = true;
1720
+ },
1721
+ onDeliveryResult: ctx.onDeliveryResult
1722
+ }),
1723
+ kind: "media"
1724
+ });
1725
+ }
1423
1726
  const smsMessageAdapter = defineChannelMessageAdapter({
1424
1727
  id: CHANNEL_ID,
1425
1728
  durableFinal: { capabilities: {
1426
1729
  text: true,
1427
- media: false,
1730
+ media: true,
1428
1731
  messageSendingHooks: true
1429
1732
  } },
1430
- send: { text: async (ctx) => await sendSmsText(ctx) }
1733
+ send: {
1734
+ lifecycle: {
1735
+ beforeSendAttempt: async (ctx) => {
1736
+ if (ctx.kind !== "media") return;
1737
+ return await getOrPrepareSmsAttachmentAttempt(ctx);
1738
+ },
1739
+ afterSendFailure: async (ctx) => {
1740
+ if (ctx.kind !== "media") return;
1741
+ const attemptToken = resolveSmsAttachmentAttemptToken(ctx.attemptToken);
1742
+ if (!attemptToken || attemptToken.platformDispatchStarted) return;
1743
+ await attemptToken.attempt.cleanupHostedMedia();
1744
+ }
1745
+ },
1746
+ text: async (ctx) => await sendSmsText(ctx),
1747
+ media: async (ctx) => await sendPreparedSmsAttachment(ctx)
1748
+ }
1431
1749
  });
1432
1750
  function resolveSmsOutboundSessionRoute(params) {
1433
1751
  const to = normalizeSmsPhoneNumber(params.resolvedTarget?.to ?? params.target);
@@ -1454,15 +1772,15 @@ const smsPlugin = createChatChannelPlugin({
1454
1772
  id: CHANNEL_ID,
1455
1773
  label: "SMS",
1456
1774
  selectionLabel: "SMS (Twilio)",
1457
- detailLabel: "Twilio SMS",
1775
+ detailLabel: "Twilio SMS/MMS",
1458
1776
  docsPath: "/channels/sms",
1459
1777
  docsLabel: "sms",
1460
- blurb: "Twilio-backed SMS with inbound webhooks and outbound replies.",
1778
+ blurb: "Twilio-backed SMS/MMS with inbound webhooks and outbound replies.",
1461
1779
  order: 88
1462
1780
  },
1463
1781
  capabilities: {
1464
1782
  chatTypes: ["direct"],
1465
- media: false,
1783
+ media: true,
1466
1784
  threads: false,
1467
1785
  reactions: false,
1468
1786
  edit: false,
@@ -1473,11 +1791,6 @@ const smsPlugin = createChatChannelPlugin({
1473
1791
  },
1474
1792
  reload: { configPrefixes: [`channels.${CHANNEL_ID}`] },
1475
1793
  configSchema: SmsChannelConfigSchema,
1476
- setup: { applyAccountConfig: ({ cfg, accountId, input }) => applySmsAccountConfig({
1477
- cfg,
1478
- accountId,
1479
- input
1480
- }) },
1481
1794
  setupContract: smsSetupContract,
1482
1795
  config: {
1483
1796
  ...smsConfigAdapter,
@@ -1494,6 +1807,7 @@ const smsPlugin = createChatChannelPlugin({
1494
1807
  messaging: {
1495
1808
  targetPrefixes: ["twilio-sms"],
1496
1809
  normalizeTarget: (target) => normalizeSmsPhoneNumber(target),
1810
+ inferTargetChatType: ({ to }) => looksLikeSmsPhoneNumber(normalizeSmsPhoneNumber(to)) ? "direct" : void 0,
1497
1811
  resolveOutboundSessionRoute: (params) => resolveSmsOutboundSessionRoute(params),
1498
1812
  targetResolver: {
1499
1813
  looksLikeId: looksLikeSmsPhoneNumber,
@@ -1506,35 +1820,47 @@ const smsPlugin = createChatChannelPlugin({
1506
1820
  ctx.log?.warn?.("SMS channel runtime is not available; webhook route not started");
1507
1821
  return;
1508
1822
  }
1823
+ const statusSink = createAccountStatusSink({
1824
+ accountId: ctx.account.accountId,
1825
+ setStatus: ctx.setStatus
1826
+ });
1509
1827
  return await startSmsGatewayAccount({
1510
1828
  cfg: ctx.cfg,
1511
1829
  account: ctx.account,
1512
1830
  channelRuntime: ctx.channelRuntime,
1513
1831
  abortSignal: ctx.abortSignal,
1514
- log: ctx.log
1832
+ log: ctx.log,
1833
+ statusSink
1515
1834
  });
1516
1835
  } },
1517
- status: {
1518
- buildAccountSnapshot: ({ account }) => {
1836
+ status: createComputedAccountStatusAdapter({
1837
+ defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID),
1838
+ resolveAccountSnapshot: ({ account }) => {
1519
1839
  const configured = isSmsAccountConfigured(account);
1520
1840
  return {
1521
1841
  accountId: account.accountId,
1522
1842
  name: account.fromNumber || account.messagingServiceSid || "SMS",
1523
1843
  enabled: account.enabled,
1524
1844
  configured,
1525
- statusState: !account.enabled ? "disabled" : configured ? "configured" : "unconfigured"
1845
+ extra: { statusState: !account.enabled ? "disabled" : configured ? "configured" : "unconfigured" }
1526
1846
  };
1527
1847
  },
1528
- probeAccount: async ({ account, timeoutMs }) => await probeSmsAccount({
1529
- account,
1530
- timeoutMs
1531
- }),
1848
+ probeAccount: async ({ account, timeoutMs }) => {
1849
+ const startedAt = Date.now();
1850
+ const deliveryRecords = await listRecentSmsDeliveryRecords(account);
1851
+ const elapsedMs = Math.max(0, Date.now() - startedAt);
1852
+ return await probeSmsAccount({
1853
+ account,
1854
+ timeoutMs: Math.max(1, timeoutMs - elapsedMs),
1855
+ options: { deliveryRecords }
1856
+ });
1857
+ },
1532
1858
  formatCapabilitiesProbe: ({ probe }) => formatSmsProbeLines(probe),
1533
1859
  buildCapabilitiesDiagnostics: async ({ account }) => ({ lines: collectSmsStartupWarnings(account).map((text) => ({
1534
1860
  text,
1535
1861
  tone: "warn"
1536
1862
  })) })
1537
- },
1863
+ }),
1538
1864
  secrets: {
1539
1865
  secretTargetRegistryEntries,
1540
1866
  collectRuntimeConfigAssignments
@@ -1542,7 +1868,7 @@ const smsPlugin = createChatChannelPlugin({
1542
1868
  agentPrompt: { messageToolHints: () => [
1543
1869
  "",
1544
1870
  "### SMS Formatting",
1545
- "SMS is plain text only. Keep replies brief, avoid markdown tables, and split long details into short messages."
1871
+ "SMS text is plain text. MMS attachments are supported; keep captions brief and avoid markdown tables."
1546
1872
  ] },
1547
1873
  message: smsMessageAdapter
1548
1874
  },