Skip to content

Commit 0758316

Browse files
authored
feat(sms): track Twilio delivery status (#118665)
* feat(sms): track Twilio delivery status * fix(sms): preserve Twilio delivery callbacks under inbound load * fix(sms): correct delivery status contracts * fix(sms): retry transient Twilio callback reads * fix(sms): bound delivery callback admission * docs(sms): clarify delivery callback recovery
1 parent 1be662a commit 0758316

20 files changed

Lines changed: 2565 additions & 75 deletions

‎docs/channels/index.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ install. Channels marked "official plugin" install with one command
3838
- [Reef](/channels/reef) - Reef channel setup: guarded, end-to-end-encrypted messaging between OpenClaw agents of different people (bundled plugin).
3939
- [Signal](/channels/signal) - Signal support via signal-cli (native daemon or bbernhard container), setup paths, and number model (official plugin).
4040
- [Slack](/channels/slack) - Slack setup and runtime behavior (Socket Mode, HTTP Request URLs, and relay mode) (official plugin).
41-
- [SMS](/channels/sms) - Twilio SMS/MMS setup, access controls, and webhook configuration (official plugin).
41+
- [SMS](/channels/sms) - Twilio SMS/MMS setup, access controls, webhooks, and delivery status (official plugin).
4242
- [Synology Chat](/channels/synology-chat) - Synology Chat webhook setup and OpenClaw config (official plugin).
4343
- [Telegram](/channels/telegram) - Telegram bot support status, capabilities, and configuration (bundled plugin).
4444
- [Tlon](/channels/tlon) - Tlon/Urbit support status, capabilities, and configuration (official plugin).

‎docs/channels/sms.md‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
---
2-
summary: "Twilio SMS/MMS setup, access controls, and webhook configuration"
2+
summary: "Twilio SMS/MMS setup, access controls, webhooks, and delivery status"
33
read_when:
44
- You want to connect OpenClaw to SMS or MMS through Twilio
55
- You need SMS/MMS webhook or allowlist setup
66
title: "SMS"
77
---
88

9-
OpenClaw receives and sends SMS/MMS through a Twilio phone number or Messaging Service. The Gateway registers an inbound webhook route (default `/webhooks/sms`), validates Twilio request signatures by default, and sends replies back through Twilio's Messages API.
9+
OpenClaw receives and sends SMS/MMS through a Twilio phone number or Messaging Service. The Gateway registers a webhook route (default `/webhooks/sms`), validates Twilio request signatures by default, sends replies through Twilio's Messages API, and records outbound delivery callbacks.
1010

1111
Status: official plugin, installed separately. SMS text and MMS attachments, direct messages only.
1212

@@ -325,12 +325,18 @@ Outbound OpenClaw deliveries attach one media item. OpenClaw caps JPEG, JPG, PNG
325325

326326
For incoming MMS, OpenClaw processes at most 10 attachments and downloads at most 5 MiB total. Any additional or unavailable attachments produce a visible unavailable-media notice instead of discarding the signed message or silently delivering an empty turn. Downloads happen only after sender authorization, with Twilio authentication and an `api.twilio.com` host restriction.
327327

328+
### Delivery status
329+
330+
After each successful outbound send, OpenClaw stores the initial Twilio API status when the response includes one. When `publicWebhookUrl` is valid, every outbound message also gives Twilio a derived `StatusCallback` URL that preserves its base URL and connection overrides while adding the required delivery-callback retry settings. Invalid or oversized derived URLs are omitted.
331+
332+
Later delivery callbacks update the same plugin-scoped SQLite record. Semantic retries are deduplicated, older transitions cannot regress a terminal state, and conflicting terminal observations are reported as `conflicted` instead of choosing a false winner. Records contain message SIDs, status/error metadata, and timestamps, but not message bodies or phone-number addresses. Each record is retained for up to 30 days after its latest observation, subject to the plugin-wide 5,000-message cap and oldest-record eviction.
333+
328334
## Verify Setup
329335

330336
After the Gateway starts:
331337

332338
1. Confirm the Gateway log shows the SMS webhook route.
333-
2. Run a Twilio-side probe (checks the configured Twilio webhook URL/method and recent inbound errors):
339+
2. Run a Twilio-side probe (checks the configured Twilio webhook URL/method, recent inbound errors, and the most recent stored outbound delivery state):
334340

335341
```bash
336342
openclaw channels capabilities --channel sms
@@ -369,14 +375,19 @@ The webhook route also enforces, independent of signature validation:
369375

370376
- `POST` only.
371377
- Failed-request budget of 300 requests per minute per SMS account, webhook route, and resolved client address. All requests count toward this budget, but HTTP 429 is applied only after body parsing or Twilio signature validation fails.
378+
- Signed delivery callbacks are classified before inbound sender quotas and commit to bounded, plugin-scoped SQLite state before HTTP 200. They do not consume inbound dispatch quotas: those quotas protect raw inbound message admission and downstream agent dispatch. Delivery persistence instead has a separate 3,000-callback-per-minute safety fuse per SMS account route and returns HTTP 503 without the durable-acceptance marker above that limit. This is fail-closed overload protection, not lossless backpressure. With signature validation disabled, delivery callbacks first use the stricter 30/minute resolved-client-address cap before persistence.
372379
- Dispatchable callback rate limit of 30 accepted callbacks per minute per SMS account, webhook route, and validated sender after body parsing and signature validation pass (HTTP 429 above that). The sender key is the canonicalized, signature-covered `From` value, so equivalent SMS/RCS address forms share one budget, one flooding sender exhausts only its own budget, and callbacks from other senders behind Twilio's shared egress addresses remain dispatchable. Invalid or missing sender values share a separate empty-sender budget.
373380
- Aggregate validated-callback ceiling of 300 accepted callbacks per minute per SMS account and webhook route. This bounds durable-ingress pressure from many distinct signed senders without recreating shared-egress cross-throttling. If signature validation is disabled, nothing authenticates `From`; the stricter 30/min resolved-client-address dispatch cap applies instead of the validated sender and aggregate policy.
374381
- Client addresses are resolved through the shared Gateway trusted-proxy rules. If `gateway.trustedProxies` contains the reverse proxy that forwards Twilio callbacks, OpenClaw keys the address-based limits from the forwarded client address; otherwise it falls back to the direct socket address.
375-
- The payload `AccountSid` must exactly match the configured `accountSid`. Direct-number callbacks must target the configured `fromNumber`; Messaging Service callbacks must carry the configured `MessagingServiceSid`. The raw callback is first committed to the durable ingress queue and acknowledged; an identity mismatch is then marked as a permanent invalid-payload failure during drain and is never dispatched or allowed to download media.
382+
- Inbound payloads must carry a nonempty `AccountSid` that exactly matches the configured `accountSid`. Direct-number callbacks must target the configured `fromNumber`; Messaging Service callbacks must carry the configured `MessagingServiceSid`. The raw callback is first committed to the durable ingress queue and acknowledged; an identity mismatch is then marked as a permanent invalid-payload failure during drain and is never dispatched or allowed to download media.
383+
- Delivery callbacks with a missing or different `AccountSid` are acknowledged, logged, and intentionally not stored.
376384
- Replayed `MessageSid` values are deduplicated by the durable ingress queue. Completed-message tombstones are retained for 24 hours (up to 20,000 entries per account); permanent-failure tombstones are retained for 30 days (up to 1,000 entries).
385+
- Delivery observations use a semantic, non-PII fingerprint of source, message SID, normalized status, error code, and carrier completion date. Multiple states for one outbound message remain distinct. Records expire 30 days after their latest observation, while the 5,000-message cap can evict older records sooner.
377386
- Request bodies over 32 KB are rejected.
378387

379-
Twilio does not retry HTTP 429 by default. The `#rp=4xx` and `#rp=all` connection overrides opt into 4xx retries, but Twilio caps the complete retry transaction at 15 seconds. Configure a fallback URL when another handler must receive failed deliveries; treat a 429 as a fail-closed rejection, not reliable backpressure.
388+
OpenClaw adds the `5xx` retry policy and a retry count to generated delivery `StatusCallback` URLs so Twilio can retry a failed SQLite commit or an overloaded delivery-state route. Twilio does not retry HTTP 429 by default. The `#rp=4xx` and `#rp=all` connection overrides opt into 4xx retries, but Twilio caps the complete retry transaction at 15 seconds. Neither a 429 nor a delivery-state 503 guarantees later recovery; use reconciliation when final-state completeness matters. Missed intermediate transitions cannot be reconstructed.
389+
390+
For completeness-sensitive workflows, persist Message SIDs and reconcile stale nonterminal records by polling Twilio's Message resource. Twilio's [delivery logging guidance](https://www.twilio.com/docs/messaging/guides/outbound-message-logging) recommends polling when a message has not reached `delivered` or `undelivered` within 12 hours because a status callback may not have arrived. The SMS fallback URL is not a substitute: it only handles failures retrieving or executing the [inbound SMS TwiML webhook](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource).
380391

381392
For local tunnel testing only, you can set:
382393

‎extensions/sms/src/accounts.test.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Sms tests cover accounts plugin behavior.
22
import { afterEach, describe, expect, it } from "vitest";
3-
import { listSmsAccountIds, resolveSmsAccount } from "./accounts.js";
3+
import { inspectSmsAccount, listSmsAccountIds, resolveSmsAccount } from "./accounts.js";
44
import { SmsChannelConfigSchema } from "./config-schema.js";
55
import type { SmsChannelConfig } from "./types.js";
66

@@ -68,6 +68,24 @@ describe("SMS account config", () => {
6868
});
6969
});
7070

