# Yapper API Reference

The Yapper API lets an application you build read and act on your Yapper data, and
receive events as they happen. It is designed so a no-code platform (Zapier, n8n,
Make, Merge, Paragon, etc.) or your own backend can sync Yapper to your CRM.

There are two halves:

- **The REST API** (`/api/v1alpha1/*`) — your app **pulls** data and **acts** (create a
  contact, move a contact to a new stage).
- **Webhooks** — Yapper **pushes** signed events to a URL you register (a contact
  changed stage, a message arrived, and so on).

> **Status: alpha.** The version in the path (`v1alpha1`) marks this as an
> unstable surface: endpoints and fields may change, or be removed, without a
> deprecation window.

---

## Concepts

| Term | Meaning |
|---|---|
| **Account** | Your Yapper organization. Everything your app can see belongs to exactly one account. |
| **App** | The credential your integration uses (a `client_id` + `client_secret`). You create apps from **Settings → Developer** in the Yapper dashboard. |
| **Endpoint** | A messaging address you own on a channel (a WhatsApp number, or an Instagram account). Each endpoint carries a `channel` (`whatsapp` or `instagram`) and is bound to one playbook. |
| **Customer** | One of your end customers. A customer exists once across your whole account and carries one or more **addresses** (their handle on each endpoint they have reached you on). In API paths and fields they are `customers` / `customer_id`. |
| **Address** | A customer's handle on one endpoint, channel-prefixed: `wa:+15551234567` (WhatsApp) or `ig:17841400000` (Instagram). A customer may have several, across or within endpoints. |
| **Playbook** | A phase graph you author in the dashboard. An endpoint is bound to one playbook; a customer that reaches that endpoint enters its graph. |
| **Phase** | A stage in a playbook's graph. A phase belongs to its playbook, so a `phase_id` implies its playbook. Map CRM *events* onto phase transitions (deal won leads to onboarding); phases are not a mirror of your CRM's stage list. |
| **Lifecycle** | A customer's current position in one playbook: `(customer, playbook)` leads to a phase. A customer may hold several lifecycles at once, one per playbook it has entered. There is no single "current phase" on a customer. |
| **Skill** | An account-level definition the agent runs. Two kinds, one collection (discriminated by `kind`): a **checklist** is a form the agent fills over a conversation; a **report** is an analytics summary it generates on demand. Each has a stable `skill_id`. |
| **Artifact** | A checklist run, report run, or note, produced for one customer. Each is stamped, frozen, with the phase it was produced under (so it stays attributable after that phase is renamed or deleted). |

Every request is scoped to the single account that owns the app credential. You
never pass an account id; it is derived from your token. A request that references
another account's endpoint or customer is rejected.

---

## Authentication

The API uses **OAuth 2.0 client credentials** (machine-to-machine). Your app
exchanges its `client_id` and `client_secret` for a short-lived access token, then
sends that token as a Bearer header on every API call.

### 1. Create an app

