> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.rasen.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.rasen.ai/_mcp/server.

# Build and publish an agent

> Create an agent with its voice, edit and validate its draft, publish it for new calls, list its versions and roll back.

## Summary

An agent has one draft that you edit and numbered versions that you publish; a publish freezes the
complete draft into a version and makes it live for new calls in one step. This guide creates an
agent with its voice, edits its draft and a variable, validates and publishes it, lists its
versions and rolls back. It does not cover authored tools, Knowledge, credentials or starting a
call; see [Tools and MCP servers](/guides/tools), [Knowledge](/guides/knowledge) and
[Start a call](/guides/calls#start-a-call).

## Facts

| Item                  | Value                                                                                                                                                                                                                                                                                                  |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Operations            | `listVoices`, `createAgent`, `getAgentDraft`, `updateAgentDraft`, `setAgentVariable`, `validateAgentDraft`, `publishAgent`, `listAgentVersions`, `rollbackAgent`                                                                                                                                       |
| Paths                 | `GET /voices`, `POST /agents`, `GET /agents/{agent_id}/draft`, `PATCH /agents/{agent_id}/draft`, `PUT /agents/{agent_id}/variables/{variable_key}`, `POST /agents/{agent_id}/draft/validate`, `POST /agents/{agent_id}/publish`, `GET /agents/{agent_id}/versions`, `POST /agents/{agent_id}/rollback` |
| Related reads         | `listAgents`, `getAgent`, `getAgentReadiness`, `getAgentDraftDiff`, `listAgentVariables`, `getAgentVersion`, `getAgentVersionDiff`                                                                                                                                                                     |
| Capability            | `config.read` for reads; `agents.write` for create, draft, variable and validate; `agents.publish` for publish and rollback                                                                                                                                                                            |
| Required headers      | `Authorization` on every request; `Idempotency-Key` on every write except `validateAgentDraft`; `If-Match` with the draft ETag on draft and variable writes, validate and publish                                                                                                                      |
| Draft ETag            | Covers what a publish would freeze: draft revision, tools, MCP servers, pinned secret versions, the direct agent library and its source state and revision, and the default-tool policy. It equals the draft's `revision`                                                                              |
| Agent ETag            | `getAgent` answers an identity ETag, used only by `PATCH /agents/{agent_id}` (name and description)                                                                                                                                                                                                    |
| `settings.language`   | `english`, `hindi`, `hinglish` in `initial_draft` on create; `en`, `hi`, `hinglish` in later draft edits                                                                                                                                                                                               |
| Voicemail             | `voicemail_detection` turns detection on. `voicemail_action` is `hang_up` (the default) or `leave_message`. `voicemail_message` holds at most 500 characters                                                                                                                                           |
| Reserved names        | Variable keys that start with `system__`; tool names `end_call`, `transfer` and `transfer_to_number`                                                                                                                                                                                                   |
| Single-brace warnings | At most 20 `single_brace_variable` warnings in one validation                                                                                                                                                                                                                                          |
| Environment           | `RASEN_API_BASE` (the base URL, ending in `/v1`), `RASEN_API_KEY`, `AGENT_ID`, `VOICE_ID`, `ETAG`, `VERSION_ID`, `LIVE_VERSION_ID`                                                                                                                                                                     |
| Python                | 3.10 or later, with the `httpx` package                                                                                                                                                                                                                                                                |
| TypeScript            | Node.js 22 or later (built-in `fetch`)                                                                                                                                                                                                                                                                 |

## Steps

### 1. Choose a voice

Supported voices depend on the voice model an agent is assigned. Before your first agent exists,
list without `agent_id`: the answer is the catalogue of the voice model a new agent starts on.

**`curl`**

```bash curl
curl -sS "$RASEN_API_BASE/voices" \
  -H "Authorization: Bearer $RASEN_API_KEY"
```

**`Python`**

```python Python
import os

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]

response = httpx.get(f"{BASE}/voices", headers={"Authorization": f"Bearer {KEY}"})
response.raise_for_status()
for voice in response.json()["items"]:
    print(voice["id"], voice["name"], voice["is_default"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY } = process.env;

const response = await fetch(`${RASEN_API_BASE}/voices`, {
  headers: { Authorization: `Bearer ${RASEN_API_KEY}` },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const page = await response.json();
for (const voice of page.items) {
  console.log(voice.id, voice.name, voice.is_default);
}
```

The default voice comes first. Set `VOICE_ID` to the `id` of the voice you choose. Each voice
carries `grammatical_gender` (`female`, `male`, an unknown future value, or null when none is
recorded); match a draft's grammatical gender with it, never with the voice name or ID. A voice has
no `languages` field.

To change the voice of an existing agent, list with `?agent_id=$AGENT_ID` instead: an existing
agent keeps the voice model it is assigned, which can differ from the one a new agent gets. A
`next_cursor` from one list does not page the other.

### 2. Create the agent

**`curl`**

```bash curl
curl -sS -i -X POST "$RASEN_API_BASE/agents" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Support line",
    "description": "Answers support calls.",
    "resource_key": "support-line",
    "initial_draft": {
      "prompt": "You are the support agent.",
      "voice": {"voice_id": "'"$VOICE_ID"'"},
      "settings": {
        "language": "english",
        "grammatical_gender": "female",
        "call_direction": "inbound",
        "first_message": "Hello, how can I help?"
      },
      "default_tools": {"end_call": {"enabled": true}}
    }
  }'
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
VOICE_ID = os.environ["VOICE_ID"]

response = httpx.post(
    f"{BASE}/agents",
    headers={"Authorization": f"Bearer {KEY}", "Idempotency-Key": str(uuid.uuid4())},
    json={
        "name": "Support line",
        "description": "Answers support calls.",
        "resource_key": "support-line",
        "initial_draft": {
            "prompt": "You are the support agent.",
            "voice": {"voice_id": VOICE_ID},
            "settings": {
                "language": "english",
                "grammatical_gender": "female",
                "call_direction": "inbound",
                "first_message": "Hello, how can I help?",
            },
            "default_tools": {"end_call": {"enabled": True}},
        },
    },
)
response.raise_for_status()
print(response.headers["ETag"])
print(response.json())
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, VOICE_ID } = process.env;

const response = await fetch(`${RASEN_API_BASE}/agents`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    name: "Support line",
    description: "Answers support calls.",
    resource_key: "support-line",
    initial_draft: {
      prompt: "You are the support agent.",
      voice: { voice_id: VOICE_ID },
      settings: {
        language: "english",
        grammatical_gender: "female",
        call_direction: "inbound",
        first_message: "Hello, how can I help?",
      },
      default_tools: { end_call: { enabled: true } },
    },
  }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(response.headers.get("ETag"));
console.log(await response.json());
```

The answer is `201` with the agent and its identity `ETag`. Set `AGENT_ID` to its `id`. With
`initial_draft`, the identity and these draft fields are stored in one transaction; the agent is
not published. The initial block can set the prompt, voice, settings and built-in-tool policy.
Variables, authored tools, Knowledge and credentials use their own operations. Without
`initial_draft`, the draft has the platform's initial defaults: read it before you edit it.

The create checks the voice against the voice model the new agent actually gets. A refused initial
field, such as an unsupported voice, leaves no agent and no idempotency claim; a voice is never
substituted.

To find an agent you created before, list `GET /agents?resource_key=support-line`: a
`resource_key` lookup also finds an archived agent. `GET /agents` lists every agent except archived
ones, newest first; repeat `agent_id` to read several, and add `state=archived` for archived ones.
`GET /agents/{agent_id}` answers the agent's identity and its live pointer, `live_version_id`.

### 3. Read the draft and its ETag

**`curl`**

```bash curl
curl -sS -i "$RASEN_API_BASE/agents/$AGENT_ID/draft" \
  -H "Authorization: Bearer $RASEN_API_KEY"
```

**`Python`**

```python Python
import os

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
AGENT_ID = os.environ["AGENT_ID"]

response = httpx.get(f"{BASE}/agents/{AGENT_ID}/draft", headers={"Authorization": f"Bearer {KEY}"})
response.raise_for_status()
print(response.headers["ETag"])
print(response.json())
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, AGENT_ID } = process.env;

const response = await fetch(`${RASEN_API_BASE}/agents/${AGENT_ID}/draft`, {
  headers: { Authorization: `Bearer ${RASEN_API_KEY}` },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(response.headers.get("ETag"));
console.log(await response.json());
```

Set `ETAG` to the `ETag` of the answer. It is the publication token, and it equals the body's
`revision`. Variables marked `pii` or `confidential` read as `"value": null, "redacted": true`; a
null value without the marker is a real null. `GET /agents/{agent_id}/draft/diff` shows what a
publish would change against the live version, as JSON pointers with sensitive values suppressed,
and `GET /agents/{agent_id}/variables` lists the variables.

### 4. Edit the draft

**`curl`**

```bash curl
curl -sS -i -X PATCH "$RASEN_API_BASE/agents/$AGENT_ID/draft" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "If-Match: $ETAG" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "You are the support agent.",
    "voice": {"voice_id": "'"$VOICE_ID"'"},
    "settings": {
      "language": "en", "first_message": "Hello, how can I help?",
      "voicemail_detection": true, "voicemail_action": "leave_message",
      "voicemail_message": "Sorry we missed you. We will call you back."
    },
    "default_tools": {"transfer": {"enabled": true, "destination_number": "+14155550100"}}
  }'
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
AGENT_ID = os.environ["AGENT_ID"]
VOICE_ID = os.environ["VOICE_ID"]
ETAG = os.environ["ETAG"]

response = httpx.patch(
    f"{BASE}/agents/{AGENT_ID}/draft",
    headers={
        "Authorization": f"Bearer {KEY}",
        "Idempotency-Key": str(uuid.uuid4()),
        "If-Match": ETAG,
    },
    json={
        "prompt": "You are the support agent.",
        "voice": {"voice_id": VOICE_ID},
        "settings": {
            "language": "en",
            "first_message": "Hello, how can I help?",
            "voicemail_detection": True,
            "voicemail_action": "leave_message",
            "voicemail_message": "Sorry we missed you. We will call you back.",
        },
        "default_tools": {"transfer": {"enabled": True, "destination_number": "+14155550100"}},
    },
)
response.raise_for_status()
print(response.headers["ETag"])
print(response.json())
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, AGENT_ID, VOICE_ID, ETAG } = process.env;

const response = await fetch(`${RASEN_API_BASE}/agents/${AGENT_ID}/draft`, {
  method: "PATCH",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "If-Match": ETAG!,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    prompt: "You are the support agent.",
    voice: { voice_id: VOICE_ID },
    settings: {
      language: "en",
      first_message: "Hello, how can I help?",
      voicemail_detection: true,
      voicemail_action: "leave_message",
      voicemail_message: "Sorry we missed you. We will call you back.",
    },
    default_tools: { transfer: { enabled: true, destination_number: "+14155550100" } },
  }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(response.headers.get("ETag"));
console.log(await response.json());
```

The answer is the draft with its new `ETag`; set `ETAG` to it. A `PATCH` merges `settings` one
level deep, and an array replaces its field. Draft edits do not change live calls. This edit also
makes the agent leave a message on a voicemail ([Voicemail](#voicemail)).

### 5. Set a variable default

**`curl`**

```bash curl
curl -sS -i -X PUT "$RASEN_API_BASE/agents/$AGENT_ID/variables/hotline" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "If-Match: $ETAG" \
  -H "Content-Type: application/json" \
  -d '{"value": "+14155550100", "sensitivity": "public"}'
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
AGENT_ID = os.environ["AGENT_ID"]
ETAG = os.environ["ETAG"]

response = httpx.put(
    f"{BASE}/agents/{AGENT_ID}/variables/hotline",
    headers={
        "Authorization": f"Bearer {KEY}",
        "Idempotency-Key": str(uuid.uuid4()),
        "If-Match": ETAG,
    },
    json={"value": "+14155550100", "sensitivity": "public"},
)
response.raise_for_status()
print(response.headers["ETag"])
print(response.json())
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, AGENT_ID, ETAG } = process.env;

const response = await fetch(`${RASEN_API_BASE}/agents/${AGENT_ID}/variables/hotline`, {
  method: "PUT",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "If-Match": ETAG!,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ value: "+14155550100", sensitivity: "public" }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(response.headers.get("ETag"));
console.log(await response.json());
```

Set `ETAG` to the `ETag` of the answer. A write with `"value": null` clears the stored default and
keeps the variable declared with its description and sensitivity; each call then supplies the
value in `dynamic_variables` ([Start a call](/guides/calls#start-a-call)). `pii` and `confidential`
values are never returned.

### 6. Validate the draft

The body is a draft patch applied over the draft for the check, and it must name at least one
field (`{}` is refused). To check the draft as it stands, send one field with its current value.

**`curl`**

```bash curl
curl -sS -X POST "$RASEN_API_BASE/agents/$AGENT_ID/draft/validate" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "If-Match: $ETAG" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "You are the support agent."}'
```

**`Python`**

```python Python
import os

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
AGENT_ID = os.environ["AGENT_ID"]
ETAG = os.environ["ETAG"]

response = httpx.post(
    f"{BASE}/agents/{AGENT_ID}/draft/validate",
    headers={"Authorization": f"Bearer {KEY}", "If-Match": ETAG},
    json={"prompt": "You are the support agent."},
)
response.raise_for_status()
result = response.json()
print(result["valid"], result["errors"], result["warnings"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, AGENT_ID, ETAG } = process.env;

const response = await fetch(`${RASEN_API_BASE}/agents/${AGENT_ID}/draft/validate`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "If-Match": ETAG!,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ prompt: "You are the support agent." }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const result = await response.json();
console.log(result.valid, result.errors, result.warnings);
```

`validateAgentDraft` runs every check a publish would make, then discards the result: nothing is
saved, published or called. It answers `valid`, a list of `errors` and `warnings` (each with its
field, code and message) and the agent's `readiness`. It is not a simulated call and does not prove
that a call will be admitted. Warnings never make a draft invalid or block a publish.

A variable name in single braces in the prompt or an opening message (`{customer_name}`) is filled
in like `{{customer_name}}` when the call has that variable. A single-brace name that the agent
does not declare, and that is not a built-in (`agent_name`, `language`), is filled in only when a
call passes it, so validation answers a `single_brace_variable` warning for it. Without a value,
the agent reads it as written.

### 7. Publish the draft

**`curl`**

```bash curl
curl -sS -X POST "$RASEN_API_BASE/agents/$AGENT_ID/publish" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "If-Match: $ETAG"
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
AGENT_ID = os.environ["AGENT_ID"]
ETAG = os.environ["ETAG"]

response = httpx.post(
    f"{BASE}/agents/{AGENT_ID}/publish",
    headers={
        "Authorization": f"Bearer {KEY}",
        "Idempotency-Key": str(uuid.uuid4()),
        "If-Match": ETAG,
    },
)
response.raise_for_status()
publication = response.json()
print(publication["version"]["id"], publication["created"], publication["live_version_id"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, AGENT_ID, ETAG } = process.env;

const response = await fetch(`${RASEN_API_BASE}/agents/${AGENT_ID}/publish`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "If-Match": ETAG!,
  },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const publication = await response.json();
console.log(publication.version.id, publication.created, publication.live_version_id);
```

A publish freezes the whole draft (prompt, settings, variables, default-tool policy, tools with
their pinned credential versions, MCP connections and eligible direct-library knowledge) and makes
it live for new calls in one step. Ready library sources are frozen as retrieval data or bounded
prompt context ([Knowledge](/guides/knowledge)). The answer names the `version`, whether it was
`created` (`false` when identical content reused an existing version) and the `live_version_id`.
Calls already admitted keep their version.

Two publishes of the same token make one version. A replay returns the original publication
receipt; it never activates an older version again. A refused publish leaves the previous version
live and the draft unchanged (Errors, below).

### 8. List the versions

**`curl`**

```bash curl
curl -sS "$RASEN_API_BASE/agents/$AGENT_ID/versions" \
  -H "Authorization: Bearer $RASEN_API_KEY"
```

**`Python`**

```python Python
import os

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
AGENT_ID = os.environ["AGENT_ID"]

response = httpx.get(f"{BASE}/agents/{AGENT_ID}/versions", headers={"Authorization": f"Bearer {KEY}"})
response.raise_for_status()
for version in response.json()["items"]:
    print(version["id"], version["number"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, AGENT_ID } = process.env;

const response = await fetch(`${RASEN_API_BASE}/agents/${AGENT_ID}/versions`, {
  headers: { Authorization: `Bearer ${RASEN_API_KEY}` },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const page = await response.json();
for (const version of page.items) {
  console.log(version.id, version.number);
}
```

Versions are numbered, newest first. `GET /agents/{agent_id}/versions/{version_id}` reads one, and
`GET /agents/{agent_id}/versions/{version_id}/diff?from_version_id=<older id>` compares two. A
version is immutable: its tools are frozen safe descriptors with credential references only, its
`default_tools` is the frozen built-in policy, and sensitive variables read redacted.

### 9. Roll back

Set `VERSION_ID` to the `id` of the version to activate, and `LIVE_VERSION_ID` to the agent's
current `live_version_id`.

**`curl`**

```bash curl
curl -sS -X POST "$RASEN_API_BASE/agents/$AGENT_ID/rollback" \
  -H "Authorization: Bearer $RASEN_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{"version_id": "'"$VERSION_ID"'", "expected_live_version_id": "'"$LIVE_VERSION_ID"'"}'
```

**`Python`**

```python Python
import os
import uuid

import httpx

BASE = os.environ["RASEN_API_BASE"]
KEY = os.environ["RASEN_API_KEY"]
AGENT_ID = os.environ["AGENT_ID"]
VERSION_ID = os.environ["VERSION_ID"]
LIVE_VERSION_ID = os.environ["LIVE_VERSION_ID"]

response = httpx.post(
    f"{BASE}/agents/{AGENT_ID}/rollback",
    headers={"Authorization": f"Bearer {KEY}", "Idempotency-Key": str(uuid.uuid4())},
    json={"version_id": VERSION_ID, "expected_live_version_id": LIVE_VERSION_ID},
)
response.raise_for_status()
activation = response.json()
print(activation["from_version_id"], activation["to_version_id"], activation["warnings"])
```

**`TypeScript`**

```typescript TypeScript
const { RASEN_API_BASE, RASEN_API_KEY, AGENT_ID, VERSION_ID, LIVE_VERSION_ID } = process.env;

const response = await fetch(`${RASEN_API_BASE}/agents/${AGENT_ID}/rollback`, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${RASEN_API_KEY}`,
    "Idempotency-Key": crypto.randomUUID(),
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ version_id: VERSION_ID, expected_live_version_id: LIVE_VERSION_ID }),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const activation = await response.json();
console.log(activation.from_version_id, activation.to_version_id, activation.warnings);
```

The answer is an activation receipt: `from_version_id`, `to_version_id` and `warnings`. Rollback
activates an existing version by its ID and records a new activation. It never creates a version,
and it keeps the draft and admitted calls unchanged. A replay returns the original activation.

A rollback never restores a revoked credential: `warnings` lists, under `credential_unavailable`,
the tools of the activated version whose pinned credential version is revoked, and those tools are
refused when a call uses them. A rollback also does not restore model placements that are no longer
available.

## Rules

* MUST send the draft ETag in `If-Match` on every draft write, variable write, validation and
  publish, and a new `Idempotency-Key` on every write except validation.
* MUST read the draft again after `409 draft_conflict`, review it and send the change with the new
  ETag. See [Revisions and ETags](/concepts/revisions).
* MUST send the agent's identity ETag from `GET /agents/{agent_id}`, not the draft ETag, to
  `PATCH /agents/{agent_id}`. That operation changes only the name and description.
* MUST use `english`, `hindi` or `hinglish` for `settings.language` in `initial_draft`, and `en`,
  `hi` or `hinglish` in later draft edits.
* MUST NOT copy a redacted null from a read into a write.
* MUST NOT start a variable key with `system__`.
* MUST NOT expect a refused voice or setting to be substituted: it is refused, never replaced.
* An agent name is stored without its outer spaces. A name that is blank after that, or holds a
  control character such as a tab, is refused.
* Repeating a create with the same `Idempotency-Key` and body returns the same `201` body with
  `Idempotent-Replayed: true`.

### Built-in tools: the default-tool policy

The draft's `default_tools` decides the two built-in tools, and each publish freezes it into the
version:

```json
{"end_call": {"enabled": true}, "transfer": {"enabled": false, "destination_number": null, "destinations": []}}
```

* **End call** is on unless you disable it. It has no other settings. It cannot be disabled while
  IVR hang-up or voicemail detection is on, because those rely on it.
* **Transfer** is off until you enable it with 1 to 10 named `destinations`, or one E.164 `destination_number`.
  An enabled transfer without a destination is refused. A disabled transfer may keep its destinations for later.
  See [Configure call transfers](/guides/call-transfers) for destination types and carrier setup.
* A `PATCH` merges field by field: a tool or field you leave out keeps its setting. The merged
  result must still give an enabled transfer a destination.
* Writing `destinations` replaces the whole list. Preserve each existing destination's `id` when editing it.
  MUST NOT write `destinations` and `destination_number` together.
* A draft that never set the policy reads as end-call on and transfer off, and so does a version
  published before the policy existed.
* After you disable end-call and publish, nothing answers to `end_call` during that version's
  calls. External hang-up, the inactivity timer and call duration limits are separate and keep
  working.
* `end_call`, `transfer` and `transfer_to_number` are reserved: no authored tool can take those
  names ([Tools and MCP servers](/guides/tools)).

The built-in tools never appear in the tool list; the draft and each version show them under
`default_tools`. `GET /tools/catalog` describes them.

### Voicemail

When `settings.voicemail_detection` is on and the agent reaches a voicemail, `settings.voicemail_action` decides what it
does:

* `hang_up` ends the call at once.
* `leave_message` speaks `settings.voicemail_message`, then ends the call.

An agent that never set `voicemail_action` reads `hang_up`.

A call that reached a voicemail ends with `end_reason` `voicemail_detected`, with either action. The
same `end_reason` follows when the carrier reports a machine. `dial_outcome` can still be
`answered`, because the carrier connected the call before the mailbox answered. Read `end_reason`
to find a voicemail.

`voicemail_message` holds at most 500 characters. It can name call variables as `{{name}}`, and
the agent fills them in once for each call. MUST send a message that is not blank with
`leave_message`: the API refuses a blank message with `invalid_request` on `voicemail_message`.
Draft and version reads always include `voicemail_action` and `voicemail_message`. Read
`voicemail_action` as an open list, and keep an unknown value.

### Readiness

`GET /agents/{agent_id}/readiness` answers `state` and `reasons`. Readiness is a snapshot, not a
reservation. Reason codes include `agent_not_published`, `agent_not_live`, `agent_archived`,
`credential_unavailable` (the live version pins a revoked credential version) and
`no_ready_placement` (a serving model is not ready).

### Archived agents

Archived agents are left out of agent lists unless you ask for `state=archived`, and read with
`state: archived`. An archived agent refuses every draft edit, validation, publish and rollback
with `409 agent_archived`. Starting a call with it answers `agent_not_live` with
`details.state = "archived"`. See [Archive and restore an agent](/guides/archive-agent).

## Verify

```bash
curl -sS "$RASEN_API_BASE/agents/$AGENT_ID" \
  -H "Authorization: Bearer $RASEN_API_KEY"
```

Expected output after step 7: the agent with `state: live` and the published version in
`live_version_id`.

```json
{"id": "agent_01j00000000000000000000000", "name": "Support line", "state": "live", "live_version_id": "pub_01j00000000000000000000000"}
```

## Errors

| Code                                                      | Cause                                                                                                                                                         | Fix                                                                                                |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `draft_conflict`                                          | Something the ETag covers changed since you read it, or you sent an old agent ETag. `details` has `expected_etag` and `current_etag`.                         | Read the draft (or agent) again, review it and send the change with the new ETag.                  |
| `resource_key_conflict`                                   | Another agent has this `resource_key`. `details.existing_id` names it.                                                                                        | Read that agent instead of creating it again.                                                      |
| `invalid_request` (`details.field = "voice"`)             | The voice model of the agent does not support the voice.                                                                                                      | Choose a voice from `listVoices` for that agent, or without `agent_id` for a new agent.            |
| `invalid_request` (`details.field = "name"`)              | The name is blank after trimming, or holds a control character.                                                                                               | Send a name with visible characters and no control characters.                                     |
| `invalid_request` (`details.field = "voicemail_message"`) | `voicemail_action` is `leave_message` and the message is blank.                                                                                               | Send a message, or set `voicemail_action` to `hang_up`.                                            |
| `invalid_request`                                         | You rolled back to the version that is already live.                                                                                                          | Choose another version.                                                                            |
| `credential_unavailable`                                  | A pinned credential version was revoked.                                                                                                                      | Pin a version that is not revoked and publish again.                                               |
| `conflict` (`reason: live_version_changed`)               | Another publish or rollback changed the live version while this one ran, or `expected_live_version_id` is no longer live (`details.current_live_version_id`). | Read the agent, then publish or roll back again with a new `Idempotency-Key` if you still want to. |
| `agent_archived`                                          | The agent is archived.                                                                                                                                        | Unarchive it first ([Archive and restore an agent](/guides/archive-agent)).                        |
| `unavailable` (`details.dependency = "voice_catalogue"`)  | The voice catalogue could not be read. It is not empty.                                                                                                       | Retry after `Retry-After`.                                                                         |
| `not_found`                                               | The agent does not exist, or belongs to another workspace.                                                                                                    | Check `AGENT_ID`.                                                                                  |

A publish is also refused when a selected knowledge source is no longer eligible. An empty voice
list means that no voice model is ready for that agent, or for new agents.

## Related

* [Revisions and ETags](/concepts/revisions)
* [Idempotency and replay](/concepts/idempotency)
* [Tools and MCP servers](/guides/tools)
* [Knowledge](/guides/knowledge)
* [Archive and restore an agent](/guides/archive-agent)
* [Start a call](/guides/calls#start-a-call)