# 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`.

<Steps>
<Step title="Start the service">

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

</Step>
<Step title="Install the SDK">

```bash
npm init -y && npm install @opensequence/sdk tsx
```

</Step>
<Step title="Save the sequence">

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" }
  }
}
```

</Step>
<Step title="Run the flow">

```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=<...>
```

</Step>
<Step title="Simulate a reply">

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.

</Step>
</Steps>

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:

<CodeGroup>

```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' });
```

</CodeGroup>

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]

<Cards>
  <Card title="Integrate OpenSequence into your product" href="/docs/get-started/integrate">The checklist, one call per step.</Card>
  <Card title="Modules" href="/docs/modules">Email, Allo, Attio, webhooks, MCP and the SDK.</Card>
  <Card title="Concepts" href="/docs/concepts/project">Projects, senders, contacts, sequences and runs.</Card>
</Cards>
