# API conventions: auth, envelope, errors, pagination (https://docs.opensequence.dev/api/conventions) How every OpenSequence REST endpoint behaves: keys and scopes, the response envelope, field names, ids, pagination, rate limits and dates. The rules every endpoint follows, so you can call the raw REST API from any language. The API lives under `/v1` on your instance; it also serves Swagger UI at `/docs` and the OpenAPI document at `/docs/json`. ## Authentication [#authentication] ```bash curl $SEQ/v1/sequences -H "Authorization: Bearer $KEY" ``` ```python r = requests.get(f"{SEQ}/v1/sequences", headers={"Authorization": f"Bearer {KEY}"}) ``` | Caller | Header | Covers | |---|---|---| | Project API key | `Bearer sk_live_…` | everything except `/v1/admin/*` | | Operator token (`SEQ_ADMIN_TOKEN`) | `Bearer ` | `/v1/admin/*` only: projects, keys, platform health | Keys are stored as SHA-256 hashes, shown once, and revocable. Each key belongs to one project; another project's ids return `404`. ## Scopes [#scopes] Scopes rank `read` < `enroll` < `admin`. A higher scope can do everything a lower one can. Missing scope: `403 INSUFFICIENT_SCOPE`. | Scope | Can | |---|---| | `read` | every `GET`, `contacts:status`, `sequences:validate`, `enrollments:preview`, `/v1/schema*`, `GET /v1/project` | | `enroll` | contacts (upsert, batch, patch, events), enroll, pause, resume, complete and cancel tasks | | `admin` | everything else: senders, sequences, publish, exit, outreach consent, settings, credentials, keys, flags, webhooks | Give `enroll` to code that reacts to user actions. Keep `admin` for configuration. ## Response envelope [#response-envelope] ```json { "success": true, "data": { … }, "meta": { "request_id": "req_…" } } { "success": false, "error": { "code": "ALREADY_IN_SEQUENCE", "message": "…", "details": { … } }, "meta": { "request_id": "req_…" } } ``` Branch on `error.code`; every code is on [Errors](/api/errors). Quote `request_id` when you ask for help: it is on every log line of the request. An incoming `X-Request-Id` header is not used yet. Creation returns `201`, everything else `200`. ## Field names [#field-names] - You send **snake_case**: bodies and query strings (`first_name`, `lock_version`). - Computed results come back **snake_case**: errors, `meta`, enroll results, analytics, webhook endpoints and every webhook payload. - Stored records come back **camelCase**: contacts, senders, sequences, versions, enrollments, runs, messages, signals, tasks (`externalId`, `lockVersion`). Each endpoint's reference page shows the exact shape, and [`openapi.json`](/openapi.json) has it under `components.schemas`. ## Ids [#ids] Service ids are prefixed ULIDs (`ctc_`, `seq_`, `enr_`, …). Wherever a sender, contact or sequence `{id}` appears, your own id works too. If your id could look like a service id, prefix it with `ext:`. ## Pagination [#pagination] ```bash curl "$SEQ/v1/enrollments?status=active&limit=100&updated_since=2026-10-13T00:00:00Z" -H "Authorization: Bearer $KEY" ``` `limit` is 1 to 200 (default 50). Pass `meta.next_cursor` back as `cursor` until it is `null`. `data` is the array itself. `updated_since` lets a client without webhooks poll for changes. ## Bodies [#bodies] JSON only, 2 MB at most. A `POST` with no body is fine where the body is optional (`publish`, `pause`, `exit`). Strict schemas reject unknown fields with `400 VALIDATION_ERROR`. ## Rate limits [#rate-limits] 600 requests per minute per key (per client IP without one), then `429` with `Retry-After`. With several API replicas and no shared store, the count is per replica. ## Idempotency [#idempotency] `PUT` upserts. Contact events are keyed by your event `id`. Enrolling twice is refused, not duplicated. The `Idempotency-Key` header is not implemented yet, so a repeated `POST /v1/sequences` creates a second sequence. ## Dates, zones and phones [#dates-zones-and-phones] Timestamps are ISO 8601 UTC. Time zones are IANA names. Durations match `^\d+(m|h|d|bd)$`. Phones are E.164 and countries ISO 3166-1 alpha-2. ## Health [#health] `GET /healthz` (liveness) and `GET /readyz` (database migrated and reachable) need no auth. `GET /v1/engine/health` (`admin`) returns kill switches, queue depths and the last run of each job. See [Observability](/docs/self-hosting/observability). # Comparing email and SMS fairly (https://docs.opensequence.dev/docs/analytics/comparing-channels) Why an email versus SMS chart misleads, and how to compare channels fairly at the same touch number. The question "does SMS work better than email?" has a wrong answer built into the data. A text in a typical sequence is the third or fourth touch: it reaches the people who did not reply to two emails, and only those with a phone, consent and an allowed country. Its reply rate measures a different population, later in the sequence, not a different channel. ```bash title="curl" curl $SEQ/v1/sequences/seq_01J9…/analytics/channels -H "Authorization: Bearer $KEY" # {"sequence":"seq_01J9…","channels":[ # {"channel":"email","touch_number":0,"reached":14,"sent":0,"skipped":14,…}, # {"channel":"email","touch_number":1,"reached":398,"sent":398,"skipped":0,"delivered":398,"bounced":6,"replies":31,"meetings":4,"reply_rate_per_100_sent":7.8,"meeting_rate_per_100_sent":1}, # {"channel":"email","touch_number":2,…}, # {"channel":"sms","touch_number":0,"reached":179,"sent":0,"skipped":179,…}, # {"channel":"sms","touch_number":3,"reached":61,"sent":61,"skipped":0,"delivered":60,"replies":9,"reply_rate_per_100_sent":14.8,…}]} ``` ```ts title="TypeScript" const { channels } = await oseq.analytics.channels('seq_01J9…'); const byTouch = Object.groupBy(channels.filter((r) => r.touch_number > 0), (r) => r.touch_number); ``` ## Compare at the same touch number [#compare-at-the-same-touch-number] `GET /v1/sequences/{id}/analytics/channels` returns one row per `(channel, touch_number)` on purpose. The touch number is the position of a message among those actually sent to the contact in that enrollment: 1 is the first one sent. A step that was skipped or failed takes no touch number, so all of a channel's unsent runs share one row with `touch_number: 0`. The 14.8 per 100 sent of the text above is not better than the 7.8 of the first email: it is the rate of touch 3 among people already filtered by two silences. Read the table by row, not by column: - Within one touch number, two channels are comparable only when the same people could have received either. That happens when a `condition` splits the population by something unrelated to the channel (a region, a plan), or when two versions of the sequence differ only in the channel of that step. - Across touch numbers, compare the same channel with itself: email at touch 1 against email at touch 2 says how much a follow-up adds. ## What the numbers mean [#what-the-numbers-mean] | Field | Meaning | |---|---| | `reached` | runs of this channel in this row | | `sent`, `skipped` | runs the provider accepted, runs a gate refused. Skipped runs are all in the `touch_number: 0` row; `skipped_by_reason` on the per-node endpoint says why | | `delivered`, `bounced` | from the run's recorded outcome | | `replies`, `meetings` | signals attributed to these runs (the first reply and the first meeting per enrollment) | | `reply_rate_per_100_sent`, `meeting_rate_per_100_sent` | rates on `sent`, rounded to one decimal, `null` without a denominator | Rates are per sent, not per reached, so a channel with many skips (SMS without consent) is not punished for the gates. ## Isolate what you want to compare [#isolate-what-you-want-to-compare] - **Per version**: every analytics endpoint takes `version`, a version id (`ver_…`). Publish `v2` with the text moved to touch 2, enroll the next batch on it, and compare `channels?version=` with `channels?version=` at the same touch number. - **Per step**: `GET /v1/sequences/{id}/analytics/nodes` returns `reached`, `executed`, `skipped_by_reason`, `replies`, `meetings` and `median_time_to_reply_seconds` per node, so two steps of the same channel at different positions are told apart. - **Per sender and country**: `sender` and `country` filters remove the two biggest confounders between batches. - **Per period**: `from` and `to` filter `channels` and `nodes` on when the run was created, and `summary` and `exits` on when the contact was enrolled. To separate a batch enrolled before a copy change from one enrolled after, filter by version rather than by date. ## What a fair comparison looks like [#what-a-fair-comparison-looks-like] Two versions that differ in one step, the same senders, the same period, enough enrollments for the rates to mean something (`GET /v1/analytics/sequences?min_enrolled=` hides small samples on the cross-sequence table). Then one row of `channels` per version, at the touch number that changed. A `split` node that assigns each enrollment to a cohort at random, so one sequence can run both variants on the same population, is planned and not shipped. Until then, two versions are the experiment. See [Outcomes and attribution](/docs/analytics/outcomes) for how replies and meetings are credited, and [Endpoints](/docs/analytics/endpoints) for every field. # Sequence analytics endpoints (https://docs.opensequence.dev/docs/analytics/endpoints) What the summary, exits, nodes, channels and cross-sequence analytics endpoints return, and what each number means. ```bash title="curl" curl $SEQ/v1/sequences/seq_01J9…/analytics/summary -H "Authorization: Bearer $KEY" curl $SEQ/v1/sequences/seq_01J9…/analytics/exits -H "Authorization: Bearer $KEY" curl $SEQ/v1/sequences/seq_01J9…/analytics/nodes -H "Authorization: Bearer $KEY" curl $SEQ/v1/sequences/seq_01J9…/analytics/channels -H "Authorization: Bearer $KEY" curl "$SEQ/v1/analytics/sequences?min_enrolled=20" -H "Authorization: Bearer $KEY" ``` ```ts title="TypeScript" const [summary, exits, nodes, channels, all] = await Promise.all([ oseq.analytics.summary('seq_01J9…'), oseq.analytics.exits('seq_01J9…'), oseq.analytics.nodes('seq_01J9…'), oseq.analytics.channels('seq_01J9…'), oseq.analytics.sequences({ min_enrolled: 20 }), ]); ``` All five take `version` (a version id), `from`, `to`, `sender` and `country`; scope `read`. `from` and `to` apply to the enrollment date for `summary`, `exits` and the cross-sequence table, and to the run's creation date for `nodes` and `channels`. Rates are per 100 and rounded to one decimal; a rate with no denominator is `null`, never `NaN`. ## Summary [#summary] `GET /v1/sequences/{id}/analytics/summary` | Field | Meaning | |---|---| | `enrolled` | enrollments created (in the filter) | | `active`, `exited`, `completed` | by current status (`active` includes `paused` and `waiting_limit`) | | `touches_delivered` | outreach runs whose message was delivered (the send time for email, which has no receipt; Allo's `sms.sent` for texts); the second denominator | | `replies`, `meetings` | enrollments with a first reply or a first meeting | | `reply_rate_per_100_enrolled`, `meeting_rate_per_100_enrolled` | per enrolled | | `reply_rate_per_100_delivered`, `meeting_rate_per_100_delivered` | per delivered touch | | `replies_by_channel` | `{ email, sms, call }` counts of attributed replies | ## Exits [#exits] `GET /v1/sequences/{id}/analytics/exits` returns `exits: [{ reason, count }]` largest first: `replied`, `meeting_booked`, `opt_out`, `bounced`, `suppressed`, `manual`, `deleted`. ## Nodes [#nodes] `GET /v1/sequences/{id}/analytics/nodes` returns one row per step: | Field | Meaning | |---|---| | `node_id`, `node_type`, `channel` | the step | | `reached` | runs of this node | | `executed` | outreach runs that were sent | | `skipped`, `skipped_by_reason` | runs a gate refused, with `{ no_consent: 12, suppressed: 3, … }` | | `failed` | runs that ran out of retries | | `delivered`, `bounced` | from the run's recorded outcome | | `replies`, `meetings` | signals attributed to this step's runs | | `reply_rate_per_100_delivered` | | | `median_time_to_reply_seconds` | median of reply time minus send time | ## Channels [#channels] `GET /v1/sequences/{id}/analytics/channels` returns one row per `(channel, touch_number)`: `reached`, `sent`, `skipped`, `delivered`, `bounced`, `replies`, `meetings`, `reply_rate_per_100_sent`, `meeting_rate_per_100_sent`. The touch number counts only messages actually sent (1 is the first one the contact received); a channel's skipped and failed runs share a row with `touch_number: 0`. The split is deliberate: SMS usually comes later and to warmer contacts, so an email-versus-SMS chart is only fair at the same position in the sequence. See [Comparing channels](/docs/analytics/comparing-channels). ## Cross-sequence [#cross-sequence] `GET /v1/analytics/sequences?min_enrolled=` returns `sequences: [{ sequence, name, status, enrolled, replies, meetings, replies_per_100_enrolled, meetings_per_100_enrolled }]`, every sequence of the project ranked by replies then meetings per 100 enrolled; `min_enrolled` hides tiny samples. It has no status counts: for a list screen that also shows running and finished, read `counts` from [`GET /v1/sequences`](/docs/concepts/sequence/versions#reading) (active, paused, waiting_limit, completed, exited, failed per sequence, in the same page) and join the two on the sequence id. Neither call is per sequence, so a list screen costs one analytics call plus one page of sequences, not one request per row. The architecture document also lists `GET /v1/analytics/channels` (all sequences compared by channel) and a 60-second cache. Neither exists in the code today. ## What a client can show [#what-a-client-can-show] | Screen | Numbers | Endpoint | |---|---|---| | Sequence overview | replies and meetings (rate vs enrolled and delivered), replies by channel, exit reasons | `summary`, `exits` | | Per step | reached, executed, skipped by reason, failed, delivered, bounced, replies, meetings, median time to reply | `nodes` | | Channel comparison | per channel and touch number | `channels` | | By version | any of the above with `?version=` | | | Cross-sequence | sequences ranked by replies and meetings per 100 enrolled | `/v1/analytics/sequences` | # Reply and meeting attribution (https://docs.opensequence.dev/docs/analytics/outcomes) How replies and reported meetings are attributed: direct and assisted credit, the 14-day default window, each counted once per enrollment. ```bash title="curl" curl "$SEQ/v1/sequences/seq_01J9…/analytics/summary?from=2026-09-01&to=2026-10-01" -H "Authorization: Bearer $KEY" # {"sequence":"seq_…","enrolled":412,"active":140,"exited":230,"completed":42,"touches_delivered":980,"replies":61,"meetings":12, # "reply_rate_per_100_enrolled":14.8,"meeting_rate_per_100_enrolled":2.9,"reply_rate_per_100_delivered":6.2,"meeting_rate_per_100_delivered":1.2, # "replies_by_channel":{"email":44,"sms":9,"call":8}} ``` ```ts title="TypeScript" const summary = await oseq.analytics.summary('seq_01J9…', { from: new Date('2026-09-01'), to: new Date('2026-10-01') }); ``` **The only two outcomes are replies and meetings booked**, attributed to a sequence, a channel and a step. There is no goal, no funnel and no score. ## Definitions [#definitions] - **Reply**: an inbound email in a thread the service started, an inbound text, a reply you report, or a task completed with an outcome in its `connected_outcomes` (a `call_connected` signal). Out-of-office auto-replies, bounces and opt-outs are not replies. - **Meeting booked**: a `meeting_booked` you report with [contact events](/docs/get-started/integrate#report-what-the-service-cannot-see). It is idempotent by its id and counted once per enrollment. - **Attribution window**: the signal is matched to enrollments whose last touch is within `settings.attribution_days` (14 by default) before it occurred. - **Counted once per enrollment**: the **first** reply and the **first** meeting are attributed and set `repliedAt` / `meetingBookedAt` on the enrollment (`replied_at` / `meeting_booked_at` in webhook payloads), never rewritten; later ones are stored with `attribution: "none"` and appear only in the timeline. ## Attribution rules [#attribution-rules] | Signal | Credited run | Attribution | |---|---|---| | reply on channel X | the latest sent touch on channel X before the reply, in this enrollment | `direct` | | reply on channel X, no touch on X | the latest sent touch on any channel | `assisted` | | connected call | the task's own run | `direct` | | meeting booked | the most recently touched enrollment of the contact in the window, even one that already exited (a reply often exits it; the meeting comes later); then the latest touch before the booking | `direct` | The result is written once on the signal (`attributed_run`, `attribution`) and on the enrollment, and shows in the journey and in `signal.received`. ## Filters [#filters] Every analytics endpoint accepts `version` (a version id), `from` and `to` (ISO dates), `sender` (a sender id) and `country` (the contact's). `from` and `to` filter on the enrollment date for `summary`, `exits` and the cross-sequence table, and on the run's creation date for `nodes` and `channels`. Responses are not cached. ## What the numbers are made from [#what-the-numbers-are-made-from] The endpoints read the ledgers directly (enrollments, runs, signals) with no pre-aggregation to keep correct, which is fine at the volumes the service targets. See [Endpoints](/docs/analytics/endpoints) for each one. # Attributes: custom data on contacts and senders (https://docs.opensequence.dev/docs/concepts/attributes) How contact attrs and sender attrs work: free JSON you store once and read in templates and conditions, such as a plan, a company or a calendar URL. Attributes are your own data on a contact or a sender. Templates and conditions read them. Both are free JSON objects named `attrs`. | | Contact `attrs` | Sender `attrs` | |---|---|---| | Set with | `PUT` or `PATCH /v1/contacts/{id}` | `PUT /v1/senders/{id}` | | On update | Merged by top-level key | Replaced as a whole | | In templates | `{{ attrs.plan }}` (or `{{ contact.attrs.plan }}`) | `{{ sender.attrs.calendar_url }}` | | In conditions | `attrs.plan` | `sender.attrs.region` | ## Example [#example] ```ts await oseq.contacts.upsert('p_7', { attrs: { plan: 'trial', company: { name: 'Example Inc', size: 40 } } }); await oseq.senders.upsert('u_42', { name: 'Max Rivera', attrs: { calendar_url: 'https://cal.com/max-rivera/30min' } }); ``` ```text Hi {{ contact.first_name | "there" }}, how is the trial going at {{ attrs.company.name | "your team" }}? If it helps, grab 20 minutes here: {{ sender.attrs.calendar_url }} ``` Nested paths work with dots. A missing value renders empty, so give it a fallback: `{{ attrs.company.name | "your team" }}`. A contact upsert that sends `{ "attrs": { "company": { "size": 50 } } }` replaces the whole `company` object and keeps `plan`. Send the full nested object when you change part of it. To show typed pickers in a condition editor, describe your contact attributes once in `settings.attrs_schema` (`PUT /v1/project/settings`). `GET /v1/schema/fields` returns them. # Contact: the person who receives a sequence (https://docs.opensequence.dev/docs/concepts/contact) What a contact is: name, email, E.164 phone, LinkedIn URL, ISO country, time zone and attributes, keyed by your own id, plus outreach consent and suppressions. A contact is the person a sequence reaches. This page shows the fields, consent and suppressions. You create a contact with your own person id. Upserting needs an `enroll` key. ```bash title="curl" curl -X PUT $SEQ/v1/contacts/p_7 -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{ "first_name": "Dana", "last_name": "Whitfield", "email": "dana@example.com", "phone": "+14155550123", "linkedin_url": "linkedin.com/in/dana-whitfield", "country": "US", "timezone": "America/Los_Angeles", "attrs": { "plan": "trial", "company": { "name": "Example Inc" } } }' ``` ```ts title="TypeScript" await oseq.contacts.upsert('p_7', { first_name: 'Dana', last_name: 'Whitfield', email: 'dana@example.com', phone: '+14155550123', linkedin_url: 'linkedin.com/in/dana-whitfield', country: 'US', timezone: 'America/Los_Angeles', attrs: { plan: 'trial', company: { name: 'Example Inc' } }, }); ``` | Field | Rules | |---|---| | `email` | Needed for email steps and for Attio lookups. | | `phone` | E.164, like `+14155550123`. Other formats are normalized; an invalid number is a `422 INVALID_CONTACT`. | | `linkedin_url` | The profile, for [LinkedIn](/docs/modules/linkedin) steps. Stored as `https://www.linkedin.com/in/…`; an address off linkedin.com is a `422 INVALID_CONTACT`. | | `country` | ISO 3166-1 alpha-2, like `US`. Texts go only to countries in the project's `sms_countries`. | | `timezone` | An IANA zone. Used for send windows, business days and SMS quiet hours. | | `attrs` | Free JSON, merged by top-level key on every upsert. See [Attributes](/docs/concepts/attributes). | A field you leave out keeps its stored value. Up to 500 contacts at once: `POST /v1/contacts:batch` (`oseq.contacts.batch()`). OpenSequence does not fill `country` from the phone number. Derive it yourself when you have no better source: ```ts import { parsePhoneNumber } from 'libphonenumber-js'; const country = parsePhoneNumber(phone)?.country; // '+447700900123' -> 'GB' ``` ## Consent and suppressions [#consent-and-suppressions] Outreach consent is off by default. Only an `admin` key can record it, and no text or agent call goes out without it. It was called SMS consent before 0.3.0; the old names still work. ```ts await oseq.contacts.setOutreachConsent('p_7', { consent: true, source: 'signup form' }); // PUT /v1/contacts/{id}/outreach-consent ``` A suppression means "do not contact on this channel". The service adds one on an unsubscribe click, a STOP text, a hard bounce or a complaint, and the contact's enrollments exit. You add one by reporting `{ "type": "suppressed" }` or `{ "type": "opt_out" }` with `POST /v1/contacts/{id}/events`. Suppressions are checked when you enroll and again before every send. The API cannot remove a suppression yet. `DELETE /v1/contacts/{id}` erases the contact and everything attached, for privacy requests. # Enrollment: where a contact is in a sequence (https://docs.opensequence.dev/docs/concepts/enrollment) What an enrollment is: one contact in one sequence version, its status, its current step and its journey, and how to show where a contact is. An enrollment is one contact going through one sequence version as one sender. This page covers its status, its current step and its journey. ## Enrolling [#enrolling] You enroll contacts with an `enroll` key. A contact can be in one active sequence per project. A second enrollment fails with `409 ALREADY_IN_SEQUENCE`, and nobody in that batch is enrolled. ```ts const { enrollments } = await oseq.sequences.enroll(sequenceId, { contacts: ['p_7'], sender: 'u_42' }); // POST /v1/sequences/{id}/enrollments ``` The enrollment stays pinned to the version it started on, even after you publish a new one. ## Status [#status] | Status | Meaning | |---|---| | `active` | Moving through the flow, or waiting for a timer, an event or a task. | | `paused` | Paused by you, by an out-of-office reply (until the return date or 7 days) or by a failed step. | | `waiting_limit` | Held by the sender's daily limit. It retries an hour later. | | `completed` | Reached an `end` node or an unwired exit. | | `exited` | Left early. `exitReason` is `replied`, `meeting_booked`, `opt_out`, `bounced`, `suppressed`, `manual` or `deleted`. | | `failed` | Reserved. The engine does not set it today: a failed step pauses the enrollment with `pauseReason: "step_failed"`. | The current step is `currentNodeId`. `nextRunAt` is when the engine looks at it next. Replies, bookings and opt-outs end the enrollment. An unsubscribe, a STOP text, a hard bounce or a suppression always exits. A reply or a booked meeting exits when the definition's `exit_on` lists it, and otherwise can wake a `wait_for`. Pause, resume and exit: `POST /v1/enrollments/{id}/pause`, `/resume` (`enroll` key) and `/exit` (`admin` key). ## The journey [#the-journey] `GET /v1/enrollments/{id}` (`oseq.enrollments.get()`) returns the journey: the enrollment, the contact, the pinned version with its definition, and what happened. Each step that ran is a run, in `runs[]`: its `nodeId`, `status`, the `branch` it took, and a `result` with what it saw and did (`result.facts` for a condition, `result.skip_reason` for a skipped step, `result.until` for a wait). `messages[]` are the emails and texts, each linked to its step by `runId`. `signals[]` are the replies, bounces, opt-outs and other events that came back, and `tasks[]` are the tasks. To draw this as a path on your sequence, see [Where a contact is](/docs/concepts/enrollment/where-a-contact-is). # Show where a contact is in a sequence (https://docs.opensequence.dev/docs/concepts/enrollment/where-a-contact-is) How to draw one contact's path through a sequence from GET /v1/enrollments/{id}: visited nodes, edges taken, the current step and the timeline. These steps turn one journey into a picture: the visited nodes, the edges taken, the current step and a timeline. ```bash title="curl" curl $SEQ/v1/enrollments/enr_01JA… -H "Authorization: Bearer $KEY" ``` ```ts title="TypeScript" const journey = await oseq.enrollments.get('enr_01JA…'); // type Journey ``` `GET /v1/enrollments/{id}` needs a `read` key. It returns `enrollment`, `contact`, `version`, `runs`, `messages`, `signals` and `tasks`. Stored records are camelCase. Abridged: ```json { "enrollment": { "id": "enr_01JA…", "status": "active", "currentNodeId": "wait_reply", "nextRunAt": "2026-10-24T16:00:00.000Z", "ownerRunId": null, "waiting": { "runId": "run_04…", "events": { "reply": "end" }, "onTimeout": "call_1" }, "pausedUntil": null, "pauseReason": null, "exitReason": null, "touchCount": 1, "versionId": "ver_01JA…" }, "contact": { "id": "ctc_01JA…", "externalId": "p_7", "firstName": "Dana", "email": "dana@example.com" }, "version": { "id": "ver_01JA…", "tag": "v2", "status": "published", "definition": { "entry": "start", "nodes": { "…": "…" } } }, "runs": [ { "id": "run_01…", "nodeId": "start", "nodeType": "start", "status": "done", "branch": "then", "next": { "then": "check_plan" }, "result": {} }, { "id": "run_02…", "nodeId": "check_plan", "nodeType": "condition", "status": "done", "branch": "yes", "next": { "yes": "intro", "no": "end" }, "result": { "mode": "all", "branch": "yes", "note": "The condition matched.", "facts": [{ "field": "attrs.plan", "label": "attrs.plan", "value": "trial", "rule": "is trial", "matched": true }] } }, { "id": "run_03…", "nodeId": "intro", "nodeType": "outreach", "channel": "email", "status": "done", "branch": "sent", "touchNumber": 1, "next": { "sent": "wait_reply" }, "result": { "rendered": { "contact.first_name": "Dana" } } }, { "id": "run_04…", "nodeId": "wait_reply", "nodeType": "wait_for", "status": "waiting", "branch": null, "next": { "reply": "end", "timeout": "call_1" }, "result": { "until": "2026-10-24T16:00:00.000Z", "events": ["reply"] } } ], "messages": [{ "id": "msg_01…", "runId": "run_03…", "channel": "email", "direction": "out", "subject": "Hi Dana", "status": "sent", "occurredAt": "2026-10-21T16:00:02.000Z" }], "signals": [], "tasks": [] } ``` Every field is on the [reference page](/api/enrollments/get-enrollments-id) and in the SDK's `Journey` type. The journey has no sequence name: read it with `GET /v1/sequences/{id}` (`oseq.sequences.get(journey.enrollment.sequenceId)`). ## Run order [#run-order] `runs` are sorted by `createdAt`, then `id`. Steps the engine takes in one pass (a `start`, a `condition` and an email, say) share the same `createdAt`, and their ids are not ordered within the same millisecond. So inside a group with the same `createdAt`, the array order can differ from the path. Chain those runs by their edges instead: a run's `next[branch]` is the `nodeId` of the run after it. ## 1. Draw the sequence [#1-draw-the-sequence] Lay out `version.definition.nodes`. This is the version the enrollment is pinned to, not the latest one, so the drawing always matches the path. ## 2. Mark the visited nodes [#2-mark-the-visited-nodes] Every `runs[].nodeId` is a visited node. A `start` node always produces a run with `branch: "then"` when the definition has one; a definition may also begin directly with another node. Color each node by its run's `status`: | `status` | Show | |---|---| | `done` | Done, with the `branch` it took. | | `skipped` | Skipped, with `result.skip_reason`, such as `no_consent`. | | `deferred` | Retrying at `result.retry_at`, because of `result.deferred` (a limit, the send window, quiet hours). | | `waiting` | Waiting. A `wait_for` run has `result.until` (its timeout, or `null`) and `result.events`. When it closes, `branch` is the event or `timeout`, and `result.woken_by` is the signal id that woke it. | | `running` | Sending now. | | `failed`, `needs_review` | Stopped, with `error`. | | `skipped_dry_run` | Rehearsed in a dry run. Nothing was sent. | A node can have several runs when a step was retried (`attempt` goes up). Show the last one. ## 3. Draw the edges taken [#3-draw-the-edges-taken] For each run with a `branch`, the edge taken goes from `run.nodeId` to `run.next[run.branch]`. In the example, `check_plan` took `yes` to `intro`. A run with `branch: null` has not finished. Its `next` holds the possible next steps. ## 4. Mark the current step [#4-mark-the-current-step] The current step is `enrollment.currentNodeId`. Read it with `status`, `waiting` and `nextRunAt`: | When | Show | |---|---| | `status` is `completed` or `exited` | Finished. Show `exitReason` and `finishedAt`. | | `status` is `paused` | Paused for `pauseReason` (`manual`, `ooo` or `step_failed`), until `pausedUntil` when set. | | `status` is `waiting_limit` | Held by the sender's daily limit. Next try at `nextRunAt`. | | `status` is `active` and `ownerRunId` is set | Sending now. | | `status` is `active` and `waiting` is set | Waiting. `waiting.events` maps each awaited event to its exit. `nextRunAt` is the timeout or the task expiry. | | `status` is `active` otherwise | Scheduled for `nextRunAt`. | A `wait` node finishes its run at once, with `result.until`. During the wait, `currentNodeId` is already the step after it, scheduled for `nextRunAt`. ## 5. Build the timeline [#5-build-the-timeline] Merge `messages`, `signals` and `tasks` by time: - `messages` are the emails and texts this enrollment sent, plus replies received since it started. `runId` links an outbound message to its step. Inbound messages have `runId: null`. - `signals` are what came back: `kind` is `reply`, `bounce`, `opt_out`, `ooo`, `meeting_booked`, `call_connected`, `task_completed` and so on. `attributedRunId` names the step that earned it. - `tasks` are this enrollment's tasks, with `status`, `outcome` and `note`. ## Why a condition took its branch [#why-a-condition-took-its-branch] A condition run stores what it read at decision time in `result.facts`. Each fact has the `field`, the `value` read, the `rule` as a sentence and `matched`. A failed read also has `error`. Show these under the node, so "why did this contact take No" never depends on today's data. ## Many contacts at once [#many-contacts-at-once] `GET /v1/enrollments?sequence=seq_…&status=active` lists enrollments with their `currentNodeId`. Count them per node to show how many people are on each step. `GET /v1/contacts/{id}/timeline` merges everything that ever happened to one contact, across enrollments. # Project: one tenant per customer or workspace (https://docs.opensequence.dev/docs/concepts/project) What a project is in OpenSequence: one tenant with its own API keys, provider credentials, settings and data, so one install can serve many customers. A project is one tenant. Give each of your customers or workspaces its own project. Everything else (senders, contacts, sequences, enrollments, webhooks) belongs to exactly one project. A key from one project never sees another project's data. The operator creates projects with `SEQ_ADMIN_TOKEN`, and each new project comes with its first `admin` key. ```bash curl -X POST $SEQ/v1/admin/projects -H "Authorization: Bearer $SEQ_ADMIN_TOKEN" \ -H "Content-Type: application/json" -d '{"slug":"acme","name":"Acme"}' # {"success":true,"data":{"project":{"id":"prj_…","slug":"acme",…},"api_key":"sk_live_…"}} the key is shown once ``` A project also holds its provider credentials (an Allo key and an Attio key, both write-only) and its settings, such as the countries texts may go to. ## API keys [#api-keys] Each key has one scope. Each scope includes the ones above it. | Scope | Can | |---|---| | `read` | Read senders, contacts, sequences, journeys, tasks and analytics. | | `enroll` | Also upsert contacts, enroll, pause and resume, complete tasks and report contact events. | | `admin` | Also manage senders, sequences, webhooks, keys, outreach consent, provider credentials and settings, and exit enrollments. | Give your app an `enroll` key. Keep the `admin` key for setup screens. ```ts const { api_key } = await oseq.project.apiKeys.create({ name: 'crm-backend', scopes: ['enroll'] }); // POST /v1/api-keys ``` # Sender: the rep a sequence sends as (https://docs.opensequence.dev/docs/concepts/sender) What a sender is: the rep an enrollment acts as, with a name, time zone, email signature, attributes such as a calendar URL, and one channel per kind. A sender is the person outreach comes from. This page shows the profile fields and how a sender gets its channels. Emails go out from the sender's mailbox, texts from their Allo number, and tasks land in their inbox. You create a sender with your own user id. It needs an `admin` key. ```bash title="curl" curl -X PUT $SEQ/v1/senders/u_42 -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" -d '{ "name": "Max Rivera", "email": "max@acme.com", "timezone": "America/New_York", "signature_html": "

Max Rivera
Account Executive

", "attrs": { "calendar_url": "https://cal.com/max-rivera/30min", "direct_line": "+1 415 555 0134" } }' ``` ```ts title="TypeScript" await oseq.senders.upsert('u_42', { name: 'Max Rivera', email: 'max@acme.com', timezone: 'America/New_York', signature_html: '

Max Rivera
Account Executive

