Skip to content

Commit 9af50ee

Browse files
committed
feat(sms): track Twilio delivery status
1 parent 0fdd04b commit 9af50ee

18 files changed

Lines changed: 2156 additions & 55 deletions

‎docs/channels/sms.md‎

Lines changed: 13 additions & 4 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

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

324324
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.
325325

326+
### Delivery status
327+
328+
After each successful outbound send, OpenClaw stores the initial Twilio API status when the response includes one. When `publicWebhookUrl` is configured, every outbound message also gives Twilio that same URL, including any connection-override fragment, as its `StatusCallback`.
329+
330+
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.
331+
326332
## Verify Setup
327333

328334
After the Gateway starts:
329335

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

333339
```bash
334340
openclaw channels capabilities --channel sms
@@ -367,11 +373,14 @@ The webhook route also enforces, independent of signature validation:
367373

368374
- `POST` only.
369375
- 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.
376+
- Signed delivery callbacks are classified before inbound sender quotas. They use a separate ceiling of 3,000 callbacks per minute per SMS account and webhook route, then commit to plugin-scoped SQLite state before HTTP 200. With signature validation disabled, delivery callbacks first use the stricter 30/minute resolved-client-address cap before persistence.
370377
- 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.
371378
- 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.
372379
- 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.
373-
- 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.
380+
- 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.
381+
- Delivery callbacks with a missing or different `AccountSid` are acknowledged, logged, and intentionally not stored.
374382
- 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).
383+
- 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.
375384
- Request bodies over 32 KB are rejected.
376385

377386
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.

‎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");
@@ -21,6 +23,17 @@ const sendSmsViaTwilio = vi.hoisted(() =>
2123
const prepareHostedSmsMediaUrl = vi.hoisted(() =>
2224
vi.fn(async () => "https://gateway.example.com/webhooks/sms/media/abc?token=token"),
2325
);
26+
const listRecentSmsDeliveryRecords = vi.hoisted(() =>
27+
vi.fn(async (): Promise<SmsDeliveryRecord[]> => []),
28+
);
29+
const recordInitialSmsDeliveryResult = vi.hoisted(() => vi.fn(async () => null));
30+
const probeSmsAccount = vi.hoisted(() =>
31+
vi.fn<typeof probeSmsAccountType>(async () => ({
32+
ok: true,
33+
webhook: { status: "skipped" as const, reason: "test" },
34+
hints: [],
35+
})),
36+
);
2437

2538
beforeEach(async () => {
2639
vi.resetModules();
@@ -38,19 +51,34 @@ beforeEach(async () => {
3851
prepareHostedSmsMediaUrl.mockResolvedValue(
3952
"https://gateway.example.com/webhooks/sms/media/abc?token=token",
4053
);
54+
listRecentSmsDeliveryRecords.mockClear();
55+
recordInitialSmsDeliveryResult.mockReset();
56+
recordInitialSmsDeliveryResult.mockResolvedValue(null);
57+
probeSmsAccount.mockClear();
4158
vi.doMock("./twilio.js", () => ({
4259
sendSmsViaTwilio,
4360
TWILIO_MESSAGE_BODY_MAX_LENGTH: 1600,
4461
}));
4562
vi.doMock("./media.js", () => ({
4663
prepareHostedSmsMediaUrl,
4764
}));
65+
vi.doMock("./delivery-observations.js", () => ({
66+
listRecentSmsDeliveryRecords,
67+
recordInitialSmsDeliveryResult,
68+
}));
69+
vi.doMock("./status.js", () => ({
70+
probeSmsAccount,
71+
formatSmsProbeLines: vi.fn(() => []),
72+
}));
4873
({ smsPlugin } = await import("./channel.js"));
4974
});
5075

5176
afterEach(() => {
77+
vi.useRealTimers();
5278
vi.doUnmock("./twilio.js");
5379
vi.doUnmock("./media.js");
80+
vi.doUnmock("./delivery-observations.js");
81+
vi.doUnmock("./status.js");
5482
});
5583

5684
describe("smsPlugin status", () => {
@@ -106,6 +134,91 @@ describe("smsPlugin status", () => {
106134

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

111224
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 {
@@ -442,7 +443,16 @@ export const smsPlugin: ChannelPlugin<ResolvedSmsAccount, SmsProbe> = createChat
442443
},
443444
};
444445
},
445-
probeAccount: async ({ account, timeoutMs }) => await probeSmsAccount({ account, timeoutMs }),
446+
probeAccount: async ({ account, timeoutMs }) => {
447+
const startedAt = Date.now();
448+
const deliveryRecords = await listRecentSmsDeliveryRecords(account);
449+
const elapsedMs = Math.max(0, Date.now() - startedAt);
450+
return await probeSmsAccount({
451+
account,
452+
timeoutMs: Math.max(1, timeoutMs - elapsedMs),
453+
options: { deliveryRecords },
454+
});
455+
},
446456
formatCapabilitiesProbe: ({ probe }) => formatSmsProbeLines(probe),
447457
buildCapabilitiesDiagnostics: async ({ account }) => ({
448458
lines: collectSmsStartupWarnings(account).map((text) => ({ text, tone: "warn" })),

0 commit comments

Comments
 (0)