In the Yapper dashboard, open **Settings → Developer** and create an app. Choose a
**scope** (see [Scopes](#scopes)). You will be shown a `client_id` and a
`client_secret`.

> The `client_secret` is shown **once** and cannot be retrieved again. Store it
> securely. If you lose it, delete the app and create a new one.

### 2. Get an access token

Exchange your credentials at the token endpoint. The token is valid for about one
hour; request a new one when it expires.

```sh
curl -X POST "https://oauth.yapper.chat/oauth2/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -u "{client_id}:{client_secret}" \
  -d "grant_type=client_credentials"
```

Omit `scope` and the token carries every scope the app was granted. If you do pass
`scope`, the values are **fully qualified** (space-separated), e.g.
`scope=yapper-api/read yapper-api/write` — not the short bundle names you picked in
the dashboard. Requesting a scope the app was not granted fails with
`invalid_scope`.

Response:

```json
{
  "access_token": "eyJ...",
  "token_type": "Bearer",
  "expires_in": 3600
}
```

### 3. Call the API

```sh
curl "https://app.yapper.chat/api/v1alpha1/endpoints" \
  -H "Authorization: Bearer {access_token}"
```

### Errors

| Status | Meaning |
|---|---|
| `401` | Missing, malformed, or expired token. |
| `403` | The token is valid but lacks the required scope, or the app is not (or no longer) registered. |
| `404` | The resource does not exist, or does not belong to your account. |
| `409` | Conflict (see the endpoint's notes). |
| `429` | Rate limited. Back off and retry. |

---

## Scopes

A token only carries the permissions you grant the app. Pick the **least privilege**
that does the job. When you create an app you choose a single **bundle** by name; the
table below shows the bundle name (used in the dashboard) and the fully-qualified
scope strings the token actually carries (used in the `scope` token-request param).

| Bundle | Token scopes | Grants |
|---|---|---|
| `read` | `yapper-api/read` | Read-only access to all readable resources. |
| `write` | `yapper-api/read` `yapper-api/write` | Customer writes, notes, reports, and phase transitions (plus read). The broad umbrella — except webhooks. |
| `webhooks` | `yapper-api/read` `yapper-api/webhooks` | Manage webhook subscriptions (plus read). |
| `transition` | `yapper-api/read` `yapper-api/transition` | Move a customer to a new phase (plus read). |
| `reports` | `yapper-api/read` `yapper-api/reports` | Trigger report runs and write report memory (plus read). |
| `endpoints` | `yapper-api/read` `yapper-api/endpoints` | Rebind an endpoint to a playbook (plus read). |

Notes:

- Every write scope implies `read`, so a `read` token is never needed alongside one.
- The narrow scopes are narrow on purpose: a `webhooks` token cannot move customers or
  write customer fields, a `transition` token cannot manage webhooks, a `reports`
  token cannot do either, and an `endpoints` token can only rebind endpoints. Reading
  checklists, report definitions, and report runs needs only `read`; the `reports`
  scope is for the **actions** (triggering a run, writing report memory).
- Minting `endpoints` on its own (instead of `write`) gives an integration the
  endpoint-to-playbook rebind without any customer-write power. A `write` token
  also reaches the rebind, since it's a plain superset; `endpoints` is for an
  integration that should manage endpoint bindings and nothing else.
- The `webhooks` scope does **not** ride the `write` umbrella either: managing
  webhook subscriptions always needs its own `webhooks` scope, even on a token
  that otherwise carries broad write access.
- Use `write` only if your integration genuinely needs broad customer-write access.

---

## REST API

All paths are relative to `https://app.yapper.chat`. All requests require a Bearer token.

A customer is **global** across your account and carries an `addresses[]` of
`(endpoint, address)` entries. Reads are rooted at the customer, not under an
endpoint. A customer carries **no phase**: phase lives on a **lifecycle**
(`(customer, playbook)` leads to a phase), and a customer may hold several at once.

### Endpoints

#### `GET /api/v1alpha1/endpoints`
Scope: `read`

Lists the endpoints on your account.

```json
{
  "endpoints": [
    { "endpoint_id": "ep_...", "name": "Support line",
      "address": "wa:+14155550123", "playbook_id": "pb_...", "channel": "whatsapp" }
  ]
}
```

`channel` is the real channel of the endpoint (`whatsapp` or `instagram`).

#### `GET /api/v1alpha1/endpoints/{endpoint_id}`
Scope: `read`

One endpoint, same shape as a list entry. `404` if it is not yours.

#### `PATCH /api/v1alpha1/endpoints/{endpoint_id}`
Scope: `endpoints`

Rebinds the endpoint to a different playbook. This is the one structural write the API
allows (there is no endpoint provisioning here, that needs Meta Embedded Signup and is
dashboard-only). The endpoint keeps its channel.

```json
{ "playbook_id": "pb_4f9a01bc" }
```

Responses:

- `200` — the updated endpoint.
- `404` — unknown endpoint or unknown playbook.

### Playbooks and phases

Read-only. Authoring a playbook (its phase graph, transitions, prompts) is a dashboard
task.

#### `GET /api/v1alpha1/playbooks`
Scope: `read`

```json
{
  "playbooks": [
    { "playbook_id": "pb_...", "name": "Coaching onboarding",
      "endpoint_ids": ["ep_..."], "initial_phase_id": "ph_..." }
  ]
}
```

#### `GET /api/v1alpha1/playbooks/{playbook_id}`
Scope: `read`

One playbook, same shape. `404` if unknown.

#### `GET /api/v1alpha1/playbooks/{playbook_id}/phases`
Scope: `read`

The playbook's phase definitions. A phase belongs to its playbook, so a phase object
does not repeat `playbook_id`.

```json
{
  "phases": [
    { "phase_id": "ph_...", "name": "Onboarding", "is_initial": true,
      "enabled_skills": ["collect_details"] }
  ]
}
```

#### `GET /api/v1alpha1/playbooks/{playbook_id}/phases/{phase_id}`
Scope: `read`

One phase definition. `404` if unknown.

### Customers

#### `GET /api/v1alpha1/customers`
Scope: `read`

The global customer list, paginated. Narrow it with filters.

Query parameters:

| Param | Default | Notes |
|---|---|---|
| `endpoint_id` | — | Only customers with an address on this endpoint. |
| `playbook_id` | — | Only customers with a lifecycle in this playbook. Mutually exclusive with `phase`. |
| `phase` | — | Only customers whose lifecycle sits at this phase (the playbook is implied). Mutually exclusive with `playbook_id`. |
| `limit` | `50` | Page size, clamped to 1 to 200. |
| `since` | — | Opaque cursor from a previous response's `next_cursor`. |

```json
{
  "customers": [
    { "customer_id": "cu_...", "name": "Jordan Rivera",
      "addresses": [ { "endpoint_id": "ep_...", "address": "wa:+14155550123",
                       "last_message_at": "..." } ] }
  ],
  "next_cursor": "..."   // null when you have reached the end
}
```

Pagination is stable under concurrent writes: pages are ordered by a stable customer
id, not by recency. Pass `next_cursor` back as `since`; stop when it is `null`.

#### `GET /api/v1alpha1/customers/{customer_id}`
Scope: `read`

One customer: identity plus the `addresses[]` array (one entry per
`(endpoint, address)`). `404` if it is not yours.

#### `POST /api/v1alpha1/customers`
Scope: `write`

Creates (or finds) a customer at a phone number, and their lifecycle in the playbook the
endpoint is bound to. Idempotent: calling it again for the same phone returns the
existing customer, on any endpoint. An existing customer without a lifecycle in the
endpoint's playbook gets one, starting in the endpoint's entry phase; a lifecycle they
already hold is left as it is.

```json
{
  "endpoint_id": "ep_...",
  "phone": "+15551234567",
  "email": "jane@example.com",
  "locale": "en",
  "send_opener": true
}
```

`endpoint_id` and `phone` are required. The writable identity fields are `email`,
`contact_phone`, `contact_instagram` and `locale` only; `name` is read-only (a `400`),
and lifecycle / phase state is not settable here. The call opens the customer's
conversation on the endpoint (it shows in the inbox), which is where the opener goes out. **WhatsApp
only:** a phone number has no Instagram analogue, so an Instagram endpoint is rejected.

`send_opener` is an optional boolean, default `true`. It applies only when the call
starts a lifecycle (re-calls for a lifecycle the customer already holds never send an
opener). When `false`, the entry-phase opener — the WhatsApp entry template the
customer would otherwise receive — is not sent. Use this when you will immediately
follow the create with a `transition` to another phase, whose own opener will send, so
the customer receives exactly one message instead of two.

Responses:

- `201` — `{ "customer_id": "...", "endpoint_id": "..." }`
- `409` — the endpoint has no playbook configured.
- `422` — the endpoint is on Instagram (creation by phone is WhatsApp only).

### Lifecycles

A lifecycle is `(customer, playbook)` leads to a current phase. Read it from either
end; move it with a transition.

```json
{ "customer_id": "cu_...", "playbook_id": "pb_...",
  "phase_id": "ph_...", "phase_name": "Onboarding", "since": "..." }
```

#### `GET /api/v1alpha1/customers/{customer_id}/lifecycles`
Scope: `read`

Every playbook position one customer holds, one entry per playbook. `since` is when
the current phase started. `404` if the customer is not yours.

#### `GET /api/v1alpha1/playbooks/{playbook_id}/lifecycles`
Scope: `read`

The per-course roster: every customer with a lifecycle in the playbook. This is the
headline analytics query.

Query parameters:

| Param | Default | Notes |
|---|---|---|
| `phase` | — | Restrict to one phase of the playbook. |
| `limit` | `50` | Page size, clamped to 1 to 200. |
| `since` | — | Opaque cursor from a previous response's `next_cursor`. |

```json
{ "lifecycles": [ /* ... */ ], "next_cursor": "..." }
```

#### `POST /api/v1alpha1/customers/{customer_id}/lifecycles/{playbook_id}/transition`
Scope: `transition`

Moves the customer's lifecycle **in the named playbook** to a target phase. A
transition acts within one playbook, so you name it in the path. This drives the same
path the agent uses internally, so scheduling and side effects happen automatically.
The customer's endpoint is resolved server-side.

```json
{ "to": "ph_4f9a01bc" }
```

Phase ids are opaque (`ph_` + characters) and minted by Yapper; the human-readable
phase name is a label, not an identifier. Find them in `GET .../phases`; they also
appear in every `lifecycle.changed` event (`data.from_phase_id` / `data.to_phase_id`).

Responses:

- `202` — `{ "customer_id": "...", "to": "ph_4f9a01bc" }`. The transition was queued /
  applied.
- `400` — `unknown_phase` (the target phase does not exist in this playbook).
- `404` — the customer is not yours, or holds no lifecycle in that playbook.
- `409` — a transition conflict (retry), or
  `transition_not_applied` (the move did not land and the customer stayed in their
  current phase; retry).

Transitions are idempotent: setting a lifecycle to a phase it is already moving to is
safe to retry.

### Skills

Skill definitions for field mapping. Checklists and reports share one collection,
discriminated by `kind`; their per-customer runs stay separate (below). Read-only,
authoring is a dashboard task.

#### `GET /api/v1alpha1/skills`
Scope: `read`

Lists the account's skill definitions. `?kind=checklist` or `?kind=report` filters.

```json
{
  "skills": [
    { "skill_id": "skl_8a1c20fd", "kind": "checklist", "name": "onboarding",
      "display_name": "Onboarding", "items": [ /* template items */ ] },
    { "skill_id": "skl_3f0b91aa", "kind": "report", "name": "deal_summary",
      "display_name": "Deal Summary", "summary": "A recap of the deal so far.",
      "memory_enabled": true, "fields": [ /* declared key/label/enum contract */ ] }
  ]
}
```

`skill_id` is the stable identifier for both kinds, key on it. `name` / `display_name`
are the admin-visible label and may change. A report with no declared `fields` captures
best-effort and may emit undeclared keys.

#### `GET /api/v1alpha1/skills/{skill_id}`
Scope: `read`

One skill definition, either kind. `404` if unknown.

### Artifacts: the frozen phase stamp

Checklist runs, report runs, and notes are **artifacts**. Each is addressed under the
customer, with the endpoint and phase as filters / fields, and each carries a **frozen**
origin stamp:

```json
{ "playbook_id": "pb_...",     // frozen, may be null
  "phase_id": "ph_...",        // frozen, may be null
  "phase_name": "Onboarding"   // frozen point-in-time label, may not match any current phase
}
```

The stamp is the phase the customer was in **when the artifact was produced**. It does
not move when the customer's lifecycle moves later, and it survives renaming or
deleting that phase. It is **nullable**, artifacts produced before phases existed carry
null. On the `?phase=` filter:

- `?phase=` matches the frozen stamp, not the customer's current phase, and excludes
  null-stamp artifacts.
- `?phase=none` selects the null-stamp artifacts.
- Today only report runs carry a populated stamp. Checklists and notes are always
  null-stamped, so on those two resources `?phase=<id>` returns nothing and only
  `?phase=none` selects them.

### Checklists (runs)

#### `GET /api/v1alpha1/customers/{customer_id}/checklists`
Scope: `read`

The customer's checklist state: the live in-flight checklist merged with closed
snapshots, deduped per `(endpoint, checklist)` with the live one winning.

Query parameters: `endpoint_id`, `phase` (the frozen stamp, `none` selects null),
`skill_id`.

```json
{
  "checklists": [
    {
      "skill_id": "skl_8a1c20fd",
      "name": "onboarding",
      "display_name": "Onboarding",
      "endpoint_id": "...",
      "status": "in_progress",      // or "closed"
      "complete": false,
      "counts": { /* per-status counts */ },
      "items": [ /* items with statuses and captured values */ ],
      "playbook_id": null, "phase_id": null, "phase_name": null
    }
  ]
}
```

`status` is `in_progress` for a live checklist or `closed` for a stored snapshot.
`skill_id` is `null` on a closed entry whose skill has since been deleted.

### Notes

The operator note on a customer, the same free-text field the dashboard edits and the
report builder feeds to the model. One note per customer, across all their
conversations, carrying its frozen phase stamp.

#### `GET /api/v1alpha1/customers/{customer_id}/notes`
Scope: `read`

Query parameters: `endpoint_id`, `phase` (the frozen stamp, `none` selects null).

```json
{
  "customer_id": "...",
  "notes": [
    { "endpoint_id": "...", "address": "14155551234", "notes": "VIP, prefers email",
      "playbook_id": null, "phase_id": null, "phase_name": null }
  ]
}
```

The entry names the customer's most recently active conversation (on `endpoint_id`
when that filter is given). Empty notes, and a filter matching none of the customer's
conversations, return an empty list.

#### `PUT /api/v1alpha1/customers/{customer_id}/notes`
Scope: `write`

Sets the customer's note. Body:

```json
{ "notes": "VIP, prefers email" }
```

`notes` may be a string or `null`; `null` or blank clears the note. The notes are
the person's, one value across their conversations; the response names one
conversation's `endpoint_id` / `address`. If the customer spans more than one endpoint
or address, pin it with optional `endpoint_id` / `address` body fields; an unresolved
target (including a customer with no conversation yet) returns `409`. Returns the
stored value.

### Reports (runs)

Read a customer's runs and their captured `fields`, fetch the rendered HTML, trigger a
new run, or manage per-customer report memory.

#### `GET /api/v1alpha1/customers/{customer_id}/reports`
Scope: `read`

The customer's report runs, newest first, paginated.

Query parameters:

| Param | Default | Notes |
|---|---|---|
| `endpoint_id` | — | Filter to one endpoint. |
| `phase` | — | Filter to the frozen phase stamp (`none` selects null). |
| `skill_id` | — | Filter to one report definition. |
| `limit` | `50` | Page size, clamped to 1 to 200. |
| `since` | — | Opaque cursor from a previous response's `next_cursor`. |

```json
{
  "reports": [
    {
      "run_id": "...",
      "skill_id": "skl_3f0b91aa",
      "name": "deal_summary",
      "status": "completed",       // or "running" / "failed"
      "created_at": "2026-06-03T12:00:00Z",
      "completed_at": "2026-06-03T12:00:07Z",
      "error": null,
      "endpoint_id": "...",
      "address": "14155551234",
      "fields": { /* captured structured values */ },
      "playbook_id": "pb_...", "phase_id": "ph_...", "phase_name": "Onboarding"
    }
  ],
  "next_cursor": "..."             // null when you have reached the end
}
```

`fields` carries the captured structured values on a completed run (`{}` if it captured
none); it stays `null` while the run is `running` or `failed`. `skill_id` is `null`
once the underlying skill has been deleted. Pagination is stable: the cursor is an
immutable run id, so paging never drops or repeats a run.

#### `GET /api/v1alpha1/customers/{customer_id}/reports/{run_id}`
Scope: `read`

One run's metadata, captured `fields`, and frozen stamp, the poll target after a
trigger. Same shape as a single entry in the list above.

#### `GET /api/v1alpha1/customers/{customer_id}/reports/{run_id}/html`
Scope: `read`

The rendered report document, completed runs only. Returns sanitized HTML (not JSON).
`409` until the run is `completed`.

#### `POST /api/v1alpha1/customers/{customer_id}/reports`
Scope: `reports`

Triggers a report run. Body:

```json
{ "skill_id": "skl_3f0b91aa" }
```

Requires active billing (a run spends LLM tokens) and that the report is actually
available for this customer's conversation. If the customer spans more than one endpoint
or address, pin the target with optional `endpoint_id` / `address` body fields. The run
is stamped with the customer's current phase as its frozen origin.

Responses:

- `202` — `{ "run_id": "...", "skill_id": "...", "customer_id": "...", "endpoint_id": "...", "address": "...", "status": "running" }`. Poll `GET .../reports/{run_id}` for completion, or wait for the `report.completed` webhook.
- `404` — the skill does not exist, or is not available for this customer.
- `409` — ambiguous target (pin `endpoint_id` / `address`).

#### `GET /api/v1alpha1/customers/{customer_id}/reports/{skill_id}/memory`
Scope: `read`

The per-customer-per-report feedback note injected into the report prompt.

```json
{
  "skill_id": "skl_3f0b91aa",
  "customer_id": "...",
  "endpoint_id": "...",
  "address": "14155551234",
  "memory": "Always emphasize renewal date."   // null when unset
}
```

Pin the target with optional `endpoint_id` / `address` **query** params when the
customer spans more than one. `400` when the report is not memory-enabled.

#### `PUT /api/v1alpha1/customers/{customer_id}/reports/{skill_id}/memory`
Scope: `reports`

Writes the memory note. Body:

```json
{ "memory": "Always emphasize renewal date." }
```

`memory` may be a string or `null`; `null` or blank clears it (there is no separate
DELETE). Pin the target with optional `endpoint_id` / `address` **body** fields.
`400` when the report is not memory-enabled. Returns the stored value.

---

## Webhooks

Register a URL and Yapper will POST a signed JSON event to it whenever something
happens. This is the **push** half of the integration, the counterpart to the REST
API's pull/act.

Webhook subscriptions are managed through the **same** API and token as everything
else.

### Subscriptions

#### `POST /api/v1alpha1/webhooks`
Scope: `webhooks`

Subscribe a URL to events.

Request body:

```json
{
  "url": "https://hooks.example.com/yapper",
  "event_types": ["lifecycle.changed", "customer.updated"],
  "customer_id": "...",        // optional: only events for this customer
  "channel": "whatsapp",       // optional: only this channel (whatsapp | instagram)
  "description": "CRM sync"    // optional
}
```

- `url` must be **HTTPS** and must resolve to a public address (private, loopback,
  and link-local addresses are rejected, at subscribe time and again at delivery).
- Omit `event_types` (or use `["*"]`) to receive all events except the opt-in ones
  (see [Event types](#event-types)).

Response (`201`): the full subscription, including a `signing_secret` (prefixed
`whsec_`) returned **once**. Store it; you need it to verify signatures.

```json
{
  "id": "...",
  "url": "https://hooks.example.com/yapper",
  "event_types": ["lifecycle.changed", "customer.updated"],
  "customer_id": "*",
  "channel": "*",
  "enabled": true,
  "created_at": "2026-06-03T12:00:00Z",
  "description": "CRM sync",
  "consecutive_failures": 0,
  "disabled_at": "",
  "last_delivery_at": "",
  "last_status": "",
  "signing_secret": "whsec_..."
}
```

The `GET` endpoints return the same object **without** `signing_secret`. Watch
`enabled` / `disabled_at` to detect when a subscription has been auto-disabled (see
[Delivery & reliability](#delivery--reliability)).

#### `GET /api/v1alpha1/webhooks`
Scope: `read`

Lists your subscriptions as `{ "webhooks": [ ... ] }` (without secrets). A
subscription that has been auto-disabled (see
[Delivery & reliability](#delivery--reliability)) is visible here so you can detect
and re-subscribe.

#### `GET /api/v1alpha1/webhooks/{id}`
Scope: `read`

Fetches one subscription (without its secret). `404` if it is not yours.

#### `DELETE /api/v1alpha1/webhooks/{id}`
Scope: `webhooks`

Unsubscribes and permanently deletes the signing secret.

#### `POST /api/v1alpha1/webhooks/{id}/ping`
Scope: `webhooks`

Sends a `ping` event to this one subscription so you can validate your URL and
signature verification during setup. The ping bypasses the subscription's filters.
`202` on success; `409` if the subscription is disabled.

### Event types

Events are named `resource.verb` (past tense).

| Type | Fires when | Delivery |
|---|---|---|
| `lifecycle.changed` | A customer moves to a new phase in a playbook. The core of CRM sync. | Default |
| `customer.updated` | A customer's profile / fields change. | Default |
| `message.received` | An inbound message arrives. | Default |
| `checklist.completed` | A form skill's checklist closed (complete, escalation, or send failure). | Default |
| `report.completed` | A report run reached a terminal status (`completed` or `failed`). | Default |
| `message.status` | A message is delivered / read / failed. | **Opt-in** |
| `checklist.updated` | Mid-conversation form progress, at most once per turn that changed the checklist. | **Opt-in** |
| `ping` | Setup validation (via the ping endpoint). | Control |

`message.status` and `checklist.updated` are high-volume, so a wildcard (`["*"]`)
subscription does **not** receive them. Name them explicitly to opt in.

`lifecycle.changed` carries `playbook_id` (the lifecycle is keyed by playbook),
`from_phase_id`, `to_phase_id`, and `trigger_source`:

```json
{ "playbook_id": "pb_...", "from_phase_id": "ph_...", "to_phase_id": "ph_...",
  "trigger_source": "api|inbound|rule" }
```

`checklist.completed` and `checklist.updated` carry the full checklist snapshot in
`data` (`skill_id`, `name` / `display_name`, `endpoint_id`, `counts`, and the
`items` with statuses and values; `checklist.updated` adds a `changed_keys` list).
`report.completed` carries `run_id`, `skill_id`, `name`, `status`
(`completed` / `failed`), `endpoint_id`, `playbook_id`, `phase_id`, `error`, and
`fields` (the captured values, `{}` when none captured, `null` on failure), so you can
skip polling the run after a trigger. These webhooks are timely, not exhaustive; the
pull endpoints above are the backfill.

### Event envelope

Every delivery is a POST with this JSON body:

```json
{
  "id": "evt_01J...",
  "type": "lifecycle.changed",
  "created_at": "2026-06-03T12:00:00Z",
  "account_id": "...",
  "customer_id": "...",
  "channel": "whatsapp",
  "data": { /* event-type-specific */ }
}
```

`id` is a unique, time-sortable event id. **Use it as your idempotency key** (see
below).

### Verifying signatures

Every delivery carries these headers:

| Header | Meaning |
|---|---|
| `X-Yapper-Signature` | `sha256=<hex>` — HMAC-SHA256 of `<timestamp>.<raw body>` using your subscription's signing secret. |
| `X-Yapper-Timestamp` | The timestamp included in the signed material. |
| `X-Yapper-Event-Id` | Same as the body's `id`. |
| `X-Yapper-Event-Type` | The event type. |
| `X-Yapper-Delivery` | The delivery attempt number. |

To verify, recompute the HMAC over `"{X-Yapper-Timestamp}.{raw request body}"` with
your signing secret and compare (constant-time) against the hex in
`X-Yapper-Signature`. Because the timestamp is part of the signed material, you also
get replay protection: reject deliveries whose timestamp is too old.

Example (Python):

```python
import hashlib, hmac

def verify(secret: str, timestamp: str, raw_body: bytes, header: str) -> bool:
    expected = hmac.new(
        secret.encode(),
        f"{timestamp}.".encode() + raw_body,
        hashlib.sha256,
    ).hexdigest()
    sent = header.removeprefix("sha256=")
    return hmac.compare_digest(expected, sent)
```

### Delivery & reliability

- **At-least-once.** A delivery may arrive more than once. You **must** dedupe on
  `X-Yapper-Event-Id`.
- **Order is not guaranteed.** Reconcile by `created_at` / the event `id` and treat
  the latest state as authoritative.
- **Respond `2xx` fast.** Yapper expects a 2xx within ~10 seconds. Do your real work
  asynchronously.
- **Retries.** Non-2xx responses, timeouts, and DNS failures are retried with
  backoff. After repeated consecutive failures the subscription is **auto-disabled**
  (a circuit breaker); its disabled state is visible via `GET /api/v1alpha1/webhooks`.
  Re-subscribe once your endpoint is healthy.
- **No redirects.** Yapper does not follow 3xx redirects. Register the final URL.

### Backfill

If your endpoint was down, replay recent events instead of waiting for retries:

#### `GET /api/v1alpha1/events`
Scope: `read`

```
GET /api/v1alpha1/events?since={event_id}&limit={N}
```

Returns events oldest-to-newest:

```json
{
  "events": [ /* same envelope as webhook deliveries */ ],
  "next_cursor": "evt_..."
}
```

The cursor **is** an event id (the same one you dedupe on), so paging and dedupe
share one concept. Events are retained for 14 days.

---

## Avoiding sync loops

If you mirror Yapper phases into a CRM and mirror CRM stages back into Yapper, guard
against an endless loop:

- Phase changes your app makes through
  `POST /api/v1alpha1/customers/{customer_id}/lifecycles/{playbook_id}/transition`
  are tagged as API-originated and are **not** echoed back to you as a
  `lifecycle.changed` webhook. So a CRM-driven change you push in will not bounce back
  out.
- Outbound is at-least-once, so dedupe on the event id; inbound "set phase to X" is
  idempotent, so retries are safe.
- If both sides change a customer at once, your integration decides which wins.
  Yapper stays mechanical: it applies what you tell it and emits what happened.

---

## Rate limits

The API is throttled to protect capacity. Over-limit requests return `429`; back off
and retry. Per-app quotas are not currently exposed.