', attrs: { calendar_url: 'https://cal.com/max-rivera/30min', direct_line: '+1 415 555 0134' }, }); ```
| Field | What it does | |---|---| | `name` | Required. Templates read `{{ sender.name }}` and `{{ sender.first_name }}` (the first word). | | `email` | The person's address, for `{{ sender.email }}`. | | `timezone` | An IANA zone, default `UTC`. Task due dates and a send window with `tz: "sender"` follow it. | | `signature_html` | The email signature, up to 1 MB, so a base64 logo fits. Sanitized on save. | | `signature_text` | The plain-text signature for `format: "text"` emails. Built from the HTML when you leave it out. | | `attrs` | Anything else a template needs. See [Attributes](/docs/concepts/attributes). | `PUT` replaces the profile. Send `attrs` every time, or they are cleared. Leaving out the signature keeps the stored one, and `null` clears it. ## The signature [#the-signature] `{{ sender.signature }}` inserts `signature_html` in an html email and `signature_text` in a text email. It can be as rich as a branded email: a table layout, inline styles and a logo. On save, an email allowlist keeps tables, inline styles, links and images over `https` or base64, and drops scripts, forms, frames, event handlers and images over plain `http`. A base64 logo goes out as an inline attachment with every email, so keep it to a few kilobytes. ## A calendar link per sender [#a-calendar-link-per-sender] Yes, each sender can have their own booking link. Store it in `attrs` and use it in any template: ```text Worth a quick call? Pick a time: {{ sender.attrs.calendar_url | "just reply to this email" }} {{ sender.signature }} ``` The same works for a direct line, a title or a LinkedIn URL. OpenSequence never reads the calendar. Report a booked meeting with a [contact event](/docs/get-started/integrate#report-what-the-service-cannot-see). ## Channels [#channels] A sender has at most one channel per kind. Only an `active` channel sends. | Channel | Connect it with | Module | |---|---|---| | `email` | `PUT /v1/senders/{id}/channels/email` | [Email](/docs/modules/email) | | `sms` | `PUT /v1/senders/{id}/channels/sms` | [Allo](/docs/modules/sms/allo) | `GET /v1/senders/{id}/readiness` says which steps the sender can run now, and why not. `DELETE /v1/senders/{id}` disables the sender. Their new enrollments are refused with `409 SENDER_DISABLED`. The API cannot re-enable a disabled sender yet. # Branching with conditions (https://docs.opensequence.dev/docs/concepts/sequence/conditions) How conditions branch: the field registry, the operators, how missing data behaves, and how every fact is recorded on the run. ```json "check": { "type": "condition", "params": { "mode": "all", "rules": [ { "field": "contact.has_phone", "op": "is_true" }, { "field": "history.last_task_outcome", "op": "is", "value": "voicemail" }, { "field": "attrs.deal.stage", "op": "is_not", "value": "won" } ] }, "next": { "yes": "sms_follow", "no": "email_2" } } ``` ```bash title="curl" curl $SEQ/v1/schema/fields -H "Authorization: Bearer $KEY" # {"sources":[{"prefix":"contact","label":"Contact","open":false,"fields":[{"field":"contact.country","label":"Contact country","type":"text"},…]},…],"attrs":[{"field":"attrs.deal.stage","label":"Deal stage","type":"enum","values":[…]}]} ``` ```ts title="TypeScript" const { sources, attrs } = await oseq.schema.fields(); ``` A condition is a list of `{ field, op, value }` combined with `all` or `any` (1 to 20 rules). The registry of fields is closed and served at `GET /v1/schema/fields`, so your picker, the validator and the evaluator cannot disagree. The generated table of every field and operator is in the [reference](/reference/condition-fields). ## Fields [#fields] | Prefix | Fields | Source | |---|---|---| | `contact.` | `country`, `timezone` (text), `has_email`, `has_phone`, `outreach_consent` (bool; `sms_consent` is its old name); also `first_name`, `last_name`, `email` are readable | the contact row | | `attrs.` | anything you pushed, read as text | the contact's `attrs` | | `sender.` | `timezone` (text), `has_sms` (bool); also `name` | the sender and its active channels | | `history.` | `touches`, `days_since_last_touch`, `emails_sent`, `days_since_last_task`, `tasks_last_14d` (number), `replied_since_enrollment` (bool), `last_reply_channel` (enum: `email`, `sms`, `call`), `last_task_outcome`, `last_task_kind` (text) | the enrollment, runs, signals and tasks: one indexed query each | | `crm.` | `person.exists`, `company.exists`, `deal.exists`, `deal.count_open` and any `person.`, `company.`, `deal.` | one live Attio lookup per contact per step ([Attio](/docs/modules/crm/attio)) | ## Operators [#operators] | Type | Operators | |---|---| | text | `is`, `is_not`, `contains`, `is_empty`, `is_not_empty` (case-insensitive) | | enum | `is`, `is_not` (the value must be one of the field's values) | | number | `eq`, `ne`, `gt`, `gte`, `lt`, `lte` | | bool | `is_true`, `is_false` | | date | `before`, `after` (ISO dates) | The validator refuses an operator the field's type does not support (`BAD_OPERATOR`), a missing value where one is needed, a non-number for a number field, and a value outside an enum (`BAD_VALUE`). Fields the registry does not know are `UNKNOWN_FIELD`. ## Missing data never matches [#missing-data-never-matches] A fact that is `null` (the contact has no country, no task was ever completed, the CRM lookup found nothing or failed) fails **every** operator, including `is_not` and `ne`. So in `all` mode a missing fact sends the contact to `no`; in `any` mode it is simply not a match. Design for it: put the "has the data" rule first (`contact.has_phone is_true`), and treat `no` as the safe path. ## Evaluation is lazy and recorded [#evaluation-is-lazy-and-recorded] Rules are read in order and the evaluation stops at the first decisive one (`all` stops at the first false, `any` at the first true). Each read is stored on the run as `result.facts`: ```json "facts": [ { "field": "contact.has_phone", "label": "Contact has a phone", "value": true, "rule": "is true", "matched": true }, { "field": "history.last_task_outcome", "label": "Last task outcome", "value": "connected", "rule": "is voicemail", "matched": false } ], "mode": "all", "branch": "no", "note": "1 of 3 rules matched, so the contact took No." ``` A read that failed (Attio down) also carries `error`. This is what the [journey](/docs/concepts/enrollment/where-a-contact-is) shows, so "why did they take No" is answered from what the decision saw. ## Keeping facts fresh [#keeping-facts-fresh] `attrs.*` is what you last pushed; keep it current with `PATCH /v1/contacts/{id}`. `history.*` is maintained by the service. `crm.*` is read at decision time and needs no sync. # Sequence definition format (https://docs.opensequence.dev/docs/concepts/sequence/definition) What the one JSON document that holds a whole sequence contains: its shape, ids, transitions, durations, settings and exit_on. A sequence is one JSON document: nodes, transitions, settings and the exit choice. It is what you save into a draft version and what the engine runs once published. Validate one without saving: ```bash title="curl" curl -X POST $SEQ/v1/sequences:validate -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \ -d "{\"definition\": $(cat definition.json)}" # {"success":true,"data":{"ok":true,"problems":[{"path":"nodes.email_intro.params.body","code":"NO_UNSUBSCRIBE","message":"…","severity":"warning"}]}} ``` ```ts title="TypeScript" const { ok, problems } = await oseq.sequences.validate(definition); ``` ## Shape [#shape] ```json { "schema_version": 1, "entry": "email_intro", "settings": { "send_window": { "days": ["mon", "tue", "wed", "thu", "fri"], "from": "08:00", "to": "18:00", "tz": "contact" }, "jitter": "15m", "reenroll": "after_90d" }, "exit_on": ["reply", "meeting_booked"], "nodes": { "email_intro": { "type": "outreach", "channel": "email", "action": "send", "params": { "name": "Intro email", "subject": "Quick question, {{ contact.first_name | \"there\" }}", "body": "…\n\n{{ unsubscribe_url }}", "reply_in_thread": false }, "next": { "sent": "wait_2d", "skipped": "wait_2d", "failed": "end_failed" } }, "wait_2d": { "type": "wait", "params": { "duration": "2bd" }, "next": { "then": "check_stage" } }, "check_stage": { "type": "condition", "params": { "mode": "all", "rules": [ { "field": "history.last_task_outcome", "op": "is", "value": "voicemail" }, { "field": "attrs.deal.stage", "op": "is", "value": "contacting" } ] }, "next": { "yes": "call_1", "no": "sms_follow" } }, "sms_follow": { "type": "outreach", "channel": "sms", "action": "send", "params": { "body": "Hi {{ contact.first_name | \"there\" }}, did you see my email? Reply STOP to opt out." }, "next": { "sent": "call_1", "skipped": "call_1" } }, "call_1": { "type": "task", "params": { "kind": "call", "title": "Call {{ contact.first_name | \"them\" }}", "due": "1bd", "expire": "3bd", "dialer": true }, "next": { "completed": "end_done", "no_answer": "email_2" }, "branches_by_outcome": { "connected": "end_connected" } }, "email_2": { "type": "outreach", "channel": "email", "action": "send", "params": { "subject": "Re: Quick question", "body": "…\n\n{{ unsubscribe_url }}", "reply_in_thread": true }, "next": { "sent": "end_done" } }, "end_done": { "type": "end", "params": { "label": "Done" } }, "end_connected": { "type": "end", "params": { "label": "Connected" } }, "end_failed": { "type": "end", "params": { "label": "Email failed" } } } } ``` | Key | Meaning | |---|---| | `schema_version` | always `1` today. Bumped only for breaking changes; the service keeps reading every version it has ever published | | `entry` | the id of the first node. Most sequences start with an `outreach` or a `start` node; `start` is optional | | `settings.send_window` | days and hours outside which outreach steps wait, in the contact's zone (`tz: "contact"`, the default, falling back to the sender's when the contact has none) or the sender's (`"sender"`). Time is `HH:MM`, 24-hour; the window is `[from, to)` | | `settings.jitter` | a random delay added to each outreach step so sends do not burst on the hour, pushed back inside the window if it lands outside | | `settings.reenroll` | `never` (default: a contact who was ever in this sequence is skipped), `always`, or `after_d` (skipped while the last enrollment finished less than n days ago) | | `exit_on` | `reply`, `meeting_booked`, both, or none (default `[]`). See below | | `nodes` | a flat map from id to node. Ids are `lower_snake_case`, up to 64 characters, chosen by you | A node is `{ type, name?, channel?, action?, params?, next, branches_by_outcome? }`. `next` maps each transition key the node emits to a node id; a key left unwired ends the enrollment (`completed`) when taken, except the keys a node type requires (`then`, `yes`, `no`). `branches_by_outcome` is for `task` nodes only. The full list of node types, params and transitions: [Nodes](/docs/concepts/sequence/nodes) and the generated [catalogue](/reference/nodes). ## Durations [#durations] One grammar everywhere, `^\d+(m|h|d|bd)$`: `m` minutes, `h` hours, `d` calendar days, `bd` business days (Monday to Friday in the relevant zone; holidays are not modelled). Waits, timeouts, task due and expiry, jitter. ## Exit rules [#exit-rules] `exit_on` is the only exit configuration: **Replied** (on any channel; a connected call counts) and **Meeting booked**. Everything else is built in and not configurable: | Always on | Behaviour | Who detects it | |---|---|---| | Opt-out (a STOP text, a click on the hosted opt-out link) | exits, suppresses the channel | the service | | Hard bounce, complaint | exits, suppresses email | the service | | Out-of-office auto-reply | **pauses** until the stated date or 7 days; never exits | the service | | Opt-out recorded elsewhere | exits, suppresses | you, `events { type: "opt_out" }` | | Do not contact, bad number, invalid email, left the company | exits | you, `events { type: "suppressed" }` | | Contact deleted or merged | exits with `deleted` and erases | you, `DELETE /v1/contacts/{id}` | | Sender disabled | steps skip; the enrollment runs on | you, `DELETE /v1/senders/{id}` | | Exit through the API | exits with reason `manual` and your label | you | An exit ends the enrollment and emits `enrollment.exited`. A reply that arrives when `exit_on` does not list `reply` is still attributed and can wake a `wait_for`; it just does not end the flow. ## Conventions that keep it safe to edit by hand or by an agent [#conventions-that-keep-it-safe-to-edit-by-hand-or-by-an-agent] Human-readable string ids; a flat node map with named transitions; a closed vocabulary (node types, transition keys, event names, field names, operators); one duration grammar; no expressions and no code. The JSON Schema is served at `GET /v1/schema` and reproduced in the [reference](/reference/definition-schema); the limits are 200 nodes and 256 KB. # Sequence: a named flow with versioned JSON definitions (https://docs.opensequence.dev/docs/concepts/sequence) What a sequence is: a named flow whose steps live in versioned JSON definitions, a draft you edit and published versions that never change. A sequence is a named flow, such as "Trial intro". This page explains how its versions work. The steps live in a JSON document called the **definition**: [nodes](/docs/concepts/sequence/nodes) joined by named exits. ```json { "schema_version": 1, "entry": "intro", "exit_on": ["reply"], "nodes": { "intro": { "type": "outreach", "channel": "email", "action": "send", "params": { "subject": "Hi {{ contact.first_name | \"there\" }}", "body": "…" }, "next": { "sent": "wait_2d" } }, "wait_2d": { "type": "wait", "params": { "duration": "2bd" }, "next": { "then": "end" } }, "end": { "type": "end" } } } ``` ## Versions [#versions] A sequence holds versions (`v1`, `v2`, …). You edit a **draft**, then publish it. A published version never changes, and new enrollments use it. To change a live flow, copy it into a new draft, edit it and publish again. Contacts already enrolled stay pinned to the version they started on. ```ts const { sequence, version } = await oseq.sequences.create({ name: 'Trial intro', definition }); // a v1 draft await oseq.sequences.versions.publish(sequence.id, version.id); ``` Validation errors block publishing. Warnings, such as a missing unsubscribe link, do not. Details: [The definition](/docs/concepts/sequence/definition) and [Versions](/docs/concepts/sequence/versions). # Sequence nodes: every node type and its exits (https://docs.opensequence.dev/docs/concepts/sequence/nodes) Every sequence node type with its params and transitions, one example each, and which node types count as touches. A node is one step of a sequence. Each node lists where to go next for each outcome, in `next`. | `type` | Params | Transitions | Runs | |---|---|---|---| | `start` | none | `then` (required) | inline | | `outreach` `email` `send` | `subject`, `body`, `format` (`text` or `html`), `reply_in_thread`, `name` | `sent`, `skipped`, `failed` | queue `seq_email` | | `outreach` `sms` `send` | `body`, `name` | `sent`, `skipped`, `failed` | queue `seq_sms` | | `outreach` `call` `agent_call` | `agent_id`, `title`, `description`, `skills`, `give_up_after`, `exit_on_connect`, `name` | `completed`, `reached`, `transferred`, `not_interested`, `wrong_number`, `do_not_call`, `not_reached`, `skipped`, `failed` | queue `seq_call`, then waits | | `wait` | `duration` | `then` (required) | inline timer | | `wait_for` | `events[]`, `timeout` | one per event, `timeout` | timer and signal | | `condition` | `mode`, `rules[]` | `yes`, `no` (both required) | inline | | `task` | `kind`, `title`, `body`, `link`, `due`, `expire`, `connected_outcomes`, `dialer`, `auto_complete` | `completed`, `no_answer`, plus `branches_by_outcome` | inline, then waits | | `end` | `label` | none | inline | Exact schemas, defaults and limits are generated from the registries: [Nodes and channels](/reference/nodes). An unwired transition that is taken ends the enrollment as `completed`. ## `start` [#start] Optional. A no-op that makes the entry obvious on a canvas. ```json "start": { "type": "start", "next": { "then": "email_intro" } } ``` ## `outreach` email [#outreach-email] ```json "email_intro": { "type": "outreach", "channel": "email", "action": "send", "params": { "name": "Intro", "subject": "Quick question, {{ contact.first_name | \"there\" }}", "body": "

