Twilio Connector (experimental)
Send SMS / MMS and configure Twilio messaging from a Caffeine canister.
⚠️ Experimental (twilio-client@0.1.2) — no call has ever been made from this
client. Its write path could work at all only recently: before, every write
discarded its arguments and posted an empty body. The wire format now matches
what Twilio documents (form-encoded body, percent-encoded values, optional
fields omitted) and all 118 files typecheck, but structurally correct is not
verified. Treat the first successful send as the acceptance
test, and do not present Twilio to a user as a fully supported platform feature
until one has happened. Sends cost money, so a failed experiment is not free.
Scope — the package is the messaging surface only. twilio-client is
pruned to 35 API modules (all of Messaging v1 plus the v2010 messaging path:
Account, Message, Media, IncomingPhoneNumber and its variants,
AvailablePhoneNumber, the A2P registries). Voice/calls, recordings, conferences,
queues, applications, SIP and usage records are not in the package — if a
build needs those, they are outside this connector. (Counts: 35 API modules, 82
models, 118 files, all typechecking.)
Orchestrator routing notes
Load this skill when the user, spec, or a prior task mentions sending a text
message, SMS/MMS, notifying someone by phone, buying or listing phone numbers, or
any Twilio messaging concept. Raw ic.http_request to *.twilio.com is an
anti-pattern that re-implements auth, host routing, percent-encoding and JSON
parsing by hand — and, done naively, sends every message ~13 times.
Intent → capability mapping:
| User intent |
Capability |
| Send an SMS |
Api20100401MessageApi.createMessage with from = a Twilio number |
| Send an MMS (image) |
same, with mediaUrl = ["https://…"] and sendAsMms = true |
| Send via a Messaging Service (recommended for US traffic) |
same, from = "" + messagingServiceSid |
| Check delivery status |
fetchMessage (status, error_code) |
| List / search sent messages |
listMessage (paginated) |
| Own or browse phone numbers |
Api20100401IncomingPhoneNumberApi, …AvailablePhoneNumberCountryApi |
| Set up a Messaging Service |
MessagingV1ServiceApi.createService |
| Register for US A2P 10DLC |
MessagingV1BrandRegistrationApi → MessagingV1UsAppToPersonApi → MessagingV1PhoneNumberApi (in that order — see US A2P 10DLC) |
| Verify a toll-free number |
MessagingV1TollfreeVerificationApi |
Twilio credentials are something a human must go and fetch from a console, so
the build is not done when the backend compiles — it is done when the app tells
the admin where to get the credential and gives them somewhere to paste it. See
Auth model, then Frontend for the page that MUST ship, and repeat the steps in
the completion message.
Ask before writing code: which number sends? A US-bound production app needs a
Messaging Service + A2P registration (weeks of lead time, real fees); a
demo/internal app can send from a single trial number to verified recipients
only. Report the choice and its consequences back to the prompting user.
Auth model — HTTP Basic, two flavours
Both flavours are the same #basicAuth { user; password } credential and the
client treats them identically; they differ in blast radius.
| Flavour |
user / password |
When |
| API Key (default — prefer this) |
API Key SID (SK…) / its Secret |
Production. Revocable and scoped: leaking one does not surrender the account. |
| Account SID + Auth Token |
Account SID (AC…) / Auth Token |
Dev only. The Auth Token is the account — it can create sub-accounts, buy numbers, and spend money. |
The Account SID (AC…) is also a required positional argument to every
v2010 operation (it is in the URL path), regardless of which flavour is used. So
an app using an API Key stores three values: Account SID, Key SID, Key Secret.
Obtaining credentials
- Sign in at https://console.twilio.com.
- The Account SID (
AC…) is on the console dashboard — copy it.
- For production, Account → API keys & tokens → Create API key (Standard);
copy the SID (
SK…) and the Secret. The Secret is shown once — if
the admin navigates away it cannot be recovered, only replaced.
For dev only, take the Auth Token from the dashboard instead.
- Buy a sending number: Phone Numbers → Manage → Buy a number, with the
SMS capability ticked (not every number has it).
- On a trial account: verify each recipient under Phone Numbers → Verified
Caller IDs, or sends fail with
21608; trial messages also carry a
"Sent from your Twilio trial account" prefix.
Handing the credentials to the canister
The admin pastes them through an admin-gated setter — gated on
AccessControl.hasPermission(state, caller, #admin). They are held by the
canister only and never returned to the frontend.
⚠️ Never gate the setter on a first-caller-claims-ownership scheme. On the
IC every unauthenticated caller is the same anonymous principal, so if an
anonymous call claims ownership first, every anonymous caller passes the
caller == owner check and can overwrite the credential — and this one spends
money.
The canister hands them to the client only through
config.auth = ?#basicAuth { user; password }, which every method turns into an
Authorization: Basic … header. No method takes a credential argument and none
puts it in the URL, so it cannot leak through a logged query string.
Outcalls are already non-replicated — and this CORRECTS earlier guidance
defaultConfig ships is_replicated = ?false, so anything derived from it by
record update is correct as-is. Nothing to remember, nothing to add.
⚠️ Do not set it to ?true or null, and disregard any older advice to do
so. An older version of this SKILL claimed writes should stay
replicated "so IC consensus dedups retries". That is false and expensive. A
replicated outcall is performed by every node in the subnet: the request is
sent 13 times, so **13 SMS are sent and ~13 are billed**, the credential
leaves every node, and consensus fails anyway because Twilio stamps each reply
with a unique sid (so the responses never agree byte-for-byte). This is the
same defect that produced ~13 duplicate emails via the Gmail connector and drove
slack-client 0.1.0.
Reads (fetch* / list*) are equally fine non-replicated: one node's view of a
message log is what you want, and it is the cheaper path.
Backend
Add dependencies
The admin gate in the recipe below needs the authorization component alongside the
client:
mops add twilio-client@0.1.2
mops add caffeineai-authorization@1.0.1
Calling shape — free functions or the class facade
Every module offers both. The free function takes config first and is async*;
the module class captures config and is async:
// Illustrative sketch, not a file to copy: `cfg`/`accountSid` are assumed to
// exist and the argument lists are elided. Marked motoko-check:skip for that
// reason — the compiled examples are the three mixins below.
import MessageApi "mo:twilio-client/Apis/Api20100401MessageApi";
// free function — config passed explicitly
let m = await* MessageApi.createMessage(cfg, accountSid, /* … */);
// class facade — config captured once
let messages = MessageApi.Api20100401MessageApi(cfg);
let m2 = await messages.createMessage(accountSid, /* … */);
All parameters are positional and there are 27 of them on createMessage.
Pass "" / false / 0 / 0.0 / [] / null for the ones you do not
use — the optional enum parameters are ?T precisely so that null omits them
from the wire. Count carefully; a misplaced empty string silently sends the
wrong field. The order is:
config, accountSid, to, statusCallback, applicationSid, maxPrice, provideFeedback, attempt, validityPeriod, forceDelivery, contentRetention, addressRetention, smartEncoded, persistentAction, trafficType, shortenUrls, scheduleType, sendAt, sendAsMms, contentVariables, riskCheck, from, fallbackFrom, messagingServiceSid, body, mediaUrl, contentSid
The recipe
import AccessControl "mo:caffeineai-authorization/access-control";
import MixinAuthorization "mo:caffeineai-authorization/MixinAuthorization";
import MixinTwilioConfig "mixins/twilio-config";
import MixinTwilioMessaging "mixins/twilio-messaging";
actor {
let accessControlState : AccessControl.AccessControlState;
include MixinAuthorization(accessControlState, null);
// Admin-held Twilio credentials — never returned to the frontend.
let twilioConfig : {
var accountSid : Text; // AC… — also a positional arg on every v2010 call
var keySid : Text; // SK… (or the Account SID again, in dev)
var keySecret : Text; // the API-key secret (or the Auth Token, in dev)
var fromNumber : Text; // E.164, e.g. "+15551234567"
};
include MixinTwilioConfig(accessControlState, twilioConfig);
include MixinTwilioMessaging(twilioConfig);
};
The migration chain head:
import AccessControl "mo:caffeineai-authorization/access-control";
module {
type NewActor = {
accessControlState : AccessControl.AccessControlState;
twilioConfig : {
var accountSid : Text;
var keySid : Text;
var keySecret : Text;
var fromNumber : Text;
};
};
public func migration(_old : {}) : NewActor {
{
accessControlState = AccessControl.initState();
twilioConfig = {
var accountSid = "";
var keySid = "";
var keySecret = "";
var fromNumber = "";
};
};
};
};
import AccessControl "mo:caffeineai-authorization/access-control";
import Runtime "mo:core/Runtime";
mixin (
accessControlState : AccessControl.AccessControlState,
twilioConfig : {
var accountSid : Text;
var keySid : Text;
var keySecret : Text;
var fromNumber : Text;
},
) {
// All THREE are required, and this must agree with the guard in
// twilio-messaging.mo: `keySid` is the Basic-Auth *username*, so a blank one
// means every request goes out unauthenticated and Twilio answers 20003 —
// while the UI cheerfully reports "Configured".
public query func isTwilioConfigured() : async Bool {
twilioConfig.accountSid.size() > 0 and twilioConfig.keySid.size() > 0 and twilioConfig.keySecret.size() > 0;
};
// The sending number is not a secret — the UI may display it.
public query func getTwilioFromNumber() : async Text {
twilioConfig.fromNumber;
};
// Admin-only. NOTE `#admin` — never a first-caller-claims-ownership check,
// which the shared anonymous principal would defeat.
public shared ({ caller }) func setTwilioCredentials(
accountSid : Text,
keySid : Text,
keySecret : Text,
) : async () {
if (not AccessControl.hasPermission(accessControlState, caller, #admin)) {
Runtime.trap("Unauthorized: Only admins can set Twilio credentials");
};
twilioConfig.accountSid := accountSid;
twilioConfig.keySid := keySid;
twilioConfig.keySecret := keySecret;
};
public shared ({ caller }) func setTwilioFromNumber(number : Text) : async () {
if (not AccessControl.hasPermission(accessControlState, caller, #admin)) {
Runtime.trap("Unauthorized: Only admins can set the sending number");
};
twilioConfig.fromNumber := number;
};
};
import Principal "mo:core/Principal";
import Runtime "mo:core/Runtime";
import { createMessage } "mo:twilio-client/Apis/Api20100401MessageApi";
import { defaultConfig; type Config } "mo:twilio-client/Config";
mixin (
twilioConfig : {
var accountSid : Text;
var keySid : Text;
var keySecret : Text;
var fromNumber : Text;
},
) {
// Credentials ride config.auth; defaultConfig is already non-replicated.
func twilioClientConfig() : Config {
{
defaultConfig with
auth = ?#basicAuth { user = twilioConfig.keySid; password = twilioConfig.keySecret };
max_response_bytes = ?(200_000 : Nat64);
};
};
/// Send an SMS to `to` (E.164). Returns the message SID.
public shared ({ caller }) func sendSms(to : Text, body : Text) : async Text {
if (caller.isAnonymous()) Runtime.trap("Sign in to send messages");
// Same three-way check as isTwilioConfigured(): accountSid goes in the URL
// path, keySid is the Basic-Auth user, keySecret the password. Missing any
// one of them fails at Twilio, not here, so check before spending cycles.
if (
twilioConfig.accountSid.size() == 0 or twilioConfig.keySid.size() == 0 or twilioConfig.keySecret.size() == 0
) {
Runtime.trap("Twilio is not configured (an admin must set all three credentials)");
};
let msg = await* createMessage(
twilioClientConfig(),
twilioConfig.accountSid, // accountSid — in the URL path, not the credential
to, // to (E.164)
"", "", // statusCallback, applicationSid
0.0, // maxPrice (0 = no cap)
false, // provideFeedback
0, 0, // attempt, validityPeriod
false, // forceDelivery
null, null, // contentRetention, addressRetention (omitted)
false, // smartEncoded
[], // persistentAction
null, // trafficType (omitted)
false, // shortenUrls
null, // scheduleType — MUST be null for an immediate send
"", // sendAt (scheduled sends only)
false, // sendAsMms
"", // contentVariables
null, // riskCheck (omitted)
twilioConfig.fromNumber, // from (use EITHER from OR messagingServiceSid)
"", // fallbackFrom
"", // messagingServiceSid
body, // body
[], // mediaUrl (set for MMS)
"", // contentSid (Content API templates)
);
// `sid` is optional in the generated model because the spec marks it
// nullable, though Twilio always sets it on a successful create. Fall back
// to "" rather than trapping: the outcall has already happened, so a trap
// would roll back this canister's own state while the SMS stays delivered.
switch (msg.sid) { case (?sid) sid; case null "" };
};
};
For MMS: mediaUrl = ["https://example.com/image.jpg"] and sendAsMms = true.
To send through a Messaging Service, leave from = "" and set
messagingServiceSid instead.
Addressing — E.164, and which sender
to must be E.164: +, country code, no spaces, dashes or parentheses —
"+15551234567". "555-1234" fails with 21211. Normalize in the frontend and
again in the canister; do not trust either alone.
from vs messagingServiceSid — exactly one. Setting both is an error.
A bare from number is fine for non-US traffic and demos; US-bound
production traffic should go through a Messaging Service (sender pool,
sticky sender, and it is what A2P registration attaches to).
- The sending number needs the SMS capability, which not every purchasable
number has. Filter on it when browsing
Api20100401AvailablePhoneNumberCountryApi.
US A2P 10DLC — three resources, in this order
Before any US long code can text US destinations, all three must exist. Without
them US carriers reject the traffic outright.
- Brand registration —
MessagingV1BrandRegistrationApi.createBrandRegistrations,
referencing Trust Hub customerProfileBundleSid + a2PProfileBundleSid
(created out of band). Pass mock = true in dev to skip the fee. Status starts
PENDING and settles to APPROVED / FAILED over hours to days; it fails if
business details are incomplete, inconsistently formatted, or do not match
registry data.
- A2P campaign —
MessagingV1UsAppToPersonApi.createUsAppToPerson,
referencing both the Messaging Service and the brand. Most onboarding
failures land here. T-Mobile rejects campaigns whose messageFlow does not
describe opt-in, or whose messageSamples do not match the declared
usAppToPersonUsecase.
- Number → service assignment —
MessagingV1PhoneNumberApi.createPhoneNumber(cfg, serviceSid, phoneNumberSid).
A number lives in exactly one Messaging Service at a time; reassignment needs
deletePhoneNumber first.
Registration deadline in force: campaigns without working privacyPolicyUrl
and termsAndConditionsUrl hard-400 since 2026-06-30. Both are positional
arguments on createUsAppToPerson and "" fails; the URLs must resolve to public
HTTPS pages, because Twilio fetches them during registration.
Toll-free numbers use a separate flow —
MessagingV1TollfreeVerificationApi — not A2P.
Available API surface
Documented and messaging-focused (this recipe):
| Module |
For |
Api20100401MessageApi |
send / fetch / list / update / delete messages |
Api20100401MediaApi, …MediaInstanceApi |
MMS media on a message |
Api20100401IncomingPhoneNumberApi (+ Local/Mobile/TollFree) |
numbers you own; delete = release |
Api20100401AvailablePhoneNumberCountryApi |
browse numbers to buy |
Api20100401BalanceApi, …AccountApi |
account balance and account records |
Api20100401UserDefinedMessageApi (+ Subscription) |
user-defined message events |
MessagingV1ServiceApi |
Messaging Services (sender pools) |
MessagingV1BrandRegistrationApi (+ Otp, BrandVettingApi) |
A2P brand |
MessagingV1UsAppToPersonApi (+ UsecaseApi) |
A2P campaigns |
MessagingV1PhoneNumberApi, …ShortCodeApi, …AlphaSenderApi, …ChannelSenderApi |
sender pool membership |
MessagingV1TollfreeVerificationApi |
toll-free verification |
MessagingV1Linkshortening*, …DomainConfig*, …DomainCertsApi |
branded link shortening |
MessagingV1DeactivationsApi |
carrier deactivation list |
Not in the package (pruned from the generated surface): calls, recordings,
conferences, participants, queues, applications, SIP domains and credentials,
usage records and triggers, addresses, keys, tokens, balance transactions. The
package ships the messaging surface only — for anything above, this connector is
not the path.
Errors and pagination
- Methods return the decoded record on 2xx and
throw Error.reject("HTTP <status> body[…]: …")
on 4xx/5xx. diagnostics is on, so the reject text carries Twilio's own error
body (code, message, more_info). Wrap in
try { … } catch (e) { Error.message(e) }.
- Codes worth mapping to real UI text: 20003 authenticate failed (bad
credential), 21211 invalid
To, 21408 region not permissioned (enable
the destination country's geo permissions in the console), 21608 unverified
recipient on a trial account, 21610 recipient has unsubscribed (STOP),
21703 sender pool exhausted, 21704 the Messaging Service has no numbers,
21714 pool size capped.
- A 2xx does not mean delivered.
createMessage returns status = #queued
or #accepted; delivery is asynchronous. Poll fetchMessage for
#delivered / #undelivered / #failed and read error_code, or configure a
statusCallback URL (needs an inbound HTTP endpoint — out of scope here).
- Pagination differs between the two API versions. v2010 lists —
listMessage
and every other Api20100401* list — return top-level next_page_uri /
previous_page_uri (?Text, and a path such as /2010-04-01/…, not a full
URL). Messaging v1 lists (listService, listPhoneNumber, the A2P registries)
instead nest pagination under meta, as next_page_url / previous_page_url
(full URLs) plus page_size. Only 10 of the 70 list responses use the meta
form; listMessage is not one of them. The meta field is typed
?ListAlphaSenderResponseMeta on every v1 list, including
ListServiceResponse — identical records are deduplicated to one shared module
at codegen time, so the name reflects whichever list sorted first, not the
endpoint you called.
pageSize defaults to 50 and caps at 1000. Bound every list call — an unbounded
listMessage on a busy account will blow max_response_bytes.
Reading the two shapes:
// Illustrative sketch, not a file to copy — `res` is assumed to be the decoded
// list response. Marked motoko-check:skip for that reason.
// v2010 (listMessage and every other Api20100401* list): top-level, a path
switch (res.next_page_uri) { case (?path) { /* fetch the next page */ }; case null {} };
// Messaging v1 (listService, listPhoneNumber, the A2P registries): nested, a full URL
switch (res.meta) { case (?m) { m.next_page_url }; case null null };
Field gotchas
usecase on createService is Text, not a variant. Valid: notifications,
marketing, verification, discussion, poll, undeclared. Anything else 400s.
usAppToPersonUsecase is a different, brand-tier-dependent enum — query
MessagingV1UsAppToPersonUsecaseApi.fetchUsAppToPersonUsecase for what a given
brand may use.
- Optional enum arguments are
?T — pass null to omit them, and prefer that.
The variants are closed: contentRetention #retain/#discard,
addressRetention #retain/#obfuscate, trafficType #free,
scheduleType #fixed, riskCheck #enable/#disable. There is no
#Text escape hatch — a value the spec does not list cannot be expressed.
Passing ?#fixed for scheduleType on an immediate send is a 400:
Twilio reads it as a scheduled message and then finds no SendAt. null is
the correct value for every one of these unless you specifically want the
behaviour.
maxPrice is omitted when 0.0, which is what you want. Sending
MaxPrice=0 would cap the message price at zero and make Twilio refuse paid
delivery; omitting it means "no cap". Pass 0.0 to omit.
xTwilioApiVersion (on the UsAppToPerson methods) — pass "" unless Twilio
support asks otherwise.
- Throughput is per sender: long code 1 message/second, toll-free ~3,
international long code ~10, short code 100. Per-number MPS cannot be raised —
scale by adding numbers to the Messaging Service's sender pool.
stickySender / areaCodeGeomatch are US + Canada only.
Config.baseUrl is unused. Every operation carries a hardcoded host
(api.twilio.com for v2010, messaging.twilio.com for v1), pinned at codegen
time from the merged spec. Do not set it and do not expect it to redirect
traffic.
Frontend
Twilio needs no OAuth: the credential is a long-lived pair the admin pastes,
so there is no redirect URI, no /connect/twilio route, and no per-user
handshake. Do not build one. What a Twilio build MUST ship is the page that lets
the admin get and enter the credentials — acceptance criteria, not
suggestions; a build missing them is broken, not merely incomplete:
- The credentials page exists and is reachable. A "send SMS" feature with
nowhere to enter a credential is unusable. A signed-in admin must reach
/settings/twilio from the nav or from the not-configured prompt.
- The console steps are in the UI, not only in the chat reply — the admin
returns weeks later, after the chat is gone.
- The API-Key secret is shown once by Twilio. Say so next to the input, or
admins will navigate away and have to create a second key.
A login flow — required. setTwilioCredentials gates on #admin, so the
app needs non-anonymous callers. Take login, useInternetIdentity / useActor
plumbing and the admin-role gate from
extension-authorization.
An admin settings page — /settings/twilio (admin-gated). Required:
- A "How to get your Twilio credentials" panel above the inputs, framed as
a one-time ~5-minute setup, with these numbered steps (the completion message
must repeat them verbatim):
- sign in at https://console.twilio.com;
- copy the Account SID (
AC…) from the dashboard;
- Account → API keys & tokens → Create API key (Standard); copy the
SID (
SK…) and the Secret — the Secret is displayed only once;
- Phone Numbers → Manage → Buy a number with the SMS capability;
- paste the three values plus the number below and save;
- on a trial account, verify each recipient under Verified Caller IDs.
Include a convenience link that opens the Twilio console.
- Three inputs: Account SID (plain text — not a secret), Key SID, Key
Secret (password input). Bound to
setTwilioCredentials; clear the secret on
success; keep the form re-submittable, because keys get rotated.
- A sending-number field bound to
setTwilioFromNumber, with an E.164
example (+15551234567) beside it and client-side validation.
- Status driven by
isTwilioConfigured() (Bool) — "Configured" / "Not
configured". That predicate requires all three values, Key SID
included: it is the Basic-Auth username, so a blank one means every request
is unauthenticated and Twilio answers 20003 while the page claims to be
configured. Never render the secret back, not even masked. The sending
number may be displayed (getTwilioFromNumber); it is not a secret.
- Make the page reachable. The shared Layout nav MUST link here when
isCallerAdmin is true and hide it otherwise. Add the link where the nav is
defined, not inside this page.
Empty-state nudges. When isTwilioConfigured() is false, never render a
dead "Send" button: admins get a "Set up Twilio" link to /settings/twilio;
non-anonymous non-admins get an explanation — e.g. "Texting isn't set up yet —
an administrator needs to add Twilio credentials in Settings."
Translate Twilio's errors. Failures arrive as rejected calls carrying
Twilio's code. Map at least these to an action rather than showing the raw
reject:
20003 → "The Twilio credentials are wrong — an admin should re-paste them"
21211 → "That phone number isn't valid — use the +15551234567 format"
21408 → "Texting that country isn't enabled on this Twilio account"
21608 → "On a trial account the recipient must be verified in Twilio first"
21610 → "That number has replied STOP and cannot be texted"
Never promise delivery. A successful call means queued, not delivered.
Word the UI accordingly ("Message queued") and, if delivery matters, show the
polled status from fetchMessage.
Suggested route layout:
/ → Main UI (any signed-in user; empty-state when unconfigured)
/settings/twilio → Admin credentials + sending number (admin-only)
# No /connect/twilio: Twilio uses pasted long-lived credentials, not a redirect flow.
What the composer must tell the Caffeine user
The app cannot send anything until a human creates a Twilio account, buys a
number and pastes credentials — so the completion message is part of the
deliverable, not a summary of it. It MUST contain, in this order:
- That credentials are required, and who enters them — an admin, on
/settings/twilio, reachable from the nav once signed in.
- The six numbered steps verbatim from Frontend item 2, including that the
API-key Secret is shown only once.
- That Twilio costs money — per-message pricing plus a monthly number fee,
and that a trial account can only text verified numbers and prefixes every
message with a trial notice.
- For US-bound traffic: the A2P 10DLC requirement, named as weeks of lead
time and additional fees, with the three ordered resources — otherwise the
user will ship an app that silently fails to reach US phones.
- The failure map, one line each:
20003 → re-paste credentials; 21211 →
E.164 format; 21408 → enable the destination country; 21608 → verify the
recipient (trial); 21610 → recipient unsubscribed.
Do not compress this to "configure Twilio in Settings" and do not substitute a
link to Twilio's documentation. Use the same wording here as in the settings-page
panel so the two cannot drift.
Known limitations
- Only the messaging surface is shipped. The package is pruned to the
messaging path; voice/recordings/SIP/usage and the rest are not in it.
- Inbound messages are out of scope. Receiving SMS, and
statusCallback
delivery receipts, need an inbound HTTP endpoint on the canister — a different
component, not this client.
- Binary media is not uploadable.
mediaUrl takes a public URL Twilio
fetches; the canister cannot POST image bytes through this client.
- No idempotency key. Twilio's messaging API has none, so a retry after a
timeout may send twice. Guard at the application level (a stable-variable
dedupe key per logical send) rather than retrying blindly. The non-replicated
default removes the ~13× amplification, not retry semantics.
- One dropped field.
POST …/IncomingPhoneNumbers/{Sid}.json accepts an
AccountSid form field (used to move a number between subaccounts) while
AccountSid is also its path parameter. The generator has a single namespace
for both, so the form copy is dropped and transferring a number to a
subaccount is not reachable through this client. Every other endpoint is
unaffected.
- Nothing here has been exercised against live Twilio. The wire format is at
least structurally right — writes send an
application/x-www-form-urlencoded
body with percent-encoded parameters, which is what Twilio requires — but no
call has been made. Treat a first successful send as the real acceptance test.
- Spec vintage: generated from Twilio's published OpenAPI specs merged by
spec-merge (Messaging v1 + API v2010), then pruned to the messaging surface.
Newer Twilio features absent from those specs are absent here.
Related
1---
2name: connector-twilio
3description: >-
4 EXPERIMENTAL, NOT YET VERIFIED AGAINST LIVE TWILIO, and it spends real money —
5 every message is billed, and a US-bound production number additionally needs
6 A2P 10DLC registration (fees, weeks of lead time). Say both things to the user
7 before building. That said, if a Caffeine build does send SMS or MMS, or
8 configures Twilio messaging, from a canister, the `twilio-client` mops package
9 (Twilio REST API) with a canister-held HTTP Basic credential is the only
10 supported path. Hand-rolling `ic.http_request` calls to `api.twilio.com` or
11 `messaging.twilio.com` is a FORBIDDEN anti-pattern — it bypasses the typed
12 bindings, the per-operation host routing, the Basic-Auth header construction,
13 and above all the non-replicated outcall default that stops one `send` from
14 becoming ~13 billed messages. Load this skill whenever the user, spec, or any
15 prior task mentions SMS, MMS, "text message", "send a text", phone numbers,
16 Twilio, a Messaging Service, A2P 10DLC, toll-free verification, short codes, or
17 an alphanumeric sender — and BEFORE writing any code that touches a Twilio
18 endpoint.
19version: 0.1.1
20caffeineai-subscription: [none]
21compatibility:
22 mops:
23 twilio-client: "~0.1.2"
24 caffeineai-authorization: "~1.0.1"
25metadata:
26 source: https://skillmd.com/skills/caffeinelabs/connector-twilio
27---
28
29# Twilio Connector (experimental)
30
31Send SMS / MMS and configure Twilio messaging from a Caffeine canister.
32
33> ⚠️ **Experimental (`twilio-client@0.1.2`) — no call has ever been made from this
34> client.** Its write path could work at all only recently: before, every write
35> discarded its arguments and posted an empty body. The wire format now matches
36> what Twilio documents (form-encoded body, percent-encoded values, optional
37> fields omitted) and all 118 files typecheck, but *structurally correct* is not
38> *verified*. Treat the first successful send as the acceptance
39> test, and do not present Twilio to a user as a fully supported platform feature
40> until one has happened. Sends cost money, so a failed experiment is not free.
41
42> **Scope — the package is the messaging surface only.** `twilio-client` is
43> pruned to **35 API modules** (all of Messaging v1 plus the v2010 messaging path:
44> Account, Message, Media, IncomingPhoneNumber and its variants,
45> AvailablePhoneNumber, the A2P registries). Voice/calls, recordings, conferences,
46> queues, applications, SIP and usage records are **not in the package** — if a
47> build needs those, they are outside this connector. (Counts: 35 API modules, 82
48> models, **118 files**, all typechecking.)
49
50## Orchestrator routing notes
51
52Load this skill when the user, spec, or a prior task mentions sending a text
53message, SMS/MMS, notifying someone by phone, buying or listing phone numbers, or
54any Twilio messaging concept. Raw `ic.http_request` to `*.twilio.com` is an
55anti-pattern that re-implements auth, host routing, percent-encoding and JSON
56parsing by hand — and, done naively, sends every message ~13 times.
57
58Intent → capability mapping:
59
60| User intent | Capability |
61| --- | --- |
62| Send an SMS | `Api20100401MessageApi.createMessage` with `from` = a Twilio number |
63| Send an MMS (image) | same, with `mediaUrl = ["https://…"]` and `sendAsMms = true` |
64| Send via a Messaging Service (recommended for US traffic) | same, `from = ""` + `messagingServiceSid` |
65| Check delivery status | `fetchMessage` (`status`, `error_code`) |
66| List / search sent messages | `listMessage` (paginated) |
67| Own or browse phone numbers | `Api20100401IncomingPhoneNumberApi`, `…AvailablePhoneNumberCountryApi` |
68| Set up a Messaging Service | `MessagingV1ServiceApi.createService` |
69| Register for US A2P 10DLC | `MessagingV1BrandRegistrationApi` → `MessagingV1UsAppToPersonApi` → `MessagingV1PhoneNumberApi` (in that order — see *US A2P 10DLC*) |
70| Verify a toll-free number | `MessagingV1TollfreeVerificationApi` |
71
72Twilio credentials are something a **human must go and fetch from a console**, so
73the build is not done when the backend compiles — it is done when the app tells
74the admin where to get the credential and gives them somewhere to paste it. See
75*Auth model*, then *Frontend* for the page that MUST ship, and repeat the steps in
76the completion message.
77
78**Ask before writing code:** which number sends? A US-bound production app needs a
79Messaging Service + A2P registration (weeks of lead time, real fees); a
80demo/internal app can send from a single trial number to *verified* recipients
81only. Report the choice and its consequences back to the prompting user.
82
83## Auth model — HTTP Basic, two flavours
84
85Both flavours are the same `#basicAuth { user; password }` credential and the
86client treats them identically; they differ in blast radius.
87
88| Flavour | `user` / `password` | When |
89| --- | --- | --- |
90| **API Key** *(default — prefer this)* | API Key **SID** (`SK…`) / its **Secret** | Production. Revocable and scoped: leaking one does not surrender the account. |
91| **Account SID + Auth Token** | Account **SID** (`AC…`) / **Auth Token** | Dev only. The Auth Token *is* the account — it can create sub-accounts, buy numbers, and spend money. |
92
93The **Account SID** (`AC…`) is *also* a required positional argument to every
94v2010 operation (it is in the URL path), regardless of which flavour is used. So
95an app using an API Key stores **three** values: Account SID, Key SID, Key Secret.
96
97### Obtaining credentials
98
991. Sign in at <https://console.twilio.com>.
1002. The **Account SID** (`AC…`) is on the console dashboard — copy it.
1013. For production, **Account → API keys & tokens → Create API key** (Standard);
102 copy the **SID** (`SK…`) and the **Secret**. **The Secret is shown once** — if
103 the admin navigates away it cannot be recovered, only replaced.
104 For dev only, take the **Auth Token** from the dashboard instead.
1054. Buy a sending number: **Phone Numbers → Manage → Buy a number**, with the
106 **SMS** capability ticked (not every number has it).
1075. On a **trial** account: verify each recipient under **Phone Numbers → Verified
108 Caller IDs**, or sends fail with `21608`; trial messages also carry a
109 "Sent from your Twilio trial account" prefix.
110
111### Handing the credentials to the canister
112
113The admin pastes them through an **admin-gated** setter — gated on
114`AccessControl.hasPermission(state, caller, #admin)`. They are held by the
115canister only and **never** returned to the frontend.
116
117> ⚠️ **Never gate the setter on a first-caller-claims-ownership scheme.** On the
118> IC every unauthenticated caller is the *same* anonymous principal, so if an
119> anonymous call claims ownership first, every anonymous caller passes the
120> `caller == owner` check and can overwrite the credential — and this one spends
121> money.
122
123The canister hands them to the client **only** through
124`config.auth = ?#basicAuth { user; password }`, which every method turns into an
125`Authorization: Basic …` header. No method takes a credential argument and none
126puts it in the URL, so it cannot leak through a logged query string.
127
128## Outcalls are already non-replicated — and this CORRECTS earlier guidance
129
130`defaultConfig` ships `is_replicated = ?false`, so anything derived from it by
131record update is correct as-is. Nothing to remember, nothing to add.
132
133> ⚠️ **Do not set it to `?true` or `null`, and disregard any older advice to do
134> so.** An older version of this SKILL claimed writes should stay
135> replicated "so IC consensus dedups retries". **That is false and expensive.** A
136> replicated outcall is performed by *every* node in the subnet: the request is
137> sent ~13 times, so **~13 SMS are sent and ~13 are billed**, the credential
138> leaves every node, and consensus fails anyway because Twilio stamps each reply
139> with a unique `sid` (so the responses never agree byte-for-byte). This is the
140> same defect that produced ~13 duplicate emails via the Gmail connector and drove
141> `slack-client` 0.1.0.
142
143Reads (`fetch*` / `list*`) are equally fine non-replicated: one node's view of a
144message log is what you want, and it is the cheaper path.
145
146# Backend
147
148## Add dependencies
149
150The admin gate in the recipe below needs the authorization component alongside the
151client:
152
153```bash
154mops add twilio-client@0.1.2
155mops add caffeineai-authorization@1.0.1
156```
157
158## Calling shape — free functions or the class facade
159
160Every module offers both. The free function takes `config` first and is `async*`;
161the `module class` captures `config` and is `async`:
162
163<!-- motoko-check:skip -->
164```motoko filepath=src/backend/calling-shape.mo
165// Illustrative sketch, not a file to copy: `cfg`/`accountSid` are assumed to
166// exist and the argument lists are elided. Marked motoko-check:skip for that
167// reason — the compiled examples are the three mixins below.
168import MessageApi "mo:twilio-client/Apis/Api20100401MessageApi";
169
170// free function — config passed explicitly
171let m = await* MessageApi.createMessage(cfg, accountSid, /* … */);
172
173// class facade — config captured once
174let messages = MessageApi.Api20100401MessageApi(cfg);
175let m2 = await messages.createMessage(accountSid, /* … */);
176```
177
178**All parameters are positional and there are 27 of them on `createMessage`.**
179Pass `""` / `false` / `0` / `0.0` / `[]` / **`null`** for the ones you do not
180use — the optional enum parameters are `?T` precisely so that `null` omits them
181from the wire. Count carefully; a misplaced empty string silently sends the
182wrong field. The order is:
183
184`config, accountSid, to, statusCallback, applicationSid, maxPrice,
185provideFeedback, attempt, validityPeriod, forceDelivery, contentRetention,
186addressRetention, smartEncoded, persistentAction, trafficType, shortenUrls,
187scheduleType, sendAt, sendAsMms, contentVariables, riskCheck, from, fallbackFrom,
188messagingServiceSid, body, mediaUrl, contentSid`
189
190## The recipe
191
192```motoko filepath=src/backend/main.mo
193import AccessControl "mo:caffeineai-authorization/access-control";
194import MixinAuthorization "mo:caffeineai-authorization/MixinAuthorization";
195import MixinTwilioConfig "mixins/twilio-config";
196import MixinTwilioMessaging "mixins/twilio-messaging";
197
198actor {
199 let accessControlState : AccessControl.AccessControlState;
200 include MixinAuthorization(accessControlState, null);
201
202 // Admin-held Twilio credentials — never returned to the frontend.
203 let twilioConfig : {
204 var accountSid : Text; // AC… — also a positional arg on every v2010 call
205 var keySid : Text; // SK… (or the Account SID again, in dev)
206 var keySecret : Text; // the API-key secret (or the Auth Token, in dev)
207 var fromNumber : Text; // E.164, e.g. "+15551234567"
208 };
209 include MixinTwilioConfig(accessControlState, twilioConfig);
210 include MixinTwilioMessaging(twilioConfig);
211};
212```
213
214The migration chain head:
215
216```motoko filepath=src/backend/migrations/00000000_000000.mo
217import AccessControl "mo:caffeineai-authorization/access-control";
218
219module {
220 type NewActor = {
221 accessControlState : AccessControl.AccessControlState;
222 twilioConfig : {
223 var accountSid : Text;
224 var keySid : Text;
225 var keySecret : Text;
226 var fromNumber : Text;
227 };
228 };
229
230 public func migration(_old : {}) : NewActor {
231 {
232 accessControlState = AccessControl.initState();
233 twilioConfig = {
234 var accountSid = "";
235 var keySid = "";
236 var keySecret = "";
237 var fromNumber = "";
238 };
239 };
240 };
241};
242```
243
244```motoko filepath=src/backend/mixins/twilio-config.mo
245import AccessControl "mo:caffeineai-authorization/access-control";
246import Runtime "mo:core/Runtime";
247
248mixin (
249 accessControlState : AccessControl.AccessControlState,
250 twilioConfig : {
251 var accountSid : Text;
252 var keySid : Text;
253 var keySecret : Text;
254 var fromNumber : Text;
255 },
256) {
257 // All THREE are required, and this must agree with the guard in
258 // twilio-messaging.mo: `keySid` is the Basic-Auth *username*, so a blank one
259 // means every request goes out unauthenticated and Twilio answers 20003 —
260 // while the UI cheerfully reports "Configured".
261 public query func isTwilioConfigured() : async Bool {
262 twilioConfig.accountSid.size() > 0 and twilioConfig.keySid.size() > 0 and twilioConfig.keySecret.size() > 0;
263 };
264
265 // The sending number is not a secret — the UI may display it.
266 public query func getTwilioFromNumber() : async Text {
267 twilioConfig.fromNumber;
268 };
269
270 // Admin-only. NOTE `#admin` — never a first-caller-claims-ownership check,
271 // which the shared anonymous principal would defeat.
272 public shared ({ caller }) func setTwilioCredentials(
273 accountSid : Text,
274 keySid : Text,
275 keySecret : Text,
276 ) : async () {
277 if (not AccessControl.hasPermission(accessControlState, caller, #admin)) {
278 Runtime.trap("Unauthorized: Only admins can set Twilio credentials");
279 };
280 twilioConfig.accountSid := accountSid;
281 twilioConfig.keySid := keySid;
282 twilioConfig.keySecret := keySecret;
283 };
284
285 public shared ({ caller }) func setTwilioFromNumber(number : Text) : async () {
286 if (not AccessControl.hasPermission(accessControlState, caller, #admin)) {
287 Runtime.trap("Unauthorized: Only admins can set the sending number");
288 };
289 twilioConfig.fromNumber := number;
290 };
291};
292```
293
294```motoko filepath=src/backend/mixins/twilio-messaging.mo
295import Principal "mo:core/Principal";
296import Runtime "mo:core/Runtime";
297import { createMessage } "mo:twilio-client/Apis/Api20100401MessageApi";
298import { defaultConfig; type Config } "mo:twilio-client/Config";
299
300mixin (
301 twilioConfig : {
302 var accountSid : Text;
303 var keySid : Text;
304 var keySecret : Text;
305 var fromNumber : Text;
306 },
307) {
308 // Credentials ride config.auth; defaultConfig is already non-replicated.
309 func twilioClientConfig() : Config {
310 {
311 defaultConfig with
312 auth = ?#basicAuth { user = twilioConfig.keySid; password = twilioConfig.keySecret };
313 max_response_bytes = ?(200_000 : Nat64);
314 };
315 };
316
317 /// Send an SMS to `to` (E.164). Returns the message SID.
318 public shared ({ caller }) func sendSms(to : Text, body : Text) : async Text {
319 if (caller.isAnonymous()) Runtime.trap("Sign in to send messages");
320 // Same three-way check as isTwilioConfigured(): accountSid goes in the URL
321 // path, keySid is the Basic-Auth user, keySecret the password. Missing any
322 // one of them fails at Twilio, not here, so check before spending cycles.
323 if (
324 twilioConfig.accountSid.size() == 0 or twilioConfig.keySid.size() == 0 or twilioConfig.keySecret.size() == 0
325 ) {
326 Runtime.trap("Twilio is not configured (an admin must set all three credentials)");
327 };
328 let msg = await* createMessage(
329 twilioClientConfig(),
330 twilioConfig.accountSid, // accountSid — in the URL path, not the credential
331 to, // to (E.164)
332 "", "", // statusCallback, applicationSid
333 0.0, // maxPrice (0 = no cap)
334 false, // provideFeedback
335 0, 0, // attempt, validityPeriod
336 false, // forceDelivery
337 null, null, // contentRetention, addressRetention (omitted)
338 false, // smartEncoded
339 [], // persistentAction
340 null, // trafficType (omitted)
341 false, // shortenUrls
342 null, // scheduleType — MUST be null for an immediate send
343 "", // sendAt (scheduled sends only)
344 false, // sendAsMms
345 "", // contentVariables
346 null, // riskCheck (omitted)
347 twilioConfig.fromNumber, // from (use EITHER from OR messagingServiceSid)
348 "", // fallbackFrom
349 "", // messagingServiceSid
350 body, // body
351 [], // mediaUrl (set for MMS)
352 "", // contentSid (Content API templates)
353 );
354 // `sid` is optional in the generated model because the spec marks it
355 // nullable, though Twilio always sets it on a successful create. Fall back
356 // to "" rather than trapping: the outcall has already happened, so a trap
357 // would roll back this canister's own state while the SMS stays delivered.
358 switch (msg.sid) { case (?sid) sid; case null "" };
359 };
360};
361```
362
363For MMS: `mediaUrl = ["https://example.com/image.jpg"]` and `sendAsMms = true`.
364To send through a Messaging Service, leave `from = ""` and set
365`messagingServiceSid` instead.
366
367## Addressing — E.164, and which sender
368
369- **`to` must be E.164**: `+`, country code, no spaces, dashes or parentheses —
370 `"+15551234567"`. `"555-1234"` fails with `21211`. Normalize in the frontend and
371 again in the canister; do not trust either alone.
372- **`from` vs `messagingServiceSid` — exactly one.** Setting both is an error.
373 A bare `from` number is fine for non-US traffic and demos; **US-bound
374 production traffic should go through a Messaging Service** (sender pool,
375 sticky sender, and it is what A2P registration attaches to).
376- **The sending number needs the SMS capability**, which not every purchasable
377 number has. Filter on it when browsing
378 `Api20100401AvailablePhoneNumberCountryApi`.
379
380## US A2P 10DLC — three resources, in this order
381
382Before any US long code can text US destinations, all three must exist. Without
383them US carriers reject the traffic outright.
384
3851. **Brand registration** — `MessagingV1BrandRegistrationApi.createBrandRegistrations`,
386 referencing Trust Hub `customerProfileBundleSid` + `a2PProfileBundleSid`
387 (created out of band). Pass `mock = true` in dev to skip the fee. Status starts
388 `PENDING` and settles to `APPROVED` / `FAILED` over hours to days; it fails if
389 business details are incomplete, inconsistently formatted, or do not match
390 registry data.
3912. **A2P campaign** — `MessagingV1UsAppToPersonApi.createUsAppToPerson`,
392 referencing both the Messaging Service and the brand. **Most onboarding
393 failures land here.** T-Mobile rejects campaigns whose `messageFlow` does not
394 describe opt-in, or whose `messageSamples` do not match the declared
395 `usAppToPersonUsecase`.
3963. **Number → service assignment** —
397 `MessagingV1PhoneNumberApi.createPhoneNumber(cfg, serviceSid, phoneNumberSid)`.
398 A number lives in exactly one Messaging Service at a time; reassignment needs
399 `deletePhoneNumber` first.
400
401**Registration deadline in force:** campaigns without working `privacyPolicyUrl`
402*and* `termsAndConditionsUrl` hard-400 since 2026-06-30. Both are positional
403arguments on `createUsAppToPerson` and `""` fails; the URLs must resolve to public
404HTTPS pages, because Twilio fetches them during registration.
405
406Toll-free numbers use a **separate** flow —
407`MessagingV1TollfreeVerificationApi` — not A2P.
408
409## Available API surface
410
411Documented and messaging-focused (this recipe):
412
413| Module | For |
414| --- | --- |
415| `Api20100401MessageApi` | send / fetch / list / update / delete messages |
416| `Api20100401MediaApi`, `…MediaInstanceApi` | MMS media on a message |
417| `Api20100401IncomingPhoneNumberApi` (+ `Local`/`Mobile`/`TollFree`) | numbers you own; delete = release |
418| `Api20100401AvailablePhoneNumberCountryApi` | browse numbers to buy |
419| `Api20100401BalanceApi`, `…AccountApi` | account balance and account records |
420| `Api20100401UserDefinedMessageApi` (+ `Subscription`) | user-defined message events |
421| `MessagingV1ServiceApi` | Messaging Services (sender pools) |
422| `MessagingV1BrandRegistrationApi` (+ `Otp`, `BrandVettingApi`) | A2P brand |
423| `MessagingV1UsAppToPersonApi` (+ `UsecaseApi`) | A2P campaigns |
424| `MessagingV1PhoneNumberApi`, `…ShortCodeApi`, `…AlphaSenderApi`, `…ChannelSenderApi` | sender pool membership |
425| `MessagingV1TollfreeVerificationApi` | toll-free verification |
426| `MessagingV1Linkshortening*`, `…DomainConfig*`, `…DomainCertsApi` | branded link shortening |
427| `MessagingV1DeactivationsApi` | carrier deactivation list |
428
429**Not in the package** (pruned from the generated surface): calls, recordings,
430conferences, participants, queues, applications, SIP domains and credentials,
431usage records and triggers, addresses, keys, tokens, balance transactions. The
432package ships the messaging surface only — for anything above, this connector is
433not the path.
434
435## Errors and pagination
436
437- Methods return the decoded record on 2xx and `throw Error.reject("HTTP <status> body[…]: …")`
438 on 4xx/5xx. `diagnostics` is on, so the reject text carries Twilio's own error
439 body (`code`, `message`, `more_info`). Wrap in
440 `try { … } catch (e) { Error.message(e) }`.
441- Codes worth mapping to real UI text: **20003** authenticate failed (bad
442 credential), **21211** invalid `To`, **21408** region not permissioned (enable
443 the destination country's geo permissions in the console), **21608** unverified
444 recipient on a trial account, **21610** recipient has unsubscribed (STOP),
445 **21703** sender pool exhausted, **21704** the Messaging Service has no numbers,
446 **21714** pool size capped.
447- **A 2xx does not mean delivered.** `createMessage` returns `status = #queued`
448 or `#accepted`; delivery is asynchronous. Poll `fetchMessage` for
449 `#delivered` / `#undelivered` / `#failed` and read `error_code`, or configure a
450 `statusCallback` URL (needs an inbound HTTP endpoint — out of scope here).
451- **Pagination differs between the two API versions.** v2010 lists — `listMessage`
452 and every other `Api20100401*` list — return **top-level** `next_page_uri` /
453 `previous_page_uri` (`?Text`, and a *path* such as `/2010-04-01/…`, not a full
454 URL). Messaging v1 lists (`listService`, `listPhoneNumber`, the A2P registries)
455 instead nest pagination under `meta`, as `next_page_url` / `previous_page_url`
456 (full URLs) plus `page_size`. Only 10 of the 70 list responses use the `meta`
457 form; `listMessage` is **not** one of them. The `meta` field is typed
458 `?ListAlphaSenderResponseMeta` on *every* v1 list, including
459 `ListServiceResponse` — identical records are deduplicated to one shared module
460 at codegen time, so the name reflects whichever list sorted first, not the
461 endpoint you called.
462- `pageSize` defaults to 50 and caps at 1000. Bound every list call — an unbounded
463 `listMessage` on a busy account will blow `max_response_bytes`.
464
465Reading the two shapes:
466
467<!-- motoko-check:skip -->
468```motoko filepath=src/backend/pagination-shape.mo
469// Illustrative sketch, not a file to copy — `res` is assumed to be the decoded
470// list response. Marked motoko-check:skip for that reason.
471
472// v2010 (listMessage and every other Api20100401* list): top-level, a path
473switch (res.next_page_uri) { case (?path) { /* fetch the next page */ }; case null {} };
474
475// Messaging v1 (listService, listPhoneNumber, the A2P registries): nested, a full URL
476switch (res.meta) { case (?m) { m.next_page_url }; case null null };
477```
478
479## Field gotchas
480
481- `usecase` on `createService` is **`Text`, not a variant**. Valid: `notifications`,
482 `marketing`, `verification`, `discussion`, `poll`, `undeclared`. Anything else 400s.
483- `usAppToPersonUsecase` is a *different*, brand-tier-dependent enum — query
484 `MessagingV1UsAppToPersonUsecaseApi.fetchUsAppToPersonUsecase` for what a given
485 brand may use.
486- **Optional enum arguments are `?T` — pass `null` to omit them, and prefer that.**
487 The variants are *closed*: `contentRetention` `#retain`/`#discard`,
488 `addressRetention` `#retain`/`#obfuscate`, `trafficType` `#free`,
489 `scheduleType` `#fixed`, `riskCheck` `#enable`/`#disable`. There is **no
490 `#Text` escape hatch** — a value the spec does not list cannot be expressed.
491 Passing `?#fixed` for `scheduleType` on an immediate send is a **400**:
492 Twilio reads it as a scheduled message and then finds no `SendAt`. `null` is
493 the correct value for every one of these unless you specifically want the
494 behaviour.
495- **`maxPrice` is omitted when `0.0`, which is what you want.** Sending
496 `MaxPrice=0` would cap the message price at zero and make Twilio refuse paid
497 delivery; omitting it means "no cap". Pass `0.0` to omit.
498- `xTwilioApiVersion` (on the `UsAppToPerson` methods) — pass `""` unless Twilio
499 support asks otherwise.
500- **Throughput is per sender:** long code 1 message/second, toll-free ~3,
501 international long code ~10, short code 100. Per-number MPS cannot be raised —
502 scale by adding numbers to the Messaging Service's sender pool.
503- `stickySender` / `areaCodeGeomatch` are US + Canada only.
504- `Config.baseUrl` is **unused**. Every operation carries a hardcoded host
505 (`api.twilio.com` for v2010, `messaging.twilio.com` for v1), pinned at codegen
506 time from the merged spec. Do not set it and do not expect it to redirect
507 traffic.
508
509# Frontend
510
511Twilio needs **no OAuth**: the credential is a long-lived pair the admin pastes,
512so there is no redirect URI, no `/connect/twilio` route, and no per-user
513handshake. Do not build one. What a Twilio build MUST ship is the page that lets
514the admin *get* and *enter* the credentials — **acceptance criteria, not
515suggestions**; a build missing them is **broken, not merely incomplete**:
516
517- **The credentials page exists and is reachable.** A "send SMS" feature with
518 nowhere to enter a credential is unusable. A signed-in admin must reach
519 `/settings/twilio` from the nav or from the not-configured prompt.
520- **The console steps are in the UI**, not only in the chat reply — the admin
521 returns weeks later, after the chat is gone.
522- **The API-Key secret is shown once by Twilio.** Say so next to the input, or
523 admins will navigate away and have to create a second key.
524
5251. **A login flow — required.** `setTwilioCredentials` gates on `#admin`, so the
526 app needs non-anonymous callers. Take login, `useInternetIdentity` / `useActor`
527 plumbing and the admin-role gate from
528 [`extension-authorization`](../extension-authorization/SKILL.md).
529
5302. **An admin settings page** — `/settings/twilio` (admin-gated). Required:
531 - A "How to get your Twilio credentials" panel **above** the inputs, framed as
532 a one-time ~5-minute setup, with these numbered steps (the completion message
533 must repeat them verbatim):
534 1. sign in at <https://console.twilio.com>;
535 2. copy the **Account SID** (`AC…`) from the dashboard;
536 3. **Account → API keys & tokens → Create API key** (Standard); copy the
537 **SID** (`SK…`) and the **Secret** — *the Secret is displayed only once*;
538 4. **Phone Numbers → Manage → Buy a number** with the **SMS** capability;
539 5. paste the three values plus the number below and save;
540 6. on a trial account, verify each recipient under **Verified Caller IDs**.
541 Include a convenience link that opens the Twilio console.
542 - **Three inputs**: Account SID (plain text — not a secret), Key SID, Key
543 Secret (password input). Bound to `setTwilioCredentials`; clear the secret on
544 success; keep the form re-submittable, because keys get rotated.
545 - **A sending-number field** bound to `setTwilioFromNumber`, with an E.164
546 example (`+15551234567`) beside it and client-side validation.
547 - Status driven by `isTwilioConfigured()` (`Bool`) — "Configured" / "Not
548 configured". That predicate requires **all three** values, Key SID
549 included: it is the Basic-Auth username, so a blank one means every request
550 is unauthenticated and Twilio answers `20003` while the page claims to be
551 configured. **Never** render the secret back, not even masked. The sending
552 number may be displayed (`getTwilioFromNumber`); it is not a secret.
553 - **Make the page reachable.** The shared Layout nav MUST link here when
554 `isCallerAdmin` is true and hide it otherwise. Add the link where the nav is
555 defined, not inside this page.
556
5573. **Empty-state nudges.** When `isTwilioConfigured()` is `false`, never render a
558 dead "Send" button: admins get a "Set up Twilio" link to `/settings/twilio`;
559 non-anonymous non-admins get an explanation — e.g. "Texting isn't set up yet —
560 an administrator needs to add Twilio credentials in Settings."
561
5624. **Translate Twilio's errors.** Failures arrive as *rejected* calls carrying
563 Twilio's `code`. Map at least these to an action rather than showing the raw
564 reject:
565 - `20003` → "The Twilio credentials are wrong — an admin should re-paste them"
566 - `21211` → "That phone number isn't valid — use the +15551234567 format"
567 - `21408` → "Texting that country isn't enabled on this Twilio account"
568 - `21608` → "On a trial account the recipient must be verified in Twilio first"
569 - `21610` → "That number has replied STOP and cannot be texted"
570
5715. **Never promise delivery.** A successful call means *queued*, not delivered.
572 Word the UI accordingly ("Message queued") and, if delivery matters, show the
573 polled `status` from `fetchMessage`.
574
575Suggested route layout:
576
577```
578/ → Main UI (any signed-in user; empty-state when unconfigured)
579/settings/twilio → Admin credentials + sending number (admin-only)
580# No /connect/twilio: Twilio uses pasted long-lived credentials, not a redirect flow.
581```
582
583## What the composer must tell the Caffeine user
584
585The app cannot send anything until a human creates a Twilio account, buys a
586number and pastes credentials — so the **completion message is part of the
587deliverable**, not a summary of it. It MUST contain, in this order:
588
5891. **That credentials are required, and who enters them** — an admin, on
590 `/settings/twilio`, reachable from the nav once signed in.
5912. **The six numbered steps verbatim** from *Frontend* item 2, including that the
592 API-key **Secret is shown only once**.
5933. **That Twilio costs money** — per-message pricing plus a monthly number fee,
594 and that a trial account can only text **verified** numbers and prefixes every
595 message with a trial notice.
5964. **For US-bound traffic: the A2P 10DLC requirement**, named as weeks of lead
597 time and additional fees, with the three ordered resources — otherwise the
598 user will ship an app that silently fails to reach US phones.
5995. **The failure map, one line each**: `20003` → re-paste credentials; `21211` →
600 E.164 format; `21408` → enable the destination country; `21608` → verify the
601 recipient (trial); `21610` → recipient unsubscribed.
602
603Do not compress this to "configure Twilio in Settings" and do not substitute a
604link to Twilio's documentation. Use the same wording here as in the settings-page
605panel so the two cannot drift.
606
607## Known limitations
608
609- **Only the messaging surface is shipped.** The package is pruned to the
610 messaging path; voice/recordings/SIP/usage and the rest are not in it.
611- **Inbound messages are out of scope.** Receiving SMS, and `statusCallback`
612 delivery receipts, need an inbound HTTP endpoint on the canister — a different
613 component, not this client.
614- **Binary media is not uploadable.** `mediaUrl` takes a *public URL* Twilio
615 fetches; the canister cannot POST image bytes through this client.
616- **No idempotency key.** Twilio's messaging API has none, so a retry after a
617 timeout may send twice. Guard at the application level (a stable-variable
618 dedupe key per logical send) rather than retrying blindly. The non-replicated
619 default removes the ~13× amplification, not retry semantics.
620- **One dropped field.** `POST …/IncomingPhoneNumbers/{Sid}.json` accepts an
621 `AccountSid` *form* field (used to move a number between subaccounts) while
622 `AccountSid` is also its path parameter. The generator has a single namespace
623 for both, so the form copy is dropped and **transferring a number to a
624 subaccount is not reachable** through this client. Every other endpoint is
625 unaffected.
626- **Nothing here has been exercised against live Twilio.** The wire format is at
627 least structurally right — writes send an `application/x-www-form-urlencoded`
628 body with percent-encoded parameters, which is what Twilio requires — but no
629 call has been made. Treat a first successful send as the real acceptance test.
630- **Spec vintage:** generated from Twilio's published OpenAPI specs merged by
631 `spec-merge` (Messaging v1 + API v2010), then pruned to the messaging surface.
632 Newer Twilio features absent from those specs are absent here.
633
634## Related
635
636- [`mops add twilio-client@0.1.2`](https://mops.one/twilio-client) — the generated Twilio REST bindings (35 messaging modules).
637- [Twilio Messaging docs](https://www.twilio.com/docs/messaging) — the API this wraps.
638- [`chat`-free quickstart: sending SMS](https://www.twilio.com/docs/messaging/api/message-resource) — the `Message` resource, its fields and statuses.
639- [Twilio error codes](https://www.twilio.com/docs/api/errors) — the numeric codes surfaced in reject messages.
640- [A2P 10DLC overview](https://www.twilio.com/docs/messaging/compliance/a2p-10dlc) — brand, campaign, number assignment.
641- [API keys vs Auth Token](https://www.twilio.com/docs/iam/api-keys) — why production uses `SK…`.
642- [extension-authorization](../extension-authorization/SKILL.md) — **required prerequisite**. Internet Identity login, `useInternetIdentity` / `useActor` plumbing, and the `#admin` gate the credential setter needs.