71+
it("reports an invalid public webhook URL without unconfiguring SMS credentials", () => {
72+
expect(
73+
inspectSmsAccount({
74+
channels: {
75+
sms: {
76+
accountSid: "AC123",
77+
authToken: "secret",
78+
fromNumber: "+15557654321",
79+
publicWebhookUrl: "https://sms_gateway.example.com/webhooks/sms",
80+
},
81+
},
82+
}),
83+
).toMatchObject({
84+
configured: true,
85+
signatureValidation: "invalid-public-url",
86+
});
87+
});
88+
7189
it("merges named accounts over the top-level defaults", () => {
7290
const cfg = {
7391
channels: {

‎extensions/sms/src/accounts.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
} from "openclaw/plugin-sdk/secret-input";
1515
import { normalizeStringEntries } from "openclaw/plugin-sdk/string-coerce-runtime";
1616
import { normalizeSmsAllowFrom, normalizeSmsPhoneNumber } from "./phone.js";
17+
import { parseSmsPublicWebhookUrl } from "./public-webhook-url.js";
1718
import type { ResolvedSmsAccount, SmsChannelConfig } from "./types.js";
1819

1920
const CHANNEL_ID = "sms";
@@ -143,10 +144,13 @@ export function inspectSmsAccount(cfg: OpenClawConfig, accountId?: string | null
143144
configured,
144145
tokenStatus: account.authToken ? "available" : "missing",
145146
webhookPath: account.webhookPath,
146-
signatureValidation:
147-
account.dangerouslyDisableSignatureValidation || account.publicWebhookUrl
148-
? "configured"
149-
: "missing-public-url",
147+
signatureValidation: account.dangerouslyDisableSignatureValidation
148+
? "configured"
149+
: !account.publicWebhookUrl
150+
? "missing-public-url"
151+
: parseSmsPublicWebhookUrl(account.publicWebhookUrl)
152+
? "configured"
153+
: "invalid-public-url",
150154
};
151155
}
152156

‎extensions/sms/src/channel.test.ts‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Sms tests cover channel plugin behavior.
22
import { isChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
33
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4+
import type { SmsDeliveryRecord } from "./delivery-observations.js";
5+
import type { probeSmsAccount as probeSmsAccountType } from "./status.js";
46
import type { sendSmsViaTwilio as sendSmsViaTwilioType } from "./twilio.js";
57

68
type ChannelModule = typeof import("./channel.js");
@@ -31,6 +33,17 @@ const hostedMediaMocks = vi.hoisted(() => {
3133
})),
3234
};
3335
});
36+
const listRecentSmsDeliveryRecords = vi.hoisted(() =>
37+
vi.fn(async (): Promise<SmsDeliveryRecord[]> => []),
38+
);
39+
const recordInitialSmsDeliveryResult = vi.hoisted(() => vi.fn(async () => null));
40+
const probeSmsAccount = vi.hoisted(() =>
41+
vi.fn<typeof probeSmsAccountType>(async () => ({
42+
ok: true,
43+
webhook: { status: "skipped" as const, reason: "test" },
44+
hints: [],
45+
})),
46+
);
3447

