# Voiceflow SMS relay example

Use the provider's Voiceflow Channel manual for account provisioning, callback registration, credentials and live tests. This is the shared executable implementation for those manuals. It is a single-worker, incoming-first, text-only example, using Node 22.13+, Docker Compose and a persistent SQLite volume. It does not register a managed Voiceflow number or implement human hand-off, MMS, rich response controls or outbound-first campaigns.

## Install

1. Download `sms-relay.zip`, unpack into `sms-relay`, then `cd sms-relay`.
2. Run `cp .env.example .env` and `chmod 600 .env`. Set the provider, E.164 business number, published Chat test Environment alias, project ID and runtime API key. Add the exact provider variables in its manual. Generate independent `IDENTITY_SECRET` and `WEBHOOK_SECRET` values using `openssl rand -hex 32` twice. Keep the identity secret stable across deployments.
3. On a server with Docker Engine and Compose, point the domain's DNS A/AAAA records to that server and allow inbound 80/443 and outbound HTTPS. Set `SMS_DOMAIN=sms.your-domain.example` and `PUBLIC_ORIGIN=https://sms.your-domain.example` (no trailing slash) in `.env`.
4. Complete the provider manual’s credential/resource prerequisites before the first start. Bird must create its endpoint to obtain the signing secret; Bandwidth needs its application ID; AWS needs its topic, queue, configuration set and IAM identity. Do not use placeholder credentials to bypass startup validation. Follow the manual’s start point, then run `docker compose up -d --build`. Caddy manages TLS and proxies to the private relay port. Run `curl --fail https://sms.your-domain.example/health`; expect `{"ok":true}`. Do not enable full access logging for private callback URLs.
5. Configure the provider's incoming route using its manual. The callback URL is `PUBLIC_ORIGIN/inbound/WEBHOOK_SECRET` with the actual values substituted; status reports use `/status/WEBHOOK_SECRET`. AWS receives from a restricted SNS-to-SQS subscription instead of HTTP. No browser should receive the Voiceflow or provider keys.
6. Run the manual's known-question and follow-up test. Compare the intended Voiceflow Transcript, relay ledger, provider record and phone. Health, callback acknowledgment, local tests and API acceptance prove different things from live delivery.

For local, offline checks use Node 22.13 or later: `npm ci --ignore-scripts`, then `npm test`. `npm start` loads `.env` for direct execution; production Compose supplies it through `env_file`. No SDK or provider credentials are required by the test suite. Dependencies are lock-pinned; only AWS/Azure sending dynamically loads their SDKs. Review dependencies before adopting the example into your application.

## Message path and boundaries

- An authenticated callback is normalized into a provider event ID, E.164 customer, E.164 business recipient and text. The business recipient must match `SMS_FROM`. Malformed incoming schemas are rejected. Recognized event envelopes of other types are acknowledged without creating a conversation. The full incoming batch is validated before its durable transaction; only then is HTTP success returned. AWS deletes its SQS message after that commit.
- The worker serializes all jobs in this deployment. It creates a Voiceflow v4 session in the explicit Published Environment, launches once, discards launch greeting text, then sends the customer text. The agent must stay available for this first text; a launch that ends or requests hand-off is held for review.
- The HMAC user ID includes provider, business/customer numbers, project, Environment and route generation. The session token is stored server-side. Follow-ups reuse it; `end` clears it, and a definite missing-session `404` starts a replacement once. A provider phone number is a routing identifier, not authenticated customer identity.
- Only `text` traces become a reply. One answer of at most 640 UTF-16 units is submitted; the provider handles SMS segmentation/encoding. Missing text, oversized output and hand-off traces become `uncertain`. Keep the test agent concise. API Transcripts retain the agent's original output, including a discarded launch greeting.
- SQLite stores event IDs, input text, reply text, tokens, suppression records and optional raw status receipts. Protect the host, volume and backups; choose access and retention appropriate to this data. Full raw callbacks and secrets are not printed by the sample.
- Most providers supply stable incoming IDs. CM.com and the selected Gupshup callback use timestamp/content hashes: identical messages at an identical provider timestamp can collapse. Delivery order is local receipt order, not a guarantee of carrier send order.
- STOP/START/HELP bypass the agent. The local suppression list supplements the provider's keyword handling; it does not send the required provider response or override the provider's block list. Telesign's stop/start/help actions are honored even for non-English keywords. Configure and test the provider's required responses before customer use. A route-generation change preserves local suppression; changing the identity secret loses that association.
- Status callbacks are retained separately and never become agent inputs. They are raw evidence for an operator, not a normalized delivery-state machine. AWS uses its configuration-set destination for outgoing delivery records. Sinch's sample send uses delivery-report lookup. No accepted job is labeled delivered.
- The outgoing send and runtime turn are not retried automatically on uncertainty. A crash during either can leave a remote write without a local receipt. This chooses operator review over automatic duplicates; it is not an exactly-once delivery guarantee.

