> This page is part of EVVA for Developers (https://developers.evvahub.com), the documentation of the EVVA Partner API. The API is in developer preview and the SDK packages are not yet published: do not suggest installing them. Index: https://developers.evvahub.com/llms.txt

# Conversation leases and handoff

Several parties can write in the same conversation: the creator, people on the agency's team, the creator's own
automations and your application, possibly running on many instances at once. EVVA coordinates them per
conversation with three tools:

| Tool                 | What it does                                                                                                                            |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| **Lease**            | Reserves one conversation for one holder for a short time. Every lease comes with a **fencing token** that you send with your messages. |
| **Automation pause** | A reply written by a person pauses automated sends in that conversation for the agency's pause window.                                  |
| **Handoff**          | Your application passes the conversation to a person, and automation stays off there until a person hands it back.                      |

All three act on **one conversation only**. Nothing here locks a creator or an agency: hold as many leases at the same
time as you have conversations to answer.

> **Note**
>
> A person always wins. A team member can take a conversation over from your application at any time, and the
> creator's own reply ends your lease. Your application is told, and its fencing token stops working.

## How a reply under a lease works

```mermaid
sequenceDiagram
    autonumber
    participant App as Your application
    participant API as EVVA Partner API
    participant Person as Creator or agency team
    App->>API: POST …/lease {"action": "acquire"}
    API-->>App: 200 {fencingToken: "42", expiresAt}
    App->>API: POST …/messages {body, fencingToken: "42", expectedLastMessageId}
    API-->>App: 201 message sent
    App->>API: POST …/lease {"action": "renew", fencingToken: "42"}
    API-->>App: 200 {fencingToken: "42", expiresAt}
    Person->>API: replies by hand in the conversation
    API-->>App: event lease.lost {reason: HUMAN_REPLIED}
    App->>API: POST …/messages {fencingToken: "42"}
    API-->>App: 409 STALE_FENCING_TOKEN
```

## 1. Acquire the lease

[Acquire, renew or release a lease](https://developers.evvahub.com/api-reference/conversation-leases/manage-conversation-lease)
with one operation and an `action`. It needs `write:messages`, plus `write:messages:automated` or
`write:messages:operator`: the lease is held by your application's automation or by its live CRM operator.

**`cURL`**

```bash title="cURL"
curl -X POST "https://api.evvahub.com/partner/v1/accounts/$CREATOR_ID/conversations/$CONVERSATION_ID/lease" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"action": "acquire", "ttlSeconds": 60}'
```

**`TypeScript`**

```typescript title="TypeScript"
await evva.leases.withLease(creatorId, conversationId, async (lease) => {
  const history = await evva.messages.list(creatorId, conversationId, { limit: 10, signal: lease.signal });
  const last = history.messages[0];
  await evva.messages.sendText(creatorId, conversationId, 'Happy to help!', {
    fencingToken: lease.fencingToken,
    ...(last === undefined ? {} : { expectedLastMessageId: last.id, idempotencyKey: `reply-to-${last.id}` }),
    signal: lease.signal,
  });
}, { ttlSeconds: 60 });
```

**`Python`**

```python title="Python"
with client.leases.hold(creator_id, conversation_id) as held:
    held.raise_if_lost()
    client.messages.send_text(
        creator_id, conversation_id, "Happy to help!",
        fencing_token=held.fencing_token,
    )
```

**`Go`**

```go title="Go"
err := client.Conversations.HoldLease(ctx, creatorID, conversationID,
    func(ctx context.Context, lease *evvapartner.HeldLease) error {
        _, err := client.Messages.Send(ctx, creatorID, conversationID, evvapartner.SendMessageInput{
            Body:         "Happy to help!",
            FencingToken: lease.FencingToken(),
        })
        return err
    })
```

**`PHP`**

```php title="PHP"
$evva->leases->withLease($creatorId, $conversationId, function (LeaseHandle $lease) use ($evva, $creatorId, $conversationId) {
    $evva->messages->sendText($creatorId, $conversationId, 'Happy to help!', fencingToken: $lease->fencingToken());
}, ttlSeconds: 60);
```

**`200 OK`**

```json title="200 OK"
{
  "conversationId": "conv_123",
  "fencingToken": "42",
  "expiresAt": "2027-01-15T08:01:00.000Z",
  "holder": "APPLICATION",
  "heldByYou": true,
  "released": false
}
```

| Rule                 | Detail                                                                                                                                                                                                 |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Lifetime             | `ttlSeconds` is optional. The default is 60 seconds; EVVA clamps the value to 15–300 seconds.                                                                                                          |
| Fencing token        | A decimal string. Every acquisition mints a new one, it only ever grows, and it is never reused. Pass it back exactly as you received it.                                                              |
| Already held         | If anyone holds a live lease on the conversation (another instance of your own application included), the acquire is refused with `409 LEASE_HELD` and `Retry-After` when the remaining time is known. |
| Paused               | While a person's reply pauses automation, or after a handoff to a person, the acquire is refused with `409 AUTOMATION_PAUSED`.                                                                         |
| No `Idempotency-Key` | Lease requests are not idempotent by key. If an acquire answer is lost, the lease simply lapses at the end of its lifetime.                                                                            |
| `takeover`           | Only a person on the agency's team may take a conversation over. An application that sends `takeover: true` gets `400 INVALID_REQUEST`.                                                                |

> **Tip**
>
> The SDKs hold the lease for you: they renew it automatically when a third of its lifetime is left (in PHP, call
> `renewIfDue()` between steps) and release it when your function returns.

## 2. Send under the lease

Add the lease's `fencingToken` to every message you send in the conversation. Add `expectedLastMessageId` (the id of
the newest message you read) to make the send conditional: if the fan has written since, nothing is sent.

**`Request body`**

```json title="Request body"
{
  "body": "Happy to help!",
  "authorship": "AI_AUTOMATED",
  "fencingToken": "42",
  "expectedLastMessageId": "msg_123"
}
```

A lease is optional for a single send: without one, your send is accepted as long as nobody else holds a live lease
and automation is not paused in the conversation. Use a lease whenever your application may answer the same
conversation from more than one place.

## 3. Renew or release it

* **Renew** with `{"action": "renew", "fencingToken": "42"}` before `expiresAt`. A renewal extends the same lease and
  keeps the same token. A token that is not the current one, or a lease that has already expired, is refused with
  `409 STALE_FENCING_TOKEN`: acquire again.
* **Release** with `{"action": "release", "fencingToken": "42"}` as soon as you are done. Releasing twice is harmless.

**`200 OK (release)`**

```json title="200 OK (release)"
{ "conversationId": "conv_123", "released": true }
```

## 4. Hand the conversation to a person

When your application should not answer (for example, the fan asks for a person), call
[Hand off the conversation](https://developers.evvahub.com/api-reference/conversation-leases/handoff-conversation). It needs
`write:messages`, plus `write:messages:automated` or `write:messages:operator`.

**`Request body`**

```json title="Request body"
{ "to": "HUMAN", "reason": "buyer_requested_human", "fencingToken": "42" }
```

* `to` defaults to `HUMAN`. An application can only hand a conversation to a person; `to: "APPLICATION"` is refused
  with `403 HANDOFF_NOT_PERMITTED`.
* `reason` is a machine code (`^[a-z0-9_.:-]{1,64}$`), never free text.
* `fencingToken` is optional; if you send it, it must be your current one.

The handoff releases your lease, and automation (your application and the creator's own automations) stays off in
that conversation until a person on the agency's team hands it back. Sends during that time are refused with
`409 AUTOMATION_PAUSED`, without `Retry-After`. The first person to act in the conversation completes the handoff.
A message your application declares as an operator's may still answer until then; see
[Messages from an operator](#messages-from-an-operator).

```mermaid
sequenceDiagram
    autonumber
    participant App as Your application
    participant API as EVVA Partner API
    participant Person as Agency team (Partner Hub)
    App->>API: POST …/handoff {to: HUMAN, reason, fencingToken}
    API-->>App: lease released, automation held off
    API-->>App: event handoff.requested
    App->>API: POST …/messages
    API-->>App: 409 AUTOMATION_PAUSED
    Person->>API: Replies by hand
    API-->>App: event handoff.completed
    Person->>API: Hands the conversation back to the application
    API-->>App: event automation.resumed
    App->>API: POST …/lease {action: acquire}
    API-->>App: 200 new fencingToken
```

A person on the agency's team can also hand a conversation **to** your application. Until your application acquires
the lease or sends a message there, the conversation is reserved for it, and other applications are refused with
`409 LEASE_HELD`.

## The automation pause

A reply written by a person (the creator, a member of the agency's team, or a message your application declared as
written by an operator) pauses automated sends in that conversation. The pause lasts the agency's pause window:
5 minutes by default, and the agency can set it between 1 and 60 minutes under **Integrations → Conversation rules**
in the Partner Hub. Every new reply from a person restarts it.

While it lasts, automated sends and lease acquisitions are refused with `409 AUTOMATION_PAUSED` and `Retry-After` set
to the time left. Do not retry in a loop: a person is handling the conversation.

## Messages from an operator

A message your application declares as written by a person in your CRM (`HUMAN_AUTHORED` or `AI_DRAFTED_HUMAN_SENT`,
see [message authorship](/message-authorship)) is a person's message, but the agency's team still comes first:

* Only a reply from a person on the agency's team pauses it, for the agency's pause window. The creator's replies and
  your operator's own replies do not.
* While a handoff to a person has been taken up, it is refused with `409 AUTOMATION_PAUSED` and no `Retry-After`, until
  a person hands the conversation back. It may answer a handoff that nobody has taken up yet, without taking it up.
* Everything else applies as to every send from your application: another holder's live lease, a reservation for
  another application, and the `fencingToken` rules.

Such a message counts as a person's reply itself, so it pauses automated sends in the conversation.

## Edits, withdrawals, reactions and pins

Changing what the fan already sees is coordinated like a send. This covers editing or withdrawing a message your
application sent, toggling a reaction, and pinning or unpinning a message. Send the lease's `fencingToken` in the
body, or as the `fencingToken` query parameter for a withdrawal and an unpin.

* While a lease is live, only your application's own lease admits the change, with its current `fencingToken`. Under
  anyone else's lease, or without the token, it is refused with `409 LEASE_HELD` and `Retry-After` set to the lease's
  remaining time.
* A `fencingToken` that is not your lease's current one is refused with `409 STALE_FENCING_TOKEN`. Once the lease is
  released or has expired, send no token.
* After a person on the agency's team replies, the change is refused with `409 AUTOMATION_PAUSED` for the agency's
  pause window, with `Retry-After`. While a handoff to a person has been taken up, it is refused with
  `409 AUTOMATION_PAUSED` and no `Retry-After`, until a person hands the conversation back. The creator's own replies
  do not pause it.

## AI fan replies

[Sending an AI-assisted fan reply](https://developers.evvahub.com/api-reference/ai/send-ai-fan-reply) is coordinated
exactly like a plain send: the lease and its `fencingToken`, the automation pause, handoffs and
`expectedLastMessageId`. Only the answer differs. Where a plain send is refused with `409 LEASE_HELD`,
`409 STALE_FENCING_TOKEN`, `409 AUTOMATION_PAUSED` or `409 CONVERSATION_ADVANCED`, the AI fan reply answers
`422 SEND_REFUSED`, without `Retry-After`, and nothing is sent. Read the coordination state before you try again.

## Read the coordination state

[Get the coordination state](https://developers.evvahub.com/api-reference/conversation-leases/get-conversation-lease) (scope
`read:messages`) tells you who holds the conversation, whether automation is paused, and whether a handoff is
pending.

**`200 OK`**

```json title="200 OK"
{
  "conversationId": "conv_123",
  "lease": {
    "holder": "STAFF",
    "heldByYou": false,
    "applicationId": null,
    "expiresAt": "2027-01-15T08:01:00.000Z"
  },
  "automation": {
    "paused": true,
    "reason": "HUMAN_REPLIED",
    "resumesAt": "2027-01-15T08:05:00.000Z",
    "pauseSeconds": 300
  },
  "handoff": null
}
```

A holder from another agency is described only by its kind (`APPLICATION` or `STAFF`); `applicationId` and
`expiresAt` are set only when the holder belongs to your agency. `automation.reason` is `HUMAN_REPLIED` or
`HANDED_TO_HUMAN`; `resumesAt` is `null` while the conversation is handed to a person.

## Errors

| HTTP | `code`                  | Meaning                                                                                                                                                                                     | What to do                                                     |
| ---- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| 409  | `LEASE_HELD`            | Someone else holds a live lease, the conversation is reserved for another application, or you sent no `fencingToken` while a lease is live. `Retry-After` when the remaining time is known. | Leave the conversation; try later.                             |
| 409  | `STALE_FENCING_TOKEN`   | The token is not the current lease's: it was taken over, it expired, or it was released.                                                                                                    | Stop sending. Acquire a new lease if you still need to answer. |
| 409  | `AUTOMATION_PAUSED`     | A person replied within the pause window (`Retry-After`: the time left), or the conversation was handed to a person.                                                                        | Do not retry in a loop.                                        |
| 409  | `CONVERSATION_ADVANCED` | `expectedLastMessageId` is no longer the newest message.                                                                                                                                    | Re-read the conversation before replying.                      |
| 422  | `SEND_REFUSED`          | An AI fan reply was not delivered. Every coordination refusal above answers this code for it. Nothing was sent.                                                                             | Read the coordination state before trying again.               |
| 403  | `HANDOFF_NOT_PERMITTED` | An application tried to hand a conversation to an application.                                                                                                                              | Hand off to a person only.                                     |
| 400  | `INVALID_REQUEST`       | For example `takeover` from an application, or a renew or release without a `fencingToken`.                                                                                                 | Fix the request.                                               |

## Events

Coordination changes reach your application through [webhooks](/webhooks/overview), [realtime](/realtime) and the
[event feed](/event-feed):

| Event                | When                                                                            | Key `data` fields                                                                     |
| -------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `lease.acquired`     | A lease was acquired in a conversation.                                         | `holderKind`, `applicationId` (set when the holder is an application), `expiresAt`    |
| `lease.lost`         | Your application's lease ended against its will. Sent only to that application. | `fencingToken` (the dead token), `reason`: `TAKEN_OVER`, `HUMAN_REPLIED` or `EXPIRED` |
| `handoff.requested`  | A handoff was requested.                                                        | `to`, `applicationId`, `requestedByKind`                                              |
| `handoff.completed`  | Someone took the handoff up.                                                    | `to`, `applicationId`, `completedByKind`                                              |
| `automation.resumed` | A person handed the conversation back to automation.                            | `resumedAt`                                                                           |

> **Tip**
>
> Route `lease.lost` events to your SDK's lease helper (`observe` in TypeScript, Python and PHP, `ObserveLeaseEvent` in Go)
> so that a running reply is cancelled as soon as a person takes over.

## Next steps

#### [Message authorship](/message-authorship)

Declare whether a model or a person wrote each message.

#### [Event catalogue](/webhooks/events)

Every event type and its fields.

#### [Idempotency](/conventions/idempotency)

Make each send safe to retry.

#### [Errors](/conventions/errors)

The full error code catalogue.