3548
beforeEach(async () => {
3649
vi.resetModules();
@@ -51,20 +64,35 @@ beforeEach(async () => {
5164
url: "https://gateway.example.com/webhooks/sms/media/abc?token=token",
5265
cleanup: hostedMediaMocks.cleanup,
5366
});
67+
listRecentSmsDeliveryRecords.mockClear();
68+
recordInitialSmsDeliveryResult.mockReset();
69+
recordInitialSmsDeliveryResult.mockResolvedValue(null);
70+
probeSmsAccount.mockClear();
5471
vi.doMock("./twilio.js", () => ({
5572
sendSmsViaTwilio,
5673
TWILIO_MESSAGE_BODY_MAX_LENGTH: 1600,
5774
}));
5875
vi.doMock("./media.js", () => ({
5976
prepareHostedSmsMedia: hostedMediaMocks.prepare,
6077
}));
78+
vi.doMock("./delivery-observations.js", () => ({
79+
listRecentSmsDeliveryRecords,
80+
recordInitialSmsDeliveryResult,
81+
}));
82+
vi.doMock("./status.js", () => ({
83+
probeSmsAccount,
84+
formatSmsProbeLines: vi.fn(() => []),
85+
}));
6186
({ PlatformMessageNotDispatchedError } = await import("openclaw/plugin-sdk/error-runtime"));
6287
({ smsPlugin } = await import("./channel.js"));
6388
});
6489