## Inspect and resolve

Run these commands on the host, replacing `JOB_ID` with the hash in the relay log:

```sh
docker compose exec relay node ops.mjs list
docker compose exec relay node ops.mjs inspect JOB_ID
```

`accepted` means the provider accepted the outgoing request and an ID/reference was retained. `uncertain` requires comparing the original Transcript and provider message record; the turn may have executed tools or the SMS may have been accepted. Later customer texts for that same conversation become `held`.

Pause provider ingress (or the AWS receiver), stop the worker, then compare the original Transcript and provider record. Record the established outcome and any follow-up in your incident log, and arrange for the customer to restate the latest question. Resolve using a one-off container while the worker remains stopped:

```sh
docker compose stop relay
docker compose run --rm --no-deps relay node ops.mjs resolve JOB_ID
docker compose up -d relay
```

This atomically records resolution, skips queued and held messages for that conversation and clears its local session token. The one-off command sends nothing. Resume provider ingress after restarting the worker. Keep it stopped during reconciliation so another worker cannot process a queued follow-up concurrently. The next customer text starts a new session. It never replays an uncertain turn or send; account-specific workflows may require a separate reconciliation process before this reset. Do not modify phases or delete the database to force work to rerun.

## Release and back up

Publish the reviewed Voiceflow test/production Environment, drain queued work, back up the ledger, set the final project/alias and increment `ROUTE_GENERATION` before the final controlled test. The constructor refuses a route change while queued work remains. Existing accepted and uncertain records remain in the ledger. When changing only the agent publication, deliberately choose whether existing sessions should continue or a route generation should start new ones.

For a consistent backup, first pause provider ingress, wait for queued jobs to drain and stop the relay:

```sh
docker compose stop relay
docker compose cp relay:/app/data ./sms-backup
```

Keep all SQLite/WAL files together while stopped. Restart with `docker compose up -d` after backing up. Restore only while the relay is stopped, with the same identity secret, and inspect the original message outcomes before accepting traffic again. Backups also contain secrets and customer data.

Rotate provider keys in `.env`, then recreate the container. Coordinate callback-secret rotations with the provider route. Keep one worker, the same `sms-data` volume and stable identity secret. For horizontal scale, replace this example's SQLite/worker ownership with an actual distributed queue and locking scheme before running more replicas.

To disconnect, disable provider ingress/subscriptions, drain queued jobs, then stop the worker. Restore the prior provider handler when required and verify any separate voice route. Never use `docker compose down -v` as a repair: it deletes the durable message and suppression history. Releasing a number and canceling its billing are separate provider actions.

## Provider contracts

Read the matching manual and primary provider references for the chosen interface. In particular, Bird uses the regional `bk_...` API and Standard Webhooks, Gupshup uses Enterprise Gateway international SMS, Tata uses Kaleyra `/sms/json` DEFAULT traffic, and Clickatell uses the legacy SMS Gateway HTTP API. These are explicit interface choices, not universal adapters for every account bearing the vendor's name. Unsigned callback providers use the private token URL as bearer authentication over TLS; no cryptographic origin signature is claimed for those interfaces.