Hi {{ contact.first_name | \"there\" }},

…

Unsubscribe

", "format": "html", "reply_in_thread": false }, "next": { "sent": "wait_2d", "skipped": "wait_2d", "failed": "end_failed" } } ``` Sends from the sender's mailbox over SMTP with the service's own `Message-ID`. `format: "html"` sends the body as HTML with a text alternative and HTML-escapes every rendered value; `text` (default) sends plain text. `reply_in_thread: true` replies in the thread of the previous email of this enrollment (`In-Reply-To` and `References`), which is how a follow-up shows under the first message. A body without `{{ unsubscribe_url }}` publishes with the warning `NO_UNSUBSCRIBE`. `sent` is taken after the provider accepted the message; `skipped` after a gate refused it (no email, suppressed, channel missing or not active, country, and so on; `skipped` falls back to `sent` when unwired); `failed` after the retries ran out (five reads of the queue message), and when `failed` is unwired the enrollment pauses with `step_failed`. Caps and windows **defer** rather than skip. Limits: subject 300, body 100,000 characters. ## `outreach` sms [#outreach-sms] ```json "sms_follow": { "type": "outreach", "channel": "sms", "action": "send", "params": { "body": "Hi {{ contact.first_name | \"there\" }}, this is {{ sender.first_name }} from Acme. Did you see my email? Reply STOP to opt out." }, "next": { "sent": "wait_1d", "skipped": "wait_1d" } } ``` Gates that skip: `no_consent`, `no_phone`, `country_not_allowed`, `no_timezone`, `suppressed`, `no_sms_channel`; the quiet-hours gate (08:00 to 21:00 recipient-local) defers. Over 320 characters the validator warns (`TOO_LONG`, it is more than two segments); the hard limit is 1000. An unknown send outcome is never retried: the run goes `needs_review`. ## `outreach` call [#outreach-call] ```json "confirm_call": { "type": "outreach", "channel": "call", "action": "agent_call", "params": { "agent_id": "agt-…", "title": "Confirm the demo with {{ contact.first_name | \"them\" }}", "description": "Ask if Friday 10am still works. If not, offer Monday." }, "next": { "reached": "end_confirmed", "not_reached": "sms_follow", "completed": "end_done" } } ``` An Allo Outbound agent phones the contact. The step waits for the result and follows the outcome's transition; an outcome with no transition follows `completed`. `not_reached` is also taken when `give_up_after` (default `3d`) passes. The call goes out from the sender's Allo number; `allo_number` fixes another line. Gates that skip: `no_consent`, `no_phone`, `suppressed`, `no_allo_number`. `skipped` falls back to `completed` when unwired. A call that reaches the contact exits a sequence that lists `reply` in `exit_on`, unless the step sets `exit_on_connect: false`. See [Allo agent calls](/docs/modules/calls/allo). ## `wait` [#wait] ```json "wait_2d": { "type": "wait", "params": { "duration": "2bd" }, "next": { "then": "check_stage" } } ``` A timer. `bd` counts business days in the contact's zone (the sender's when the contact has none), ending at the same time of day; the next outreach step is then pushed into the send window. ## `wait_for` [#wait_for] ```json "wait_reply": { "type": "wait_for", "params": { "events": ["reply:email", "meeting_booked"], "timeout": "5bd" }, "next": { "reply:email": "end_replied", "meeting_booked": "end_booked", "timeout": "call_1" } } ``` The only event wait. Events: `reply`, `reply:email`, `reply:sms`, `call_connected`, `meeting_booked`. Each waited event needs a transition (`BAD_EVENT`); `timeout` is optional, and without one the enrollment waits forever (or until something exits it). A `reply` on any channel matches `reply` and `reply:`; a connected call matches `call_connected` and `reply`. When an awaited event arrives, the enrollment moves on at once. When the timeout passes first, it takes `timeout`. An event that arrives while the enrollment is not waiting for it does not wake anything, but a reply still exits when `exit_on` lists `reply`. ## `condition` [#condition] ```json "check_stage": { "type": "condition", "params": { "mode": "any", "rules": [ { "field": "history.replied_since_enrollment", "op": "is_true" }, { "field": "crm.deal.stage", "op": "is", "value": "Proposal" } ] }, "next": { "yes": "end_done", "no": "sms_follow" } } ``` `all` or `any` over 1 to 20 rules; `yes` and `no` both required. Evaluation is lazy (stops at the first decisive rule) and every value read is recorded on the run. Missing data never matches. Fields and operators: [Conditions](/docs/concepts/sequence/conditions). ## `task` [#task] ```json "call_1": { "type": "task", "params": { "kind": "call", "title": "Call {{ contact.first_name | \"them\" }} about {{ attrs.company.name | \"their company\" }}", "body": "Last email: {{ sequence.name }}", "due": "1bd", "expire": "3bd", "dialer": true }, "next": { "completed": "wait_3d", "no_answer": "email_2" }, "branches_by_outcome": { "connected": "end_connected", "voicemail": "sms_follow" } } ``` Creates a task for the sender and waits. Completing it with an outcome takes `branches_by_outcome[outcome]`, else `completed`. Expiry or cancellation takes `no_answer`. | Param | Meaning | |---|---| | `kind` | Required. The task's type. `call` gets the Allo behaviour; any other kind, such as `manual`, is yours to render. LinkedIn has its own step, [`linkedin_connect`](#linkedin_connect). | | `title`, `body`, `link` | Templates, rendered once when the task is created. | | `due` | Required. A duration on the sender's calendar, like `2h` or `1bd`. | | `expire` | When the task expires if nobody completes it. Default: seven days after `due`. | | `connected_outcomes` | Outcomes that count as a reply. Default `["connected"]`. | | `dialer` | Push the contact into the sender's Allo power dialer. Default `false`. | | `auto_complete` | Let Allo's finished call complete a `call` task. Default `true`. | Your app completes a task with `POST /v1/tasks/{id}/complete` and an `outcome`. A `call` task also completes by itself when the rep calls from Allo: see [Allo](/docs/modules/sms/allo#call-tasks). A task is not a touch. ## `linkedin_connect` [#linkedin_connect] ```json "li_connect": { "type": "linkedin_connect", "params": { "note": "Hi {{ contact.first_name | \"there\" }}, happy to connect.", "expire": "5bd" }, "next": { "completed": "wait_3d", "no_answer": "email_2", "skipped": "email_2" } } ``` Creates a `linkedin_connect` task with the contact's profile as `link` and the rendered note as `body`, then waits. The task completes as `sent` when the sender opens it (`POST /v1/tasks/{id}/open`); expiry or cancellation takes `no_answer`; a contact without `linkedin_url` takes `skipped`. Notes are cut at 300 characters. Params and the one-click flow: [LinkedIn](/docs/modules/linkedin). ## `end` [#end] ```json "end_connected": { "type": "end", "params": { "label": "Connected" } } ``` Ends the enrollment as `completed`. The label shows in the journey and in your canvas; several `end` nodes make the per-step analytics tell the paths apart. ## Which node types count as touches [#which-node-types-count-as-touches] Only outreach steps (`email send`, `sms send`, `call agent_call`) are touches: they increment the enrollment's `touch_count`, set `last_touch_at` and are the denominators of the delivered rates. A task, LinkedIn requests included, is not a touch; a connected call is credited to the task's run as a reply. An agent call that reaches the contact is credited to its own run the same way. # Message templates and variables (https://docs.opensequence.dev/docs/concepts/sequence/templates) How message templates work: syntax, paths, fallbacks, text and html bodies, branded HTML emails with images, and the unsubscribe link. ```text Quick question, {{ contact.first_name | "there" }} Hi {{ contact.first_name | "there" }}, {{ sender.first_name }} here from {{ sender.attrs.company | "Acme" }}. I saw {{ attrs.company.name | "your company" }} is hiring. Worth a chat about {{ sequence.name }}? Unsubscribe: {{ unsubscribe_url }} ``` Subjects, bodies, task titles, bodies and links are rendered by one small engine. The syntax is `{{ path }}` and `{{ path | "fallback" }}`. Nothing else: no logic, no loops, no filters, no code. ## Paths [#paths] | Path | Value | |---|---| | `contact.first_name`, `contact.last_name`, `contact.email`, `contact.phone`, `contact.country`, `contact.timezone` | the contact's columns | | `attrs.` | the contact's attrs (`contact.attrs.` is accepted as an alias) | | `sender.name`, `sender.first_name`, `sender.email`, `sender.timezone` | the sender's columns | | `sender.attrs.` | the sender's attrs | | `sender.signature` | the sender's signature: the sanitized HTML in an html body, the text twin in a text body. The only path rendered without escaping ([Sender](/docs/concepts/sender)) | | `sequence.name` | the sequence's name | | `unsubscribe_url` | the opt-out link for this run: your own page when the project sets `unsubscribe_url`, else the page this server hosts | A path outside these roots is a publish error (`BAD_TEMPLATE`). ## The signature [#the-signature] Store each sender's signature once (`PUT /v1/senders/{id}` with `signature_html`, and `signature_text` if the derived text is not what you want) and end the body with `{{ sender.signature }}`. One template then serves every sender: ```json "body": "Hi {{ contact.first_name | \"there\" }},

Welcome aboard.

{{ sender.signature }}

{{ unsubscribe_url }}

", "format": "html" ``` The HTML is sanitized when saved with an email allowlist: table layouts, inline styles, links (`http`, `https`, `mailto`, `tel`) and images over `https` or as base64 stay; scripts, forms, frames, event handlers and CSS that loads anything are dropped ([Sender](/docs/concepts/sender#the-signature)). An empty signature renders as nothing, or as the fallback when you give one. ## Missing values and fallbacks [#missing-values-and-fallbacks] A missing or empty value renders as the fallback, or as an empty string when there is none, and never throws. Three paths **must** carry a fallback to publish, because they are empty for some contacts: `contact.first_name`, `contact.last_name`, `contact.email` (`BAD_TEMPLATE`: "can be empty for some contacts. Give it a fallback"). Everything else may be empty. A fallback is a double-quoted string; escape a quote inside it with a backslash. ## Text and HTML [#text-and-html] Email bodies are `text` (default) or `html` (`params.format`). In `html`, every rendered value is HTML-escaped, and the message carries a plain-text alternative made from the HTML: one line per block, links as `label (url)`, images as `[alt]`. In `text`, values are inserted as is. SMS bodies and task fields are plain text. A text body holds up to 100,000 characters and an html body up to 5,000,000, enough for a branded layout with a few embedded images. ## HTML emails and images [#html-emails-and-images] An `html` body is sent as you wrote it. Write it the way email builders such as Customer.io or Mailchimp do: tables for layout, inline `style` attributes, widths in pixels. The body is written by your project's admins, so the service does not sanitize it; only signatures, which any rep can edit, go through the allowlist. An image can be hosted or embedded. - **Hosted**: ``. The email stays small, and the client loads the image when the reader opens it. Hosted images are untouched at send time. They are the best choice for large campaigns and for anything above a few kilobytes. - **Embedded**: `` with a PNG, JPEG, GIF or WebP. Gmail, Outlook and Apple Mail do not show `data:` images, so at send time every embedded image becomes an inline attachment: a part of a `multipart/related` with its own `Content-ID`, and its `src` becomes `cid:...`. The same image used twice, in the body and in the signature for example, is attached once. `alt`, `width`, `height` and `style` are kept. Embedded images show without a click on "load images", and work without a CDN. | Limit | Value | When it is broken | |---|---|---| | One embedded image, decoded | 1 MB | the step fails with `IMAGE_TOO_LARGE` | | The whole message, both bodies and the encoded images | 10 MB | the step fails with `MESSAGE_TOO_LARGE` | | Embedded images in one html body, decoded | 400 KB | the warning `HEAVY_EMAIL` on save and publish; the email still sends | A failed step is never truncated or sent without its images: the run fails with the code in `error`, and the enrollment follows the step's `failed` transition. Keep emails light. Every embedded byte travels with every message, large emails are clipped by Gmail above about 100 KB of HTML and are scored as bulk mail, and an email that is mostly image reads as spam. Embed a logo or an icon; host photos and banners. Always give every image an `alt`: many readers block images, and the text alternative shows `[alt]` in its place. A branded email with a table layout and an embedded logo: ```html
Acme
Hi {{ contact.first_name | "there" }},
Your workspace is ready.
Open Acme
{{ sender.signature }}
Unsubscribe
``` In the definition the HTML is the `body` string, with `"format": "html"`. Embedded images count toward the definition limit of 10 MB. ## The unsubscribe link [#the-unsubscribe-link] `{{ unsubscribe_url }}` renders a signed link, valid for 90 days, that writes an email suppression and exits the enrollment with one click. By default it points at a page this server hosts, `SEQ_PUBLIC_URL/u/{token}`. When the project setting `unsubscribe_url` is set, for example `https://app.example.com/u/{token}`, it renders that URL with the token in place of `{token}`, so the link is on your own domain. Every email also carries `List-Unsubscribe` and `List-Unsubscribe-Post` headers with the same URL. An email body without it publishes with the warning `NO_UNSUBSCRIBE`. See [Host the unsubscribe page in your app](/docs/modules/email#host-the-unsubscribe-page-in-your-app). ## What is recorded [#what-is-recorded] Every run that rendered something stores the values it used in `result.rendered` (`{ "contact.first_name": "Dana", "attrs.company.name": null }`), so the journey shows what the contact received. Task titles and bodies are stored on the task itself. ## Preview [#preview] Render a definition against a sample contact before publishing: the `POST /v1/sequences:simulate` endpoint the architecture document describes is **not implemented yet**. Use `POST /v1/sequences:validate` for the template path and fallback checks, and a `dry_run` enrollment (`mode: "dry_run"` when you enroll) to see rendered outreach steps recorded as `skipped_dry_run`. # Validation codes and fixes (https://docs.opensequence.dev/docs/concepts/sequence/validation) What every validation code means and how to fix it. Warnings come back on save; errors block publish. Validation runs on `POST /v1/sequences:validate`, on every draft save (problems are returned, the save goes through) and on publish (errors block). Every problem is `{ path, code, message, severity }` with a JSON path into the definition and a sentence a person or an agent can act on: ```json { "path": "nodes.sms_follow.params.body", "code": "TOO_LONG", "message": "The SMS is 412 characters (3 segments).", "severity": "warning" } ``` | Code | Severity | When | Fix | |---|---|---|---| | `INVALID_DEFINITION` | error | the document does not match the schema: a wrong type, a missing required param, a bad duration, an id that is not `lower_snake_case`, over 200 nodes or 256 KB, a transition key the node type does not emit, a `next` on an `end` node | follow the `path`; the message is the schema's own | | `UNKNOWN_NODE_TYPE` | error | `type` is not registered | one of `start`, `outreach`, `wait`, `wait_for`, `condition`, `task`, `end` | | `UNKNOWN_CHANNEL`, `UNKNOWN_ACTION` | error | an `outreach` node without a channel, with an unknown one, or with an action the channel does not have | `channel: "email"` or `"sms"`, `action: "send"` | | `UNKNOWN_NODE` | error | `entry`, a `next` target or a `branches_by_outcome` target names a node that does not exist | fix the id | | `MISSING_TRANSITION` | error | a required transition is unwired (`then` on `start` and `wait`, `yes` and `no` on `condition`) | wire it | | `UNREACHABLE_NODE` | error | a node no path from `entry` reaches | wire it or delete it | | `CYCLE` | error | a loop with no timed step on it (a `wait`, a `task`, or a `wait_for` with a `timeout`) | put a wait on the loop, or break it | | `UNKNOWN_FIELD` | error | a condition names a field the registry does not know | pick one from `GET /v1/schema/fields` | | `BAD_OPERATOR` | error | the operator does not fit the field's type (`gte` on text, `contains` on a bool) | see the operators per type in [Conditions](/docs/concepts/sequence/conditions) | | `BAD_VALUE` | error | a missing value where the operator needs one, a non-number for a number field, a value outside an enum | fix the value | | `BAD_EVENT` | error | a `wait_for` lists an event with no transition | wire `next.` | | `BAD_TEMPLATE` | error | a `{{ path }}` outside the known roots, or `contact.first_name`, `contact.last_name`, `contact.email` without a fallback | use `contact.*`, `attrs.*`, `sender.*`, `sequence.name`, `unsubscribe_url`; add `\| "fallback"` | | `NO_UNSUBSCRIBE` | warning | an email body without `{{ unsubscribe_url }}` | add it; recipients cannot opt out with one click otherwise | | `TOO_LONG` | warning | an SMS body over 320 characters (three or more segments) | shorten it; the hard limit is 1000 | Problems that stop a publish are also what the engine refuses at enrollment time, so a published version never fails for a reason validation could have caught. The generated list of every code, including the HTTP ones, is in the [reference](/reference/error-codes). The architecture document also lists `NO_END` and `BAD_EXIT`. The code has neither: a path may end on an unwired transition (the enrollment completes), and `exit_on` is checked by the schema as `INVALID_DEFINITION`. # Sequence versions and publishing (https://docs.opensequence.dev/docs/concepts/sequence/versions) How drafts, the optimistic lock, publishing, new versions and archiving work, and what enrolled contacts do when a new version ships. ```bash title="curl" curl -X POST $SEQ/v1/sequences -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{"name":"UK intro","description":"First touch for UK facilities managers"}' # {"sequence":{"id":"seq_…","status":"active","defaultVersionId":null},"version":{"id":"ver_…","tag":"v1","status":"draft","lockVersion":0}} curl -X PUT $SEQ/v1/sequences/seq_…/versions/ver_…/draft -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{"definition":{…},"lock_version":0}' curl -X POST $SEQ/v1/sequences/seq_…/versions/ver_…/publish -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" curl -X POST $SEQ/v1/sequences/seq_…/versions -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" -d '{"from_version":"ver_…","tag":"v2"}' curl -X POST $SEQ/v1/sequences/seq_…/versions/ver_…/archive -H "Authorization: Bearer $KEY" ``` ```ts title="TypeScript" const { sequence, version } = await oseq.sequences.create({ name: 'UK intro' }); const saved = await oseq.sequences.versions.saveDraft(sequence.id, version.id, { definition, lock_version: version.lockVersion }); await oseq.sequences.versions.publish(sequence.id, version.id); const v2 = await oseq.sequences.versions.create(sequence.id, { from_version: version.id, tag: 'v2' }); await oseq.sequences.versions.archive(sequence.id, version.id); ``` ## Lifecycle [#lifecycle] ```text POST /v1/sequences ──► v1 draft ──PUT …/draft (edit)──► ──POST …/publish──► published (immutable, the default) ──POST …/archive──► archived │ POST /v1/sequences/{id}/versions {from_version, tag} ──► v2 draft … ``` | Status | Meaning | |---|---| | `draft` | editable with `PUT .../draft`; deletable with `DELETE .../versions/{vid}`; cannot enroll | | `published` | frozen; the sequence's default version for new enrollments; cannot be edited (`409 VERSION_NOT_EDITABLE`) | | `archived` | no new enrollments into it; people already in it finish on it | Creating a sequence makes `v1` as a draft; pass `definition` in the create body to start from your own document instead of the empty `start → end`. `external_id` lets you address the sequence by your own id, and `labels` is free JSON for your UI. ## Saving a draft [#saving-a-draft] `PUT /v1/sequences/{id}/versions/{vid}/draft` takes `{ definition, lock_version }`. The version's `lockVersion` increments on every save; sending a stale one is `409 STALE_LOCK` ("someone else saved this draft after you loaded it"), so two editors cannot overwrite each other. Saving accepts a definition with **errors**: they come back as `problems` so a canvas can show them while the user works. Only publishing refuses them. ## Publishing [#publishing] `POST .../publish` validates (errors block with `422 INVALID_DEFINITION` and `details.problems`; warnings pass and are returned), freezes the definition, records `published_by` (the body's `published_by`, else the key id) and makes the version the sequence's default. Publishing a published version is a no-op that returns it. ## A new version [#a-new-version] `POST /v1/sequences/{id}/versions` with `{ from_version?, tag }` copies any version (default: the sequence's default, else the latest) into a new draft. Tags are unique per sequence (`409 TAG_TAKEN`), up to 24 letters, digits, dots and dashes (`BAD_TAG`). ## What enrolled contacts do when a new version ships [#what-enrolled-contacts-do-when-a-new-version-ships] Nothing changes for them: an enrollment is pinned to its version id, the definition is immutable, and the journey shows the definition the contact actually ran. New enrollments (and `POST .../enrollments` without an explicit `version`) use the new default. To move people, exit them (`POST /v1/enrollments:exit { sequence, status: "active" }`) and enroll them again; they start the new version from its entry node, and the re-enrollment rule (`settings.reenroll`) applies, so `never` will skip them with `already_enrolled_before`. ## Pausing and archiving a sequence [#pausing-and-archiving-a-sequence] `PATCH /v1/sequences/{id}` with `status: "paused"` stops planning for every version (enrollments keep their state and resume when the sequence is active again); `status: "archived"` is refused with `409 HAS_ACTIVE_ENROLLMENTS` while contacts are in it, unless `exit_active: true`, which exits them with reason `manual` and the label `sequence archived`. The same `PATCH` renames (`name`), describes (`description`) and relabels (`labels`). ## Reading [#reading] `GET /v1/sequences` lists sequences, each with its version summaries and its enrollment counts by status. The sequence itself is a stored record (camelCase); `versions` and `counts` are built for the list (snake_case). One row: ```json { "id": "seq_01J9…", "projectId": "prj_01J9…", "externalId": null, "name": "UK intro", "description": null, "createdBy": null, "labels": {}, "status": "active", "defaultVersionId": "ver_01J9…", "createdAt": "…", "updatedAt": "…", "versions": [ { "id": "ver_01J9…", "tag": "v1", "status": "published", "published_at": "2026-10-13T09:00:00.000Z", "created_at": "…" }, { "id": "ver_01JA…", "tag": "v2", "status": "draft", "published_at": null, "created_at": "…" } ], "counts": { "active": 142, "paused": 3, "waiting_limit": 0, "completed": 57, "exited": 88, "failed": 0 } } ``` `counts` is every enrollment of the sequence, all versions together, by its current status; every key is present, `0` when empty. For a list screen: running is `active + paused + waiting_limit`, finished is `completed + exited`. Replies and meetings are not in this list: read them from [`GET /v1/analytics/sequences`](/docs/analytics/endpoints#cross-sequence) (one call for every sequence) or from a sequence's `analytics/summary`. `GET /v1/sequences/{id}` returns the same record with `versions` and without `counts`. `GET /v1/sequences/{id}/versions` returns the full version records. `GET /v1/sequences/{id}/versions/{vid}` returns the version with its current validation problems; the definition is inside `version`: ```json { "version": { "id": "ver_01J9…", "sequenceId": "seq_01J9…", "tag": "v1", "status": "draft", "lockVersion": 4, "schemaVersion": 1, "definition": { "schema_version": 1, "entry": "start", "nodes": { … }, "...": "..." }, "basedOnVersionId": null, "createdBy": null, "publishedBy": null, "publishedAt": null, "archivedAt": null, "createdAt": "…", "updatedAt": "…" }, "problems": [ { "path": "nodes.email_intro.params.subject", "code": "TEMPLATE_UNKNOWN_FIELD", "message": "…", "severity": "warning" } ] } ``` `PUT .../draft`, `POST .../publish` and `POST /v1/sequences` return this same `{ version, problems }` pair (the create adds `sequence`). # Integrate OpenSequence into your product (https://docs.opensequence.dev/docs/get-started/integrate) The integration checklist: run the server, connect each module, then upsert contacts, enroll them and handle webhooks, one API call per step. This is the checklist for adding OpenSequence to an existing app. Each line is one call, and each module links to its own page. OpenSequence ships no UI. Your app keeps its screens and calls the API from your server. ## 1. Set up once [#1-set-up-once] - [ ] **Run the server** and create a project: [Quickstart](/docs/get-started/quickstart#run-it-on-your-own-postgres). - [ ] **Install the SDK**: `npm install @opensequence/sdk`. See the [SDK reference](/sdks/typescript). - [ ] **Register your webhook endpoint** and store its secret: [Webhooks to your app](/docs/webhooks). - [ ] **Connect Allo** if you send texts or call tasks: [Allo](/docs/modules/sms/allo). - [ ] **Connect Attio** if conditions read your CRM: [Attio](/docs/modules/crm/attio). - [ ] **Connect MCP** if an AI agent should build sequences: the [MCP server README](https://github.com/lguerberg/open-sequence/tree/main/packages/mcp). ## 2. For each rep [#2-for-each-rep] - [ ] **Create the sender** with your user id, signature and attributes such as a calendar URL: [Sender](/docs/concepts/sender). ```ts await oseq.senders.upsert(user.id, { name, email, timezone, signature_html, attrs: { calendar_url } }); // PUT /v1/senders/{id} ``` - [ ] **Connect their mailbox**: [Email](/docs/modules/email) ([Gmail](/docs/modules/email/gmail), [Outlook](/docs/modules/email/outlook), [other SMTP](/docs/modules/email/other-smtp)). ```ts await oseq.senders.setSmtp(user.id, { provider: 'smtp', smtp, imap }); // PUT /v1/senders/{id}/channels/email ``` - [ ] **Connect their Allo number** (SMS and calls only). ```ts await oseq.senders.setSms(user.id, { allo_user_id, number }); // PUT /v1/senders/{id}/channels/sms ``` ## 3. Every time your app saves a person [#3-every-time-your-app-saves-a-person] - [ ] **Upsert the contact** by your own id: [Contact](/docs/concepts/contact). ```ts await oseq.contacts.upsert(person.id, { first_name, email, phone, country, timezone, attrs: { plan } }); // PUT /v1/contacts/{id} ``` `country` is ISO-2. When you have none, take it from the phone number with `libphonenumber-js`. Texts and agent calls need recorded consent: `oseq.contacts.setOutreachConsent()` with an `admin` key. ## 4. Build and publish a sequence [#4-build-and-publish-a-sequence] - [ ] **Create it, then publish it**: [Sequence](/docs/concepts/sequence) and [The definition](/docs/concepts/sequence/definition). ```ts const { sequence, version } = await oseq.sequences.create({ name, definition }); // POST /v1/sequences await oseq.sequences.versions.publish(sequence.id, version.id); // POST /v1/sequences/{id}/versions/{vid}/publish ``` ## 5. Enroll [#5-enroll] - [ ] **Enroll contacts as a sender** and store each `enr_…` id. ```ts const { enrollments } = await oseq.sequences.enroll(sequence.id, { contacts: [person.id], sender: user.id }); // POST /v1/sequences/{id}/enrollments ``` A contact is in one active sequence at a time. One conflict fails the whole batch with `409 ALREADY_IN_SEQUENCE`, and `error.details.conflicts` names each contact, its sequence and its enrollment. `POST /v1/sequences/{id}/enrollments:preview` runs the same checks without writing. ## 6. Handle the events [#6-handle-the-events] - [ ] **Write each webhook into your app**, deduped by `event.id`. | Event | Write | |---|---| | `run.done` | An outbound activity on the person. | | `signal.received` with `reply` or `meeting_booked` | An inbound activity and a notification to the rep. | | `signal.received` with `bounce` or `opt_out` | A flag on the address or number. | | `enrollment.exited`, `enrollment.completed` | The outcome. Clear the "in sequence" badge. | | `task.created`, `task.expired` | Add or remove an item in the rep's task list. | | `sender.channel_status` | A "reconnect your mailbox" banner. | ## Report what the service cannot see [#report-what-the-service-cannot-see] - [ ] **Report meetings, opt-outs and do-not-contact flags** that happen outside OpenSequence. ```ts await oseq.contacts.reportEvent(person.id, { id: booking.id, type: 'meeting_booked' }); // POST /v1/contacts/{id}/events ``` `type` is `meeting_booked`, `opt_out`, `suppressed` or `reply`. The same `id` twice is recorded once. ## 7. Exit when the work is done [#7-exit-when-the-work-is-done] ```ts await oseq.enrollments.exit(enrollmentId, { label: 'deal closed' }); // POST /v1/enrollments/{id}/exit, admin key ``` ## Screens to build [#screens-to-build] - **Sequences**: `GET /v1/sequences` and `GET /v1/analytics/sequences`. - **Where a contact is**: `GET /v1/enrollments/{id}`. See [Show where a contact is in a sequence](/docs/concepts/enrollment/where-a-contact-is). - **Senders and mailboxes**: `GET /v1/senders/{id}` for channels, status and readiness. - **Task list**: `GET /v1/tasks?sender=…&status=open`, then `POST /v1/tasks/{id}/complete`. Each task has a `kind` (`call`, `linkedin_connect`, …); a `linkedin_connect` task completes itself when you call `POST /v1/tasks/{id}/open` as the sender opens its profile ([LinkedIn](/docs/modules/linkedin)). # Quickstart: run OpenSequence and enroll your first contact (https://docs.opensequence.dev/docs/get-started/quickstart) How to run the OpenSequence server, create a project, connect a mailbox and enroll a first contact with the TypeScript SDK, then run it on your own Postgres. You run the server, create a project, connect a mailbox and enroll one contact who replies and leaves the sequence. It runs locally on mock providers, so you need no mail server or Allo account. You need Docker, Node 20 or newer, `curl` and `jq`. ```bash git clone https://github.com/lguerberg/open-sequence && cd open-sequence docker compose up -d curl -s http://localhost:8080/readyz # {"ok":true} ``` Compose starts Postgres and one OpenSequence container (`ghcr.io/lguerberg/open-sequence:main`) on port 8080. If `/readyz` says `{"ok":false,...}`, wait two seconds: it turns ready once migrations ran. ```bash npm init -y && npm install @opensequence/sdk tsx ``` One email, then a wait of up to three days for a reply. `exit_on: ["reply"]` makes a reply end the enrollment. ```json title="definition.json" { "schema_version": 1, "entry": "start", "exit_on": ["reply"], "nodes": { "start": { "type": "start", "next": { "then": "intro" } }, "intro": { "type": "outreach", "channel": "email", "action": "send", "params": { "subject": "Quick question, {{ contact.first_name | \"there\" }}", "body": "Hi {{ contact.first_name | \"there\" }}, this is {{ sender.name }}.\n\nUnsubscribe: {{ unsubscribe_url }}" }, "next": { "sent": "wait_reply", "skipped": "end", "failed": "end" } }, "wait_reply": { "type": "wait_for", "params": { "events": ["reply"], "timeout": "3d" }, "next": { "reply": "end", "timeout": "end" } }, "end": { "type": "end" } } } ``` ```ts title="quickstart.mts" import { readFileSync } from 'node:fs'; import { OpenSequence, OpenSequenceAdmin } from '@opensequence/sdk'; const baseUrl = 'http://localhost:8080'; const definition = JSON.parse(readFileSync('definition.json', 'utf8')); // A project is one tenant. The operator token creates it and returns its first admin key, once. const operator = new OpenSequenceAdmin({ baseUrl, adminToken: 'dev-admin-token' }); const { api_key } = await operator.projects.create({ slug: 'acme', name: 'Acme' }); const admin = new OpenSequence({ baseUrl, apiKey: api_key }); // Your app's key: an enroll key upserts contacts and enrolls, but cannot change senders or sequences. const appKey = await admin.project.apiKeys.create({ name: 'crm-backend', scopes: ['enroll'] }); const app = new OpenSequence({ baseUrl, apiKey: appKey.api_key }); // A sender (the rep, by your user id) and their mailbox. Mock providers accept any login. await admin.senders.upsert('u_42', { name: 'Max Rivera', email: 'max@acme.com', timezone: 'America/New_York' }); const box = (host: string, port: number) => ({ host, port, secure: true, user: 'max@acme.com', password: 'app-password' }); await admin.senders.setSmtp('u_42', { provider: 'smtp', smtp: box('smtp.gmail.com', 465), imap: box('imap.gmail.com', 993) }); // A contact (the recipient, by your person id). attrs is free JSON for templates and conditions. await app.contacts.upsert('p_7', { first_name: 'Dana', email: 'dana@example.com', timezone: 'Europe/London', attrs: { plan: 'trial' } }); // Create, save the draft, publish. Errors block publishing; warnings come back in problems. const { sequence, version } = await admin.sequences.create({ name: 'Trial intro' }); await admin.sequences.versions.saveDraft(sequence.id, version.id, { definition, lock_version: 0 }); await admin.sequences.versions.publish(sequence.id, version.id); // Enroll. The planner runs every five seconds, then the email goes out through the mock mailbox. const { enrollments } = await app.sequences.enroll(sequence.id, { contacts: ['p_7'], sender: 'u_42' }); await new Promise((r) => setTimeout(r, 10_000)); const journey = await app.enrollments.get(enrollments[0].id); console.log(journey.enrollment.id, journey.enrollment.currentNodeId, journey.messages[0]?.subject); console.log(`APP_KEY=${appKey.api_key} ENR_ID=${journey.enrollment.id} THREAD=${journey.messages[0]?.threadRef}`); ``` ```bash npx tsx quickstart.mts # enr_... wait_reply Quick question, Dana # APP_KEY=sk_live_... ENR_ID=enr_... THREAD=<...> ``` With mock providers on, `POST /hooks/mock/{project slug}` injects an inbound event as if the mailbox had reported it. Paste the three values the script printed: ```bash export APP_KEY=sk_live_... ENR_ID=enr_... THREAD='<...>' curl -s -X POST http://localhost:8080/hooks/mock/acme -H "Content-Type: application/json" \ -d "{\"kind\":\"reply\",\"channel\":\"email\",\"externalId\":\"evt_1\",\"from\":\"dana@example.com\",\"to\":\"max@acme.com\",\"threadRef\":\"$THREAD\"}" # {"ok":true,"stored":1,"ignored":0} sleep 6 curl -s http://localhost:8080/v1/enrollments/$ENR_ID -H "Authorization: Bearer $APP_KEY" \ | jq '{status: .data.enrollment.status, reason: .data.enrollment.exitReason}' # { "status": "exited", "reason": "replied" } ``` The reply became a signal, was credited to the `intro` email, and ended the enrollment. `GET /v1/sequences/{id}/analytics/summary` now counts one enrollment and one email reply. Run it a second time and enrolling `p_7` returns `409 ALREADY_IN_SEQUENCE`: a contact is in one active sequence at a time. Start over with `docker compose down -v` (`-v` also deletes the database). ## Run it on your own Postgres [#run-it-on-your-own-postgres] The server is one Docker image, `ghcr.io/lguerberg/open-sequence`, and one Postgres 14 or newer. The queue lives in Postgres too, so you need no Redis. ```bash docker run -d -p 8080:8080 \ -e SEQ_DB_DSN=postgres://user:pass@db.example.com:5432/postgres \ -e SEQ_ENCRYPTION_KEYS="$(docker run --rm ghcr.io/lguerberg/open-sequence:main node dist/cli.js secrets new-key)" \ -e SEQ_ADMIN_TOKEN="$(openssl rand -base64 32)" \ -e SEQ_PUBLIC_URL=https://sequences.example.com \ -e SEQ_ROLES=all \ -e SEQ_RUN_MIGRATIONS=1 \ ghcr.io/lguerberg/open-sequence:main ``` | Variable | Meaning | |---|---| | `SEQ_DB_DSN` | The Postgres connection string. A transaction pooler is fine. | | `SEQ_ENCRYPTION_KEYS` | Encrypts every stored password and key. Back it up with the database. | | `SEQ_ADMIN_TOKEN` | The operator token that creates projects. Required for the `api` and `all` roles. | | `SEQ_PUBLIC_URL` | The HTTPS address the outside world reaches: unsubscribe links and the Allo webhook use it. | | `SEQ_ROLES` | `all` for one process, or `api` and `worker` apart. | | `SEQ_RUN_MIGRATIONS` | `1` applies migrations at boot. | OpenSequence creates and owns two schemas, `seq` and `seq_auth`, so it can share a database such as Supabase's. `GET /healthz` answers while the process runs. `GET /readyz` answers `{"ok":true}` once the database answers and, on a worker, the scheduler has run in the last two minutes. Then create a project with the operator token: ```bash title="curl" curl -X POST https://sequences.example.com/v1/admin/projects -H "Authorization: Bearer $SEQ_ADMIN_TOKEN" \ -H "Content-Type: application/json" -d '{"slug":"acme","name":"Acme"}' ``` ```ts title="TypeScript" const { project, api_key } = await new OpenSequenceAdmin({ baseUrl, adminToken }).projects.create({ slug: 'acme', name: 'Acme' }); ``` The response holds the project's first `admin` key, shown once. Next, connect real accounts: [Modules](/docs/modules). Production setup: [Install](/docs/self-hosting/install). ## Where next [#where-next] The checklist, one call per step. Email, Allo, Attio, webhooks, MCP and the SDK. Projects, senders, contacts, sequences and runs. # AI agent calls with Allo (https://docs.opensequence.dev/docs/modules/calls/allo) How to add an AI phone call to a sequence with an Allo Outbound agent: the permissions, picking the agent and its line, the brief, skills, consent, and branching on the outcome of the call. An agent call step asks an Allo Outbound agent to phone the contact. The step waits for the result, then the sequence follows the outcome of the call. This places real phone calls to real people. Allo has no dry-run mode. Test with your own number as the contact's phone, or with [mock providers](#try-it-without-calling-anyone). ## What it gives you [#what-it-gives-you] - A phone call to the contact's `phone`, placed by an AI agent with the objective and brief you write. - The agent can text the contact, book a meeting or transfer the call to a person. - Allo places the call inside the agent's calling hours in the contact's time zone (08:00 to 21:00 unless the agent is set otherwise) and tries up to 3 times when nobody answers. - Branches on how the call ended: `reached`, `transferred`, `not_interested`, `wrong_number`, `do_not_call`, `not_reached`. Call tasks for a human rep are a different step and work as before: see [Allo for texts and call tasks](/docs/modules/sms/allo#call-tasks). ## What you need [#what-you-need] - An [Allo](https://withallo.com) workspace with the Outbound agent turned on. Allo refuses HIPAA workspaces. - The Allo API key saved in OpenSequence ([Save the Allo key](/docs/modules/sms/allo#steps)), with these permissions on top of the ones texts need: `OUTBOUND_CALLS_WRITE`, `AGENTS_READ` and `TASKS_READ`. - Contacts with a `phone` in E.164 and recorded [outreach consent](#consent). The step names the agent. The call goes out from the enrolling sender's Allo number, the one set on their SMS channel, so each contact is called from their own rep's line. Every sender's number must be one of the agent's lines. ## Steps [#steps] ```bash title="curl" curl $SEQ/v1/project/providers/allo/agents -H "Authorization: Bearer $KEY" # [{ "id": "agt-…", "name": "Outbound agent", "numbers": ["+14155550100", "+14155550101"] }] ``` ```ts title="TypeScript" const agents = await oseq.project.alloAgents(); const agent = agents[0]!; ``` `numbers` are the only lines that agent can call from. Check that each sender's Allo number is in the list: a call from a sender whose number is not fails with `LINE_NOT_AGENT_CALLING_LINE`. Senders get their number with `PUT /v1/senders/{id}/channels/sms` ([Give each sender a number](/docs/modules/sms/allo#steps)). ```json "confirm_call": { "type": "outreach", "channel": "call", "action": "agent_call", "params": { "agent_id": "agt-…", "title": "Confirm Friday delivery with {{ contact.first_name | \"the customer\" }}", "description": "{{ contact.first_name | \"The customer\" }} ordered 3 pallets. Confirm the Friday 10am delivery slot. If they want to change it, transfer the call.", "skills": { "transfer": { "type": "member", "user_id": "usr-…" } }, "give_up_after": "3d" }, "next": { "reached": "end_confirmed", "transferred": "end_confirmed", "not_reached": "sms_follow", "completed": "end_done" } } ``` | Param | Required | Notes | |---|---|---| | `agent_id` | yes | The Allo Outbound agent, from `GET /v1/project/providers/allo/agents`. | | `allo_number` | no | A fixed line to call from, E.164, for every contact. Leave it out to call from the enrolling sender's Allo number. | | `title` | yes | The objective of the call. A template, up to 200 characters. | | `description` | no | The brief the agent reads as written: context, what to say, when to use each skill. A template, up to 4,000 characters. | | `skills` | no | What the agent may do during the call. See [Skills](#skills). | | `give_up_after` | no | How long the step waits for a result. Default `3d`. | | `exit_on_connect` | no | `false` keeps the contact in the sequence after a call that reaches them. Default `true`. See [How the call ends](#how-the-call-ends). | ```bash title="curl" curl -X PUT $SEQ/v1/contacts/p_7/outreach-consent -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" \ -d '{"consent":true,"source":"signup form"}' ``` ```ts title="TypeScript" await oseq.contacts.setOutreachConsent('p_7', { consent: true, source: 'signup form' }); ``` ## Skills [#skills] A skill that is present is on. Say in `description` when the agent should use each one: the agent follows the description, and Allo does not parse it. The validator warns (`NO_BRIEF`) when a step turns on a skill and has no description. | Skill | Shape | Notes | |---|---|---| | `sms` | `{}` or `{ "text": "…" }` | `{}` lets the agent write the text. `text` is a template, sent as written, up to 1,000 characters. | | `book` | `{ "calendar_id", "event_type_id" }` | The calendar and event type ids from Allo. | | `transfer` | one target | `{ "type": "member", "user_id": "usr-…" }` or `{ "type": "line", "number": "+1…" }` for a warm transfer; `{ "type": "external", "number": "+1…" }` for a cold transfer to an outside number, which needs a verified Allo account. | ## How the call ends [#how-the-call-ends] The step creates the call at Allo and waits. OpenSequence reads the result once a minute. The sequence then follows the transition of the outcome. An outcome with no transition follows `completed`. When `completed` has no transition either, the enrollment ends as `completed`. | Transition | When | |---|---| | `reached` | The agent spoke to the contact and handled the objective. | | `transferred` | The contact was handed to a person. | | `not_interested` | The contact declined. | | `wrong_number` | Not the right person. | | `do_not_call` | The contact asked not to be called. Calls to this contact are suppressed from now on. | | `not_reached` | Voicemail, no answer or busy on all 3 attempts, the call was cancelled in Allo, or `give_up_after` passed with no result. | | `skipped` | A check failed and no call was made. See [Rules every call follows](#rules-every-call-follows). | | `failed` | The step is set up wrong. See [Common errors](#common-errors). | `reached` and `transferred` count as a connected call. They wake a `wait_for` on `call_connected` or `reply`, and they exit the enrollment as `replied` when the sequence lists `reply` in `exit_on`. Set `exit_on_connect: false` on the step to keep the contact in the sequence after the agent spoke to them. The sequence then follows `reached` or `transferred` and goes on with the next steps. A reply by email or text still exits. The call is still credited as a reply, so `history.replied_since_enrollment` is true afterwards. To stop for a contact who declined, wire `not_interested` to an `end` step. When the agent books a meeting on the call, Allo tags the call `meeting_booked`. OpenSequence reads that tag from the `call.completed` webhook and records a `meeting_booked` signal for the contact whose phone was called. A sequence that lists `meeting_booked` in `exit_on` exits, also when the step has `exit_on_connect: false`. A contact who asks to be called back keeps the call open at Allo. The step keeps waiting until Allo closes the call or `give_up_after` passes. A call step is a touch. It counts when the call is handed to the agent. ## Consent [#consent] Agent calls use the same consent as texts. It was called SMS consent before 0.3.0 and is now outreach consent, because it gates both. Nothing changes for contacts that already had it. | Old name | New name | |---|---| | `PUT /v1/contacts/{id}/sms-consent` | `PUT /v1/contacts/{id}/outreach-consent` | | `oseq.contacts.setSmsConsent()` | `oseq.contacts.setOutreachConsent()` | | `smsConsent` on a contact | `outreachConsent` | | `contact.sms_consent` in conditions | `contact.outreach_consent` | The old names still work and are deprecated. ## Rules every call follows [#rules-every-call-follows] | Check | Skip reason | |---|---| | The contact has outreach consent | `no_consent` | | The contact has a phone number | `no_phone` | | The sender has an Allo number, or the step fixes `allo_number` | `no_allo_number` | | No call suppression | `suppressed` | The sequence's send window applies to when the step runs. Calling hours are Allo's: a call created outside them waits at Allo. ## Try it without calling anyone [#try-it-without-calling-anyone] With `SEQ_DEV_MOCK_PROVIDERS=1` no call is placed. `GET /v1/project/providers/allo/agents` returns one mock agent (`agt-mock`), whose line is the mock Allo number `+15550000001`. Give the sender that number. End a mock call with: ```bash curl -X POST $SEQ/hooks/mock/{project slug}/agent-calls -H "Content-Type: application/json" \ -d '{"to":"+14155551234","outcome":"reached","status":"closed"}' ``` The step closes within a minute. ## Check it works [#check-it-works] 1. `GET /v1/project/providers/allo/agents` lists your agent and its lines. 2. Enroll a consenting test contact with your own phone number in a one-step sequence. 3. `GET /v1/enrollments/{id}` shows the call run as `waiting`, with Allo's task id in `providerRef`. 4. Answer the call. Within a minute of hanging up the run is `done` and its `branch` is the outcome. ## Common errors [#common-errors] | Error | Fix | |---|---| | The run fails with `LINE_NOT_AGENT_CALLING_LINE` | The sender's Allo number is not one of the agent's lines. Add the number to the agent in Allo, or give the sender a number the agent has. | | The run is skipped with `no_allo_number` | The sender has no Allo number. Set one with `PUT /v1/senders/{id}/channels/sms`. | | The run fails with `OUTBOUND_AGENT_NOT_FOUND` | No Outbound agent has that `agent_id` in the workspace. | | The run fails with `OUTBOUND_CALLS_NOT_AVAILABLE` | The Outbound agent is not turned on for the workspace, or it is a HIPAA workspace. | | The run fails with a `403` | The Allo key lacks `OUTBOUND_CALLS_WRITE`, `AGENTS_READ` or `TASKS_READ`. | | The run fails with `SKILL_INVALID` | A skill field is wrong, for example an event type that is not on the calendar. The error names the field. | | The run is skipped with `provider_rejected` | Allo refused the contact's number. It is not a valid E.164 number. | When a `failed` transition is not wired, a failed step pauses the enrollment with `step_failed`. Allo cannot cancel a call through its API. When an enrollment exits while a call is waiting, the step closes here, but Allo may still place the call. Cancel it in Allo. A call whose creation result is unknown is not created twice: the retry first looks for the call at Allo. After three unknown results the run becomes `needs_review`. # Connect Attio for live CRM conditions (https://docs.opensequence.dev/docs/modules/crm/attio) How to connect Attio to OpenSequence with one read-only token, then branch sequences on person, company and deal data read live when a condition runs. The Attio module lets a condition read the contact's person, company and open deal from Attio. Connect one token per project, then use `crm.*` fields in conditions. ## What it gives you [#what-it-gives-you] - `crm.*` condition fields read live when the step runs, with no sync and nothing stale. - A schema endpoint that lists your Attio attributes, for your condition editor. - Read-only access: OpenSequence never writes to Attio. ## What you need [#what-you-need] - An Attio access token with read access to records (`record_permission:read`) and to the object configuration (`object_configuration:read`). Create it in Attio's workspace settings, under Developers. - An OpenSequence `admin` key. ## Steps [#steps] ```bash title="curl" curl -X PUT $SEQ/v1/project/providers/attio -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" \ -d '{"api_key":"…"}' ``` ```ts title="TypeScript" await oseq.project.setProvider('attio', { api_key: process.env.ATTIO_TOKEN! }); ``` The token is checked with Attio, then stored encrypted and never returned. Save it again to rotate it. ```bash title="curl" curl $SEQ/v1/project/providers/attio/schema -H "Authorization: Bearer $KEY" # {"objects":[{"name":"person","attributes":[{"slug":"job_title","label":"Job title","type":"text"},…]}, # {"name":"deal","attributes":[{"slug":"stage","label":"Stage","type":"status","values":["Lead","In Progress","Won","Lost"]},…]}]} ``` ```ts title="TypeScript" const schema = await oseq.project.attioSchema(); ``` It lists the `person`, `company` and `deal` attributes that are not archived. It is cached for an hour. ```json "check_deal": { "type": "condition", "params": { "mode": "all", "rules": [ { "field": "crm.deal.exists", "op": "is_true" }, { "field": "crm.deal.stage", "op": "is", "value": "Lead" } ] }, "next": { "yes": "call_1", "no": "email_2" } } ``` ## The fields [#the-fields] | Field | Type | |---|---| | `crm.person.exists`, `crm.company.exists`, `crm.deal.exists` | bool: `is_true`, `is_false` | | `crm.deal.count_open` | number: `eq`, `ne`, `gt`, `gte`, `lt`, `lte` | | `crm.deal.stage` | text: the selected deal's stage | | `crm.person.`, `crm.company.`, `crm.deal.` | text: any attribute by its Attio slug | The person is found by the contact's email, the company by the email's domain (or the person's company), and deals by their link to either. A deal is open unless its stage starts with closed, won, lost or churn, or Attio marks it as won. When several are open, `settings.crm.deal_selection` picks one: `newest_open` (default), `highest_value` or `any_open` (the oldest). Every value is compared as text, so use `is`, `is_not`, `contains`, `is_empty` and `is_not_empty` on attributes. A multi-value attribute gives its first value. ## Check it works [#check-it-works] 1. `GET /v1/project` lists the Attio credential with `status: "active"`. 2. `GET /v1/project/providers/attio/schema` returns your attributes. 3. Enroll a test contact whose email matches an Attio person. Read the condition's `result.facts` in [the journey](/docs/concepts/enrollment/where-a-contact-is): each fact shows the value read. ## Common errors [#common-errors] | Error | Fix | |---|---| | `422 INVALID_CREDENTIAL` | The token is wrong, revoked or inactive. Create a new one. | | Every `crm.*.exists` is false | The contact has no email, or no Attio person has that email. | | A fact shows an `error` | Attio failed or rate-limited the lookup. The fact is empty, the rule fails, and an `all` condition takes `no`. Design `no` as the safe branch. | | The schema call fails with a permission error | The token lacks `object_configuration:read`. | With mock providers on, every lookup finds nothing and the schema is a fixed sample. # Connect Gmail and Google Workspace with an app password (https://docs.opensequence.dev/docs/modules/email/gmail) How to connect a Gmail or Google Workspace mailbox to OpenSequence: turn on 2-Step Verification, create an app password, then save smtp.gmail.com and imap.gmail.com. This page connects a Google mailbox as a sender's email channel. It takes about two minutes per rep. ## What it gives you [#what-it-gives-you] The rep's emails leave from their own Gmail or Workspace address, and replies come back over IMAP. See [Email](/docs/modules/email) for limits and send windows. ## What you need [#what-you-need] - 2-Step Verification on the Google account. - An app password: a 16-character password Google generates for one app. - An OpenSequence `admin` key and the [sender](/docs/concepts/sender) id. ## Steps [#steps] Open [myaccount.google.com/security](https://myaccount.google.com/security) and turn on 2-Step Verification. App passwords need it. Open [myaccount.google.com/apppasswords](https://myaccount.google.com/apppasswords), name it "OpenSequence" and copy the 16 characters. Use it as both the SMTP and the IMAP password. | | Host | Port | `secure` | |---|---|---|---| | SMTP | `smtp.gmail.com` | 465 | `true` | | IMAP | `imap.gmail.com` | 993 | `true` | The user is the full address in both. ```bash title="curl" curl -X PUT $SEQ/v1/senders/u_42/channels/email -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" -d '{ "provider": "smtp", "smtp": { "host": "smtp.gmail.com", "port": 465, "secure": true, "user": "max@acme.com", "password": "abcdefghijklmnop" }, "imap": { "host": "imap.gmail.com", "port": 993, "secure": true, "user": "max@acme.com", "password": "abcdefghijklmnop" } }' ``` ```ts title="TypeScript" const login = { user: 'max@acme.com', password: process.env.MAX_GOOGLE_APP_PASSWORD! }; await oseq.senders.setSmtp('u_42', { provider: 'smtp', smtp: { host: 'smtp.gmail.com', port: 465, secure: true, ...login }, imap: { host: 'imap.gmail.com', port: 993, secure: true, ...login }, }); ``` ## Check it works [#check-it-works] `GET /v1/senders/u_42/readiness` returns `"email": { "ok": true }`. Send yourself a test sequence and reply: the enrollment exits with `replied` within about a minute. ## Daily caps [#daily-caps] Google limits one mailbox to about 2,000 emails a day on Google Workspace and about 500 on a free Gmail account. Keep `daily_limit` far below that. The default is 30. ## Common errors [#common-errors] | Error | Fix | |---|---| | The app passwords page says the setting is not available | 2-Step Verification is off, or a Workspace admin blocked app passwords. Ask the admin to allow them for this user. | | `422 SMTP_AUTH_FAILED` or `IMAP_AUTH_FAILED` | You used the normal Google password, or the app password was revoked. Create a new app password. | | `422 IMAP_AUTH_FAILED` only | IMAP is turned off for the Workspace domain. An admin can turn it on in the Google Admin console. | | Steps skip with `sender_channel_credentials_needed` | The rep changed their Google password, which revokes app passwords. Create a new one and save the mailbox again. | # Email: send over SMTP and read replies over IMAP (https://docs.opensequence.dev/docs/modules/email) How to connect a sender's mailbox to OpenSequence: SMTP to send, IMAP to read replies and bounces, daily limits, send windows and deliverability basics. The Email module sends each email from the rep's own mailbox and reads their replies. Connect one mailbox per sender, then set its limits. ## What it gives you [#what-it-gives-you] - Emails sent through the sender's SMTP server, from their own address, with a copy filed in Sent. - Replies, out-of-office messages and bounces read from the IMAP inbox about once a minute. - A reply ends the enrollment when the sequence's `exit_on` lists `reply`. A hard bounce always ends it. ## What you need [#what-you-need] - An `admin` API key. - A [sender](/docs/concepts/sender) to attach the mailbox to. - The mailbox's SMTP and IMAP host, port and login. Use an app password wherever the provider has one. Provider settings: [Gmail and Google Workspace](/docs/modules/email/gmail), [Outlook and Microsoft 365](/docs/modules/email/outlook), [other SMTP providers](/docs/modules/email/other-smtp). ## Steps [#steps] ```bash title="curl" curl -X PUT $SEQ/v1/senders/u_42/channels/email -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" -d '{ "provider": "smtp", "smtp": { "host": "smtp.gmail.com", "port": 465, "secure": true, "user": "max@acme.com", "password": "abcd efgh ijkl mnop" }, "imap": { "host": "imap.gmail.com", "port": 993, "secure": true, "user": "max@acme.com", "password": "abcd efgh ijkl mnop" } }' ``` ```ts title="TypeScript" const box = (host: string, port: number) => ({ host, port, secure: true, user: 'max@acme.com', password: process.env.MAX_APP_PASSWORD! }); await oseq.senders.setSmtp('u_42', { provider: 'smtp', smtp: box('smtp.gmail.com', 465), imap: box('imap.gmail.com', 993) }); ``` The service signs in to SMTP, then IMAP, before it stores anything. Both passwords are encrypted and never returned. `from` is optional: it defaults to the SMTP login when that is an address. `secure: true` means TLS from the first byte (465, 993). `secure: false` means STARTTLS (587, 143). ```bash title="curl" curl -X PATCH $SEQ/v1/senders/u_42/channels/email -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" \ -d '{"daily_limit":30,"min_gap_seconds":90}' ``` ```ts title="TypeScript" await oseq.senders.patchChannel('u_42', 'email', { daily_limit: 30, min_gap_seconds: 90 }); ``` `daily_limit` (default 30) counts sends in a rolling 24 hours. Over it, the step waits an hour and the enrollment shows `waiting_limit`. `min_gap_seconds` (default 60) spaces sends out. `{ "status": "paused" }` stops the channel without removing it. ## Check it works [#check-it-works] ```bash curl $SEQ/v1/senders/u_42/readiness -H "Authorization: Bearer $KEY" # {"email":{"ok":true},"sms":{"ok":false,"reason":"no_allo_number"},"task":{"ok":true}} ``` `oseq.senders.readiness('u_42')` returns the same. Then enroll yourself in a one-email sequence and reply to it. Within about a minute the enrollment exits with `replied`. ## Common errors [#common-errors] | Error | Fix | |---|---| | `422 SMTP_AUTH_FAILED`, `IMAP_AUTH_FAILED` | The server refused the login. Use an app password and check that SMTP and IMAP access are on. | | `422 SMTP_UNREACHABLE`, `IMAP_UNREACHABLE` | Wrong host or port, a firewall, or an untrusted certificate. For a private certificate authority, set `NODE_EXTRA_CA_CERTS`. | | `422 SMTP_REFUSED`, `IMAP_REFUSED` | Connected, then refused, for example no STARTTLS on a remote host with `secure: false`. | | `422 FROM_REQUIRED` | Set `from`, or use the full address as the SMTP user. | | Steps skip with `sender_channel_credentials_needed` | The password stopped working. Save the mailbox again. A `sender.channel_status` webhook tells you. | ## Send window [#send-window] Put working hours in the sequence definition. A step outside them waits for the next opening. ```json "settings": { "send_window": { "days": ["mon", "tue", "wed", "thu", "fri"], "from": "09:00", "to": "17:00", "tz": "contact" }, "jitter": "20m" } ``` `tz` is `contact` (default) or `sender`. `jitter` adds a random delay so sends do not all land on the hour. ## Deliverability basics [#deliverability-basics] - Mail leaves through the sender's own provider, so there is no DNS record to add for OpenSequence. Check that the sending domain has SPF, DKIM and DMARC. - Every email carries `List-Unsubscribe` and one-click unsubscribe headers. Put `{{ unsubscribe_url }}` in the body too; publishing without it returns the warning `NO_UNSUBSCRIBE`. - An unsubscribe, a hard bounce or a complaint suppresses email for the contact and exits the enrollment. - Warm up a new mailbox at 10 to 15 emails a day for two weeks, then raise `daily_limit` slowly. - `reply_in_thread: true` on a follow-up sends it in the same thread as the previous email. ## Host the unsubscribe page in your app [#host-the-unsubscribe-page-in-your-app] By default `{{ unsubscribe_url }}` and the `List-Unsubscribe` headers point at a page this server hosts, `SEQ_PUBLIC_URL/u/{token}`. To put the link on your own domain, set the project's `unsubscribe_url`, an `https` URL with `{token}`: ```bash title="curl" curl -X PUT $SEQ/v1/project/settings -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" \ -d '{"unsubscribe_url":"https://app.example.com/u/{token}"}' ``` ```ts title="TypeScript" await oseq.project.updateSettings({ unsubscribe_url: 'https://app.example.com/u/{token}' }); ``` Your page then calls the API with an `enroll` key: 1. On GET, read the token and show a confirmation: `oseq.unsubscribes.get(token)` (`GET /v1/unsubscribes/{token}`). It returns `valid`, `expired`, a masked email and `already_unsubscribed`, and changes nothing. 2. On confirm, apply it: `oseq.unsubscribes.apply(token)` (`POST /v1/unsubscribes/{token}`). The contact gets an email suppression and their enrollments exit with `opt_out`. A second call changes nothing. 3. Accept a POST on the same URL with the body `List-Unsubscribe=One-Click`. Gmail, Yahoo and Apple Mail send it for one-click unsubscribe (RFC 8058). Apply the token and answer `200`, with no login, redirect or CSRF check. A URL that is not `https` or has no `{token}` is refused with `INVALID_SETTINGS`. An invalid token is a `400 UNSUBSCRIBE_TOKEN_INVALID`, an expired one `UNSUBSCRIBE_TOKEN_EXPIRED`. Set `unsubscribe_url` to `null` to go back to the hosted page. ## How replies are read [#how-replies-are-read] The service reads only the IMAP inbox, only new messages, and only messages that answer an email it sent from this mailbox in the last 30 days. Everything else is skipped and never stored. An out-of-office reply pauses the enrollment until the return date it mentions, or for seven days. Reply bodies are not stored. Meetings booked elsewhere are invisible to the service: report them with `POST /v1/contacts/{id}/events`. Every 15 minutes the service signs in again. A refused login sets the channel to `credentials_needed` and email steps skip until you save the mailbox again. `DELETE /v1/senders/{id}/channels/email` (`oseq.senders.deleteChannel(id, 'email')`) removes the channel and deletes the passwords. # Connect any other SMTP and IMAP mail provider (https://docs.opensequence.dev/docs/modules/email/other-smtp) How to connect any mailbox with SMTP and IMAP to OpenSequence: host, port and TLS settings, with Fastmail, Zoho, iCloud, Proton Bridge and self-hosted examples. This page connects any mailbox that offers SMTP and IMAP. You need its host names, ports and a login. ## What it gives you [#what-it-gives-you] The rep's emails leave from their own address, and replies come back over IMAP. See [Email](/docs/modules/email) for limits and send windows. ## What you need [#what-you-need] - The SMTP and IMAP host and port, from the provider's help pages. - A login. Use an app password where the provider offers one. - An OpenSequence `admin` key and the [sender](/docs/concepts/sender) id. ## Settings [#settings] `secure: true` is TLS from the first byte, usually ports 465 (SMTP) and 993 (IMAP). `secure: false` is STARTTLS, usually ports 587 (SMTP) and 143 (IMAP). STARTTLS is required unless the host is `localhost`, so a password never crosses the network in clear. | Provider | SMTP | IMAP | Notes | |---|---|---|---| | Fastmail | `smtp.fastmail.com`, 465, `true` | `imap.fastmail.com`, 993, `true` | An app password with SMTP and IMAP access. | | Zoho Mail | `smtp.zoho.com`, 465, `true` | `imap.zoho.com`, 993, `true` | Organization accounts use `smtppro.zoho.com` and `imappro.zoho.com`. Turn on IMAP access. | | iCloud Mail | `smtp.mail.me.com`, 587, `false` | `imap.mail.me.com`, 993, `true` | An app-specific password. | | Proton Mail | `127.0.0.1`, 1025, `false` | `127.0.0.1`, 1143, `false` | Through Proton Mail Bridge on the server's host. Trust Bridge's certificate with `NODE_EXTRA_CA_CERTS`. | | Your own server | your host | your host | Any server with SMTP AUTH and IMAP. | ## Steps [#steps] ```bash title="curl" curl -X PUT $SEQ/v1/senders/u_42/channels/email -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" -d '{ "provider": "smtp", "from": "max@acme.com", "smtp": { "host": "smtp.fastmail.com", "port": 465, "secure": true, "user": "max@acme.com", "password": "app-password" }, "imap": { "host": "imap.fastmail.com", "port": 993, "secure": true, "user": "max@acme.com", "password": "app-password" } }' ``` ```ts title="TypeScript" const login = { user: 'max@acme.com', password: process.env.MAX_APP_PASSWORD! }; await oseq.senders.setSmtp('u_42', { provider: 'smtp', from: 'max@acme.com', smtp: { host: 'smtp.fastmail.com', port: 465, secure: true, ...login }, imap: { host: 'imap.fastmail.com', port: 993, secure: true, ...login }, }); ``` Set `from` when the SMTP login is not an email address. ## Check it works [#check-it-works] `GET /v1/senders/u_42/readiness` returns `"email": { "ok": true }`. Send yourself a test sequence and reply: the enrollment exits with `replied` within about a minute. ## Common errors [#common-errors] | Error | Fix | |---|---| | `422 SMTP_AUTH_FAILED`, `IMAP_AUTH_FAILED` | Wrong login, or SMTP or IMAP access is off. Use an app password. | | `422 SMTP_UNREACHABLE`, `IMAP_UNREACHABLE` | Wrong host or port, a firewall, or a certificate the server does not trust. Set `NODE_EXTRA_CA_CERTS` for a private certificate authority. | | `422 SMTP_REFUSED`, `IMAP_REFUSED` | Often `secure` does not match the port: `true` for 465 and 993, `false` for 587 and 143. | | iCloud refuses the full address on IMAP | Try the part before the `@` as the IMAP user. | # Connect Outlook and Microsoft 365 mailboxes over SMTP and IMAP (https://docs.opensequence.dev/docs/modules/email/outlook) How to connect an Outlook or Microsoft 365 mailbox to OpenSequence: the servers and ports, Authenticated SMTP, app passwords with MFA, and what Microsoft blocks. This page connects a Microsoft mailbox as a sender's email channel. Read the limits below first: most Microsoft 365 mailboxes cannot connect today. ## What it gives you [#what-it-gives-you] The rep's emails leave from their own Microsoft address, and replies come back over IMAP. See [Email](/docs/modules/email) for limits and send windows. OpenSequence signs in to SMTP and IMAP with a password. Exchange Online (Microsoft 365) turned off password sign-in for IMAP in 2022, and app passwords count as password sign-in. Outlook.com accounts need Microsoft's OAuth sign-in too. OpenSequence has no Microsoft OAuth sign-in yet, so these mailboxes are not supported: saving one fails with `IMAP_AUTH_FAILED`. The steps below work only for a Microsoft mailbox that still accepts a password on both SMTP and IMAP, such as an on-premises Exchange server. ## What you need [#what-you-need] - Authenticated SMTP turned on for the mailbox. In Microsoft 365 an admin turns it on in the admin center under the user's Mail settings, "Manage email apps". - IMAP turned on for the mailbox, in the same place. - With MFA on, an app password instead of the normal password, where the organization allows app passwords. - An OpenSequence `admin` key and the [sender](/docs/concepts/sender) id. ## Steps [#steps] | | Host | Port | `secure` | |---|---|---|---| | SMTP | `smtp.office365.com` | 587 | `false` (STARTTLS) | | IMAP | `outlook.office365.com` | 993 | `true` | For an on-premises Exchange server, use its own host names. The user is the full address. ```bash title="curl" curl -X PUT $SEQ/v1/senders/u_42/channels/email -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" -d '{ "provider": "smtp", "smtp": { "host": "smtp.office365.com", "port": 587, "secure": false, "user": "max@acme.com", "password": "app-password" }, "imap": { "host": "outlook.office365.com", "port": 993, "secure": true, "user": "max@acme.com", "password": "app-password" } }' ``` ```ts title="TypeScript" const login = { user: 'max@acme.com', password: process.env.MAX_APP_PASSWORD! }; await oseq.senders.setSmtp('u_42', { provider: 'smtp', smtp: { host: 'smtp.office365.com', port: 587, secure: false, ...login }, imap: { host: 'outlook.office365.com', port: 993, secure: true, ...login }, }); ``` ## Check it works [#check-it-works] `GET /v1/senders/u_42/readiness` returns `"email": { "ok": true }`. Send yourself a test sequence and reply: the enrollment exits with `replied` within about a minute. ## Common errors [#common-errors] | Error | Fix | |---|---| | `422 IMAP_AUTH_FAILED` on Microsoft 365 or Outlook.com | Microsoft refuses password sign-in for IMAP. This mailbox cannot connect until OpenSequence supports Microsoft OAuth. | | `422 SMTP_AUTH_FAILED` with "SmtpClientAuthentication is disabled" | Authenticated SMTP is off. An admin turns it on for the mailbox. | | `422 SMTP_AUTH_FAILED` with MFA on | Use an app password, not the normal password. | | `422 SMTP_REFUSED` | `secure` must be `false` on port 587, so the connection upgrades with STARTTLS. | # Modules: the channels and data a sequence can use (https://docs.opensequence.dev/docs/modules) Every OpenSequence module in one table: email over SMTP and IMAP with Gmail, Outlook or any provider, SMS and AI agent calls with Allo, LinkedIn connection requests and CRM conditions with Attio. A module is something a sequence step can use: a channel to send on, or data to branch on. This page lists them and says which ones you need. Every install needs the server and one Postgres first: see the [Quickstart](/docs/get-started/quickstart) or [Install](/docs/self-hosting/install). | | Module | What it does | Required | |---|---|---|---| | | [Email](/docs/modules/email) | Sends from each rep's mailbox over SMTP and reads replies over IMAP. | For email steps | | | Email: [Gmail and Google Workspace](/docs/modules/email/gmail) | The Email module with a Google app password. | One email provider | | | Email: [Outlook and Microsoft 365](/docs/modules/email/outlook) | The Email module with Microsoft's servers. | One email provider | | | Email: [Other SMTP providers](/docs/modules/email/other-smtp) | The Email module with Fastmail, Zoho, iCloud or your own server. | One email provider | | | SMS: [Allo](/docs/modules/sms/allo) | Texts, inbound replies and STOP, and call tasks that complete themselves. | For SMS and call steps | | | Calls: [Allo agent calls](/docs/modules/calls/allo) | An AI agent phones the contact with your brief; the outcome of the call picks the next step. | For AI call steps | | | [LinkedIn](/docs/modules/linkedin) | Connection requests with a note, as tasks the sender sends by hand in one click. | For LinkedIn steps | | | CRM: [Attio](/docs/modules/crm/attio) | Lets conditions read live person, company and deal data. | For `crm.*` conditions | Signed events back to your app are in [Webhooks](/docs/webhooks). Every module page follows the same order: what it gives you, what you need, the steps with curl and the SDK, how to check it works, and common errors. Logos identify each integration. They do not imply endorsement by their owners. ## Try without accounts [#try-without-accounts] With `SEQ_DEV_MOCK_PROVIDERS=1`, every provider is a mock. Mailbox logins are not checked, nothing leaves the machine, and `POST /hooks/mock/{project slug}` injects replies, bounces and calls. The process refuses mock providers when `NODE_ENV=production`. # LinkedIn connection requests with a note (https://docs.opensequence.dev/docs/modules/linkedin) How OpenSequence puts LinkedIn connection requests in a sequence: a linkedin_connect step writes the note, the sender opens the profile in one click and the task completes itself. The LinkedIn module adds connection requests to a sequence. A `linkedin_connect` step writes the note for each contact and gives the sender a task with the profile link. The sender opens the profile, pastes the note and clicks Send. Opening the task marks it done, so there is nothing to tick afterwards. ## What it gives you [#what-it-gives-you] - A `linkedin_connect` step with a templated note, like any other step on the canvas. - One task per contact, of kind `linkedin_connect`, with the profile as `link` and the rendered note as `body`. - The task completes as `sent` the moment the sender opens it (`POST /v1/tasks/{id}/open`), and the sequence moves on. - Contacts with no LinkedIn URL take the step's `skipped` branch instead of waiting. ## What you need [#what-you-need] - Each contact's `linkedin_url`. `linkedin.com/in/dana` and `https://www.linkedin.com/in/dana/` are both accepted and stored as `https://www.linkedin.com/in/dana`. - An app that shows the sender their tasks: your CRM, or anything that calls the [tasks API](#show-the-tasks). - Nothing to connect. OpenSequence never logs in to LinkedIn and stores no LinkedIn credentials. ## Steps [#steps] ```bash title="curl" curl -X PUT $SEQ/v1/contacts/p_7 -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \ -d '{"first_name":"Dana","linkedin_url":"linkedin.com/in/dana-whitfield"}' ``` ```ts title="TypeScript" await oseq.contacts.upsert('p_7', { first_name: 'Dana', linkedin_url: 'linkedin.com/in/dana-whitfield' }); ``` A URL that is not on linkedin.com is a `422 INVALID_CONTACT`. ```json "li_connect": { "type": "linkedin_connect", "params": { "note": "Hi {{ contact.first_name | \"there\" }}, I work with teams like {{ attrs.company.name | \"yours\" }} on outbound. Happy to connect.", "expire": "5bd" }, "next": { "completed": "wait_3d", "no_answer": "email_2", "skipped": "email_2" } } ``` | Param | Meaning | |---|---| | `note` | The connection note, a template. Rendered notes over 300 characters are cut at a word. Without Premium or Sales Navigator, LinkedIn takes 200; the validator warns above that. | | `title` | The task's title. Default: `Connect with {{ contact.first_name \| "them" }} on LinkedIn`. | | `due` | A duration on the sender's calendar. Default: due as soon as the step runs. | | `expire` | When the task takes `no_answer` if nobody opens it. Default: seven days after `due`. | | Transition | When | |---|---| | `completed` | The sender opened the task (outcome `sent`), or your app completed it with another outcome. `branches_by_outcome` works as on a [`task`](/docs/concepts/sequence/nodes#task). | | `no_answer` | The task expired or was cancelled. | | `skipped` | The contact has no `linkedin_url`. | List a sender's open LinkedIn tasks: ```bash title="curl" curl "$SEQ/v1/tasks?sender=u_42&status=open&kind=linkedin_connect" -H "Authorization: Bearer $KEY" ``` ```ts title="TypeScript" const { items } = await oseq.tasks.list({ sender: 'u_42', status: 'open', kind: 'linkedin_connect' }); ``` Each task carries what the button needs: ```json { "id": "task_01J…", "kind": "linkedin_connect", "title": "Connect with Dana on LinkedIn", "link": "https://www.linkedin.com/in/dana-whitfield", "body": "Hi Dana, I work with teams like Example Inc on outbound. Happy to connect.", "status": "open", "completeOnOpen": "sent", "openedAt": null } ``` When the sender clicks the task, copy `body` to the clipboard, open `link` in a new tab and tell OpenSequence: ```bash title="curl" curl -X POST $SEQ/v1/tasks/task_01J…/open -H "Authorization: Bearer $KEY" ``` ```ts title="TypeScript" await navigator.clipboard.writeText(task.body ?? ''); window.open(task.link!, '_blank', 'noopener'); await oseq.tasks.open(task.id); // completes it as "sent" ``` The task is now `done` with outcome `sent`, and the enrollment follows `completed`. Opening it again changes nothing. On LinkedIn the sender clicks Connect, then Add a note, pastes and sends. If the sender could not send it (already connected, no Connect button), complete it with your own outcome before opening, or route that outcome with `branches_by_outcome`: ```ts await oseq.tasks.complete(task.id, { outcome: 'already_connected' }); ``` ## Check it works [#check-it-works] 1. Enroll a test contact with a `linkedin_url` in a sequence whose first step is `linkedin_connect`. 2. `GET /v1/tasks?kind=linkedin_connect&status=open` lists one task with the profile and the note. 3. `POST /v1/tasks/{id}/open` returns it with `status: "done"`, `outcome: "sent"` and `openedAt` set, and the contact's journey shows the step as done. ## Why not automatic [#why-not-automatic] LinkedIn's User Agreement forbids sending invitations or messages with bots or other automated tools, and LinkedIn offers no API that sends a connection request for a member. Tools that automate it act as the member and put the member's account at risk of restriction. OpenSequence leaves the click to the sender: the step does the writing, the timing and the follow-up, and LinkedIn sees a person using LinkedIn. A connection request is not a touch and not a reply. The step does not detect acceptance; follow it with a `wait` and the next step, or report what you learn with a [contact event](/docs/get-started/integrate#report-what-the-service-cannot-see). ## Common errors [#common-errors] | Error | Cause | Fix | |---|---|---| | `422 INVALID_CONTACT` on `linkedin_url` | The URL is not on linkedin.com. | Send the profile URL, like `linkedin.com/in/dana`. | | The step always takes `skipped` | The contact has no `linkedin_url`. | Upsert the contact with one before the step runs. | | `TOO_LONG` warning | The note is over 200 (free accounts) or 300 characters. | Shorten it; variables make it longer once rendered. | # Connect Allo for texts and call tasks (https://docs.opensequence.dev/docs/modules/sms/allo) How to connect Allo to OpenSequence: the API key and its permissions, each sender's number, allowed countries, consent, quiet hours, STOP and call tasks. The Allo module sends texts from each rep's Allo number and closes call tasks when the rep calls. Set one key per project, then one number per sender. ## What it gives you [#what-it-gives-you] - Texts from the sender's own number, with replies read back. - A reply made only of STOP (or QUIT, END, CANCEL, UNSUBSCRIBE, OPT OUT, STOPALL) suppresses SMS for the contact and exits their enrollments. - Call tasks that complete themselves when the rep calls the contact from Allo. - Optional: call tasks pushed into the rep's Allo power dialer. ## What you need [#what-you-need] - An [Allo](https://withallo.com) workspace API key with these permissions: `SMS_SEND`, `WEBHOOKS_READ_WRITE`, `PHONE_NUMBERS_READ`, `USERS_READ`, `CONVERSATIONS_READ` and `DIALING_QUEUE_READ_WRITE`. - `SEQ_PUBLIC_URL` set to an HTTPS address Allo can reach. - An OpenSequence `admin` key. ## Steps [#steps] ```bash title="curl" curl -X PUT $SEQ/v1/project/providers/allo -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" \ -d '{"api_key":"allo_…"}' ``` ```ts title="TypeScript" await oseq.project.setProvider('allo', { api_key: process.env.ALLO_API_KEY! }); ``` OpenSequence registers its own webhook at Allo for inbound texts, sent texts and finished calls, at `SEQ_PUBLIC_URL/hooks/allo/{project slug}`. It keeps the signing secret. There is nothing to set up in Allo. Then it checks the key's permissions and stores the key encrypted. ```bash title="curl" curl $SEQ/v1/project/providers/allo/users -H "Authorization: Bearer $ADMIN_KEY" # [{ id: "usr-…", email, name }] curl $SEQ/v1/project/providers/allo/numbers -H "Authorization: Bearer $ADMIN_KEY" # [{ address, capabilities, users }] curl -X PUT $SEQ/v1/senders/u_42/channels/sms -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" \ -d '{"allo_user_id":"usr-…","number":"+14155551234"}' ``` ```ts title="TypeScript" const users = await oseq.project.alloUsers(); const numbers = await oseq.project.alloNumbers(); const max = users.find((u) => u.email === 'max@acme.com')!; const line = numbers.find((n) => n.users.some((u) => u.id === max.id) && n.capabilities.includes('SMS'))!; await oseq.senders.setSms('u_42', { allo_user_id: max.id, number: line.address }); ``` `allo_user_id` is Allo's `usr-…` id, not an email. Set it for senders who only call, too: call tasks are matched by this number. ```bash title="curl" curl -X PUT $SEQ/v1/project/settings -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" \ -d '{"sms_countries":["US","CA"]}' ``` ```ts title="TypeScript" await oseq.project.updateSettings({ sms_countries: ['US', 'CA'] }); ``` The default is `["US"]`. A contact's `country` (ISO-2) must be in the list. ```bash title="curl" curl -X PUT $SEQ/v1/contacts/p_7/outreach-consent -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" \ -d '{"consent":true,"source":"signup form"}' ``` ```ts title="TypeScript" await oseq.contacts.setOutreachConsent('p_7', { consent: true, source: 'signup form' }); ``` Only an `admin` key can record consent. The same consent gates [agent calls](/docs/modules/calls/allo). ## Rules every text follows [#rules-every-text-follows] These checks are fixed. A text is skipped when one fails, except quiet hours, which wait. | Check | Skip reason | |---|---| | The contact has outreach consent | `no_consent` | | The contact has a phone number | `no_phone` | | The contact's `country` is in `sms_countries` | `country_not_allowed` | | The contact's time zone is known, from `timezone`, the phone number or a one-zone country | `no_timezone` | | No SMS suppression | `suppressed` | | Quiet hours: only 08:00 to 21:00 in the contact's zone, every day | waits until 08:00 | The default limit is 100 texts a day per sender. Nothing is appended to the body, so write "Reply STOP to opt out" yourself. ## Call tasks [#call-tasks] A `task` step with `kind: "call"` gives the rep a call to make. When Allo reports a finished outbound call from the sender's number to the contact, the open call task completes by itself: | Allo result | Outcome | |---|---| | `ANSWERED`, `TRANSFERRED_AI`, `TRANSFERRED_EXTERNAL` | `connected` | | `VOICEMAIL` | `voicemail` | | anything else | `no_answer` | Allo's call summary becomes the task note. Change the mapping with `PUT /v1/project/settings` and `{ "allo": { "outcome_map": { "VOICEMAIL": "no_answer" } } }`. With `dialer: true` on the step, the contact's number goes into the rep's Allo power dialer within a minute. Your app can also complete a task: `POST /v1/tasks/{id}/complete` with an `outcome` (`oseq.tasks.complete()`). ## Check it works [#check-it-works] 1. `GET /v1/project` shows `webhook_urls.allo` and the Allo credential. 2. `GET /v1/senders/u_42/readiness` returns `"sms": { "ok": true }`. 3. Enroll a consenting test contact with your own phone in a one-text sequence, between 08:00 and 21:00 their time. Reply to the text: the enrollment exits with `replied` when `exit_on` lists `reply`. ## Common errors [#common-errors] | Error | Fix | |---|---| | `422 INVALID_CREDENTIAL` | The key is wrong or lacks a permission. `details.missing` lists the missing ones. | | `401` or `403` with an Allo error code | Allo refused the webhook registration. The key needs `WEBHOOKS_READ_WRITE`. | | `422 UNKNOWN_NUMBER` | The key cannot see that number. Pick one from `GET /v1/project/providers/allo/numbers`. | | `422 NUMBER_HAS_NO_SMS` | The number cannot send texts. Pick one with `SMS` in `capabilities`. | | Texts skip with `no_consent` or `country_not_allowed` | Record consent, set the contact's `country`, or add it to `sms_countries`. | | No replies arrive | `SEQ_PUBLIC_URL` was not reachable when you saved the key. Fix it and save the key again. | Each save registers a new webhook at Allo. Delete old OpenSequence webhooks in Allo's settings after a rotation. A text whose result is unknown is never retried blindly: the run becomes `needs_review`, because a double text is worse than a late one. # Data retention and erasure (https://docs.opensequence.dev/docs/security/data-retention) What OpenSequence stores about contacts and messages, what it prunes on its own, how to erase a person on request, and what leaves in webhooks. This page lists the personal data OpenSequence keeps and how long it keeps it. Read it before you answer a privacy request or set your own retention policy. ```bash title="curl" # Erase a person (admin key) curl -X DELETE $SEQ/v1/contacts/p_7 -H "Authorization: Bearer $ADMIN_KEY" # Do not store reply bodies (merged into the project settings) curl -X PUT $SEQ/v1/project/settings -H "Authorization: Bearer $ADMIN_KEY" \ -H "Content-Type: application/json" -d '{"store_inbound_bodies":false}' ``` ```ts title="TypeScript" await oseq.contacts.delete('p_7'); await oseq.project.updateSettings({ store_inbound_bodies: false }); ``` ## What is stored [#what-is-stored] | Data | Stored | Why | |---|---|---| | Contacts, senders | what you send, `attrs` included | to address and personalize messages | | Outbound messages | subject and body as rendered, addresses, provider ids, thread reference | to match replies and show the timeline | | Inbound replies | addresses, subject, thread reference, provider id. The body only when `store_inbound_bodies` is on (default off): plain text, the quoted history cut off, at most 20,000 characters. With the setting off the service does not even download the body, except to read the return date of an out-of-office reply. Turning it on applies to replies that arrive afterwards; earlier replies stay without a body | to stop the sequence and attribute the reply, and to show what the contact wrote | | Runs | node, status, branch, the facts a condition read, the values a template rendered, provider references | the journey of each enrollment | | Signals | kind, channel, source, external id, attribution, a small payload | replies, bounces, opt-outs, calls, meetings | | Tasks | title, body and link as rendered, outcome, note (an Allo call summary when completed automatically) | the reps' task inbox | | Webhook deliveries | the full event payload, attempts, errors | delivery and replay | | Secrets | encrypted, write-only | provider access | The service reads only threads it started, from the last 30 days, and never stores anything else it sees in a mailbox. ## What is pruned automatically [#what-is-pruned-automatically] The `retention` job runs when a worker starts and then once a day. It deletes: | Rows | After | |---|---| | idempotency keys | 1 day | | dead-letter queue messages | 30 days | | delivered webhook deliveries | 30 days | `retention_days` (7 to 3650, default 365) is accepted in the project settings but not enforced yet. Runs, messages, signals and tasks are kept until the contact is erased. Plan your own pruning until the engine honours the setting. ## Erase on request [#erase-on-request] `DELETE /v1/contacts/{id}` (scope `admin`, accepts the id or your external id) erases a person in one transaction: 1. Every active enrollment of the contact exits with reason `deleted`, and an `enrollment.exited` webhook is queued so your systems follow. 2. The contact is deleted, and with it its enrollments, runs, messages, signals and their effects, tasks and suppressions. Analytics (enrolled, replies, meetings per sequence) are computed from what remains, so an erased contact leaves the totals. Erasing a contact also erases its suppressions. If the same person is created again later, nothing remembers that they opted out. Keep your own do-not-contact list, and when you re-create a person who opted out, suppress them again: `POST /v1/contacts/{id}/events` with `{ "id": "dnc-1", "type": "suppressed", "channel": "all" }`. ## What leaves the service [#what-leaves-the-service] Webhook payloads carry personal data in two places: `signal.received` includes the contact's id, external id, email, phone and name, and `task.created` includes the task's rendered title, body and link. The [webhook events reference](/reference/webhook-events) shows every payload. Copies of those payloads stay in `webhook_deliveries` until they are pruned 30 days after delivery, even when the contact has been erased. Your endpoints keep what they received: delete it there under your own policy. # Hardening a production install (https://docs.opensequence.dev/docs/security/security-hardening) What to lock down before going live: encryption keys and their rotation, the operator token, network layout, webhook rules, rate limits, a checklist. This page lists the settings and network rules that protect a production install. Go through the checklist at the end before you expose the API. ```bash SEQ_ENCRYPTION_KEYS='k2new:…,k1old:…' # the first entry encrypts, every entry decrypts SEQ_ADMIN_TOKEN="$(openssl rand -base64 32)" NODE_ENV=production # already set in the image: refuses mock providers, plain JSON logs ``` ## Encryption keys [#encryption-keys] Every stored secret is AES-256-GCM ciphertext under `SEQ_ENCRYPTION_KEYS`: each sender's SMTP and IMAP passwords, the Allo and Attio keys, and the webhook signing secrets. Each row records the id of the key that wrote it. The value is a comma-separated list of `id:base64key`. Each key must decode to 32 bytes, ids must be unique and at most 16 characters. `node dist/cli.js secrets new-key` prints a valid entry. | Entry | Role | |---|---| | first | encrypts every new secret | | every entry | decrypts the rows written with it | The unsubscribe links in sent emails are signed with a key derived from the whole `SEQ_ENCRYPTION_KEYS` value. Any change to it (adding, removing or reordering an entry) makes every link already sent answer "This link has expired". Plan rotations knowing this. ### Rotate a key [#rotate-a-key] 1. Generate a new entry with `secrets new-key` and put it first. Keep the old entries after it. 2. Restart both roles. New secrets are now written under the new key; old ones still decrypt. 3. Each secret moves to the new key when it is written again: a provider credential saved again, a sender's mailbox saved again. Check what still uses an old key: ```sql select 'credentials' as t, key_id, count(*) from seq_auth.credentials group by key_id union all select 'connections', key_id, count(*) from seq_auth.connections group by key_id union all select 'webhook_endpoints', key_id, count(*) from seq.webhook_endpoints group by key_id; ``` Drop an old entry only when nothing uses it. No command re-encrypts everything at once yet (the `oseq secrets rotate` command in the architecture document does not exist), so keeping old entries in the list is the safe default. If a webhook endpoint's key is gone, its next delivery disables it with a reason. `POST /v1/webhooks/{id}/rotate-secret` issues a new signing secret under the current key (update your receiver), then `POST /v1/webhooks/{id}/enable` resumes it. ## The operator token [#the-operator-token] `SEQ_ADMIN_TOKEN` protects `/v1/admin/*` only: creating projects and their keys, and platform health. It is compared in constant time and never stored. Only the `api` and `all` roles need it. Keep it out of application code, which uses project keys. To rotate it, change the variable and restart the api. ## Project keys [#project-keys] Keys are `sk_live_…` with 256 bits of entropy, stored as SHA-256 hashes, shown once, revocable with `DELETE /v1/api-keys/{id}`. Give each caller the narrowest scope: | Scope | For | |---|---| | `read` | dashboards and reporting | | `enroll` | the part of your application that reacts to user actions. It cannot publish a sequence or grant outreach consent | | `admin` | configuration jobs only | ## Network layout [#network-layout] | Component | Exposure | |---|---| | `api` | public over HTTPS behind a TLS terminator. Needs inbound from your application, Allo (webhooks) and mail clients (unsubscribe links) | | `worker` | private. Its port answers the API routes too, so never route traffic to it. Needs outbound to your senders' mail servers (SMTP and IMAP), Allo, Attio and your webhook endpoints | | Postgres, Redis | private | - `SEQ_PUBLIC_URL` must be the HTTPS origin the world sees. It is written into unsubscribe links and sent to Allo when you save the Allo key. If it changes, save the Allo key again so Allo posts to the new address. - The API trusts `X-Forwarded-For` to find the client address, which the per-IP rate limit uses. Make sure your proxy overwrites that header and that nothing reaches the api around the proxy. - The api serves an interactive API explorer at `/docs`. Block that path at your proxy if you do not want it public. ## Outbound webhooks [#outbound-webhooks] Endpoint URLs must use `https`, carry no credentials, not point at `localhost`, `.local` or `.internal`, and resolve to public addresses. Loopback, private, link-local (cloud metadata included), CGNAT, multicast and reserved ranges are refused, for IPv4 and IPv6. The host is resolved again at every attempt, redirects are not followed, and each attempt times out after 10 seconds. So a receiver must be reachable at a public HTTPS address, even when it runs next to OpenSequence. ## Inbound webhooks [#inbound-webhooks] | Path | Check | |---|---| | `/hooks/allo/{slug}` | Standard Webhooks signature with the secret Allo issued when the service registered the endpoint; timestamps older than 5 minutes are rejected | | `/hooks/mock/{slug}` | exists only with mock providers on, which `NODE_ENV=production` refuses | ## Rate limits and body size [#rate-limits-and-body-size] 600 requests a minute per `Authorization` value, or per client address without one. Over that, `429` with `Retry-After`. Bodies over 2 MB are refused. With several api replicas each keeps its own counter, so put a shared limiter at the edge if you need an exact global cap. ## Tenant isolation [#tenant-isolation] Every table carries `project_id` and every query filters on it. A key resolves to one project, and another project's ids answer `404`. ## Before going live [#before-going-live] - `NODE_ENV=production`, `SEQ_DEV_MOCK_PROVIDERS` unset. - Real `SEQ_ENCRYPTION_KEYS` and `SEQ_ADMIN_TOKEN`, in a secret store and in your backups. - TLS in front of the api; the worker port not routable. - `SEQ_PUBLIC_URL` set to the public HTTPS origin before you save any provider credential. - A webhook endpoint registered and verifying signatures ([Verifying](/docs/webhooks/verifying)). - Application keys with the narrowest scope. # Security model (https://docs.opensequence.dev/docs/security/security) How OpenSequence protects access: tenants, API keys, encrypted secrets, signed webhooks, mailbox privacy, consent rules and the gaps still open. OpenSequence sends from real people's mailboxes and phone numbers and reads their replies, so this page lists every control that protects that access. To harden a deployment, read [Security hardening](/docs/security/security-hardening); to report a vulnerability, contact the maintainer privately through their [GitHub profile](https://github.com/lguerberg), never in a public issue. ## Controls [#controls] | Concern | Control | |---|---| | Operator and projects | `SEQ_ADMIN_TOKEN` protects `/v1/admin/*` only and is compared in constant time. Project API keys protect everything else and never reach another project's data | | Authentication | keys are `sk_live_…` with 256 bits of entropy, stored as SHA-256 hashes, shown once, revocable, with `last_used_at`. Each key resolves to one project; every query filters on `project_id`; another project's ids answer `404` | | Scopes | `read` < `enroll` < `admin`. An `enroll` key cannot publish or edit a sequence, or grant outreach consent | | Secrets at rest | each sender's SMTP and IMAP passwords, the Allo and Attio keys and webhook signing secrets are AES-256-GCM under `SEQ_ENCRYPTION_KEYS`, and write-only: no endpoint returns them. Responses show status, key id, the last four characters and timestamps. Known secret fields are redacted from logs | | Mailbox passwords | checked by signing in to SMTP and IMAP before they are stored. Removing the email channel deletes them. Only the auth module and the mail adapter read them | | Mailbox privacy | the service reads only the inbox, and keeps only messages that answer an email it sent in the last 30 days. Reply bodies are not stored | | Inbound webhooks | Allo: Standard Webhooks signature with the secret Allo issued, timestamps within 5 minutes, idempotent by event id | | Outbound webhooks | Standard Webhooks signatures, HTTPS only, public addresses only (resolved again at every attempt), no redirects, 10-second timeout | | Do not contact | suppressions from your reports, unsubscribe clicks, STOP texts, bounces and complaints, checked at enrollment and again just before each send | | SMS | consent defaults to false and only an `admin` key can set it, with a `source` and a time. No text without consent, a known recipient time zone, 08:00 to 21:00 recipient time, and a country on the project's `sms_countries` list (default `["US"]`) | | Unsubscribe | always exits the sequence (not configurable) and suppresses the channel. Emails carry `List-Unsubscribe` and `List-Unsubscribe-Post` (one click). Links are signed and valid for 90 days | | Data in runs | the facts a condition read and the values a template rendered are stored at decision time. Erase a person with `DELETE /v1/contacts/{id}`: see [Data retention](/docs/security/data-retention) | | Audit | every enrollment records `enrolled_by` and its kind; every exit records its reason and signal; flag changes record the key that made them | | Input limits | definitions up to 256 KB and 200 nodes; Zod validation on every body; contact batches up to 500; 600 requests a minute per key; bodies up to 2 MB | | Dependencies | Postgres 14 or newer with no extensions; Node 22; Redis only when `SEQ_QUEUE=redis` | ## What the service never does [#what-the-service-never-does] - It never calls your application except at the webhook endpoints you registered. - It never reads your database. - It never sends from an address a sender did not connect. - It never texts without consent. - It never reads mail outside its own threads. - It never returns a secret it stored. - It never writes to your CRM: the CRM connection is read-only. ## Known gaps [#known-gaps] | Gap | Today | |---|---| | `Idempotency-Key` header | not supported; retry a create only after checking whether it happened | | `/metrics` endpoint | none; use the health endpoints and logs ([Observability](/docs/self-hosting/observability)) | | `X-Request-Id` | not propagated; the service makes its own `req_…` id | | `retention_days` | accepted, not enforced ([Data retention](/docs/security/data-retention)) | | rate limit | counted per api replica, not globally | | key rotation | no command re-encrypts stored secrets under a new key yet ([Security hardening](/docs/security/security-hardening)) | # Postgres database requirements (https://docs.opensequence.dev/docs/self-hosting/database) What OpenSequence needs from Postgres: version, schemas, how migrations run, pool size behind a pooler, and how to back up and restore. OpenSequence keeps all of its state in one Postgres database. Read this page when you provision that database, size its connections or plan backups. ```bash SEQ_DB_DSN=postgres://oseq:secret@db.internal:5432/opensequence # the only database setting SEQ_DB_POOL=10 # connections per process (1 to 100) SEQ_RUN_MIGRATIONS=1 # apply migrations at boot ``` ## Requirements [#requirements] Postgres 14 or newer, with no extensions. Ids are generated by the service (prefixed ULIDs), timers are rows, the scheduler uses lease rows, and the `postgres` queue is a table read with `FOR UPDATE SKIP LOCKED`. The service uses no session-level features: no advisory locks, no `LISTEN`, and prepared statements are turned off in the driver. So a transaction pooler works, such as PgBouncer in transaction mode or a cloud provider's pooler. ## The schemas [#the-schemas] The service creates and owns two schemas and touches nothing else, so it can share a database with your app, such as a Supabase project. Use a role that can create schemas, and leave `seq` and `seq_auth` to OpenSequence. | Schema | Owner | Tables | |---|---|---| | `seq` | the engine | `projects`, `api_keys`, `webhook_endpoints`, `webhook_deliveries`, `idempotency_keys`, `senders`, `sender_channels`, `contacts`, `suppressions`, `sequences`, `versions`, `enrollments`, `runs`, `messages`, `tasks`, `signals`, `signal_effects`, `flags`, `job_locks`, `queue_messages`, `queue_dead`, plus `migrations` and `migration_lock` | | `seq_auth` | the auth module | `credentials` (a project's provider secrets), `connections` (a sender's SMTP and IMAP passwords), plus `migrations` and `migration_lock` | Every tenant-owned table carries `project_id`. Secrets are AES-256-GCM ciphertext under `SEQ_ENCRYPTION_KEYS`, and each row records the id of the key that encrypted it. They live in `seq_auth.credentials`, `seq_auth.connections` and `seq.webhook_endpoints`. ## Migrations [#migrations] The migrations are SQL files shipped in the image, one folder per schema. Two ways run them, and both do the same thing: ```bash SEQ_RUN_MIGRATIONS=1 # every process migrates at boot, before it opens its port node dist/cli.js migrate # oseq migrate: once, from a pipeline or a Job ``` - Each migration runs in its own transaction, serialized by `SELECT … FOR UPDATE` on the schema's `migration_lock` row. Replicas that start together wait for each other instead of racing, and a transaction pooler is fine. - Applied migrations are recorded in `seq.migrations` and `seq_auth.migrations` by tag and SHA-256 hash. A file changed after it was applied is refused with an error, never silently re-run. - Running again is a no-op: `oseq migrate` prints `already up to date`. - A failed migration rolls back its transaction. At boot, the process then exits with code 1. When `SEQ_RUN_MIGRATIONS` is off, nothing checks the schema at boot. Run `oseq migrate` before you start the new image. See [Upgrades](/docs/self-hosting/upgrades) for the order. ## The queue [#the-queue] The queue lives in Postgres by default (`SEQ_QUEUE=postgres`), so you need no Redis. Messages sit in `seq.queue_messages` and are read with `FOR UPDATE SKIP LOCKED`. Enqueuing joins the transaction that records the work, so a recorded step and its queued message never diverge. | `SEQ_QUEUE` | Use it for | |---|---| | `postgres` | The default. Nothing else to run. | | `redis` | More throughput on large installs, with `SEQ_REDIS_DSN` and Redis persistence on. A message can arrive twice after a crash; the executors are idempotent. | | `memory` | Development and tests, one process only. | The worker reads four queues: `seq_email`, `seq_sms`, `seq_signals` and `seq_webhooks`. Their depths are in `GET /v1/admin/engine/health`. ## Pool size [#pool-size] `SEQ_DB_POOL` (default 10) is per process. A worker reads four queues (`seq_email`, `seq_sms`, `seq_signals`, `seq_webhooks`) with up to `SEQ_CONCURRENCY` messages in flight each, so 32 by default, plus the scheduler jobs. They share the pool: a query waits for a free connection rather than failing. Most work is short, so 10 is enough at the default concurrency. Raise both together. Behind a pooler, size the pooler for the sum over every process: `replicas × SEQ_DB_POOL` for each role. ## Backups and restore [#backups-and-restore] ```bash pg_dump --format=custom --schema=seq --schema=auth "$SEQ_DB_DSN" > oseq.dump pg_restore --dbname="$NEW_DSN" oseq.dump ``` Back up the database and `SEQ_ENCRYPTION_KEYS` together. A database restored without the key that encrypted its secrets has unreadable credentials: every mailbox password, Allo and Attio key and webhook secret must be entered again. There is no state outside the database, except queue messages when `SEQ_QUEUE=redis`. Losing those costs only a delay: the reaper rebuilds the work from the tables. ## Growth [#growth] The ledgers (`runs`, `messages`, `signals`, `webhook_deliveries`) grow by a few rows per enrollment per step. The `retention` job, which runs at boot and then daily, deletes: | Rows | After | |---|---| | `idempotency_keys` | 1 day | | `queue_dead` | 30 days | | delivered `webhook_deliveries` | 30 days | Runs, messages, signals and tasks are kept until the contact is erased. The `retention_days` project setting is accepted but not enforced yet. See [Data retention](/docs/security/data-retention). # Deploy on Fly.io (https://docs.opensequence.dev/docs/self-hosting/deploy-fly) How to run OpenSequence on Fly.io with one fly.toml: api and worker process groups from one image, migrations as the release command, secrets set once. This guide runs OpenSequence as one Fly app with two process groups, `api` and `worker`, built from `apps/server/Dockerfile`. Migrations run as the release command, before any machine is replaced. ## fly.toml [#flytoml] Put this at the root of your fork. The Dockerfile copies the whole workspace, so the build context must be the root. ```toml title="fly.toml" app = "acme-opensequence" primary_region = "iad" kill_signal = "SIGTERM" kill_timeout = 40 [build] dockerfile = "apps/server/Dockerfile" # Or skip the build and run the published image (pin a sha- or version tag): # image = "ghcr.io/lguerberg/open-sequence:main" [deploy] release_command = "node /app/dist/cli.js migrate" strategy = "rolling" [env] SEQ_PUBLIC_URL = "https://acme-opensequence.fly.dev" SEQ_PORT = "8080" SEQ_LOG_LEVEL = "info" # One image, two process groups. `env` sets the role, then runs node in its place. [processes] api = "env SEQ_ROLES=api node /app/dist/main.js" worker = "env SEQ_ROLES=worker node /app/dist/main.js" [http_service] processes = ["api"] internal_port = 8080 force_https = true auto_stop_machines = "off" auto_start_machines = true min_machines_running = 1 [[http_service.checks]] method = "GET" path = "/readyz" interval = "15s" timeout = "3s" grace_period = "20s" # The worker has no public service; this check still watches it. [checks] [checks.worker_ready] processes = ["worker"] type = "http" port = 8080 method = "GET" path = "/readyz" interval = "30s" timeout = "3s" grace_period = "30s" [[vm]] processes = ["api", "worker"] size = "shared-cpu-1x" memory = "512mb" ``` | Line | Why | |---|---| | `kill_signal`, `kill_timeout = 40` | the worker finishes in-flight messages for up to 30 seconds after `SIGTERM`, and the process exits within 35 | | `release_command` | applies the `seq` and `seq_auth` migrations once per deploy. If it fails, the deploy stops and no machine changes | | `[processes]` | the server reads its role from `SEQ_ROLES`; Fly has no per-process `[env]`, so the command sets it | | `http_service.processes = ["api"]` | only the api gets a public address. The worker answers the API routes on its port too, so it must not have one | | `auto_stop_machines = "off"` | an api stopped by Fly would miss provider webhooks and unsubscribe clicks | | `/readyz` checks | on the api, the database answers; on the worker, the scheduler also ran a job in the last 2 minutes | ## Steps [#steps] ```bash fly apps create acme-opensequence ``` Create a Fly Managed Postgres cluster, version 14 or newer, in the same region, or use any Postgres the app can reach. Copy its connection string. ```bash KEY=$(docker run --rm ghcr.io/lguerberg/open-sequence:main node dist/cli.js secrets new-key) # or any built image fly secrets set --stage \ SEQ_DB_DSN='postgres://oseq:…@…:5432/opensequence' \ SEQ_ENCRYPTION_KEYS="$KEY" \ SEQ_ADMIN_TOKEN="$(openssl rand -base64 32)" ``` Secrets reach every process group and the release command. The worker ignores `SEQ_ADMIN_TOKEN`. `--stage` stores them without deploying. Keep a copy of `SEQ_ENCRYPTION_KEYS` outside Fly. Fly will not show a secret's value again, and a database restored without it has unreadable credentials. ```bash fly deploy fly scale count api=2 worker=1 ``` Fly builds the image, runs the release command, then rolls the machines. ```bash curl -X POST https://acme-opensequence.fly.dev/v1/admin/projects \ -H "Authorization: Bearer $SEQ_ADMIN_TOKEN" -H "Content-Type: application/json" \ -d '{"slug":"acme","name":"Acme CRM"}' ``` The response holds the first `admin` key, shown once. Continue with [Install](/docs/self-hosting/install), from "Register the providers". ## Custom domain [#custom-domain] ```bash fly certs add sequences.example.com # then in fly.toml: SEQ_PUBLIC_URL = "https://sequences.example.com" fly deploy ``` Set `SEQ_PUBLIC_URL` before you save the Allo key: it builds the Allo webhook address and every unsubscribe link. ## Check it [#check-it] ```bash fly status # machines per process group and their checks fly logs # Pino JSON from both groups curl https://acme-opensequence.fly.dev/v1/admin/engine/health -H "Authorization: Bearer $SEQ_ADMIN_TOKEN" ``` ## Notes [#notes] - **No cron.** The scheduler runs inside the worker; replicas coordinate through lease rows in Postgres. - **Webhook receivers** must be public HTTPS. A `.internal` hostname or a private Fly address is refused as a webhook endpoint. - **More workers** are safe: `fly scale count worker=2`. See [Scaling](/docs/self-hosting/scaling). # Deploy on Kubernetes (https://docs.opensequence.dev/docs/self-hosting/deploy-kubernetes) How to deploy OpenSequence on Kubernetes: a Secret and ConfigMap, a migration Job, an api Deployment with probes, Service, Ingress and PDB, and a worker. This guide runs OpenSequence on any Kubernetes cluster with plain manifests. You apply four files: configuration, a migration Job, the `api` and the `worker`. ```mermaid flowchart LR ING["Ingress, TLS"] --> SVC["Service opensequence-api"] --> API["Deployment api, 2 pods"] API --> PG[("Postgres")] WRK["Deployment worker, no Service"] --> PG JOB["Job migrate"] --> PG ``` The manifests use the published image (`ghcr.io/lguerberg/open-sequence:main`; pin a `sha-` or version tag in production), a Postgres 14 or newer reachable from the cluster, the ingress-nginx controller and a TLS secret named `opensequence-tls`. Adjust those names to your cluster. ## 1. Configuration [#1-configuration] ```yaml title="config.yaml" apiVersion: v1 kind: Secret metadata: name: opensequence type: Opaque stringData: SEQ_DB_DSN: postgres://oseq:CHANGE_ME@postgres.internal:5432/opensequence SEQ_ENCRYPTION_KEYS: kmvb1mvo3:CHANGE_ME_BASE64_32_BYTES --- apiVersion: v1 kind: Secret metadata: name: opensequence-admin # the operator token, mounted on the api only type: Opaque stringData: SEQ_ADMIN_TOKEN: CHANGE_ME --- apiVersion: v1 kind: ConfigMap metadata: name: opensequence data: SEQ_PUBLIC_URL: https://sequences.example.com SEQ_PORT: "8080" SEQ_QUEUE: postgres SEQ_LOG_LEVEL: info SEQ_CONCURRENCY: "8" SEQ_DB_POOL: "10" ``` Generate the values with `node dist/cli.js secrets new-key` (for `SEQ_ENCRYPTION_KEYS`) and `openssl rand -base64 32` (for `SEQ_ADMIN_TOKEN`). The operator token sits in its own Secret so that only the api pods receive it. Every other variable has a working default; see [Configuration](/docs/self-hosting/configuration). Keep a copy of `SEQ_ENCRYPTION_KEYS` outside the cluster, next to your database backups. A database restored without it has unreadable credentials. ## 2. The migration Job [#2-the-migration-job] ```yaml title="migrate.yaml" apiVersion: batch/v1 kind: Job metadata: name: opensequence-migrate-v0-1-0 # one Job per release: rename it for each image tag spec: backoffLimit: 2 ttlSecondsAfterFinished: 86400 template: metadata: labels: app.kubernetes.io/name: opensequence app.kubernetes.io/component: migrate spec: restartPolicy: Never securityContext: runAsNonRoot: true runAsUser: 100 runAsGroup: 101 seccompProfile: type: RuntimeDefault containers: - name: migrate image: ghcr.io/lguerberg/open-sequence:main command: ["node", "dist/cli.js", "migrate"] envFrom: - configMapRef: name: opensequence - secretRef: name: opensequence securityContext: allowPrivilegeEscalation: false capabilities: drop: ["ALL"] resources: requests: { cpu: 100m, memory: 128Mi } limits: { memory: 256Mi } ``` The Job applies the `seq` and `seq_auth` migrations and exits. Jobs are immutable, so give each release its own name. Running it against an up-to-date database is a no-op. If you prefer, drop the Job and add `SEQ_RUN_MIGRATIONS: "1"` to the ConfigMap: every pod then migrates before it opens its port, serialized by a row lock. ## 3. The api [#3-the-api] ```yaml title="api.yaml" apiVersion: apps/v1 kind: Deployment metadata: name: opensequence-api spec: replicas: 2 selector: matchLabels: app.kubernetes.io/name: opensequence app.kubernetes.io/component: api strategy: type: RollingUpdate rollingUpdate: { maxUnavailable: 0, maxSurge: 1 } template: metadata: labels: app.kubernetes.io/name: opensequence app.kubernetes.io/component: api spec: terminationGracePeriodSeconds: 40 securityContext: runAsNonRoot: true runAsUser: 100 runAsGroup: 101 seccompProfile: type: RuntimeDefault containers: - name: api image: ghcr.io/lguerberg/open-sequence:main env: - name: SEQ_ROLES value: api envFrom: - configMapRef: name: opensequence - secretRef: name: opensequence - secretRef: name: opensequence-admin ports: - name: http containerPort: 8080 readinessProbe: httpGet: { path: /readyz, port: http } periodSeconds: 10 timeoutSeconds: 3 failureThreshold: 3 livenessProbe: httpGet: { path: /healthz, port: http } initialDelaySeconds: 10 periodSeconds: 15 timeoutSeconds: 3 failureThreshold: 4 resources: requests: { cpu: 500m, memory: 512Mi } limits: { memory: 512Mi } securityContext: allowPrivilegeEscalation: false capabilities: drop: ["ALL"] --- apiVersion: v1 kind: Service metadata: name: opensequence-api spec: selector: app.kubernetes.io/name: opensequence app.kubernetes.io/component: api ports: - name: http port: 80 targetPort: http --- apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: opensequence-api annotations: nginx.ingress.kubernetes.io/proxy-body-size: 2m spec: ingressClassName: nginx tls: - hosts: [sequences.example.com] secretName: opensequence-tls rules: - host: sequences.example.com http: paths: - path: / pathType: Prefix backend: service: name: opensequence-api port: name: http --- apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: opensequence-api spec: minAvailable: 1 selector: matchLabels: app.kubernetes.io/name: opensequence app.kubernetes.io/component: api ``` ## 4. The worker [#4-the-worker] ```yaml title="worker.yaml" apiVersion: apps/v1 kind: Deployment metadata: name: opensequence-worker spec: replicas: 1 selector: matchLabels: app.kubernetes.io/name: opensequence app.kubernetes.io/component: worker template: metadata: labels: app.kubernetes.io/name: opensequence app.kubernetes.io/component: worker spec: terminationGracePeriodSeconds: 40 securityContext: runAsNonRoot: true runAsUser: 100 runAsGroup: 101 seccompProfile: type: RuntimeDefault containers: - name: worker image: ghcr.io/lguerberg/open-sequence:main env: - name: SEQ_ROLES value: worker envFrom: - configMapRef: name: opensequence - secretRef: name: opensequence ports: - name: health containerPort: 8080 readinessProbe: httpGet: { path: /readyz, port: health } periodSeconds: 15 timeoutSeconds: 3 failureThreshold: 3 livenessProbe: httpGet: { path: /healthz, port: health } initialDelaySeconds: 10 periodSeconds: 15 timeoutSeconds: 3 failureThreshold: 4 resources: requests: { cpu: 500m, memory: 512Mi } limits: { memory: 512Mi } securityContext: allowPrivilegeEscalation: false capabilities: drop: ["ALL"] ``` The worker has no Service. Its port answers `/healthz` and `/readyz`, but also the API routes, so nothing should route to it. No CronJob is needed: the scheduler runs inside the worker and replicas share it through lease rows in Postgres. ## Apply [#apply] ```bash kubectl apply -f config.yaml kubectl apply -f migrate.yaml kubectl wait --for=condition=complete job/opensequence-migrate-v0-1-0 --timeout=5m kubectl apply -f api.yaml -f worker.yaml kubectl rollout status deployment/opensequence-api kubectl rollout status deployment/opensequence-worker ``` Then create the first project over HTTP: ```bash curl -X POST https://sequences.example.com/v1/admin/projects \ -H "Authorization: Bearer $SEQ_ADMIN_TOKEN" -H "Content-Type: application/json" \ -d '{"slug":"acme","name":"Acme CRM"}' ``` Continue with [Install](/docs/self-hosting/install), from "Register the providers". ## Why these settings [#why-these-settings] | Setting | Reason | |---|---| | `runAsUser: 100`, `runAsGroup: 101` | the image runs as the `oseq` user (uid 100, gid 101). The image names the user, not a number, so `runAsNonRoot` needs the uid spelled out | | readiness on `/readyz`, liveness on `/healthz` | `/readyz` fails while the database is unreachable and, on the worker, when the scheduler has not run a job in 2 minutes. Liveness only checks that the process is up, so a database outage does not restart every pod | | `terminationGracePeriodSeconds: 40` | on `SIGTERM` the api finishes in-flight requests and the worker finishes in-flight messages for up to 30 seconds; the process exits within 35 | | `maxUnavailable: 0` and the PodDisruptionBudget | the api keeps answering provider webhooks and unsubscribe clicks during rollouts and node drains | | `proxy-body-size: 2m` | the API accepts bodies up to 2 MB; ingress-nginx refuses more than 1 MB by default | | `500m` CPU, `512Mi` memory | a starting point for both roles. See [Scaling](/docs/self-hosting/scaling) | ## Notes [#notes] - **Upgrades.** Push the new image, apply a new migration Job, wait for it, then update the image in both Deployments. See [Upgrades](/docs/self-hosting/upgrades). - **Webhook receivers** must be public HTTPS. A `*.svc.cluster.local` address or a private IP is refused as a webhook endpoint. - **Client addresses.** The api trusts `X-Forwarded-For` for its per-IP rate limit; ingress-nginx sets it. Do not expose the pods another way. - **Validated** with `kubeconform -strict` against Kubernetes 1.30 schemas. # Deploy on Qovery (https://docs.opensequence.dev/docs/self-hosting/deploy-qovery) How to run OpenSequence on Qovery from the published image: a managed Postgres, a migration job, and api and worker applications on the same tag. This guide sets up OpenSequence in one Qovery environment. You get a managed Postgres, a job that migrates on every deploy, a public `api` application and a private `worker` application, all from the published image `ghcr.io/lguerberg/open-sequence`. ```mermaid flowchart LR subgraph ENV["Qovery environment"] DB[("PostgreSQL")] MIG["migrate, lifecycle job"] --> DB API["api, public 8080"] --> DB WRK["worker, private"] --> DB end NET["Internet"] -->|HTTPS| API ``` ## What you create [#what-you-create] | Service | Type | Source | Key settings | |---|---|---|---| | `postgres` | Database, PostgreSQL 14 or newer | managed by Qovery | private | | `migrate` | Lifecycle job, runs on deploy | `ghcr.io/lguerberg/open-sequence`, one pinned tag | command `node dist/cli.js migrate` | | `api` | Application | `ghcr.io/lguerberg/open-sequence`, one pinned tag | `SEQ_ROLES=api`, port 8080 public | | `worker` | Application | `ghcr.io/lguerberg/open-sequence`, one pinned tag | `SEQ_ROLES=worker`, port 8080 private | No cronjob is needed. The scheduler runs inside the worker and coordinates replicas with lease rows in the database. ## Variables [#variables] Generate the two secrets once, on your machine or in any built image: ```bash docker run --rm ghcr.io/lguerberg/open-sequence:main node dist/cli.js secrets new-key # SEQ_ENCRYPTION_KEYS openssl rand -base64 32 # SEQ_ADMIN_TOKEN ``` Set shared values at the environment level so all three services read them, and role values on each service: | Variable | Scope | Secret | Value | |---|---|---|---| | `SEQ_DB_DSN` | environment | yes | an alias of the database's internal connection URL (a built-in variable named like `QOVERY_POSTGRESQL_Z…_DATABASE_URL_INTERNAL`) | | `SEQ_ENCRYPTION_KEYS` | environment | yes | the `id:base64` entry from `secrets new-key` | | `SEQ_PUBLIC_URL` | environment | no | the api's public HTTPS URL, such as `https://sequences.example.com` | | `SEQ_ADMIN_TOKEN` | `api` | yes | the operator token | | `SEQ_ROLES` | `api` and `worker` | no | `api` on one, `worker` on the other | Every other variable has a working default. See [Configuration](/docs/self-hosting/configuration). Do not set `SEQ_RUN_MIGRATIONS`: the job migrates. Copy `SEQ_ENCRYPTION_KEYS` somewhere outside Qovery as well. A database backup restored without it has unreadable credentials. ## Steps [#steps] In the environment, add a PostgreSQL database, version 14 or newer, in managed mode for production. Keep it private. In the organization settings, add a container registry of type GitHub Container Registry, with the URL `https://ghcr.io` and a GitHub classic personal access token with the `read:packages` scope. Pick one tag for all three services. `main` follows every push to `main`; `sha-` pins a build; a release adds ``, `.` and `latest` (amd64 and arm64). Pin `sha-` or a version in production. Add a lifecycle job from that registry, image `lguerberg/open-sequence` and your tag: - Trigger it on the environment's start (deploy) event, with the command `node dist/cli.js migrate`. To run your own changes, build from your fork instead: the Dockerfile at `apps/server/Dockerfile`, root path `/` (it copies the whole workspace), for the job and both applications. Every other setting on this page stays the same. The command applies the `seq` and `seq_auth` migrations and exits. It is safe to run on every deploy: an up-to-date database prints `already up to date`. Add an application from the same registry, image and tag. - Port `8080`, publicly exposed. Add your custom domain and set `SEQ_PUBLIC_URL` to it. - Liveness probe: HTTP `GET /healthz` on 8080. - Readiness probe: HTTP `GET /readyz` on 8080. - Resources to start: 500 mCPU and 512 MB. Two instances for availability. - `SEQ_ROLES=api` and `SEQ_ADMIN_TOKEN` as a secret. Clone the api application, then change: - `SEQ_ROLES=worker`, and remove `SEQ_ADMIN_TOKEN`. - Port 8080 not publicly exposed. The worker answers the API routes on it too, so it must stay private. - Keep the same probes: on the worker, `/readyz` also fails when the scheduler has not run a job in 2 minutes. - One instance to start. - A termination grace period of at least 40 seconds, in the advanced settings. The worker finishes in-flight messages for up to 30 seconds after `SIGTERM`. In the environment's deployment pipeline, put the services in stages: database first, then `migrate`, then `api`, then `worker`. A failed migration then stops the deploy before any application changes. Deploy the environment. ```bash curl -X POST https://sequences.example.com/v1/admin/projects \ -H "Authorization: Bearer $SEQ_ADMIN_TOKEN" -H "Content-Type: application/json" \ -d '{"slug":"acme","name":"Acme CRM"}' ``` The response holds the project's first `admin` key, shown once. Continue with [Install](/docs/self-hosting/install), from "Register the providers". ## Check it [#check-it] ```bash curl https://sequences.example.com/readyz # {"ok":true} curl https://sequences.example.com/v1/admin/engine/health -H "Authorization: Bearer $SEQ_ADMIN_TOKEN" # "jobs": { "plan": "…", … } recent timestamps mean the worker is running ``` ## Notes [#notes] - **Scaling.** Add api instances on CPU. Add worker instances when queue depth grows; replicas are safe. See [Scaling](/docs/self-hosting/scaling). - **Webhook receivers.** OpenSequence only delivers webhooks to public HTTPS addresses. A receiver in the same Qovery environment needs a public domain; its internal address is refused. - **Upgrades.** Change the tag on the three services (or let `main` move) and redeploy: the pipeline runs migrate, api, worker in order. For a release that removes something, read [Upgrades](/docs/self-hosting/upgrades) first. # Install OpenSequence in production (https://docs.opensequence.dev/docs/self-hosting/install) How to install for production: build the one image, point it at your Postgres, run the api and worker roles with real secrets, create the first project. This page takes you from a clone to a production install: one Docker image, a Postgres you own, an `api` role and a `worker` role. To try it on a laptop with mock providers, run `docker compose up` from a clone, as in the [Quickstart](/docs/get-started/quickstart). ```mermaid flowchart LR APP["Your application"] -->|HTTPS, project key| API["api role, public"] EXT["Allo, mail clients"] -->|webhooks, opt-out links| API API --> PG[("Postgres")] W["worker role, private"] --> PG W -->|send, poll| P["Mail servers, Allo, Attio"] W -->|signed webhooks| APP ``` ```bash docker pull ghcr.io/lguerberg/open-sequence:main ``` Every push to `main` publishes `ghcr.io/lguerberg/open-sequence:main` and `:sha-` (amd64). A release tag `v*` publishes `:`, `:.` and `:latest` for amd64 and arm64. Pin a `sha-` or version tag in production so a redeploy never changes the code under you. To build it yourself instead: `docker build -f apps/server/Dockerfile -t opensequence/server .` from a clone. The image runs Node 22 on Alpine as the non-root user `oseq` (uid 100, gid 101). It starts `node dist/main.js`, listens on port 8080 and has a Docker `HEALTHCHECK` on `/healthz`. `NODE_ENV=production` is baked in. The operator CLI ships inside as `dist/cli.js`. Give OpenSequence its own database on Postgres 14 or newer. It needs no extensions. It creates and owns two schemas, `seq` and `seq_auth`, so it can share a database such as Supabase's. A transaction pooler is fine. See [Database](/docs/self-hosting/database). ```bash docker run --rm ghcr.io/lguerberg/open-sequence:main node dist/cli.js secrets new-key # kmvb1mvo3:Y2ItLFqx5NZ9+b+jHrY01i2ZrnGE+pnxdoeMna58BzM= -> SEQ_ENCRYPTION_KEYS openssl rand -base64 32 # -> SEQ_ADMIN_TOKEN ``` `SEQ_ENCRYPTION_KEYS` encrypts every stored secret: each sender's SMTP and IMAP passwords, the Allo and Attio keys and the webhook signing secrets. `SEQ_ADMIN_TOKEN` is the operator token that creates projects. Back up `SEQ_ENCRYPTION_KEYS` with the database. A database restored without the key that encrypted it has unreadable credentials, and every one must be entered again. ```bash docker run -d --name oseq-api -p 8080:8080 \ -e SEQ_ROLES=api \ -e SEQ_DB_DSN=postgres://oseq:secret@db.internal:5432/opensequence \ -e SEQ_ENCRYPTION_KEYS='kmvb1mvo3:…' \ -e SEQ_ADMIN_TOKEN='…' \ -e SEQ_PUBLIC_URL=https://sequences.example.com \ -e SEQ_RUN_MIGRATIONS=1 \ ghcr.io/lguerberg/open-sequence:main ``` With `SEQ_RUN_MIGRATIONS=1` the process applies the `seq` and `seq_auth` migrations before it opens its port. Each migration runs in its own transaction behind a row lock, so replicas that start together do not race. If a migration fails, the process exits with code 1. To migrate from a pipeline instead, see [Upgrades](/docs/self-hosting/upgrades). `SEQ_PUBLIC_URL` is the HTTPS origin the outside world reaches. Allo posts webhooks to it, and every email's unsubscribe link points at it. It defaults to `http://localhost:8080`, so always set it in production. The service speaks plain HTTP: put a TLS terminator in front. ```bash docker run -d --name oseq-worker \ -e SEQ_ROLES=worker \ -e SEQ_DB_DSN=postgres://oseq:secret@db.internal:5432/opensequence \ -e SEQ_ENCRYPTION_KEYS='kmvb1mvo3:…' \ -e SEQ_PUBLIC_URL=https://sequences.example.com \ ghcr.io/lguerberg/open-sequence:main ``` The worker runs the scheduler and the queue consumers. It needs no `SEQ_ADMIN_TOKEN`. It still listens on `SEQ_PORT` for `/healthz` and `/readyz`, but the API routes answer on that port too, so never expose it. It needs the same `SEQ_PUBLIC_URL` because it writes the unsubscribe links into emails. For a small install, one container with `SEQ_ROLES=all` does both jobs. You can split it later without a migration. ```bash docker exec oseq-api node dist/cli.js projects create acme --name "Acme CRM" # or over HTTP with the operator token curl -X POST https://sequences.example.com/v1/admin/projects \ -H "Authorization: Bearer $SEQ_ADMIN_TOKEN" -H "Content-Type: application/json" \ -d '{"slug":"acme","name":"Acme CRM"}' ``` Both return the project and its first `admin` API key, shown once. Keep that key for configuration. Give your application a narrower key: ```bash curl -X POST https://sequences.example.com/v1/api-keys \ -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" \ -d '{"name":"app","scopes":["enroll"]}' ``` With mock providers off, nothing is sent until the project has credentials. Each one is stored encrypted and is write-only. | What you want | What to register | |---|---| | Email | each sender's SMTP and IMAP settings, Gmail included: [Email](/docs/modules/email) | | SMS and call tasks | one Allo API key per project, then a number and user per sender: [Allo](/docs/modules/sms/allo) | | `crm.*` conditions | one Attio API key per project: [Attio](/docs/modules/crm/attio) | `GET /v1/project` shows the inbound webhook URL (`webhook_urls.allo`), built from `SEQ_PUBLIC_URL`. ## Check it is healthy [#check-it-is-healthy] | Path | Answers | |---|---| | `GET /healthz` | `{ "ok": true }` while the process runs. Use it for liveness | | `GET /readyz` | `503` when the database does not answer. On `worker` and `all`, also `503` until the scheduler has run a job, and whenever it has not run one in the last 2 minutes | | `GET /v1/admin/engine/health` | queue depths and the last run of every scheduler job, with the operator token | | `GET /v1/engine/health` | the same plus the project's flags, with an `admin` key | Logs are Pino JSON on stdout. See [Observability](/docs/self-hosting/observability). ## Next [#next] Every SEQ_ variable, its default and when it is required. What to lock down before you expose the API. Two services from one Dockerfile and a managed Postgres. One fly.toml with api and worker process groups. Manifests for both roles, probes and a migration Job. # Monitoring logs, health and alerts (https://docs.opensequence.dev/docs/self-hosting/observability) How to watch a running OpenSequence: JSON logs, the health endpoints, the alerts worth setting, runs that need review, and what is not built yet. OpenSequence reports through structured logs and a few health endpoints. There is no metrics endpoint, so this page shows what to watch and where to read it. ```bash title="curl" curl $SEQ/v1/admin/engine/health -H "Authorization: Bearer $SEQ_ADMIN_TOKEN" # {"paused":false,"disabled_channels":[], # "queues":[{"queue":"seq_email","depth":3,"oldestMs":1200}], # "jobs":{"plan":"2026-10-16T14:09:44.957Z","signals":"…","poll":"…","reap":"…","webhooks":"…","retention":"…"}} curl $SEQ/v1/engine/health -H "Authorization: Bearer $ADMIN_KEY" # {"flags":{},"queues":[…],"jobs":{…},"paused":false} ``` ```ts title="TypeScript" import { OpenSequence, OpenSequenceAdmin } from '@opensequence/sdk'; const admin = new OpenSequenceAdmin({ baseUrl: SEQ, adminToken: process.env.SEQ_ADMIN_TOKEN! }); const platform = await admin.engineHealth(); const oseq = new OpenSequence({ baseUrl: SEQ, apiKey: process.env.ADMIN_KEY! }); const project = await oseq.project.health(); ``` ## Health endpoints [#health-endpoints] | Where | What it tells you | |---|---| | `GET /healthz` | the process is up. Use it for liveness | | `GET /readyz` | the database answers; on `worker` and `all`, the scheduler also ran a job in the last 2 minutes. `503` with a `reason` otherwise | | `GET /v1/admin/engine/health` | platform-wide: `paused`, `disabled_channels`, `queues` (depth and oldest ready message per queue), `jobs` (last run of each scheduler job). Operator token | | `GET /v1/engine/health` | the same plus the project's `flags`. `admin` key. Queue depths are platform-wide numbers | | `node dist/cli.js health` | the queues and jobs, from inside the container | ## Logs [#logs] Pino JSON on stdout, at the level set by `SEQ_LOG_LEVEL` (default `info`). Outside `NODE_ENV=production` they are pretty-printed when `pino-pretty` is installed (a source checkout); the image does not ship it, so containers always log JSON. - Every request line carries `reqId`, the same `req_…` id the API returns in `meta.request_id`. Search by it when a client reports an error. - Engine lines carry the ids they touched, such as `projectId`, `enrollmentId`, `runId`, `contactId`, `endpointId` or `deliveryId`, so one search follows a contact through the system. - Every scheduler job logs one line per run, `job plan ran`, with its counts (`claimed`, `advanced`, `requeuedRuns`, …) and `durationMs`. A failing job logs `job failed` with the error. - The `Authorization` header and fields named `api_key`, `client_secret`, `secret` and `refresh_token` are redacted. The `plan` job runs every 5 seconds, so `info` is chatty. Use `warn` if you only want problems. ## Alerts worth setting [#alerts-worth-setting] | Signal | What it means | |---|---| | `/readyz` failing on a worker | the scheduler stopped, or the database is unreachable | | a queue's `depth` growing for ten minutes | the worker is behind, or a provider is failing | | the `plan` job's last run older than a minute | no planner is running | | `run.needs_review` webhooks | a text with an unknown outcome waits for a human | | `run.failed`, or `enrollment.paused` with `step_failed` | a step ran out of retries with no `failed` branch wired | | `endpoint.disabled` | your own webhook receiver has been down for three days, or its secret can no longer be decrypted | | `sender.channel_status` with `credentials_needed` | a sender must save their mailbox settings again | | `5xx` from the API, `INTERNAL_ERROR` in responses | search the logs by the `request_id` | Oldest-due lag has no endpoint; [Scaling](/docs/self-hosting/scaling) shows the SQL to read it. ## Runs that need review [#runs-that-need-review] A text whose outcome Allo could not confirm is never retried, because a retry could text the person twice. The run is marked `needs_review`, a `run.needs_review` webhook goes out, and the enrollment stops at that step. Today you resolve it by hand. Check in Allo whether the text left, then exit the enrollment with `POST /v1/enrollments/{id}/exit`. Re-enrolling starts the sequence again from the start. The `needs-review` list and resolve endpoints described in the architecture document are not built yet. ## Not built yet [#not-built-yet] - No Prometheus `/metrics` endpoint. `SEQ_METRICS` is accepted and ignored. - No per-channel circuit breaker. - An incoming `X-Request-Id` header is not propagated; the service makes its own `req_…` id. # Scaling api and worker replicas (https://docs.opensequence.dev/docs/self-hosting/scaling) How many api and worker replicas to run, the knobs that raise throughput, what really limits sending, and how to stop the engine safely. The `api` and `worker` roles scale on their own, and several replicas of each are safe. Read this page when you size a deployment or when a queue falls behind. | Setting | `api` | `worker` | |---|---|---| | Replicas | 1 to N; scale on CPU or request rate | 1 to N; scale on queue depth or oldest-due lag | | Resources to start | 500 mCPU, 512 MB | 500 mCPU, 512 MB | | Port 8080 | public, behind TLS | private: health only | | On `SIGTERM` | stops accepting, finishes in-flight requests, exits | stops reading queues, waits up to 30 s for in-flight messages, exits | The whole shutdown is capped at 35 seconds, after which the process exits with code 1. Give the platform a grace period of at least 40 seconds. Work left unfinished reappears when its visibility timeout ends. ## Replicas are safe [#replicas-are-safe] Two workers never send the same step twice: - The planner claims due enrollments with `FOR UPDATE SKIP LOCKED`, so two planners never take the same one. - An executor owns a run while it works on it (the enrollment's `owner_run_id`), and every write re-checks state under a row lock. - Each scheduler job takes a lease row in `seq.job_locks` before it runs, so one replica at a time runs a given job. The API is stateless apart from one per-replica cache: the rate-limit counter. ## The knobs [#the-knobs] | Knob | Default | Raise it when | |---|---|---| | `SEQ_CONCURRENCY` | 8 messages in flight per queue per replica (max 64) | queues have depth and the database has headroom | | worker replicas | 1 | the same, or for availability | | `SEQ_DB_POOL` | 10 connections per process (max 100) | you raise `SEQ_CONCURRENCY`: the pool serves the in-flight messages and the scheduler | | planner claim | 50 per sender, 500 per tick, every 5 seconds | thousands of enrollments come due in the same second. These are engine constants, not variables | | `SEQ_QUEUE=redis` | `postgres` | the queue table itself is hot, with many thousands of messages a minute. Most installs never need it | ## What really limits throughput [#what-really-limits-throughput] Usually not the engine. Thirty sequences with about 500 active contacts and a step every one to three days is 5,000 to 15,000 steps a day, a few hundred an hour at peak. One worker and one Postgres handle that easily. The binding limits are outside: each sender's email `daily_limit` (30 by default, with a 60-second gap between sends), the SMS `daily_limit` (100 by default), and your SMS carrier registration. More capacity means more senders or higher caps, not more replicas. ## Measure the lag [#measure-the-lag] Queue depth comes from the health endpoints (`GET /v1/admin/engine/health`). Oldest-due lag, how long enrollments wait past their `next_run_at`, has no endpoint yet; read it from the database: ```sql select now() - min(next_run_at) as oldest_due_lag from seq.enrollments where status = 'active' and owner_run_id is null and next_run_at <= now(); ``` Keep it under 2 minutes. If it grows while queues are empty, the planner is not running: check the `plan` job in the health output. ## Stopping the engine [#stopping-the-engine] | Action | Effect | |---|---| | Scale the worker to zero | hard stop. Steps, signals and deliveries wait in the tables and resume when a worker returns. Nothing is lost | | `SEQ_PAUSED=1` on the workers | the planner claims nothing and executors defer every send by 5 minutes. Signals are still recorded and webhooks still delivered. Needs a restart to change | | `SEQ_DISABLED_CHANNELS=sms` on the workers | executors defer every send on that channel by 5 minutes; the planner keeps going. Needs a restart | | project flag `global` off | executors defer that project's sends by 5 minutes, with no restart: `PUT /v1/engine/flags/global` with `{ "value": false }`. `channel:sms` does the same for one channel | # Upgrading and rolling back (https://docs.opensequence.dev/docs/self-hosting/upgrades) How to move a running install to a new image: back up, migrate once, roll the api and worker, and roll back or stop sending safely if something breaks. An upgrade is a new image plus the migrations it carries. This page gives the order that keeps sends flowing, how to roll back, and how to go live the first time. ```bash # 1. Back up the database (keep SEQ_ENCRYPTION_KEYS with it) pg_dump --format=custom --schema=seq --schema=auth "$SEQ_DB_DSN" > before-upgrade.dump # 2. Apply the new image's migrations, once docker run --rm -e SEQ_DB_DSN -e SEQ_ENCRYPTION_KEYS \ ghcr.io/lguerberg/open-sequence:NEW node dist/cli.js migrate # applied 1 migration(s) or already up to date # 3. Roll the api, then the worker, to the new image ``` ## How migrations run [#how-migrations-run] Every image ships the SQL migrations for the `seq` and `seq_auth` schemas. There are two ways to apply them, and both are safe to repeat: | Way | When to use it | |---|---| | `node dist/cli.js migrate` (`oseq migrate`) as its own step | production with several replicas: a pipeline step, a Fly `release_command`, a Kubernetes Job. A failed migration stops the release before any replica changes | | `SEQ_RUN_MIGRATIONS=1` on the processes | a single container, or when you have no release step. Every process applies the migrations before it opens its port; replicas starting together wait on a row lock | Each migration runs in one transaction and is recorded by tag and hash. A failed one rolls back and leaves the database as it was. There are no down migrations: going back means restoring the backup. ## Rolling the roles [#rolling-the-roles] Old and new replicas run side by side during a rolling deploy. That is safe because the database arbitrates: runs are owned, claims use `SKIP LOCKED`, and every write re-checks state under a row lock. 1. Migrate (step 2 above). 2. Roll the `api`. Its readiness probe (`/readyz`) holds traffic until the new replica reaches the database. 3. Roll the `worker`. Each old worker finishes its in-flight messages for up to 30 seconds on `SIGTERM`; whatever it leaves reappears for the new workers when its visibility timeout ends. The design rule is expand then contract: a migration adds columns and tables first, and a later release removes what is no longer used, so the old code keeps working against the new schema. When one release adds a capability that both roles share, deploy the role that adds it first. Not every migration so far has been additive. The engine's migration `0002` dropped tables, a column and an enum value in the same release that stopped using them, so older replicas fail against it. For a release whose notes say it removes something, scale the worker to zero, migrate, then start the new image for both roles. The public API only grows: new fields and endpoints are added, and nothing is removed or repurposed without a new version path. Every sequence definition so far is `schema_version: 1`. ## Rolling back [#rolling-back] Redeploy the previous image of the role at fault. The older image ignores migrations it does not know, so it boots against the newer schema, and an additive migration leaves it working. If a migration damaged data, restore the backup into a new database and point both roles at it: ```bash createdb -h db.internal opensequence_restore pg_restore --dbname=postgres://oseq:…@db.internal:5432/opensequence_restore before-upgrade.dump ``` ## Stopping sends in an emergency [#stopping-sends-in-an-emergency] | Lever | Speed | Effect | |---|---|---| | project flag `global` off | immediate, no deploy | `PUT /v1/engine/flags/global` with `{ "value": false }`: that project's sends are deferred | | `SEQ_PAUSED=1` on the workers | one restart | the planner stops and every send is deferred, for all projects | | scale the worker to zero | one deploy | hard stop; nothing is lost, everything resumes when a worker returns | See [Scaling](/docs/self-hosting/scaling) for what each one leaves running. ## The first go-live [#the-first-go-live] 1. Provision Postgres and run `migrate`. 2. Deploy the `api`. Create the project and its key, register the provider credentials and your webhook endpoint. 3. Turn the project's `global` flag off, then deploy the `worker`. 4. Point your application at the service, behind your own feature flag. 5. Enroll one contact with `"mode": "dry_run"` and check the journey. Then turn `global` on and enroll a small batch. A dry run is an enrollment with `mode: "dry_run"`: it runs every wait and condition and sends nothing. # Receiving webhooks (https://docs.opensequence.dev/docs/webhooks/events) How to register a webhook endpoint, which events exist, what the payloads carry, and how ordering and idempotency work. ```bash title="curl" curl -X POST $SEQ/v1/webhooks -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" \ -d '{"url":"https://app.acme.com/hooks/opensequence","event_types":["enrollment.exited","task.created","signal.received"]}' # {"endpoint":{"id":"wep_…","url":"…","event_types":[…],"status":"active"},"secret":"whsec_…"} the secret is shown once ``` ```ts title="TypeScript" const { endpoint, secret } = await oseq.webhooks.create({ url: 'https://app.acme.com/hooks/opensequence', event_types: ['enrollment.exited', 'task.created', 'signal.received'], }); // store `secret` next to the endpoint id, encrypted; it is needed to verify deliveries and is never shown again ``` The service tells your backend what happened with the delivery guarantees you expect from Svix: signed, retried for three days, ordered per enrollment, replayable. Endpoints need the `admin` scope. `event_types` is a list of the types below or `["*"]` (the default). URLs must be `https`, carry no credentials and resolve to a public address (`422 UNSAFE_URL`); they are re-resolved at every delivery. ## The catalogue [#the-catalogue] | Event | When | |---|---| | `enrollment.created` | after a successful enroll, one per contact | | `enrollment.exited` | an exit by rule or by API, with `exit_reason` and the `signal` that caused it. Two exits carry the enrollment **id** instead of the object: a contact erased with `DELETE /v1/contacts/{id}` (`contact: { id, external_id }`) and a sequence archived with `exit_active` (`contact: { id }`) | | `enrollment.completed` | an `end` node or an unwired transition | | `enrollment.paused`, `enrollment.resumed` | a pause or resume, any cause, with `pause_reason` and `paused_until` | | `run.done` | an outreach step was sent: `run` (`id`, `node_id`, `node_type`, `channel`, `action`, `status`, `touch_number`, `provider`, `provider_ref`, `branch`, `enrollment`) and `enrollment`. The subject and body are not in it: read the [journey](/docs/concepts/enrollment/where-a-contact-is) and take the message whose `runId` is `run.id` | | `run.skipped`, `run.failed`, `run.needs_review` | a step did not execute, with `run` and a `reason` or an `error` | | `task.created` | a task for a sender appeared, with the rendered `task` | | `task.expired` | a task closed without the sender: `task` is the full task when an exit cancelled it, but only the id (`task: "tsk_…"`) when its timer expired | | `signal.received` | any signal after processing, with `signal` (`kind`, `channel`, `source`, `attribution`, `attributed_run`) and `contact` (`id`, `external_id`, `email`, `phone`, `first_name`, `last_name`). `kind` is `reply`, `bounce`, `complaint`, `opt_out`, `ooo`, `task_completed`, `call_connected`, `meeting_booked` or `contact_suppressed` | | `sender.channel_status` | a channel changed status (`credentials_needed`, `restricted`, back to `active`) | | `endpoint.disabled` | an endpoint was disabled after three days of failures | The generated reference lists every payload field: [Webhook events](/reference/webhook-events). `GET /v1/schema/events` returns the type list. Payloads are snake_case, like request bodies, and reference other records by id: `data.enrollment` is a summary (`id`, `sequence`, `version`, `contact`, `sender`, `status`, `mode`, `current_node_id`, `exit_reason`, `pause_reason`, `touch_count`, `replied_at`, `meeting_booked_at`, `enrolled_at`, `finished_at`, `seq`), not the full record, and `data.contact` is present only on `signal.received` (and, reduced to ids, on the two exits noted above). Any other event finds its contact through `data.enrollment.contact` or `data.task.contact`, both contact ids; `GET /v1/contacts/{id}` has the rest. ## The payload [#the-payload] ```http POST /hooks/opensequence HTTP/1.1 content-type: application/json user-agent: OpenSequence-Webhooks/1 webhook-id: evt_01J9… webhook-timestamp: 1760346000 webhook-signature: v1,K5oZfzN95Z9UVu1EsfQmfVuOm3Q… { "id": "evt_01J9…", "type": "enrollment.exited", "project": "prj_01J9…", "occurred_at": "2026-10-13T09:00:00.000Z", "data": { "enrollment": { "id": "enr_01J9…", "sequence": "seq_…", "version": "ver_…", "contact": "ctc_…", "sender": "snd_…", "status": "exited", "exit_reason": "replied", "touch_count": 2, "replied_at": "…", "seq": 7 }, "exit_reason": "replied", "signal": "sig_01J9…" } } ``` Answer any `2xx` within 10 seconds. Anything else, a timeout or a connection error counts as a failure and the delivery is retried ([Retries and recovery](/docs/webhooks/retries-and-recovery)). Verify the signature before trusting the body ([Verifying](/docs/webhooks/verifying)). ## Ordering and idempotency [#ordering-and-idempotency] - **Idempotent by `id`.** A delivery can arrive more than once (a retry after your `2xx` was lost). Keep the ids you processed, or make the handler idempotent on the entity (`data.enrollment.id`, `data.task.id`). - **Ordered per enrollment, not globally.** Deliveries for the same endpoint and enrollment are attempted one at a time in creation order; the next waits until the previous succeeded or gave up, so a failing endpoint only blocks itself. Events that carry an enrollment also carry `data.enrollment.seq`, a per-enrollment counter, so you can discard a stale event that arrives after a newer one through a replay. - **Processing is asynchronous.** Events are written in the same transaction as the change they describe and delivered by the worker within seconds. ## Endpoint management [#endpoint-management] | Call | Does | |---|---| | `GET /v1/webhooks`, `GET /v1/webhooks/{id}` | list and read (never the secret) | | `PATCH /v1/webhooks/{id}` | change `url` or `event_types` | | `DELETE /v1/webhooks/{id}` | delete the endpoint and its deliveries | | `POST /v1/webhooks/{id}/rotate-secret` | a new secret, shown once; deliveries from this moment are signed with it, there is no overlap window, so accept both secrets while you switch ([how](/docs/webhooks/verifying#rotation)) | | `POST /v1/webhooks/{id}/enable` | re-enable a disabled endpoint and replay what was held | | `POST /v1/webhooks/{id}/recover { since }` | re-send every delivery that failed for good since a time | | `GET /v1/webhooks/{id}/deliveries` | the log: status, attempts, last status code and error, the payload | | `POST /v1/webhooks/deliveries/{id}/replay` | re-send one delivery | No endpoint? Every list endpoint accepts `updated_since`, so you can poll instead. # Webhooks to your app: receive signed events (https://docs.opensequence.dev/docs/webhooks) How to register a webhook endpoint in OpenSequence, verify the Standard Webhooks signature with or without the SDK, dedupe by event id and handle retries. Webhooks tell your backend what happened: sent, replied, exited, task created. Register one HTTPS endpoint, then verify every delivery. ## What it gives you [#what-it-gives-you] - Signed events for every enrollment, step, task and inbound reply or opt-out. - Retries with backoff, ordering per enrollment, and replay of anything that failed. ## What you need [#what-you-need] - A public HTTPS URL on your backend that reads the raw request body. - An OpenSequence `admin` key. ## Steps [#steps] ```bash title="curl" curl -X POST $SEQ/v1/webhooks -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" \ -d '{"url":"https://app.example.com/hooks/opensequence","event_types":["*"]}' # {"success":true,"data":{"endpoint":{"id":"wep_…",…},"secret":"whsec_…"}} ``` ```ts title="TypeScript" const { endpoint, secret } = await oseq.webhooks.create({ url: 'https://app.example.com/hooks/opensequence', event_types: ['*'] }); ``` The secret is shown once. Store it encrypted. `event_types` is a list of event names, or `["*"]` (the default). ```ts title="With the SDK" import express from 'express'; import { verifyWebhook, WebhookVerificationError } from '@opensequence/sdk'; app.post('/hooks/opensequence', express.raw({ type: 'application/json' }), async (req, res) => { try { const event = verifyWebhook({ secret: process.env.OSEQ_WEBHOOK_SECRET!, headers: req.headers, body: req.body }); if (await alreadyHandled(event.id)) return res.sendStatus(200); // dedupe by event id await handle(event); res.sendStatus(200); } catch (err) { if (err instanceof WebhookVerificationError) return res.status(401).send(err.code); res.sendStatus(500); // OpenSequence retries } }); ``` ```ts title="Without the SDK" import { createHmac, timingSafeEqual } from 'node:crypto'; function verify(secret: string, headers: Record, rawBody: string) { const id = headers['webhook-id'], ts = headers['webhook-timestamp'], sigs = headers['webhook-signature']; if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) throw new Error('stale'); const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64'); const expected = Buffer.from(createHmac('sha256', key).update(`${id}.${ts}.${rawBody}`).digest('base64')); const ok = sigs.split(' ').some((s) => { const got = Buffer.from(s.replace(/^v1,/, '')); return got.length === expected.length && timingSafeEqual(got, expected); }); if (!ok) throw new Error('bad signature'); return JSON.parse(rawBody); } ``` Use the raw body: a parsed and re-serialized body will not verify. Answer any `2xx` within 10 seconds. ## The events [#the-events] | Event | When | |---|---| | `enrollment.created` | A contact was enrolled. | | `enrollment.exited` | It left early, with `exit_reason`. | | `enrollment.completed` | It reached the end. | | `enrollment.paused`, `enrollment.resumed` | It was paused or resumed, with `pause_reason`. | | `run.done` | A step ran, such as an email sent. | | `run.skipped`, `run.failed`, `run.needs_review` | A step did not run, with a reason. | | `task.created`, `task.expired` | A task appeared, or closed without the rep. | | `signal.received` | A reply, bounce, opt-out, out-of-office, booked meeting or connected call arrived. | | `sender.channel_status` | A mailbox or number changed status, for example `credentials_needed`. | | `endpoint.disabled` | An endpoint was disabled after three days of failures. | Every payload field: [Webhook events](/reference/webhook-events). ## Check it works [#check-it-works] Enroll a test contact, then read `GET /v1/webhooks/{id}/deliveries` (`oseq.webhooks.deliveries(id)`). Each delivery shows its status, attempts and your last response code. ## Retries and duplicates [#retries-and-duplicates] A non-`2xx`, a timeout or a connection error is retried: nine attempts over about a day and a half. Deliveries for one enrollment arrive in order. A delivery can arrive twice, so dedupe by `event.id`. Replay one with `POST /v1/webhooks/deliveries/{id}/replay`, or everything that failed since a time with `POST /v1/webhooks/{id}/recover`. Details: [Retries and recovery](/docs/webhooks/retries-and-recovery). ## Common errors [#common-errors] | Error | Fix | |---|---| | `422 UNSAFE_URL` | The URL must be `https`, carry no credentials and resolve to a public address. | | `WebhookVerificationError` `NO_MATCHING_SIGNATURE` | You verified a parsed body, or used an old secret. Verify the raw bytes with the current secret. | | `TIMESTAMP_OUT_OF_TOLERANCE` | Your server's clock is off by more than five minutes. | | Endpoint `status: "disabled"` | It failed for three days. Fix it, then `POST /v1/webhooks/{id}/enable` replays what was held. | # Webhook retries and recovery (https://docs.opensequence.dev/docs/webhooks/retries-and-recovery) How failed webhook deliveries are retried, when an endpoint is disabled, how to recover and replay, and how to read the deliveries log. ```bash title="curl" curl "$SEQ/v1/webhooks/wep_01J9…/deliveries?limit=50" -H "Authorization: Bearer $ADMIN_KEY" curl -X POST $SEQ/v1/webhooks/wep_01J9…/recover -H "Authorization: Bearer $ADMIN_KEY" -H "Content-Type: application/json" -d '{"since":"2026-10-12T00:00:00Z"}' curl -X POST $SEQ/v1/webhooks/wep_01J9…/enable -H "Authorization: Bearer $ADMIN_KEY" curl -X POST $SEQ/v1/webhooks/deliveries/wdl_01J9…/replay -H "Authorization: Bearer $ADMIN_KEY" ``` ```ts title="TypeScript" const { items } = await oseq.webhooks.deliveries('wep_01J9…', { limit: 50 }); await oseq.webhooks.recover('wep_01J9…', { since: new Date('2026-10-12T00:00:00Z') }); // { replayed: n } await oseq.webhooks.enable('wep_01J9…'); // { endpoint, replayed: n } await oseq.webhooks.replay('wdl_01J9…'); ``` ## The schedule [#the-schedule] A delivery is attempted at once, then after each failure with this backoff, about three days in total: | Attempt | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |---|---|---|---|---|---|---|---|---|---| | Delay before it | 0 | 5 s | 5 min | 30 min | 2 h | 5 h | 10 h | 10 h | 10 h | Each attempt waits up to 10 seconds for your response. A `2xx` ends it (`delivered`); after the ninth failure the delivery is `failed` for good and only a recover or a replay sends it again. The delivery row records every attempt, the last status code and the last error. ## Disabled endpoints [#disabled-endpoints] An endpoint whose deliveries have **all** failed for three days (the oldest pending delivery is older than that) is set to `disabled`, with `disabled_reason` and `disabled_at`; its remaining deliveries are held, not lost; and `endpoint.disabled` is delivered to the project's other endpoints. An endpoint whose signing secret can no longer be decrypted (the encryption key was removed from `SEQ_ENCRYPTION_KEYS`) is disabled the same way: rotate the secret, then enable. `POST /v1/webhooks/{id}/enable` sets it back to `active` and re-queues every held delivery, oldest first. Nothing was lost. ## Recover and replay [#recover-and-replay] - `POST /v1/webhooks/{id}/recover { since }` re-sends every delivery of the endpoint that **failed for good** since that time, with a fresh attempt counter. - `POST /v1/webhooks/deliveries/{id}/replay` re-sends one delivery whatever its state (delivered, failed, pending), with a fresh counter. The endpoint must be active (`409 ENDPOINT_DISABLED`). A replayed delivery keeps its `webhook-id`, so an idempotent receiver ignores a duplicate. ## The deliveries log [#the-deliveries-log] `GET /v1/webhooks/{id}/deliveries` (paginated, `updated_since`) returns, per delivery: `id`, `event_id`, `event_type`, `enrollment`, `status` (`pending`, `delivered`, `failed`, `disabled`), `attempts`, `next_attempt_at`, `last_status_code`, `last_error`, `payload`, `created_at`, `delivered_at`. Delivered rows are pruned after 30 days. ## Ordering during failures [#ordering-during-failures] Deliveries for the same endpoint and enrollment go one at a time in creation order: while one is retrying, the ones behind it wait (`waiting`), and go out as soon as it succeeds or gives up. Other enrollments and other endpoints are not affected. ## What to alert on [#what-to-alert-on] An endpoint with `status: "disabled"`, a delivery with `attempts >= 5`, or `last_error` repeating across deliveries. The operator's `GET /v1/admin/engine/health` and the project's `GET /v1/engine/health` show the `seq_webhooks` queue depth. # Verifying webhook signatures (https://docs.opensequence.dev/docs/webhooks/verifying) How to verify Standard Webhooks signatures with the SDK or by hand, store the signing secret, and rotate it safely. Every delivery carries three headers following the [Standard Webhooks](https://www.standardwebhooks.com) specification. Verify them before you trust the body; otherwise anyone who finds your URL can enroll a fake "reply" into your CRM. ```ts title="TypeScript" import { verifyWebhook, WebhookVerificationError } from '@opensequence/sdk'; import express from 'express'; const app = express(); // the RAW body is required: a parsed and re-serialized body will not verify app.post('/hooks/opensequence', express.raw({ type: 'application/json' }), (req, res) => { try { const event = verifyWebhook({ secret: process.env.OSEQ_WEBHOOK_SECRET!, headers: req.headers, body: req.body }); // event.id, event.type, event.project, event.occurred_at, event.data handle(event); res.sendStatus(200); } catch (err) { if (err instanceof WebhookVerificationError) return res.status(401).send(err.code); res.sendStatus(500); // the service retries } }); ``` ```python title="Python" import base64, hashlib, hmac, time def verify(secrets: list[str], headers: dict, raw_body: bytes, tolerance=300) -> dict: """`secrets` holds every secret currently accepted for the endpoint: one, or two during a rotation.""" msg_id = headers["webhook-id"]; ts = headers["webhook-timestamp"]; sig = headers["webhook-signature"] if abs(time.time() - int(ts)) > tolerance: raise ValueError("timestamp outside tolerance") signed = f"{msg_id}.{ts}.".encode() + raw_body for secret in secrets: key = base64.b64decode(secret.removeprefix("whsec_")) expected = hmac.new(key, signed, hashlib.sha256).digest() for part in sig.split(" "): if part.startswith("v1,") and hmac.compare_digest(base64.b64decode(part[3:]), expected): import json; return json.loads(raw_body) raise ValueError("no signature matched") ``` ```bash title="By hand" # secret=whsec_; id and ts from the headers; body.json is the raw body printf '%s.%s.' "$ID" "$TS" | cat - body.json \ | openssl dgst -sha256 -mac HMAC -macopt hexkey:$(echo "${SECRET#whsec_}" | base64 -d | xxd -p -c 256) -binary \ | base64 # compare with the part after "v1," in webhook-signature ``` ## The scheme [#the-scheme] | Header | Value | |---|---| | `webhook-id` | the event id (`evt_…`), the same on every retry of the same delivery | | `webhook-timestamp` | Unix seconds when this attempt was signed | | `webhook-signature` | `v1,` where the MAC is `HMAC-SHA256(secret, "..")` and the key is the base64-decoded part of the secret after `whsec_`. Several space-separated `v1,…` values may appear | Reject timestamps more than five minutes from your clock (the SDK's default `toleranceSeconds` is 300) to blunt replays. Compare MACs in constant time. Use the **raw** request bytes: the service signs the exact JSON it sends, and a body that went through a JSON parser and back will not match. ## Storing the secret [#storing-the-secret] The secret is in the response of `POST /v1/webhooks` (and of `rotate-secret`) once; no later call returns it, and the service keeps only an encrypted copy for signing. Store it where you store other credentials (a secrets manager, or an encrypted column), keyed by the endpoint id (`wep_…`) so a project with several endpoints can find the right one, and never log it. If it is lost, rotate: there is no way to read it back. A receiver without the SDK should keep a **list** of accepted secrets per endpoint, not a single value, and try each one against the `webhook-signature` header. That is what makes rotation safe: ## Rotation [#rotation] `POST /v1/webhooks/{id}/rotate-secret` returns a new secret; deliveries from that moment are signed with it and there is no overlap window on the service side. The SDK's `verifyWebhook` accepts `secret: [newSecret, oldSecret]`. Without the SDK, the procedure is the same four steps: 1. Call `rotate-secret` and store the new secret **alongside** the old one for that endpoint. 2. Verify incoming deliveries against every stored secret (the Python example above takes a list and tries each one before it raises). 3. Watch the deliveries log (`GET /v1/webhooks/{id}/deliveries`) until nothing signed with the old secret is still pending: a retry of a delivery first attempted before the rotation is re-signed with the **current** secret at each attempt, so this is quick, and it is only in-flight attempts between your call and your store update that can still carry the old signature. 4. Drop the old secret. If you cannot change your receiver to accept two secrets, rotate at a quiet moment and accept that deliveries in that window fail once and are retried with the new signature five seconds later ([Retries and recovery](/docs/webhooks/retries-and-recovery)). ## Errors the SDK throws [#errors-the-sdk-throws] `WebhookVerificationError` with `code` `MISSING_HEADERS`, `BAD_TIMESTAMP`, `TIMESTAMP_OUT_OF_TOLERANCE`, `NO_MATCHING_SIGNATURE` or `INVALID_BODY`. Answer a `4xx` to a bad signature: the delivery is still retried by the service (it does not know your reason), so a persistently rejected endpoint ends up disabled after three days, which is what you want for a stolen URL. `signWebhook(secret, id, timestamp, body)` is exported for your own tests. # API and definition limits (https://docs.opensequence.dev/reference/limits) What caps apply to definitions, batches, requests and retention, and where the code enforces each one. | What | Limit | Where it is enforced | |---|---|---| | Definition size | 10 MB | `INVALID_DEFINITION` on save and publish | | Nodes per definition | 200 | `INVALID_DEFINITION` | | Node id | `^[a-z][a-z0-9_]*$`, 1 to 64 characters | schema | | Rules per condition | 1 to 20 | schema | | SMS body | 1000 characters; a warning (`TOO_LONG`) above 320 | schema and validator | | Email subject | 300 characters | schema | | Email body | 100,000 characters as `text`, 5,000,000 as `html` | schema | | Embedded (base64) image in an html email | 1 MB decoded per image (`IMAGE_TOO_LARGE`); a warning (`HEAVY_EMAIL`) above 400 KB per body | executor and validator | | Email message | 10 MB with its images (`MESSAGE_TOO_LARGE`) | executor | | Sender signature | 1 MB of HTML, 4,000 characters of text | API | | Task title, body, link, kind | 200, 4000, 2000 and 32 characters | schema | | Logic steps per advance | 25 before the enrollment is handed back to the planner | engine | | Contacts per batch upsert, per `:status`, per `:events` | 500 (`BATCH_TOO_LARGE`) | API | | Contacts per enroll call | 5,000 (`BATCH_TOO_LARGE`) | API | | Enrollments per `POST /v1/enrollments:exit` by sequence | 200 per call | API | | List page size | 1 to 200, default 50 | API | | Request body | 11 MB on the routes that carry a definition (create a sequence, save a draft, validate), 2 MB elsewhere | API (`413`) | | Requests | 600 per minute per key (`429` with `Retry-After`) | API | | Timeline and journey | the last 200 messages and signals, 100 tasks | API | | Email send retries | 5 reads of the queue message, then `failed` | executor | | SMS send retries | none without a provider confirmation: an unknown outcome is `needs_review` | executor | | Webhook delivery attempts | 9, over about 3 days (0 s, 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 10 h, 10 h); 10 s timeout per attempt | delivery | | Endpoint disabled after | every delivery failing for 3 days | delivery | | Webhook timestamp tolerance | 5 minutes | receivers (SDK default) | | Opt-out link | 90 days | opt-out token | | Planner claim | 50 per sender, 500 per tick, released after 10 minutes if not advanced | planner | | Poll scope | threads started in the last 30 days, 500 channels per tick | poll job | | Default channel caps | email 30 a day with a 60 s gap, SMS 100 a day | new channels | | Idempotency keys kept | 1 day | retention | | Dead-letter queue rows and delivered deliveries kept | 30 days | retention | | `retention_days` setting | accepted (7 to 3650, default 365) but **not enforced yet**: runs, messages and signals are kept | see [Data retention](/docs/security/data-retention) | # Using the auth package on its own (https://docs.opensequence.dev/sdks/auth-package) How to use @opensequence/auth on its own: store API keys and mailbox passwords encrypted, hand them to adapters, and rotate keys. `@opensequence/auth` is the part of OpenSequence that stores provider secrets: a tenant's API keys (Allo, Attio) and each user's mailbox settings (SMTP and IMAP passwords). It has no idea what a sequence is. Tenants and owners are opaque strings, so it works for any application that keeps third-party secrets encrypted at rest and hands them only to the code that calls the provider. ```ts import { createAuth, runAuthMigrations } from '@opensequence/auth'; import { drizzle } from 'drizzle-orm/postgres-js'; import postgres from 'postgres'; const db = drizzle(postgres(process.env.DATABASE_URL!)); await runAuthMigrations(db); // creates the `seq_auth` schema const auth = createAuth({ db, encryptionKeys: process.env.SEQ_ENCRYPTION_KEYS!, // "id:base64key[,id:base64key…]" }); // once per tenant: a workspace API key, probed before it is stored await auth.registerCredential({ tenantId: 'acme', provider: 'attio', method: 'api_key', secrets: { api_key }, probe }); // per user: their mailbox, after your code has checked the logins work const connection = await auth.savePasswordConnection({ tenantId: 'acme', ownerId: 'u_42', provider: 'smtp', account: 'max@acme.com', config: { smtp: { host: 'smtp.gmail.com', port: 465 }, imap: { host: 'imap.gmail.com', port: 993 } }, secrets: { smtp_password, imap_password }, }); // only in the adapter that talks to the mail server const { account, config, secrets } = await auth.connectionSecrets(connection.id); ``` ## What it does [#what-it-does] | Area | Behaviour | |---|---| | Credentials (tenant level) | `registerCredential({ tenantId, provider, method: 'api_key', secrets, probe? })` stores the key encrypted. An optional `probe` checks it against the provider first and refuses it with `INVALID_CREDENTIAL` when it fails. `credentialStatus` and `listCredentials` return the status, key id, last four characters and timestamps, never the secret. `credentialsFor(tenantId, provider)` returns the decrypted map, for adapters only | | Connections (owner level) | `savePasswordConnection` stores one connection per owner and provider: the passwords encrypted together, the rest as plain config. Saving again replaces the settings. `connectionSecrets(connectionId)` returns them for adapters only, and answers `CREDENTIALS_NEEDED` once the connection is disconnected | | Health | `healthCheckCredential(tenantId, provider, probe)` re-runs a probe and marks the credential `invalid` when it fails. `health(connectionId)`, `connectionStatus` and `listConnections(tenantId, ownerId?)` report connections | | Revoke | `revoke(connectionId)` deletes the stored passwords and sets the connection `disconnected` | | Key rotation | `rotateKeys()` re-encrypts every credential and connection not under the first key of `encryptionKeys`, so older entries can be removed from the list | ## Errors [#errors] `AuthError` with a stable `code` and an HTTP status: `INVALID_CREDENTIAL` and `MISSING_SECRET` (422), `CREDENTIAL_INVALID`, `CREDENTIALS_NEEDED` and `CONFLICT` (409), `NOT_FOUND` (404). ## Storage [#storage] Two tables in the `seq_auth` schema, `credentials` and `connections`, created by `runAuthMigrations(db)` (idempotent). Secrets are AES-256-GCM under the first key; each row carries its key id. The exported `authSchema`, `credentialsTable` and `connectionsTable` let you join from your own Drizzle code. `AesGcmCipher` and `parseEncryptionKeys` are exported for tests and custom wiring; pass your own `clock` to `createAuth` to control time. The package is destined for its own repository (`open-sequence/auth`); it never imports the engine. # Using the API from Go (https://docs.opensequence.dev/sdks/go) How to call OpenSequence from Go without an SDK: the REST API with net/http, or a client generated from the OpenAPI 3.1 file with openapi-generator. There is no Go SDK: the repository ships only the [TypeScript SDK](/sdks/typescript). From Go, call the REST API with `net/http` ([Conventions](/api/conventions)) or generate a client from the OpenAPI file. ## Generate a client [#generate-a-client] Your instance serves its OpenAPI document at `/docs/json`; this site has a copy at [/openapi.json](/openapi.json). ```bash curl -o openapi.json https://sequences.example.com/docs/json docker run --rm -v "$PWD:/local" openapitools/openapi-generator-cli generate \ -i /local/openapi.json -g go -o /local/oseq --package-name oseq ``` The file is OpenAPI 3.1. Pick a generator that reads 3.1; some Go generators still read only 3.0. Every request carries `Authorization: Bearer sk_live_…`. The generated request bodies and query parameters are typed. Responses are not: the OpenAPI file declares every `data` as any value, so read the shapes from the API reference pages. ## Webhooks [#webhooks] Deliveries follow [Standard Webhooks](https://www.standardwebhooks.com), so the Standard Webhooks Go library verifies them with the endpoint secret (`whsec_…`) and the raw body. See [Verifying](/docs/webhooks/verifying) for the scheme. # Using the API from Python (https://docs.opensequence.dev/sdks/python) How to call OpenSequence from Python without an SDK: the REST API directly, or a client generated from the OpenAPI file with openapi-python-client. There is no Python SDK: the repository ships only the [TypeScript SDK](/sdks/typescript). From Python, call the REST API directly or generate a client from the OpenAPI file. ## Call the API directly [#call-the-api-directly] The API is small and regular: JSON in, an envelope out, a bearer key ([Conventions](/api/conventions)). ```python import os, requests SEQ = os.environ["SEQ_URL"] session = requests.Session() session.headers["Authorization"] = f"Bearer {os.environ['SEQ_KEY']}" r = session.put(f"{SEQ}/v1/contacts/p_7", json={"first_name": "Dana", "email": "dana@example.com"}) body = r.json() if not body["success"]: raise RuntimeError(f"{body['error']['code']}: {body['error']['message']}") contact = body["data"] ``` ## Generate a client [#generate-a-client] Your instance serves its OpenAPI document at `/docs/json`; this site has a copy at [/openapi.json](/openapi.json). ```bash pip install openapi-python-client openapi-python-client generate --url https://sequences.example.com/docs/json ``` The generated request bodies and query parameters are typed. Responses are not: the OpenAPI file declares every `data` as any value, so read the shapes from the API reference pages. ## Webhooks [#webhooks] Deliveries follow [Standard Webhooks](https://www.standardwebhooks.com), so the `standardwebhooks` package verifies them with the endpoint secret (`whsec_…`) and the raw body. See [Verifying](/docs/webhooks/verifying) for the scheme. # TypeScript SDK: install and use @opensequence/sdk (https://docs.opensequence.dev/sdks/typescript) How to call OpenSequence from TypeScript: npm install @opensequence/sdk, configure the client, then every resource method and webhook verification. Install the typed client, then find every method by resource. Each method is one HTTP call to a documented endpoint. ## Install [#install] ```bash npm install @opensequence/sdk ``` ```ts import { OpenSequence } from '@opensequence/sdk'; const oseq = new OpenSequence({ baseUrl: 'https://sequences.example.com', apiKey: process.env.OSEQ_KEY! }); await oseq.senders.upsert('u_42', { name: 'Max Rivera', email: 'max@acme.com', timezone: 'America/New_York' }); await oseq.contacts.upsert('p_7', { first_name: 'Dana', email: 'dana@example.com' }); const { enrollments } = await oseq.sequences.enroll('seq_01J9…', { contacts: ['p_7'], sender: 'u_42' }); ``` ESM, Node 20 or newer, zero runtime dependencies (global `fetch` and `node:crypto`). Types are generated from the server's OpenAPI file, so every response is typed as the server sends it. ## Configuration [#configuration] | Option | Meaning | |---|---| | `baseUrl` | your instance, without `/v1` | | `apiKey` | a project key `sk_live_…` | | `fetch` | a fetch implementation (tests inject one) | | `timeoutMs` | abort after this long; default 30,000, `0` disables | | `userAgent` | sent as `user-agent`; default `opensequence-sdk/` | `oseq.http` is the HTTP core for an endpoint the SDK has no method for yet: `oseq.http.request({ method, path, query, body })`. ## Errors [#errors] Every failure, from the API or on the way to it, is one `OpenSequenceError` with `status` (0 when nothing arrived), `code` (the API's stable code, or `NETWORK_ERROR`, `TIMEOUT`, `INVALID_RESPONSE`), `message`, `details` and `requestId`. ```ts try { await oseq.sequences.enroll(seqId, { contacts, sender }); } catch (err) { if (err instanceof OpenSequenceError && err.is('ALREADY_IN_SEQUENCE')) { const { conflicts } = err.details as { conflicts: Array<{ external_id: string; sequence_name: string }> }; // show them; nobody was enrolled } else throw err; } ``` ## Lists [#lists] List methods return one page, `{ items, nextCursor }`, and take `{ limit, cursor, updated_since }` plus the endpoint's filters. `listAll()` walks every page as an async iterator. ```ts const page = await oseq.enrollments.list({ sequence: seqId, status: 'active', limit: 200 }); for await (const task of oseq.tasks.listAll({ sender: 'u_42', status: 'open' })) render(task); ``` ## Resources [#resources] ```ts await oseq.senders.upsert('u_42', { name, email, timezone, attrs, signature_html }); // the signature is sanitized on save await oseq.senders.get('u_42'); // with channels, readiness, connections await oseq.senders.list({ limit: 50 }); await oseq.senders.readiness('u_42'); // { email: { ok, reason }, sms, task } await oseq.senders.connections('u_42'); await oseq.senders.setSmtp('u_42', { provider: 'smtp', from, smtp: { host, port, secure, user, password }, imap: { host, port, secure, user, password } }); // checks both logins, replaces the email channel await oseq.senders.setSms('u_42', { allo_user_id, number }); await oseq.senders.patchChannel('u_42', 'email', { daily_limit: 50, min_gap_seconds: 90, status: 'active' }); await oseq.senders.deleteChannel('u_42', 'sms'); // or 'email': also deletes the stored SMTP and IMAP passwords await oseq.senders.disable('u_42'); await oseq.senders.tasks('u_42', { status: 'open' }); ``` ```ts await oseq.contacts.upsert('p_7', { first_name, last_name, email, phone, country, timezone, attrs }); await oseq.contacts.batch([{ external_id: 'p_7', email }, { external_id: 'p_8', email }]); await oseq.contacts.list({ email: 'dana@example.com' }); await oseq.contacts.get('p_7'); // with suppressions and the active enrollment await oseq.contacts.timeline('p_7'); await oseq.contacts.patch('p_7', { attrs: { deal: { stage: 'won' } } }); await oseq.contacts.statuses(['p_7', 'p_8']); await oseq.contacts.reportEvent('p_7', { id: 'cal_1', type: 'meeting_booked', occurred_at: new Date() }); await oseq.contacts.reportEvents([{ contact: 'p_7', id: 'dnc-1', type: 'suppressed', reason: 'do_not_contact' }]); await oseq.contacts.setOutreachConsent('p_7', { consent: true, source: 'web form' }); // admin await oseq.contacts.delete('p_7'); // admin ``` ```ts const { sequence, version } = await oseq.sequences.create({ name: 'UK intro', definition }); await oseq.sequences.list(); await oseq.sequences.get(sequence.id); await oseq.sequences.update(sequence.id, { status: 'paused' }); await oseq.sequences.validate(definition); // { ok, problems } await oseq.sequences.versions.list(sequence.id); await oseq.sequences.versions.get(sequence.id, version.id); // { version, problems } await oseq.sequences.versions.saveDraft(sequence.id, version.id, { definition, lock_version: 0 }); await oseq.sequences.versions.publish(sequence.id, version.id); await oseq.sequences.versions.create(sequence.id, { from_version: version.id, tag: 'v2' }); await oseq.sequences.versions.archive(sequence.id, version.id); await oseq.sequences.versions.delete(sequence.id, draftId); await oseq.sequences.previewEnrollment(sequence.id, { contacts, sender }); await oseq.sequences.enroll(sequence.id, { contacts, sender, mode: 'dry_run' }); ``` ```ts await oseq.enrollments.list({ sequence, status: 'active', updated_since }); await oseq.enrollments.get('enr_…'); // the journey await oseq.enrollments.pause('enr_…', { reason: 'on_hold', until }); await oseq.enrollments.resume('enr_…'); await oseq.enrollments.exit('enr_…', { label: 'Closed by phone' }); // admin await oseq.enrollments.exitMany({ sequence, status: 'active' }); // admin ``` ```ts await oseq.tasks.list({ sender, status: 'open', kind: 'call' }); await oseq.tasks.get('tsk_…'); await oseq.tasks.complete('tsk_…', { outcome: 'connected', note }); await oseq.tasks.cancel('tsk_…'); ``` ```ts const { endpoint, secret } = await oseq.webhooks.create({ url, event_types: ['*'] }); await oseq.webhooks.list(); await oseq.webhooks.get(endpoint.id); await oseq.webhooks.update(endpoint.id, { event_types: ['enrollment.exited'] }); await oseq.webhooks.rotateSecret(endpoint.id); // { endpoint, secret } await oseq.webhooks.enable(endpoint.id); await oseq.webhooks.recover(endpoint.id, { since: new Date('2026-10-12') }); await oseq.webhooks.deliveries(endpoint.id, { limit: 50 }); await oseq.webhooks.replay('wdl_…'); await oseq.webhooks.delete(endpoint.id); ``` ```ts await oseq.analytics.summary(seqId, { from, to, version, sender, country }); await oseq.analytics.exits(seqId); await oseq.analytics.nodes(seqId); await oseq.analytics.channels(seqId); await oseq.analytics.sequences({ min_enrolled: 20 }); ``` ```ts await oseq.project.get(); // settings, credential status, webhook URLs await oseq.project.updateSettings({ attribution_days: 14, sms_countries: ['US', 'GB'] }); await oseq.project.updateSettings({ unsubscribe_url: 'https://app.example.com/u/{token}' }); // your own unsubscribe page await oseq.project.setProvider('allo', { api_key }); await oseq.project.setProvider('attio', { api_key }); await oseq.project.alloNumbers(); await oseq.project.alloUsers(); await oseq.project.attioSchema(); await oseq.project.apiKeys.list(); await oseq.project.apiKeys.create({ name: 'app', scopes: ['enroll'] }); await oseq.project.apiKeys.revoke('key_…'); await oseq.project.flags.set('channel:sms', { value: false }); await oseq.project.health(); await oseq.schema.definition(); await oseq.schema.fields(); await oseq.schema.events(); ``` ```ts // For an unsubscribe page in your app (project setting unsubscribe_url). Scope enroll. const status = await oseq.unsubscribes.get(token); // { valid, expired, contact: { email: 'd***@acme.com', first_name }, already_unsubscribed } await oseq.unsubscribes.apply(token); // suppress email, exit enrollments; idempotent ``` ```ts const admin = new OpenSequenceAdmin({ baseUrl, adminToken: process.env.SEQ_ADMIN_TOKEN! }); const { project, api_key } = await admin.projects.create({ slug: 'acme', name: 'Acme CRM' }); await admin.projects.list(); await admin.projects.createApiKey(project.id, { name: 'app', scopes: ['enroll'] }); await admin.engineHealth(); ``` ## Webhooks [#webhooks] `verifyWebhook({ secret, headers, body })` checks the Standard Webhooks signature and timestamp and returns the parsed event, or throws `WebhookVerificationError`. Pass the raw body, and an array of secrets during a rotation. `signWebhook` signs a test event. Details and framework examples: [Verifying](/docs/webhooks/verifying). ```ts import { verifyWebhook } from '@opensequence/sdk'; const event = verifyWebhook({ secret: process.env.OSEQ_WEBHOOK_SECRET!, headers: req.headers, body: rawBody }); switch (event.type) { case 'enrollment.exited': /* event.data.enrollment, event.data.exit_reason */ break; case 'task.created': /* event.data.task */ break; } ``` ## Types [#types] Every request and response type is exported (`Contact`, `Enrollment`, `Journey`, `Task`, `WebhookEvent`, …), plus `paths` and `components` from the generated OpenAPI types for anything else. Response types are aliases of `components['schemas']`, so they are exactly what the server serializes. Stored records are camelCase (`contact.externalId`, `version.lockVersion`, `enrollment.currentNodeId`); request bodies and computed results are snake_case (`first_name`, `lock_version`, `next_run_at`): see [Field names](/api/conventions#field-names). # API errors and the error envelope (https://docs.opensequence.dev/api/errors) What the API error envelope looks like, how to handle it, and every error code the API returns. This page is generated from `the error helpers in packages/engine, packages/auth and apps/server` by `pnpm generate`. Do not edit it by hand; change the source and regenerate. Every failure is the same envelope, with the HTTP status that matches the code: ```json { "success": false, "error": { "code": "ALREADY_IN_SEQUENCE", "message": "2 of the 142 contacts are already in a sequence. Nobody was enrolled. Remove them from the selection or exit them from their current sequence first.", "details": { "conflicts": [] } }, "meta": { "request_id": "req_k3…" } } ``` Messages are plain English and may change; `code` is stable, so branch on it. `details` is structured when there is something to act on (the conflicts of `ALREADY_IN_SEQUENCE`, the `problems` of `INVALID_DEFINITION`, the `missing` scopes of `SCOPES_MISSING`). The TypeScript SDK throws `OpenSequenceError` with `status`, `code`, `message`, `details` and `requestId` (the envelope's `meta.request_id`). ## HTTP error codes [#http-error-codes] | Code | HTTP | Message | What to do | | --- | --- | --- | --- | | `ALREADY_IN_SEQUENCE` | 409 | … of the … contacts are already in a sequence. Nobody was enrolled. Remove them from the selection or exit them from their current sequence first. | Remove the listed contacts (`details.conflicts`) from the selection, or exit them first with `POST /v1/enrollments/\{id\}/exit`. Nobody was enrolled. | | `BAD_FLAG` | 422 | A flag is "global" or "channel:\". | | | `BAD_OUTCOME` | 422 | Give the outcome of the task, like "connected" or "no_answer". | | | `BAD_SCOPE` | 422 | Unknown scope: …. Use read, enroll or admin. | | | `BAD_TAG` | 422 | A tag is up to 24 letters, digits, dots and dashes, like v2. | | | `BATCH_TOO_LARGE` | 422 | At most … contacts per call. | | | `CONFLICT` | 409 | This owner already has a connection in another tenant. | | | `CREDENTIAL_INVALID` | 409 | The … credential was marked invalid by a health check. Register a new one. | | | `CREDENTIALS_NEEDED` | 409 | credentials_needed: connection … is …; set the channel again. | | | `ENDPOINT_DISABLED` | 409 | Enable the endpoint first; it is disabled. | | | `FROM_REQUIRED` | 422 | Say which address mail goes out from: set "from", or use the full mailbox address as the SMTP user. | | | `HAS_ACTIVE_ENROLLMENTS` | 409 | … contacts are still in this sequence. Exit them first, or send exit_active: true. | Exit them first, or send `exit_active: true` to exit them with reason `manual`. | | `INSUFFICIENT_SCOPE` | 403 | This key cannot do that; it needs the "…" scope. | Use a key with the scope the route needs (`read` \< `enroll` \< `admin`). | | `INTERNAL_ERROR` | 500 | Something went wrong on our side. Reference …. | | | `INVALID_DEFINITION` | 422 | The definition has errors; fix them before publishing. `details.problems` lists them. | Fix every problem in `details.problems` (each has a `path`, a `code` and a sentence) and publish again. Saving a draft with errors is allowed; publishing is not. | | `INVALID_EVENT` | 422 | The event is not valid: … | | | `INVALID_SLUG` | 422 | A slug is 3 to 48 lowercase letters, digits and dashes. | | | `MISSING_SECRET` | 422 | An api_key credential needs api_key. | | | `NO_CONTACTS` | 422 | Give at least one contact. | | | `NO_PUBLISHED_VERSION` | 409 | This sequence has no published version yet. | Publish a version before enrolling. | | `NOT_ACTIVE` | 409 | This enrollment is … (only active and waiting_limit enrollments can be paused). | | | `NOT_FOUND` | 404 | … "…" was not found. (Also: no route for this method and path.) | | | `NOT_PAUSED` | 409 | This enrollment is … (only paused and waiting_limit enrollments can be resumed). | | | `NUMBER_HAS_NO_SMS` | 422 | … cannot send SMS. | | | `REQUEST_ERROR` | 400, 413, 429 | A request-level error with its own message: malformed JSON (400), a body over 2 MB (413), or "Rate limit exceeded, retry in …" (429, 600 requests per minute per key, with a `Retry-After` header). | | | `SENDER_DISABLED` | 409 | … is disabled. | | | `SEQUENCE_NOT_ACTIVE` | 409 | The sequence is …. | | | `SLUG_TAKEN` | 409 | The slug "…" is already used. | | | `STALE_LOCK` | 409 | Someone else saved this draft after you loaded it. Reload and try again. | Reload the version, re-apply your change on the new `lock_version`, save again. | | `TAG_TAKEN` | 409 | Version … already exists. | | | `UNAUTHORIZED` | 401 | Send a project API key as a Bearer token. / This API key is unknown or revoked. / This endpoint needs the operator token. | Send `Authorization: Bearer \`; the key must exist and not be revoked. `/v1/admin/*` wants the operator token instead. | | `UNKNOWN_CHANNEL` | 422 | "…" is not a channel. | | | `UNKNOWN_EVENT_TYPE` | 422 | Unknown event type: …. Use "*" or one of …. | Use `"*"` or the types listed by `GET /v1/schema/events`. | | `UNKNOWN_NUMBER` | 422 | … is not a number the Allo key can see. | | | `UNSAFE_URL` | 422 | The endpoint URL …. | Endpoint URLs must be `https`, carry no credentials, and resolve to a public address. | | `UNSUBSCRIBE_TOKEN_EXPIRED` | 400 | This unsubscribe link has expired (links last 90 days). Ask the person to reply to the email instead, or report an opt_out with POST /v1/contacts/\{id\}/events. | | | `UNSUBSCRIBE_TOKEN_INVALID` | 400 | This unsubscribe token is not valid: it was not issued by this server for this project, it was altered, or its contact was deleted. | | | `VALIDATION_ERROR` | 400 | The request did not match the schema. `details` lists each path and message. | | | `VERSION_NOT_EDITABLE` | 409 | Version … is … and cannot be edited. Create a new version from it. (Also: only drafts can be deleted.) | Published and archived versions are frozen. Create a new draft from it: `POST /v1/sequences/\{id\}/versions` with `from_version`. | | `VERSION_NOT_PUBLISHED` | 409 | Version … is …; only a published version can enroll. | | ## Validation problems [#validation-problems] Returned by `POST /v1/sequences:validate`, `PUT .../draft` (as `problems`, saving is allowed) and `POST .../publish` (inside a 422 `INVALID_DEFINITION`). Each problem is `{ path, code, message, severity }`. See [Validation](/docs/concepts/sequence/validation) for the fix of each one. | Code | Severity | Example message | | --- | --- | --- | | `BAD_EVENT` | error | The event "…" is waited for but has no next step. | | `BAD_OPERATOR` | error | "…" cannot be used on … (…). Use one of: …. | | `BAD_TEMPLATE` | error | "\{\{ … \}\}" is not something a template can read. Use contact.*, attrs.*, sender.*, sequence.name or unsubscribe_url. | | `BAD_VALUE` | error | "…" needs a value. | | `CYCLE` | error | Steps … loop without a wait in between; the contact would never leave them. | | `HEAVY_EMAIL` | warning | This email embeds … KB of base64 images (more than … KB). Heavy emails land in spam and get clipped; host large images over https. | | `INVALID_DEFINITION` | error | The definition is … MB; the limit is … MB. Host large images over https instead of embedding them. | | `MISSING_TRANSITION` | error | A … step must say where "…" goes. | | `NO_BRIEF` | warning | This call turns on … but has no description. The agent only uses a skill when the description says when to. | | `NO_UNSUBSCRIBE` | warning | This email has no \{\{ unsubscribe_url \}\}. Recipients cannot opt out with one click. | | `TOO_LONG` | warning | LinkedIn takes notes of up to … characters; this one is …. It will be cut. | | `UNKNOWN_ACTION` | error | "…" is not an action of …. Available: …. | | `UNKNOWN_CHANNEL` | error | An outreach step needs a channel. | | `UNKNOWN_FIELD` | error | "…" is not a field conditions can read. | | `UNKNOWN_NODE` | error | The entry node "…" does not exist. | | `UNKNOWN_NODE_TYPE` | error | "…" is not a node type. Available: …. | | `UNREACHABLE_NODE` | error | "…" can never be reached from the entry step. | # Configuring a self-hosted install (https://docs.opensequence.dev/docs/self-hosting/configuration) How to configure OpenSequence with environment variables: every SEQ_* variable, the queue backends and the roles. This page is generated from `apps/server/src/config/env.ts` by `pnpm generate`. Do not edit it by hand; change the source and regenerate. Everything is configured through environment variables, Svix-style: you choose the database and the queue, and one image runs every role. ## Variables [#variables] | Variable | Type | Required | Default | Meaning | | --- | --- | --- | --- | --- | | `SEQ_DB_DSN` | string | yes | | Postgres connection string. Only Postgres is supported. A transaction pooler is fine: no session-level features are used. | | `SEQ_QUEUE` | `postgres`, `redis`, `memory` | no | `"postgres"` | The queue backend. `postgres` needs nothing else and is a transactional outbox; `redis` needs SEQ_REDIS_DSN; `memory` is for development and tests only. | | `SEQ_REDIS_DSN` | string | with `SEQ_QUEUE=redis` | | Redis connection, required when SEQ_QUEUE=redis. Enable persistence on the Redis side. | | `SEQ_ENCRYPTION_KEYS` | string | yes | | Encryption keys for every stored secret, `id:base64key[,id:base64key...]`; the first entry encrypts, every entry decrypts. Generate one with `oseq secrets new-key`. Back it up with the database: without it the stored secrets are unreadable and must be re-entered. | | `SEQ_ADMIN_TOKEN` | string | for `api` and `all` | | The operator token that creates projects and keys (`/v1/admin/*`). Required by the `api` and `all` roles. Long and random. | | `SEQ_PUBLIC_URL` | URL | no | `"http://localhost:8080"` | The base URL providers call back: inbound webhooks and the opt-out links. The OpenAPI document served by the instance lists it as its server. | | `SEQ_PORT` | number | no | `8080` | HTTP port. The API for `api` and `all`; `/healthz` and `/readyz` only for `worker`. | | `SEQ_HOST` | string | no | `"0.0.0.0"` | The interface to bind. | | `SEQ_ROLES` | `api`, `worker`, `all` | no | `"all"` | `api` serves HTTP, `worker` runs the scheduler and the queue consumers, `all` does both in one process. | | `SEQ_RUN_MIGRATIONS` | flag: `1` or `true` | no | | Apply the `seq` and `seq_auth` migrations at boot, serialized by a row lock so replicas starting together do not race. | | `SEQ_CONCURRENCY` | number | no | `8` | Messages in flight per queue per replica. | | `SEQ_DISABLED_CHANNELS` | comma-separated list | no | | Platform-wide kill switch per channel, comma-separated (`sms`). Steps on a disabled channel are deferred, not skipped. | | `SEQ_PAUSED` | flag: `1` or `true` | no | | Platform-wide stop: the planner claims nothing while it is on. In-flight steps finish. | | `SEQ_DEV_MOCK_PROVIDERS` | flag: `1` or `true` | no | | Every project uses the `mock` adapters: nothing reaches a mail server, Allo or Attio, sends land in the timeline, and `POST /hooks/mock/\{slug\}` simulates replies, bounces and calls. Refused when NODE_ENV=production. | | `SEQ_LOG_LEVEL` | `fatal`, `error`, `warn`, `info`, `debug`, `trace` | no | `"info"` | Pino log level. | | `SEQ_METRICS` | flag: `1` or `true` | no | | Reserved for a Prometheus `/metrics` endpoint. Accepted by the schema; the endpoint is not served yet. | | `SEQ_DB_POOL` | number | no | `10` | Postgres connections per process. | | `NODE_ENV` | string | no | `"development"` | `production` turns off pretty logs and refuses SEQ_DEV_MOCK_PROVIDERS. | Three rules are checked after parsing: `SEQ_QUEUE=redis` needs `SEQ_REDIS_DSN`; the `api` and `all` roles need `SEQ_ADMIN_TOKEN`; `SEQ_DEV_MOCK_PROVIDERS` is refused when `NODE_ENV=production`. ## Queue backends [#queue-backends] The queue interface is `send`, `read` with a visibility timeout, `release`, `delete` and `archive`; everything above it is identical across backends. | `SEQ_QUEUE` | Extra infrastructure | Notes | |---|---|---| | `postgres` | none | the default; the table `seq.queue_messages` with `FOR UPDATE SKIP LOCKED`; an enqueue joins the transaction that records the work (a transactional outbox) | | `redis` | Redis 7+ | higher throughput for large installs; an enqueue cannot join the database transaction, so the reaper's sweep re-enqueues anything recorded but never queued | | `memory` | none | development and tests only; the planner and the reaper rebuild work from the tables on boot | Because the database is the truth and queue messages are hints, a lost or empty queue never loses work. See [Queues](/docs/self-hosting/database). ## Roles [#roles] | `SEQ_ROLES` | Runs | Exposed publicly | |---|---|---| | `api` | the public API, inbound provider webhooks, the opt-out page, `/healthz` and `/readyz` | yes | | `worker` | the scheduler (planner, signals, poll, reaper, retention, webhooks) and the queue consumers (email, SMS, signals, deliveries) | no; it listens for `/healthz` and `/readyz` only | | `all` | both in one process | yes | A `worker` process still registers the API routes on its port; do not expose that port. Readiness for a worker also checks that the scheduler ran a job in the last two minutes. ## Kill switches [#kill-switches] `SEQ_PAUSED=1` stops the planner platform-wide; `SEQ_DISABLED_CHANNELS=sms` defers every step of a channel. Both are read on every tick, so they take effect without a restart. Per-project switches exist too: `PUT /v1/engine/flags/global` and `PUT /v1/engine/flags/channel:sms` with `{ "value": false }`. # Condition fields and operators (https://docs.opensequence.dev/reference/condition-fields) Which fields conditions can read from the closed field registry, and which operators each field type supports. This page is generated from `packages/core/src/domain/definition/builtins.ts and packages/core/src/domain/conditions/evaluate.ts` by `pnpm generate`. Do not edit it by hand; change the source and regenerate. A condition is `{ "mode": "all" | "any", "rules": [{ "field", "op", "value?" }] }` with 1 to 20 rules. `GET /v1/schema/fields` serves this registry plus the project's `attrs_schema`. **Missing data never matches**: a `null` fact fails every operator, including `is_not` and `ne`, so the contact takes `no`. See [Conditions](/docs/concepts/sequence/conditions). ## Operators by type [#operators-by-type] | Type | Operators | Value | | --- | --- | --- | | `enum` | `is`, `is_not` | one of the field’s values | | `text` | `is`, `is_not`, `contains`, `is_empty`, `is_not_empty` | a string; `is_empty` and `is_not_empty` take none | | `number` | `eq`, `ne`, `gt`, `gte`, `lt`, `lte` | a number | | `bool` | `is_true`, `is_false` | none | | `date` | `before`, `after` | an ISO date | Text comparisons are case-insensitive. Numbers are compared after `Number()`; dates after `Date.parse()`. ## Fields [#fields] ### `contact.*`: Contact [#contact-contact] | Field | Label | Type | Operators | Values | | --- | --- | --- | --- | --- | | `contact.country` | Contact country | text | `is`, `is_not`, `contains`, `is_empty`, `is_not_empty` | | | `contact.timezone` | Contact time zone | text | `is`, `is_not`, `contains`, `is_empty`, `is_not_empty` | | | `contact.has_email` | Contact has an email | bool | `is_true`, `is_false` | | | `contact.has_phone` | Contact has a phone | bool | `is_true`, `is_false` | | | `contact.has_linkedin` | Contact has a LinkedIn URL | bool | `is_true`, `is_false` | | | `contact.outreach_consent` | Contact consented to texts and calls | bool | `is_true`, `is_false` | | | `contact.sms_consent` | Contact consented to texts and calls (old name of contact.outreach_consent) | bool | `is_true`, `is_false` | | ### `attrs.*`: Contact attributes [#attrs-contact-attributes] Open: any `attrs.` is accepted and read as text unless the project declares a type (`attrs_schema` in the project settings for `attrs.*`; the Attio attribute types for `crm.*`). ### `sender.*`: Sender [#sender-sender] | Field | Label | Type | Operators | Values | | --- | --- | --- | --- | --- | | `sender.timezone` | Sender time zone | text | `is`, `is_not`, `contains`, `is_empty`, `is_not_empty` | | | `sender.has_sms` | Sender has an SMS number | bool | `is_true`, `is_false` | | ### `history.*`: History [#history-history] | Field | Label | Type | Operators | Values | | --- | --- | --- | --- | --- | | `history.touches` | Touches so far | number | `eq`, `ne`, `gt`, `gte`, `lt`, `lte` | | | `history.days_since_last_touch` | Days since the last touch | number | `eq`, `ne`, `gt`, `gte`, `lt`, `lte` | | | `history.replied_since_enrollment` | Replied since enrollment | bool | `is_true`, `is_false` | | | `history.last_reply_channel` | Last reply channel | enum | `is`, `is_not` | `email`, `sms`, `call` | | `history.emails_sent` | Emails sent | number | `eq`, `ne`, `gt`, `gte`, `lt`, `lte` | | | `history.last_task_outcome` | Last task outcome | text | `is`, `is_not`, `contains`, `is_empty`, `is_not_empty` | | | `history.last_task_kind` | Last task kind | text | `is`, `is_not`, `contains`, `is_empty`, `is_not_empty` | | | `history.days_since_last_task` | Days since the last task | number | `eq`, `ne`, `gt`, `gte`, `lt`, `lte` | | | `history.tasks_last_14d` | Tasks in the last 14 days | number | `eq`, `ne`, `gt`, `gte`, `lt`, `lte` | | ### `crm.*`: CRM [#crm-crm] Open: any `crm.` is accepted and read as text unless the project declares a type (`attrs_schema` in the project settings for `attrs.*`; the Attio attribute types for `crm.*`). | Field | Label | Type | Operators | Values | | --- | --- | --- | --- | --- | | `crm.person.exists` | CRM person exists | bool | `is_true`, `is_false` | | | `crm.company.exists` | CRM company exists | bool | `is_true`, `is_false` | | | `crm.deal.exists` | CRM open deal exists | bool | `is_true`, `is_false` | | | `crm.deal.stage` | CRM deal stage | text | `is`, `is_not`, `contains`, `is_empty`, `is_not_empty` | | | `crm.deal.count_open` | CRM open deals | number | `eq`, `ne`, `gt`, `gte`, `lt`, `lte` | | # Configuration variables reference (https://docs.opensequence.dev/reference/configuration) Every SEQ_* environment variable the service reads, with its type and default, validated once at boot. This page is generated from `apps/server/src/config/env.ts` by `pnpm generate`. Do not edit it by hand; change the source and regenerate. The process refuses to start when a required value is missing or malformed, with a sentence that says which one. Values come from the environment only; there is no configuration file. | Variable | Type | Required | Default | Meaning | | --- | --- | --- | --- | --- | | `SEQ_DB_DSN` | string | yes | | Postgres connection string. Only Postgres is supported. A transaction pooler is fine: no session-level features are used. | | `SEQ_QUEUE` | `postgres`, `redis`, `memory` | no | `"postgres"` | The queue backend. `postgres` needs nothing else and is a transactional outbox; `redis` needs SEQ_REDIS_DSN; `memory` is for development and tests only. | | `SEQ_REDIS_DSN` | string | with `SEQ_QUEUE=redis` | | Redis connection, required when SEQ_QUEUE=redis. Enable persistence on the Redis side. | | `SEQ_ENCRYPTION_KEYS` | string | yes | | Encryption keys for every stored secret, `id:base64key[,id:base64key...]`; the first entry encrypts, every entry decrypts. Generate one with `oseq secrets new-key`. Back it up with the database: without it the stored secrets are unreadable and must be re-entered. | | `SEQ_ADMIN_TOKEN` | string | for `api` and `all` | | The operator token that creates projects and keys (`/v1/admin/*`). Required by the `api` and `all` roles. Long and random. | | `SEQ_PUBLIC_URL` | URL | no | `"http://localhost:8080"` | The base URL providers call back: inbound webhooks and the opt-out links. The OpenAPI document served by the instance lists it as its server. | | `SEQ_PORT` | number | no | `8080` | HTTP port. The API for `api` and `all`; `/healthz` and `/readyz` only for `worker`. | | `SEQ_HOST` | string | no | `"0.0.0.0"` | The interface to bind. | | `SEQ_ROLES` | `api`, `worker`, `all` | no | `"all"` | `api` serves HTTP, `worker` runs the scheduler and the queue consumers, `all` does both in one process. | | `SEQ_RUN_MIGRATIONS` | flag: `1` or `true` | no | | Apply the `seq` and `seq_auth` migrations at boot, serialized by a row lock so replicas starting together do not race. | | `SEQ_CONCURRENCY` | number | no | `8` | Messages in flight per queue per replica. | | `SEQ_DISABLED_CHANNELS` | comma-separated list | no | | Platform-wide kill switch per channel, comma-separated (`sms`). Steps on a disabled channel are deferred, not skipped. | | `SEQ_PAUSED` | flag: `1` or `true` | no | | Platform-wide stop: the planner claims nothing while it is on. In-flight steps finish. | | `SEQ_DEV_MOCK_PROVIDERS` | flag: `1` or `true` | no | | Every project uses the `mock` adapters: nothing reaches a mail server, Allo or Attio, sends land in the timeline, and `POST /hooks/mock/\{slug\}` simulates replies, bounces and calls. Refused when NODE_ENV=production. | | `SEQ_LOG_LEVEL` | `fatal`, `error`, `warn`, `info`, `debug`, `trace` | no | `"info"` | Pino log level. | | `SEQ_METRICS` | flag: `1` or `true` | no | | Reserved for a Prometheus `/metrics` endpoint. Accepted by the schema; the endpoint is not served yet. | | `SEQ_DB_POOL` | number | no | `10` | Postgres connections per process. | | `NODE_ENV` | string | no | `"development"` | `production` turns off pretty logs and refuses SEQ_DEV_MOCK_PROVIDERS. | Three rules are checked after parsing: `SEQ_QUEUE=redis` needs `SEQ_REDIS_DSN`; the `api` and `all` roles need `SEQ_ADMIN_TOKEN`; `SEQ_DEV_MOCK_PROVIDERS` is refused when `NODE_ENV=production`. # Sequence definition JSON Schema (https://docs.opensequence.dev/reference/definition-schema) The JSON Schema of a sequence definition, generated from the Zod source of truth. This page is generated from `packages/core/src/domain/definition/schema.ts` by `pnpm generate`. Do not edit it by hand; change the source and regenerate. The same document is served by `GET /v1/schema` (with the node and channel catalogue) so a canvas, a script or an agent validates against what the service enforces. Node `params` are open here and validated per node type and channel action: see [Nodes and channels](/reference/nodes). Limits: 200 nodes, 10 MB per definition, 1000 characters per SMS body, 100,000 characters per text email body and 5,000,000 per html email body, 300 characters per LinkedIn note (longer rendered notes are cut). ## Top level [#top-level] | Param | Type | Required | Default | Constraints | | --- | --- | --- | --- | --- | | `schema_version` | `1` | yes | | | | `entry` | string | yes | | pattern `^[a-z][a-z0-9_]*$`; min length 1; max length 64 | | `settings` | object | no | `{"reenroll":"never"}` | | | `exit_on` | array of `"reply"`, `"meeting_booked"` | no | `[]` | | | `nodes` | object | yes | | | ## settings [#settings] | Param | Type | Required | Default | Constraints | | --- | --- | --- | --- | --- | | `send_window` | object | no | | | | `jitter` | string | no | | pattern `^(\d+)(m\|h\|d\|bd)$` | | `reenroll` | string | no | `"never"` | pattern `^(never\|always\|after_\d+d)$` | ## settings.send_window [#settingssend_window] | Param | Type | Required | Default | Constraints | | --- | --- | --- | --- | --- | | `days` | array of `"mon"`, `"tue"`, `"wed"`, `"thu"`, `"fri"`, `"sat"`, `"sun"` | yes | | min items 1 | | `from` | string | yes | | pattern `^([01]\d\|2[0-3]):[0-5]\d$` | | `to` | string | yes | | pattern `^([01]\d\|2[0-3]):[0-5]\d$` | | `tz` | `"contact"`, `"sender"` | no | `"contact"` | | ## nodes.\{id\} [#nodesid] Node ids are `lower_snake_case`, up to 64 characters. | Param | Type | Required | Default | Constraints | | --- | --- | --- | --- | --- | | `type` | string | yes | | min length 1 | | `name` | string | no | | max length 120 | | `channel` | string | no | | | | `action` | string | no | | | | `params` | object | no | | | | `next` | object | no | `{}` | | | `branches_by_outcome` | object | no | | | ## JSON Schema [#json-schema] ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": { "schema_version": { "type": "number", "const": 1 }, "entry": { "type": "string", "minLength": 1, "maxLength": 64, "pattern": "^[a-z][a-z0-9_]*$" }, "settings": { "default": { "reenroll": "never" }, "type": "object", "properties": { "send_window": { "type": "object", "properties": { "days": { "minItems": 1, "type": "array", "items": { "type": "string", "enum": [ "mon", "tue", "wed", "thu", "fri", "sat", "sun" ] } }, "from": { "type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$" }, "to": { "type": "string", "pattern": "^([01]\\d|2[0-3]):[0-5]\\d$" }, "tz": { "default": "contact", "type": "string", "enum": [ "contact", "sender" ] } }, "required": [ "days", "from", "to" ] }, "jitter": { "type": "string", "pattern": "^(\\d+)(m|h|d|bd)$" }, "reenroll": { "default": "never", "type": "string", "pattern": "^(never|always|after_\\d+d)$" } } }, "exit_on": { "default": [], "type": "array", "items": { "type": "string", "enum": [ "reply", "meeting_booked" ] } }, "nodes": { "type": "object", "propertyNames": { "type": "string", "minLength": 1, "maxLength": 64, "pattern": "^[a-z][a-z0-9_]*$" }, "additionalProperties": { "type": "object", "properties": { "type": { "type": "string", "minLength": 1 }, "name": { "type": "string", "maxLength": 120 }, "channel": { "type": "string" }, "action": { "type": "string" }, "params": { "type": "object", "propertyNames": { "type": "string" }, "additionalProperties": {} }, "next": { "default": {}, "type": "object", "propertyNames": { "type": "string" }, "additionalProperties": { "type": "string", "minLength": 1, "maxLength": 64, "pattern": "^[a-z][a-z0-9_]*$" } }, "branches_by_outcome": { "type": "object", "propertyNames": { "type": "string" }, "additionalProperties": { "type": "string", "minLength": 1, "maxLength": 64, "pattern": "^[a-z][a-z0-9_]*$" } } }, "required": [ "type" ] } } }, "required": [ "schema_version", "entry", "nodes" ] } ``` # Error codes reference (https://docs.opensequence.dev/reference/error-codes) Every stable error code OpenSequence returns, from definition validation problems to HTTP errors. This page is generated from `the error helpers in packages/core, packages/engine, packages/auth and apps/server` by `pnpm generate`. Do not edit it by hand; change the source and regenerate. A search for a code lands here. HTTP errors come in the [error envelope](/api/errors); validation problems come in a `problems` array with a JSON path. ## Validation problems [#validation-problems] | Code | Severity | Example message | | --- | --- | --- | | `BAD_EVENT` | error | The event "…" is waited for but has no next step. | | `BAD_OPERATOR` | error | "…" cannot be used on … (…). Use one of: …. | | `BAD_TEMPLATE` | error | "\{\{ … \}\}" is not something a template can read. Use contact.*, attrs.*, sender.*, sequence.name or unsubscribe_url. | | `BAD_VALUE` | error | "…" needs a value. | | `CYCLE` | error | Steps … loop without a wait in between; the contact would never leave them. | | `HEAVY_EMAIL` | warning | This email embeds … KB of base64 images (more than … KB). Heavy emails land in spam and get clipped; host large images over https. | | `INVALID_DEFINITION` | error | The definition is … MB; the limit is … MB. Host large images over https instead of embedding them. | | `MISSING_TRANSITION` | error | A … step must say where "…" goes. | | `NO_BRIEF` | warning | This call turns on … but has no description. The agent only uses a skill when the description says when to. | | `NO_UNSUBSCRIBE` | warning | This email has no \{\{ unsubscribe_url \}\}. Recipients cannot opt out with one click. | | `TOO_LONG` | warning | LinkedIn takes notes of up to … characters; this one is …. It will be cut. | | `UNKNOWN_ACTION` | error | "…" is not an action of …. Available: …. | | `UNKNOWN_CHANNEL` | error | An outreach step needs a channel. | | `UNKNOWN_FIELD` | error | "…" is not a field conditions can read. | | `UNKNOWN_NODE` | error | The entry node "…" does not exist. | | `UNKNOWN_NODE_TYPE` | error | "…" is not a node type. Available: …. | | `UNREACHABLE_NODE` | error | "…" can never be reached from the entry step. | ## HTTP error codes [#http-error-codes] | Code | HTTP | Message | What to do | | --- | --- | --- | --- | | `ALREADY_IN_SEQUENCE` | 409 | … of the … contacts are already in a sequence. Nobody was enrolled. Remove them from the selection or exit them from their current sequence first. | Remove the listed contacts (`details.conflicts`) from the selection, or exit them first with `POST /v1/enrollments/\{id\}/exit`. Nobody was enrolled. | | `BAD_FLAG` | 422 | A flag is "global" or "channel:\". | | | `BAD_OUTCOME` | 422 | Give the outcome of the task, like "connected" or "no_answer". | | | `BAD_SCOPE` | 422 | Unknown scope: …. Use read, enroll or admin. | | | `BAD_TAG` | 422 | A tag is up to 24 letters, digits, dots and dashes, like v2. | | | `BATCH_TOO_LARGE` | 422 | At most … contacts per call. | | | `CONFLICT` | 409 | This owner already has a connection in another tenant. | | | `CREDENTIAL_INVALID` | 409 | The … credential was marked invalid by a health check. Register a new one. | | | `CREDENTIALS_NEEDED` | 409 | credentials_needed: connection … is …; set the channel again. | | | `ENDPOINT_DISABLED` | 409 | Enable the endpoint first; it is disabled. | | | `FROM_REQUIRED` | 422 | Say which address mail goes out from: set "from", or use the full mailbox address as the SMTP user. | | | `HAS_ACTIVE_ENROLLMENTS` | 409 | … contacts are still in this sequence. Exit them first, or send exit_active: true. | Exit them first, or send `exit_active: true` to exit them with reason `manual`. | | `INSUFFICIENT_SCOPE` | 403 | This key cannot do that; it needs the "…" scope. | Use a key with the scope the route needs (`read` \< `enroll` \< `admin`). | | `INTERNAL_ERROR` | 500 | Something went wrong on our side. Reference …. | | | `INVALID_DEFINITION` | 422 | The definition has errors; fix them before publishing. `details.problems` lists them. | Fix every problem in `details.problems` (each has a `path`, a `code` and a sentence) and publish again. Saving a draft with errors is allowed; publishing is not. | | `INVALID_EVENT` | 422 | The event is not valid: … | | | `INVALID_SLUG` | 422 | A slug is 3 to 48 lowercase letters, digits and dashes. | | | `MISSING_SECRET` | 422 | An api_key credential needs api_key. | | | `NO_CONTACTS` | 422 | Give at least one contact. | | | `NO_PUBLISHED_VERSION` | 409 | This sequence has no published version yet. | Publish a version before enrolling. | | `NOT_ACTIVE` | 409 | This enrollment is … (only active and waiting_limit enrollments can be paused). | | | `NOT_FOUND` | 404 | … "…" was not found. (Also: no route for this method and path.) | | | `NOT_PAUSED` | 409 | This enrollment is … (only paused and waiting_limit enrollments can be resumed). | | | `NUMBER_HAS_NO_SMS` | 422 | … cannot send SMS. | | | `REQUEST_ERROR` | 400, 413, 429 | A request-level error with its own message: malformed JSON (400), a body over 2 MB (413), or "Rate limit exceeded, retry in …" (429, 600 requests per minute per key, with a `Retry-After` header). | | | `SENDER_DISABLED` | 409 | … is disabled. | | | `SEQUENCE_NOT_ACTIVE` | 409 | The sequence is …. | | | `SLUG_TAKEN` | 409 | The slug "…" is already used. | | | `STALE_LOCK` | 409 | Someone else saved this draft after you loaded it. Reload and try again. | Reload the version, re-apply your change on the new `lock_version`, save again. | | `TAG_TAKEN` | 409 | Version … already exists. | | | `UNAUTHORIZED` | 401 | Send a project API key as a Bearer token. / This API key is unknown or revoked. / This endpoint needs the operator token. | Send `Authorization: Bearer \`; the key must exist and not be revoked. `/v1/admin/*` wants the operator token instead. | | `UNKNOWN_CHANNEL` | 422 | "…" is not a channel. | | | `UNKNOWN_EVENT_TYPE` | 422 | Unknown event type: …. Use "*" or one of …. | Use `"*"` or the types listed by `GET /v1/schema/events`. | | `UNKNOWN_NUMBER` | 422 | … is not a number the Allo key can see. | | | `UNSAFE_URL` | 422 | The endpoint URL …. | Endpoint URLs must be `https`, carry no credentials, and resolve to a public address. | | `UNSUBSCRIBE_TOKEN_EXPIRED` | 400 | This unsubscribe link has expired (links last 90 days). Ask the person to reply to the email instead, or report an opt_out with POST /v1/contacts/\{id\}/events. | | | `UNSUBSCRIBE_TOKEN_INVALID` | 400 | This unsubscribe token is not valid: it was not issued by this server for this project, it was altered, or its contact was deleted. | | | `VALIDATION_ERROR` | 400 | The request did not match the schema. `details` lists each path and message. | | | `VERSION_NOT_EDITABLE` | 409 | Version … is … and cannot be edited. Create a new version from it. (Also: only drafts can be deleted.) | Published and archived versions are frozen. Create a new draft from it: `POST /v1/sequences/\{id\}/versions` with `from_version`. | | `VERSION_NOT_PUBLISHED` | 409 | Version … is …; only a published version can enroll. | | # Node types and channel actions (https://docs.opensequence.dev/reference/nodes) Every registered node type and channel action, with its params, defaults and transitions. This page is generated from `packages/core/src/domain/definition/builtins.ts` by `pnpm generate`. Do not edit it by hand; change the source and regenerate. The engine holds no list of node types or channels: both are registries (docs/ARCHITECTURE.md section 20). `GET /v1/schema` serves the same catalogue. For examples of each node see [Nodes](/docs/concepts/sequence/nodes). ## Node types [#node-types] ### `start`: Start [#start-start] Transitions: `then`; required: `then`. _No parameters._ ### `end`: End [#end-end] Transitions: none (terminal). | Param | Type | Required | Default | Constraints | | --- | --- | --- | --- | --- | | `label` | string | no | | max length 80 | ### `wait`: Wait [#wait-wait] Transitions: `then`; required: `then`. | Param | Type | Required | Default | Constraints | | --- | --- | --- | --- | --- | | `duration` | string | yes | | pattern `^(\d+)(m\|h\|d\|bd)$` | ### `wait_for`: Wait for an event [#wait_for-wait-for-an-event] Transitions: `reply`, `reply:email`, `reply:sms`, `call_connected`, `meeting_booked`, `timeout`. | Param | Type | Required | Default | Constraints | | --- | --- | --- | --- | --- | | `events` | array of `"reply"`, `"reply:email"`, `"reply:sms"`, `"call_connected"`, `"meeting_booked"` | yes | | min items 1 | | `timeout` | string | no | | pattern `^(\d+)(m\|h\|d\|bd)$` | ### `condition`: Condition [#condition-condition] Transitions: `yes`, `no`; required: `yes`, `no`. | Param | Type | Required | Default | Constraints | | --- | --- | --- | --- | --- | | `mode` | `"all"`, `"any"` | yes | | | | `rules` | array of object | yes | | min items 1; max items 20 | ### `task`: Task for the sender [#task-task-for-the-sender] Transitions: `completed`, `no_answer`. | Param | Type | Required | Default | Constraints | | --- | --- | --- | --- | --- | | `kind` | string | yes | | pattern `^[a-z][a-z0-9_]*$`; min length 1; max length 32 | | `title` | string | yes | | min length 1; max length 200 | | `body` | string | no | | max length 4000 | | `link` | string | no | | max length 2000 | | `due` | string | yes | | pattern `^(\d+)(m\|h\|d\|bd)$` | | `expire` | string | no | | pattern `^(\d+)(m\|h\|d\|bd)$` | | `connected_outcomes` | array of string | no | `["connected"]` | | | `dialer` | boolean | no | `false` | | | `auto_complete` | boolean | no | `true` | | ### `linkedin_connect`: LinkedIn connection request [#linkedin_connect-linkedin-connection-request] Transitions: `completed`, `no_answer`, `skipped`. | Param | Type | Required | Default | Constraints | | --- | --- | --- | --- | --- | | `title` | string | no | `"Connect with {{ contact.first_name \| \"them\" }} on LinkedIn"` | min length 1; max length 200 | | `note` | string | no | | max length 4000 | | `due` | string | no | | pattern `^(\d+)(m\|h\|d\|bd)$` | | `expire` | string | no | | pattern `^(\d+)(m\|h\|d\|bd)$` | ### `outreach`: Outreach [#outreach-outreach] Transitions: `sent`, `skipped`, `failed`. Params are defined by the channel action; see [Channels](#channels). ## Channels [#channels] ### `email`: Email [#email-email] Queue `seq_email`. #### `email send`: Send an email [#email-send-send-an-email] Counts as a touch: yes. Transitions: `sent`, `skipped`, `failed`. | Param | Type | Required | Default | Constraints | | --- | --- | --- | --- | --- | | `name` | string | no | | max length 120 | | `subject` | string | yes | | min length 1; max length 300 | | `body` | string | yes | | min length 1; max length 5000000 | | `format` | `"text"`, `"html"` | no | `"text"` | | | `reply_in_thread` | boolean | no | `false` | | ### `sms`: SMS [#sms-sms] Queue `seq_sms`. #### `sms send`: Send a text [#sms-send-send-a-text] Counts as a touch: yes. Transitions: `sent`, `skipped`, `failed`. | Param | Type | Required | Default | Constraints | | --- | --- | --- | --- | --- | | `name` | string | no | | max length 120 | | `body` | string | yes | | min length 1; max length 1000 | ### `call`: Call [#call-call] Queue `seq_call`. #### `call agent_call`: Call with an AI agent [#call-agent_call-call-with-an-ai-agent] Counts as a touch: yes. Transitions: `completed`, `reached`, `transferred`, `not_interested`, `wrong_number`, `do_not_call`, `not_reached`, `skipped`, `failed`. | Param | Type | Required | Default | Constraints | | --- | --- | --- | --- | --- | | `name` | string | no | | max length 120 | | `agent_id` | string | yes | | min length 1; max length 64 | | `allo_number` | string | no | | pattern `^\+[1-9]\d{6,14}$` | | `title` | string | yes | | min length 1; max length 200 | | `description` | string | no | | max length 4000 | | `skills` | object | no | | | | `give_up_after` | string | no | `"3d"` | pattern `^(\d+)(m\|h\|d\|bd)$` | | `exit_on_connect` | boolean | no | `true` | | # Webhook event catalogue (https://docs.opensequence.dev/reference/webhook-events) The webhook event catalogue: when each event fires and what its payload carries. This page is generated from `packages/engine/src/domain/shared/events.ts` by `pnpm generate`. Do not edit it by hand; change the source and regenerate. `GET /v1/schema/events` returns the same list. Every delivery body has the shape below, five fields and nothing else; the fields in the table are inside `data`. Subscribe to `"*"` or to a list of types when you create an endpoint. See [Receiving webhooks](/docs/webhooks/events). ```json { "id": "evt_01J9…", "type": "enrollment.exited", "project": "prj_01J9…", "occurred_at": "2026-10-13T09:00:00.000Z", "data": { "enrollment": { "id": "enr_01J9…", "seq": 7, "...": "..." }, "exit_reason": "replied", "signal": "sig_01J9…" } } ``` Payload fields are snake_case. `enrollment` in a payload is a summary built for the event (`id`, `sequence`, `version`, `contact`, `sender`, `status`, `mode`, `current_node_id`, `exit_reason`, `pause_reason`, `touch_count`, `replied_at`, `meeting_booked_at`, `enrolled_at`, `finished_at`, `seq`), with `contact` and `sender` as ids; `task` is `id`, `kind`, `title`, `body`, `link`, `opened_at`, `due_at`, `expires_at`, `status`, `outcome`, `dialer`, `enrollment`, `contact`, `sender`. Only `signal.received` carries a `contact` object; every other event names the contact by id through `enrollment.contact` or `task.contact`. | Event | When | Payload (`data`) | | --- | --- | --- | | `enrollment.created` | after a successful enroll, one per contact | `enrollment` (id, sequence, version, contact, sender, status, mode, current_node_id, touch_count, enrolled_at, seq) | | `enrollment.exited` | an exit by rule (reply, meeting, opt-out, bounce, suppression) or by API | `enrollment`, `exit_reason` (`replied`, `meeting_booked`, `opt_out`, `bounced`, `suppressed`, `manual`, `deleted`), `signal` (the signal id, when one caused it), `label` (manual exits). Two exits carry the enrollment **id** in `enrollment` instead of the object: a contact erased with `DELETE /v1/contacts/\{id\}` adds `contact: \{ id, external_id \}`; a sequence archived with `exit_active` adds `contact: \{ id \}` | | `enrollment.completed` | an `end` node, an unwired transition, or a task completed with no next step | `enrollment` | | `enrollment.paused` | a manual pause, an out-of-office reply, or a step that failed with no `failed` transition | `enrollment`, `pause_reason` (`manual`, `ooo`, `step_failed`), `paused_until` | | `enrollment.resumed` | a manual resume or a pause whose `paused_until` passed | `enrollment`, `pause_reason` (the reason it had), `paused_until: null` | | `run.done` | an outreach step was sent | `run` (id, node_id, node_type, channel, action, status, touch_number, provider, provider_ref, branch, enrollment), `enrollment`. No subject or body: the journey (`GET /v1/enrollments/\{id\}`) has the message whose `runId` is `run.id` | | `run.skipped` | a gate refused a step for good (no consent, no phone, suppressed, no channel, country not allowed, no time zone) | `run`, `reason` | | `run.failed` | a step ran out of retries or was stuck | `run`, `error` | | `run.needs_review` | the outcome of a send is unknown (an SMS that may or may not have left) | `run`, `error` | | `task.created` | a `task` or `linkedin_connect` node created a task for the sender | `task` (id, kind, title, body, link, opened_at, due_at, expires_at, status, outcome, dialer, enrollment, contact, sender) | | `task.expired` | a task reached `expires_at` (the step takes `no_answer`) or was cancelled by an exit | `task` (the id only when expired by the timer; the full task when cancelled by an exit) | | `signal.received` | any signal was processed: reply, bounce, complaint, opt-out, meeting, call, task completion, client event | `signal` (id, kind, channel, source, occurred_at, attribution, attributed_run), `contact` (id, external_id, email, phone, first_name, last_name). `kind` is one of `reply`, `bounce`, `complaint`, `opt_out`, `ooo`, `task_completed`, `call_connected`, `meeting_booked`, `contact_suppressed`; the schema also declares `sender_channel_status` and `crm_changed`, which nothing records today. The only event that carries `contact` | | `sender.channel_status` | a channel changed status (`credentials_needed`, `restricted`, back to `active`) | `sender`, `channel`, `status` | | `endpoint.disabled` | an endpoint failed every delivery for three days, or its secret can no longer be decrypted | `endpoint` (id, url, event_types, status, disabled_reason, disabled_at), `reason` | # oseq operator CLI (https://docs.opensequence.dev/sdks/cli) What the oseq operator CLI does: migrations, projects, API keys, encryption keys and health, with every command and option. This page is generated from `apps/server/src/cli.ts` by `pnpm generate`. Do not edit it by hand; change the source and regenerate. `oseq` (version 0.1.0) ships in the server image and in the `@opensequence/server` package. Every command is a thin wrapper over the same use cases the API exposes, so the docs for the API are the docs for the CLI. It reads the same `SEQ_*` environment as the server (it needs `SEQ_DB_DSN` and `SEQ_ENCRYPTION_KEYS`; `SEQ_ADMIN_TOKEN` is not needed). ```bash # in the image docker compose exec opensequence node dist/cli.js projects create acme --name "Acme CRM" # from the repository pnpm oseq -- projects create acme --name "Acme CRM" ``` ## Commands [#commands] ### `oseq secrets` [#oseq-secrets] Encryption keys ### `oseq secrets new-key` [#oseq-secrets-new-key] Print a new SEQ_ENCRYPTION_KEYS entry (id:base64 of 32 random bytes) ### `oseq migrate` [#oseq-migrate] Apply the seq and auth migrations ### `oseq projects` [#oseq-projects] Tenants ### `oseq projects create ` [#oseq-projects-create-slug] Create a project and print its first admin API key (shown once) | Option | Required | Default | Meaning | | --- | --- | --- | --- | | `-n, --name ` | no | | display name | ### `oseq projects list` [#oseq-projects-list] ### `oseq api-keys` [#oseq-api-keys] Project API keys ### `oseq api-keys create ` [#oseq-api-keys-create-project] | Option | Required | Default | Meaning | | --- | --- | --- | --- | | `-s, --scopes ` | yes | | comma-separated: read,enroll,admin | | `-n, --name ` | no | `cli` | label | ### `oseq health` [#oseq-health] Queue depths and job state The architecture document also lists `oseq secrets rotate`, `oseq webhooks replay` and `oseq queue dead list | replay`. They are not implemented yet: rotate keys through the auth module's `rotateKeys()`, replay deliveries through `POST /v1/webhooks/deliveries/\{id\}/replay`. # List projects (https://docs.opensequence.dev/api/operator/get-admin-projects) API reference page for GET /v1/admin/projects. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Create a project and its first admin key (shown once) (https://docs.opensequence.dev/api/operator/post-admin-projects) API reference page for POST /v1/admin/projects. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Create an API key for a project (shown once) (https://docs.opensequence.dev/api/operator/post-admin-projects-id-api-keys) API reference page for POST /v1/admin/projects/{id}/api-keys. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Platform-wide queue depths and job state (https://docs.opensequence.dev/api/operator/get-admin-engine-health) API reference page for GET /v1/admin/engine/health. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # The project, its settings, provider credential status and webhook URLs (https://docs.opensequence.dev/api/project/get-project) API reference page for GET /v1/project. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Update settings (merged) (https://docs.opensequence.dev/api/project/put-project-settings) API reference page for PUT /v1/project/settings. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Store or rotate a provider credential (write-only). Allo: api_key, webhook_secret?; Attio: api_key. (https://docs.opensequence.dev/api/project/put-project-providers-provider) API reference page for PUT /v1/project/providers/{provider}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Numbers the Allo key can see (for pickers) (https://docs.opensequence.dev/api/project/get-project-providers-allo-numbers) API reference page for GET /v1/project/providers/allo/numbers. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Allo team members (for mapping senders) (https://docs.opensequence.dev/api/project/get-project-providers-allo-users) API reference page for GET /v1/project/providers/allo/users. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Allo Outbound agents and the lines each one calls from (for the agent call step) (https://docs.opensequence.dev/api/project/get-project-providers-allo-agents) API reference page for GET /v1/project/providers/allo/agents. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Attio objects and attributes, for crm.* condition pickers (https://docs.opensequence.dev/api/project/get-project-providers-attio-schema) API reference page for GET /v1/project/providers/attio/schema. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # List API keys (prefix only) (https://docs.opensequence.dev/api/project/get-api-keys) API reference page for GET /v1/api-keys. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Create an API key (shown once) (https://docs.opensequence.dev/api/project/post-api-keys) API reference page for POST /v1/api-keys. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Revoke an API key (https://docs.opensequence.dev/api/project/delete-api-keys-id) API reference page for DELETE /v1/api-keys/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # This project's flags, queue depths and job state (https://docs.opensequence.dev/api/engine/get-engine-health) API reference page for GET /v1/engine/health. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Flip a kill switch: global or channel: (https://docs.opensequence.dev/api/engine/put-engine-flags-key) API reference page for PUT /v1/engine/flags/{key}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # A sender with channels, connections and readiness (https://docs.opensequence.dev/api/senders/get-senders-id) API reference page for GET /v1/senders/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Disable a sender (their enrollments pause; nothing is deleted) (https://docs.opensequence.dev/api/senders/delete-senders-id) API reference page for DELETE /v1/senders/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Create or update a sender by your own id (https://docs.opensequence.dev/api/senders/put-senders-id) API reference page for PUT /v1/senders/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # List senders (https://docs.opensequence.dev/api/senders/get-senders) API reference page for GET /v1/senders. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Which steps this sender can run, and why not (https://docs.opensequence.dev/api/senders/get-senders-id-readiness) API reference page for GET /v1/senders/{id}/readiness. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Send from any mailbox over SMTP, read replies over IMAP; both logins are checked before anything is stored (https://docs.opensequence.dev/api/senders/put-senders-id-channels-email) API reference page for PUT /v1/senders/{id}/channels/email. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Mailbox connections of a sender (no secrets) (https://docs.opensequence.dev/api/senders/get-senders-id-connections) API reference page for GET /v1/senders/{id}/connections. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # The sender's Allo number and user (https://docs.opensequence.dev/api/senders/put-senders-id-channels-sms) API reference page for PUT /v1/senders/{id}/channels/sms. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Limits and status of a channel (https://docs.opensequence.dev/api/senders/patch-senders-id-channels-channel) API reference page for PATCH /v1/senders/{id}/channels/{channel}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Remove a channel; its steps skip from now on. Removing email deletes the stored SMTP and IMAP passwords (https://docs.opensequence.dev/api/senders/delete-senders-id-channels-channel) API reference page for DELETE /v1/senders/{id}/channels/{channel}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # A sender's tasks (https://docs.opensequence.dev/api/tasks/get-senders-id-tasks) API reference page for GET /v1/senders/{id}/tasks. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # List tasks (https://docs.opensequence.dev/api/tasks/get-tasks) API reference page for GET /v1/tasks. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # A task (https://docs.opensequence.dev/api/tasks/get-tasks-id) API reference page for GET /v1/tasks/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Complete with an outcome; wakes the waiting step (https://docs.opensequence.dev/api/tasks/post-tasks-id-complete) API reference page for POST /v1/tasks/{id}/complete. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # The sender opened the task; a LinkedIn task completes as sent (https://docs.opensequence.dev/api/tasks/post-tasks-id-open) API reference page for POST /v1/tasks/{id}/open. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Cancel an open task; the step takes no_answer (https://docs.opensequence.dev/api/tasks/post-tasks-id-cancel) API reference page for POST /v1/tasks/{id}/cancel. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # A contact with suppressions and the active enrollment (https://docs.opensequence.dev/api/contacts/get-contacts-id) API reference page for GET /v1/contacts/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Change fields; changing attrs keeps conditions fresh (https://docs.opensequence.dev/api/contacts/patch-contacts-id) API reference page for PATCH /v1/contacts/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Erase a contact and everything attached (privacy requests) (https://docs.opensequence.dev/api/contacts/delete-contacts-id) API reference page for DELETE /v1/contacts/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Create or update a contact by your own id (attrs are merged) (https://docs.opensequence.dev/api/contacts/put-contacts-id) API reference page for PUT /v1/contacts/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Upsert up to 500 contacts (https://docs.opensequence.dev/api/contacts/post-contacts-batch) API reference page for POST /v1/contacts:batch. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Each contact's active enrollment or null (for badges) (https://docs.opensequence.dev/api/contacts/post-contacts-status) API reference page for POST /v1/contacts:status. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Report up to 500 events the service cannot see (meetings, opt-outs, suppressions) (https://docs.opensequence.dev/api/contacts/post-contacts-events) API reference page for POST /v1/contacts:events. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # List contacts (https://docs.opensequence.dev/api/contacts/get-contacts) API reference page for GET /v1/contacts. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Messages, runs, signals and tasks for a contact, merged and ordered (https://docs.opensequence.dev/api/contacts/get-contacts-id-timeline) API reference page for GET /v1/contacts/{id}/timeline. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Record consent to texts and agent calls (admin only) (https://docs.opensequence.dev/api/contacts/put-contacts-id-outreach-consent) API reference page for PUT /v1/contacts/{id}/outreach-consent. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Old name of PUT /v1/contacts/{id}/outreach-consent (https://docs.opensequence.dev/api/contacts/put-contacts-id-sms-consent) API reference page for PUT /v1/contacts/{id}/sms-consent. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Report an event the service cannot see: meeting_booked, opt_out, suppressed, reply (https://docs.opensequence.dev/api/contacts/post-contacts-id-events) API reference page for POST /v1/contacts/{id}/events. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # List sequences with their versions and enrollment counts by status (https://docs.opensequence.dev/api/sequences/get-sequences) API reference page for GET /v1/sequences. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Create a sequence and its v1 draft (https://docs.opensequence.dev/api/sequences/post-sequences) API reference page for POST /v1/sequences. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # A sequence with its versions (https://docs.opensequence.dev/api/sequences/get-sequences-id) API reference page for GET /v1/sequences/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Rename, describe, pause or archive (https://docs.opensequence.dev/api/sequences/patch-sequences-id) API reference page for PATCH /v1/sequences/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Versions of a sequence (https://docs.opensequence.dev/api/sequences/get-sequences-id-versions) API reference page for GET /v1/sequences/{id}/versions. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Copy a version into a new draft (https://docs.opensequence.dev/api/sequences/post-sequences-id-versions) API reference page for POST /v1/sequences/{id}/versions. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # A version: definition and validation problems (https://docs.opensequence.dev/api/sequences/get-sequences-id-versions-vid) API reference page for GET /v1/sequences/{id}/versions/{vid}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Delete a draft (https://docs.opensequence.dev/api/sequences/delete-sequences-id-versions-vid) API reference page for DELETE /v1/sequences/{id}/versions/{vid}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Save a draft (optimistic lock) (https://docs.opensequence.dev/api/sequences/put-sequences-id-versions-vid-draft) API reference page for PUT /v1/sequences/{id}/versions/{vid}/draft. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Validate (errors block), publish, make default (https://docs.opensequence.dev/api/sequences/post-sequences-id-versions-vid-publish) API reference page for POST /v1/sequences/{id}/versions/{vid}/publish. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Stop new enrollments into this version (https://docs.opensequence.dev/api/sequences/post-sequences-id-versions-vid-archive) API reference page for POST /v1/sequences/{id}/versions/{vid}/archive. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Validate a definition without saving (https://docs.opensequence.dev/api/sequences/post-sequences-validate) API reference page for POST /v1/sequences:validate. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # JSON Schema of the definition plus the node and channel catalogue (https://docs.opensequence.dev/api/schema/get-schema) API reference page for GET /v1/schema. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Condition fields: the registry plus the project attrs_schema (https://docs.opensequence.dev/api/schema/get-schema-fields) API reference page for GET /v1/schema/fields. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # The webhook event catalogue (https://docs.opensequence.dev/api/schema/get-schema-events) API reference page for GET /v1/schema/events. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Preflight: conflicts, exclusions, capacity; no writes (https://docs.opensequence.dev/api/enrollments/post-sequences-id-enrollments-preview) API reference page for POST /v1/sequences/{id}/enrollments:preview. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Enroll contacts (all-or-nothing on ALREADY_IN_SEQUENCE) (https://docs.opensequence.dev/api/enrollments/post-sequences-id-enrollments) API reference page for POST /v1/sequences/{id}/enrollments. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # List enrollments with the contact summary (https://docs.opensequence.dev/api/enrollments/get-enrollments) API reference page for GET /v1/enrollments. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # The journey: definition, runs with facts, messages, signals, tasks (https://docs.opensequence.dev/api/enrollments/get-enrollments-id) API reference page for GET /v1/enrollments/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Pause (https://docs.opensequence.dev/api/enrollments/post-enrollments-id-pause) API reference page for POST /v1/enrollments/{id}/pause. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Resume (https://docs.opensequence.dev/api/enrollments/post-enrollments-id-resume) API reference page for POST /v1/enrollments/{id}/resume. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Exit with reason manual and your label (https://docs.opensequence.dev/api/enrollments/post-enrollments-id-exit) API reference page for POST /v1/enrollments/{id}/exit. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Exit by selector: a contact, or a sequence and status (https://docs.opensequence.dev/api/enrollments/post-enrollments-exit) API reference page for POST /v1/enrollments:exit. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # List endpoints (https://docs.opensequence.dev/api/webhooks/get-webhooks) API reference page for GET /v1/webhooks. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Create an endpoint; the signing secret is shown once (https://docs.opensequence.dev/api/webhooks/post-webhooks) API reference page for POST /v1/webhooks. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # An endpoint (https://docs.opensequence.dev/api/webhooks/get-webhooks-id) API reference page for GET /v1/webhooks/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Change url or event types (https://docs.opensequence.dev/api/webhooks/patch-webhooks-id) API reference page for PATCH /v1/webhooks/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Delete an endpoint (https://docs.opensequence.dev/api/webhooks/delete-webhooks-id) API reference page for DELETE /v1/webhooks/{id}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Rotate the signing secret (shown once) (https://docs.opensequence.dev/api/webhooks/post-webhooks-id-rotate-secret) API reference page for POST /v1/webhooks/{id}/rotate-secret. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Re-enable a disabled endpoint and replay what was held (https://docs.opensequence.dev/api/webhooks/post-webhooks-id-enable) API reference page for POST /v1/webhooks/{id}/enable. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Re-send every failed delivery since a time (https://docs.opensequence.dev/api/webhooks/post-webhooks-id-recover) API reference page for POST /v1/webhooks/{id}/recover. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Deliveries of an endpoint (https://docs.opensequence.dev/api/webhooks/get-webhooks-id-deliveries) API reference page for GET /v1/webhooks/{id}/deliveries. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Re-send one delivery (https://docs.opensequence.dev/api/webhooks/post-webhooks-deliveries-id-replay) API reference page for POST /v1/webhooks/deliveries/{id}/replay. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Every sequence with enrolled, replies, meetings and rates (https://docs.opensequence.dev/api/analytics/get-analytics-sequences) API reference page for GET /v1/analytics/sequences. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Enrolled, active, exited, completed, delivered touches, replies and meetings, with rates (https://docs.opensequence.dev/api/analytics/get-sequences-id-analytics-summary) API reference page for GET /v1/sequences/{id}/analytics/summary. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Exits by reason, largest first (https://docs.opensequence.dev/api/analytics/get-sequences-id-analytics-exits) API reference page for GET /v1/sequences/{id}/analytics/exits. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Per step: reached, executed, skipped by reason, failed, delivered, bounced, replies, meetings (https://docs.opensequence.dev/api/analytics/get-sequences-id-analytics-nodes) API reference page for GET /v1/sequences/{id}/analytics/nodes. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Per channel and touch number: sent, delivered, bounced, replies, meetings (https://docs.opensequence.dev/api/analytics/get-sequences-id-analytics-channels) API reference page for GET /v1/sequences/{id}/analytics/channels. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Read an unsubscribe token without applying it, for a confirmation page (https://docs.opensequence.dev/api/unsubscribes/get-unsubscribes-token) API reference page for GET /v1/unsubscribes/{token}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json. # Apply an unsubscribe token: suppress email for the contact and exit its enrollments (https://docs.opensequence.dev/api/unsubscribes/post-unsubscribes-token) API reference page for POST /v1/unsubscribes/{token}. The full OpenAPI document is at https://docs.opensequence.dev/openapi.json.