6590
afterEach(() => {
91+
vi.useRealTimers();
6692
vi.doUnmock("./twilio.js");
6793
vi.doUnmock("./media.js");
94+
vi.doUnmock("./delivery-observations.js");
95+
vi.doUnmock("./status.js");
6896
});
6997

7098
describe("smsPlugin status", () => {
@@ -120,6 +148,91 @@ describe("smsPlugin status", () => {
120148

121149
expect(snapshot).toMatchObject({ lifecycle: "blocked", terminalDisconnect: true });
122150
});
151+
152+
it("loads delivery observations with the full Twilio account identity", async () => {
153+
const account = {
154+
accountId: "support",
155+
enabled: true,
156+
accountSid: "AC-support",
157+
authToken: "secret",
158+
fromNumber: "+15557654321",
159+
messagingServiceSid: "",
160+
defaultTo: "",
161+
webhookPath: "/webhooks/sms",
162+
publicWebhookUrl: "https://gateway.example.com/webhooks/sms",
163+
dangerouslyDisableSignatureValidation: false,
164+
dmPolicy: "pairing" as const,
165+
allowFrom: [],
166+
textChunkLimit: 1500,
167+
};
168+
const records = [
169+
{
170+
accountId: "support",
171+
accountSidHash: "account-sid-hash",
172+
messageSid: "SM123",
173+
status: "delivered",
174+
firstObservedAt: 1,
175+
lastObservedAt: 2,
176+
observations: [],
177+
},
178+
];
179+
listRecentSmsDeliveryRecords.mockResolvedValueOnce(records);
180+
181+
await smsPlugin.status?.probeAccount?.({
182+
cfg: {},
183+
account,
184+
timeoutMs: 1000,
185+
});
186+
187+
expect(listRecentSmsDeliveryRecords).toHaveBeenCalledWith(account);
188+
expect(probeSmsAccount).toHaveBeenCalledWith({
189+
account,
190+
timeoutMs: expect.any(Number),
191+
options: { deliveryRecords: records },
192+
});
193+
const remainingTimeoutMs = probeSmsAccount.mock.calls[0]?.[0]?.timeoutMs;
194+
expect(remainingTimeoutMs).toBeGreaterThan(0);
195+
expect(remainingTimeoutMs).toBeLessThanOrEqual(1000);
196+
});
197+
198+
it("passes only the remaining probe budget after loading delivery observations", async () => {
199+
vi.useFakeTimers();
200+
const account = {
201+
accountId: "support",
202+
enabled: true,
203+
accountSid: "AC-support",
204+
authToken: "secret",
205+
fromNumber: "+15557654321",
206+
messagingServiceSid: "",
207+
defaultTo: "",
208+
webhookPath: "/webhooks/sms",
209+
publicWebhookUrl: "https://gateway.example.com/webhooks/sms",
210+
dangerouslyDisableSignatureValidation: false,
211+
dmPolicy: "pairing" as const,
212+
allowFrom: [],
213+
textChunkLimit: 1500,
214+
};
215+
listRecentSmsDeliveryRecords.mockImplementationOnce(
216+
async () =>
217+
await new Promise<SmsDeliveryRecord[]>((resolve) => {
218+
setTimeout(() => resolve([]), 250);
219+
}),
220+
);
221+
222+
const probe = smsPlugin.status?.probeAccount?.({
223+
cfg: {},
224+
account,
225+
timeoutMs: 1000,
226+
});
227+
await vi.advanceTimersByTimeAsync(250);
228+
await probe;
229+
230+
expect(probeSmsAccount).toHaveBeenCalledWith({
231+
account,
232+
timeoutMs: 750,
233+
options: { deliveryRecords: [] },
234+
});
235+
});
123236
});
124237

125238
describe("smsPlugin outbound", () => {

‎extensions/sms/src/channel.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
resolveSmsAccount,
3636
} from "./accounts.js";
3737
import { SmsChannelConfigSchema } from "./config-schema.js";
38+
import { listRecentSmsDeliveryRecords } from "./delivery-observations.js";
3839
import { collectSmsStartupWarnings, startSmsGatewayAccount } from "./gateway.js";
3940
import type { SmsChannelRuntime } from "./inbound.js";
4041
import {
@@ -472,7 +473,16 @@ export const smsPlugin: ChannelPlugin<ResolvedSmsAccount, SmsProbe> = createChat
472473
},
473474
};
474475
},
475-
probeAccount: async ({ account, timeoutMs }) => await probeSmsAccount({ account, timeoutMs }),
476+
probeAccount: async ({ account, timeoutMs }) => {
477+
const startedAt = Date.now();
478+
const deliveryRecords = await listRecentSmsDeliveryRecords(account);
479+
const elapsedMs = Math.max(0, Date.now() - startedAt);
480+
return await probeSmsAccount({
481+
account,
482+
timeoutMs: Math.max(1, timeoutMs - elapsedMs),
483+
options: { deliveryRecords },
484+
});
485+
},
476486
formatCapabilitiesProbe: ({ probe }) => formatSmsProbeLines(probe),
477487
buildCapabilitiesDiagnostics: async ({ account }) => ({
478488
lines: collectSmsStartupWarnings(account).map((text) => ({ text, tone: "warn" })),

0 commit comments

Comments
 (0)