# 10 — Public API reference (design)

**Status:** Draft. Written 2026-11-07. Base URL `https://api.<domain>` (served by `apps/web`).
OpenAPI 3.1 at `/openapi.json`, docs as Markdown at `/docs/<page>.md`, index at `/llms.txt`.
The OpenAPI document is generated from the handlers' Zod schemas (T-122) and committed as
`apps/web/openapi.snapshot.json`; it covers the routes behind API keys (agents, versions, notice,
config, keys). Routes still on the internal token (lines, eval cases) are left out until they move
to API keys. `/docs` lists the published pages, `/setup.md` is a paste-in prompt for coding agents
and `@charla/sdk` is a typed client generated from the snapshot (`openapi-typescript` +
`openapi-fetch`).

## 1. Authentication and scopes

- `Authorization: Bearer sk_live_…` or `x-api-key`. Keys are org-wide or agent-bound. Sandbox
  keys `sk_test_…` run against test numbers only.
- Scopes: `<resource>:read` / `<resource>:write` for `config`, `agents`, `tools`, `lines`
  (channel identities), `secrets`, `alerts`, `usage`, `people`, `outcomes`, `handoffs`,
  `deployments`, `trace_exporters`, `webhooks`; plus `agents:chat`, `keys:manage`, `audit:read`, `*`.
  Write implies read. `/sync` requires `agents:write`, `tools:write`, `config:write`,
  `alerts:write`.
- Agent-bound keys reach only their agent (`404` for siblings; `403 org_key_required` for
  org-level routes).
- Errors (T-120): `401 invalid_key` (missing, malformed, unknown, expired or revoked: one answer
  for all), `403 insufficient_scope` (`details` `{ required, missing }`), `403 org_key_required`.
  `X-Org-Id` is optional: platform administration keys (no org) must send it (`400
  org_id_required`, `404 not_found` for an unknown org); an org key may send its own org only
  (`403 org_mismatch`).
- Rate limits per key (T-124): a sliding 60 s window in Redis, set by the org's plan
  (`api_requests_per_minute`, `docs/14` §2: 600 on Free and Starter; platform keys 600). Every
  request of a valid key counts, including ones refused for scope or org; invalid keys do not.
  Every answer carries `X-RateLimit-Limit` and `X-RateLimit-Remaining`; past the limit,
  `429 rate_limited` with `Retry-After` (seconds) and `details` `{ limit, retryAfterSeconds }`.
  A refused request does not use the budget. If Redis is unreachable the API lets requests
  through without the headers (fail open). Inbound webhooks (`/webhooks/*`) are never limited.
- Errors: `{ "error": { "code": "snake_case", "message": "…", "details": {…} } }`; `details`
  is always present (`{}` when empty). One global handler (T-124) maps what a route throws:
  Zod → `400 validation_error` (`details.issues`), a body that is not JSON → `400 invalid_json`,
  plan gating → `402 plan_required`, a row that RLS hides or refuses or a missing resource →
  `404 not_found`, a unique violation → `409 conflict`, anything else → `500 internal_error`
  (logged, cause never returned). OpenAPI: `Error` schema and the common `responses`
  (`apps/web/src/server/http/openapi-errors.ts`, published by T-122).
- Plan gating (T-103, `docs/14` §2): a write the org's plan does not allow answers
  `402 plan_required` with `details` `{ plan, requiredPlan, feature | channel | limit, max, used }`
  (`requiredPlan` is the cheapest plan that allows it, `null` for a custom contract). Applies to
  creating agents past `agents`, connecting a channel the plan lacks (Free cannot connect its own
  WhatsApp number), starting eval runs past `eval_runs_per_month` and features (BYOK, regions…).
- AI disclosure (T-140, `docs/13` §3.5): any write that creates an agent version
  (`POST`/`PATCH /agents`, `PATCH /config`, `/sync`) answers `422 eu_disclosure_required` when an
  `eu`-region org sets `disclosure.enabled = false`, and `422 disclosure_text_not_ai` when a
  custom `disclosure.text` does not say the contact is talking to an AI (or exceeds 500
  characters). Disclosure changes are written to `audit_log` as `agent.disclosure.update`.
- Idempotency: `Idempotency-Key` header honoured on all `POST` that create or send; replay
  returns the original response with `Idempotent-Replayed: true`.
  Keys are 1–255 characters (`400 invalid_idempotency_key`), scoped to the org and kept 24 h
  (Redis, `idempotent()` in `apps/web`, T-121). The fingerprint is the method, path, query and
  body (JSON compared canonically): the same key with another request is `422
  idempotency_key_reused`; a twin still running is `409 idempotency_in_progress` with
  `Retry-After: 1` after a 10 s wait; a `5xx` frees the key so a retry runs again.

## 2. Developer API (`/api/v1/developer`)

### 2.1 Agents and config
| Method | Path | Purpose |
|---|---|---|
| GET | `/agents` | List agents the key can act on |
| POST | `/agents` | Create agent `{ name, model, system_prompt, max_steps, history_limit, locale, features, harness, harness_config, turn_deadline_ms, user_secrets, workflow }` |
| GET/PATCH/DELETE | `/agents/:agentId` | Read / partial update / archive |
| GET | `/config?agent_id=` · PATCH `/config` | Keiki-compatible single-agent config read/patch (`features` patch merges flags) |
| GET | `/agents/:agentId/versions` · POST `/agents/:agentId/versions/:versionId/restore` | Version history and restore |
| POST | `/sync` | Infrastructure-as-code upsert of prompt, tools, policies, capabilities, alerts, secrets (SDK `kit.sync()`) |
| POST | `/agents/:agentId/notice` | `{ text, contact?, conversation? }` → `200 { ok, conversations, ran, queued, unavailable, results[] }`; without target → `202` broadcast ≤ 200 conversations |

**Agents, versions and config today (T-121).** Bodies and answers are snake_case; `features`,
`harness_config`, `user_secrets` and `workflow` keep the stored camelCase shape (`docs/06` §2.2). Unknown
fields → `400 invalid_request` (`details.issues`); a merged config that does not validate (or
names an unknown feature) → `422 invalid_config`. Scopes: `agents:read` for `GET /agents*`,
`agents:write` for the writes, `config:read` / `config:write` for `/config`.

- `POST /agents` (`Idempotency-Key`) needs `name`, `model`, `system_prompt`; also takes
  `reasoning_effort`, `max_steps` (default 10), `history_limit` (default 50), `locale` (default
  the org's), `disclosure { enabled, text? }`, `features`, `user_secrets`, `workflow`, `harness`,
  `harness_config`, `turn_deadline_ms` (1,000–900,000). → `201 { agent }`, `status: active`, with
  version 1 active. `agent` is `{ id, name, slug, status, harness, harness_config,
  turn_deadline_ms, active_version_id, version, config, created_at, updated_at }`; `config` is `{
  model, reasoning_effort, system_prompt, max_steps, history_limit, locale, disclosure, features,
  user_secrets, workflow }` (`workflow: null` without one). Org keys only (`403 org_key_required`); `402 plan_required` past `agents`.
- `GET /agents` → `{ data: agent[] }` without `version`/`config`, archived included; an
  agent-bound key lists only its agent. `GET /agents/:agentId` → `{ agent }`.
- `PATCH /agents/:agentId`: the same fields, all optional, plus `status: active | paused`. Agent
  fields change in place; config fields append a version (`source: api`) and activate it. A patch
  that leaves the config as it is appends nothing. Archived agents are `404 agent_not_found`.
- `DELETE /agents/:agentId` archives (`status: archived`), idempotent → `{ agent }`. Lines,
  conversations and versions stay.
- `GET /agents/:agentId/versions` → `{ data: [{ id, agent_id, version, source, active,
  config_hash, config, created_at }] }`, newest first, up to 50 (`config: null` for a version that
  no longer validates). `POST …/versions/:versionId/restore` (`Idempotency-Key`) appends a
  `restore` version with that config and activates it → `200 { agent, changed }`; `changed:
  false` when the agent already runs that config. `404 version_not_found`.
- `GET /config?agent_id=` → `{ config: { agent_id, version_id, version, …config } }`. `PATCH
  /config` `{ agent_id?, …config fields }` → `{ config, changed }`. `features` merges per feature
  and per field inside it (`{ memory: { enabled: false } }` changes only that flag; `null`
  removes a feature). Without `agent_id`: an agent-bound key's agent, else the org's only live
  agent, else `400 agent_id_required`. `409 no_active_version` for an agent with no config.
- `workflow` (T-161, [ADR-0013](adr/0013-agent-workflows.md)) is the agent's graph of stages:
  `{ nodes, transitions, settings? }`, shape in `docs/06` §2.2. It is replaced whole, never
  merged, and `null` removes it. A malformed one is `400 invalid_request`. A well-formed one
  whose graph is not valid is `422 invalid_config` with every problem at once:
  `details.issues[] = { code, path, message }`, where `code` is one of the `workflow_*` codes of
  `docs/06` §2.2 and `path` starts at the config (`["workflow", "nodes", 2, "tools", 0]`).
  A stage may only name tools the agent has, so create the tools before the workflow. The
  runtime does not follow workflows until T-163.
- A concurrent write that loses the version number → `409 conflict`; retry.

**Notices today (T-074).** `text` ≤ 4,000 characters; `conversation` is required (broadcast and
`contact` targeting are Phase 2: `400 conversation_required`). Auth: an API key with
`agents:write` that reaches the agent (T-121; another org's or archived agent → `404
agent_not_found`, checked before forwarding). `apps/web` forwards to the
runtime (`POST {RUNTIME_URL}/internal/agents/:agentId/notice`), which sends a `reactive` signal
tagged `platform-note` to the conversation's thread. Response `200 { ok, outcome, conversations:
1, ran, queued, unavailable, results: [{ conversation, outcome, turnId? }], noticeId, turnId?,
reason? }`: `ran` (idle thread woken; new turn with `trigger = notice`, `silent = true`),
`queued` (an active run reads it at its next step), `unavailable` (`reason`: `held`, `closed`,
`opted_out`, `no_active_version`, `blocked`, `busy`, `shutting_down`…; `shutting_down`: the
replica is stopping and sent nothing, retry; `blocked`: the thread is waiting on a tool
approval, the runtime retried every 2 s for up to 8 s and sent nothing, retry later). After
`blocked` or `shutting_down` the `Idempotency-Key` is freed, so a retry with the same key sends
the notice (ISSUE-1080). Unknown conversation, or one of another
agent → `404 conversation_not_found`. A `queued` notice that the run ends without taking is
sent again when that run ends. The notice is never stored as a contact message nor sent
verbatim. `Idempotency-Key` (1–255 characters, ISSUE-1069) is scoped to the org and the agent
and kept 24 h: a retry with the same key and body (for example after web's 15 s timeout
answered `502`) sends nothing and replays the first `200` with `Idempotent-Replayed: true`;
a concurrent twin waits up to 10 s for that result, else `409 idempotency_in_progress` with
`Retry-After: 1`; the same key with another body → `422 idempotency_key_reused`; an invalid
key → `400 invalid_idempotency_key`. A send that fails (`5xx`) frees the key. If the replica
dies mid-send, the key is freed after 60 s and a retry may send the notice again.
| GET/PUT | `/agents/:agentId/storage/:entity` | Durable JSON rows for tools (capability entities) |

### 2.2 Tools
| Method | Path | Purpose |
|---|---|---|
| GET/POST | `/tools?agent_id=` | List / create `{ name, description, inputSchema, executionType, webhookUrl, timeout, policy }` |
| GET/PATCH/DELETE | `/tools/:toolId` | PATCH replaces `policy` whole |
| POST | `/tools/:toolId/test` | Run with sample input in a held-back turn context |

### 2.3 Channel identities (lines)
| Method | Path | Purpose |
|---|---|---|
| GET | `/lines?agent_id=` | List identities with status, quality, tier |
| POST | `/lines/whatsapp/embedded-signup/start` | `{ agent_id, return_url }` → `{ url, state }` |
| POST | `/lines/whatsapp/embedded-signup/complete` | `{ state, code }` → identity |
| POST | `/lines/telegram` | `{ agent_id, bot_token }` |
| POST | `/lines/email` | `{ agent_id, username, domain }` |
| POST | `/lines/voice/acquire` | `{ agent_id, country, area_code? }` → monthly price shown first (`needs_payment` + `checkoutUrl`) |
| DELETE | `/lines/:lineId` | Disconnect / release |
| GET | `/lines/:lineId/templates` · POST `/templates` | WhatsApp templates sync and submit |

**Telegram today (T-113).** `POST /lines/telegram` `{ agent_id, bot_token }` (strict body) →
`200 { line: { id, agent_id, type, provider, address: "@username", status: "connected",
telegram: { bot_username }, created_at } }`. Credentials and secret names are never returned.
Errors: `400 invalid_bot_token` (malformed, or `getMe` refused it), `400 invalid_body`,
`402 plan_required` (Free has no Telegram), `404 agent_not_found` (another org's or archived),
`409 agent_has_telegram_bot` (one bot per agent; `details.lineId`),
`409 bot_connected_to_other_agent`, `409 bot_in_use` (connected in another org),
`502 telegram_error` (`details: { method, error_code, description }`; a refused `setWebhook`
leaves the line `needs_action`) and `502 telegram_unavailable`. Connecting the same bot again is
safe: same line, rotated webhook secret. `DELETE /lines/:lineId` (Telegram lines only for now,
`409 unsupported_line_type` otherwise) calls `deleteWebhook`, sets the line `disconnected`,
clears its credentials and deletes both secrets → `200 { line }`; idempotent; a token revoked in
BotFather still disconnects. The row is kept (conversations reference it) and connecting the same
bot revives it. Auth is provisional: `Authorization: Bearer <INTERNAL_API_TOKEN>` plus
`X-Charla-Org-Id` until API keys (T-120). The dashboard uses the same flow at
`POST /api/webapp/agents/:agentId/lines/telegram` `{ bot_token }` and
`DELETE /api/webapp/lines/:lineId` (every role but viewer).

### 2.4 Partner deployments (Keiki-compatible)

Tenancy (ADR-0012): every `external_ref` is a separate **client org** linked to the partner org in
`registry.partner_links`. `POST /deployments` with a new `external_ref` creates the client org
(`region` in the body, default the partner's), the link, the agent and the deployment; the
answer includes `org_id`. The client org has its own contacts, consent and opt-outs, DSAR,
memory, AI notice, secrets and region. Partner keys act only on client orgs with an `active` link,
one org per request (`withOrg(clientOrgId)`), never across client orgs; an unknown or revoked
`external_ref` → `404 deployment_not_found`. `DELETE /deployments/:external_ref` deletes the client
org and everything in it, then revokes the link. Partner keys and `partner_links` are post-MVP.

Proposed in [ADR-0023](adr/0023-partner-deployments-and-account-linking.md) (#650; defaults pending
the Lead, docs/18): a partner key is an org-wide key of an org enabled as partner by Charla staff
(`403 partner_not_enabled` otherwise) with `deployments:read|write`. The link goes `provisioning →
active → deleting → revoked`; creation is resumable and a `DELETE` answers `202` and finishes in a
job (immediate, ≤ 15 min). Errors: `404 deployment_not_found` (unknown or revoked, not told apart),
`409 deployment_provisioning`, `409 deployment_deleting`, `409 partner_limit_reached` (100
deployments by default), `503` with `Retry-After` when the registry or the region is down.
Concurrent `POST`s with one `external_ref` create one client org; a repeated `DELETE` is
idempotent. Every `/deployments` route runs through `withPartnerDeployment`
(`apps/web/src/server/developer/partner.ts`, #653): it authenticates the key (an agent-bound key →
`403 org_key_required`, a platform key → `403 partner_key_required`), checks the scope and the
partner row, resolves `(partner_org_id of the key, external_ref)` and runs the route in
`withOrg(client_org_id)` in the client org's region. A malformed `external_ref` → `400
invalid_request`; `409 deployment_provisioning` and both `503` (`registry_unavailable`,
`region_unavailable`) carry `Retry-After: 5`. Request rate (ADR-0023 §2.2, Q5 — **default,
pendiente de confirmar por el Lead**): the partner key keeps the per-key limit of the partner org's
plan (`api_requests_per_minute`), counted once per request whatever client org it targets, with
the usual `429 rate_limited`. Requests are counted in `charla_partner_requests_total{route,outcome}`.
Account linking (ADR-0023 §3) adds
`DELETE /deployments/:external_ref/account-links?channel=&user_id=` (`deployments:write`, always
`204`, also while `deleting`; #658) and, for an agent without a deployment,
`DELETE /api/v1/developer/agents/:agentId/account-links?channel=&user_id=` (`people:write`,
`204`; `404 agent_not_found`). Both revoke every `linked` binding of the tenant's `user_id` held
by a contact of `channel` (`docs/09` §2.3); `400 invalid_request` for a missing or bad query.

| Method | Path | Purpose |
|---|---|---|
| POST | `/deployments` | Create (`201`) or update (`200`, `created: false`) by `external_ref`; body `{ external_ref, agent: { template | spec }, channels[], webhook_url, identity, actions, mcp_connections[], tools[] }`; partial-update semantics; unknown fields `400` |
| GET/DELETE | `/deployments/:external_ref` | Read (no credentials) / delete the client org and everything in it |
| DELETE | `/deployments/:external_ref/channels/:type?ref=` | Detach one channel |
| DELETE | `/deployments/:external_ref/identity/cache?channel=&user_id=` | Evict identity cache |
| GET/PUT/DELETE | `/deployments/:external_ref/mcp-senders` | Per-sender MCP headers `{ source, channel, user_id | conversation_id, headers, connection? }` |
| DELETE | `/deployments/:external_ref/account-links?channel=&user_id=` | Revoke a sender's account link (ADR-0023 §3.6, #658) |

Channel specs: `{ type: 'whatsapp', access_token?, phone_number_id?, app_secret?, verify_token?,
waba_id? }` (omit credentials → response includes an Embedded Signup `connectUrl`),
`{ type: 'telegram', bot_token }`, `{ type: 'instagram', page_id, ig_user_id, access_token }`,
`{ type: 'messenger', page_id, access_token }`, `{ type: 'email', mode, username, domain }`,
`{ type: 'api', passthrough }`, `{ type: 'voice', country, area_code }`. Per-channel result
`status: connected | needs_action | needs_payment | error | skipped` with `connectUrl` /
`checkoutUrl`.

### 2.5 Actions, handoffs, people
| Method | Path | Purpose |
|---|---|---|
| GET | `/actions?agent_id=&status=&limit=` | List governed actions |
| GET | `/actions/:actionId` | Public record |
| POST | `/actions/:actionId/decide` | `{ decision: approve | decline, reason? }` (addition over Keiki; approver = key owner principal, counts as `verified`) |
| POST | `/actions/groups/:groupId/decide` | Approve/decline all |
| GET | `/handoffs?status=` · POST `/handoffs` · POST `/handoffs/:id/resolve` | Queue |
| GET | `/people?agent_id=` · GET `/people/:contactId` · DELETE `/people/:contactId` (DSAR erase) · POST `/people/:contactId/export` · GET `/people/:contactId/export` | Contacts |
| GET | `/conversations?agent_id=&contact=` · GET `/conversations/:id/messages` · POST `/conversations/:id/messages` (team reply; template required outside window) · POST `/conversations/:id/takeover` · POST `/conversations/:id/handback` | Conversations |
| POST | `/sessions/exchange` | `{ token }` from a chat link → `{ contact, principal, conversation }` |

DSAR (T-142, `docs/13` §4.5; org keys only, `403 org_key_required` for agent-bound ones):
`DELETE /people/:contactId` (`people:write`) opens an erasure and answers `202 { data: request }`;
a repeat while it is open answers the same request, and once the contact is erased `200` with
its last erasure. `POST /people/:contactId/export` (`people:write`, `Idempotency-Key`) opens an
export, `202`. `GET /people/:contactId/export` (`people:read`) answers the latest export, with
`download_url` (presigned) and `expires_at` once `completed`, for 24 h after it was built
(`null` before and after); `404 export_not_found` when none was requested. A request is
`{ id, type: export | erase, status: pending | running | completed | failed, contact_id,
created_at, completed_at }`. An unknown, malformed or erased (export) contact is
`404 contact_not_found`. The work runs in the runtime's `maintenance` worker within minutes
(the `dsar-sweep` every 5 minutes re-runs a lost or interrupted request; an erasure finishes in
under an hour).

### 2.6 Secrets, keys, usage, audit
| Method | Path | Purpose |
|---|---|---|
| GET | `/secrets` · PUT/DELETE `/secrets/:NAME` | Names only on GET |
| POST/GET | `/api/v1/keys` · POST `/keys/:id/rotate` · POST `/keys/:id/revoke` | Org key management (`keys:manage`), see below |
| GET | `/usage?from=&to=&agent_id=` | Credits, tokens, messages, templates, minutes |
| GET | `/api/v1/audit?from=&to=&actor=&action=&cursor=&limit=&format=` | Audit log (`audit:read`; CSV export on Max+) |

Key management (T-120). `POST /api/v1/keys` takes `{ name, scopes, environment?: "live" | "test",
agentId?, expiresAt? }` and answers `201 { key, secret }`; the secret appears in that response
only (and in the rotation response). A key cannot grant scopes it does not hold (`403
insufficient_scope`), so `keys:manage` alone cannot mint a `*` key. `key` is `{ id, name, agentId,
environment, hint: "sk_live_…abcd", scopes, expiresAt, revokedAt, lastUsedAt, createdBy,
createdAt, rotatedAt }`; `GET` answers `{ data: key[] }`. `rotate` keeps the id, scopes, expiry and
environment and answers `{ key, secret }` (`409 key_revoked` for a revoked key); `revoke` is
immediate and idempotent (`{ key }`). Create, rotate and revoke are written to `audit_log`
(`key.create`, `key.rotate`, `key.revoke`).

Audit (T-145). `GET /api/v1/audit` answers `{ data: entry[], nextCursor }`, newest first, 50 per
page (`limit` ≤ 500); `entry` is `{ id, createdAt, actor: { type, id }, action, target: { type, id }
| null, diff, ip }`. Filters: `from` / `to` (inclusive; a bare `YYYY-MM-DD` covers that UTC day),
`actor` (`member`, `member:mem_…`, `api_key:key_…`, `system`, `mcp`), `action` (exact, or a family
ending in `.` such as `agent.`) and `cursor` (the previous `nextCursor`). `format=csv` answers the
same filters as CSV (up to 10 000 rows; columns `id, created_at, actor_type, actor_id, action,
target_type, target_id, ip, diff`; cells a spreadsheet would run are prefixed with `'`) on plans
with `audit_export`, else `402 plan_required`. The dashboard reads the same through
`GET /api/webapp/audit` (owners and admins) at `/[org]/settings/audit`.

### 2.7 Traces and evals
| Method | Path | Purpose |
|---|---|---|
| GET | `/api/v1/traces?agent_id=&limit=` · GET `/traces/:traceId` | Trace + spans |
| POST | `/traces/:traceId/retry` | Replay failed turn (refused if conversation moved on) |
| GET/POST/PUT/DELETE | `/api/v1/evals/cases` · POST `/cases/generate` · POST `/runs` · GET `/runs/:id` · GET `/runs/:id/cases` · POST `/runs/:id/cancel` · GET `/suggestions` | Eval Studio |
| GET/PUT | `/api/v1/replay/settings` · corpora · runs | Replay (Later) |
| GET/POST | `/api/v1/evals/channel/ping|runs|runs/:id/cases/:caseId|reset|finish` | External-channel driver protocol (Later) |

Eval cases (T-090, internal until API keys land in T-120: `Authorization: Bearer
<INTERNAL_API_TOKEN>` plus `X-Charla-Org-Id: org_…`; every query runs under RLS for that org):

| Method | Path | Purpose |
|---|---|---|
| GET | `/api/v1/evals/cases?agent_id=` | The agent's live cases, oldest first |
| POST | `/api/v1/evals/cases` | `{ agentId, createdFrom?, …case }` (`docs/12` §2.1) → `201 { data, warnings }` |
| GET/PUT/DELETE | `/api/v1/evals/cases/:caseId` | Read; replace (new `version`); archive (`204`) |
| GET | `/api/v1/evals/cases/:caseId/versions` | Every version, newest first |
| GET | `/api/v1/evals/cases/export?agent_id=` | Suite file `{ format: "charla.eval-suite/v1", agentId, cases }` |
| POST | `/api/v1/evals/cases/import` | `{ agentId, suite }`, all cases or none → `201`; CLI: `pnpm evals:import <file> --org <org_…> [--agent <agt_…>]` |
| POST | `/api/v1/evals/cases/generate` | `{ agentId, agentVersionId?, locale? }` (T-093) → `200 { data: { agentId, agentVersionId, locale, model, attempts, cases[], issues[] } }`: 20–30 **drafts, not saved**, each `{ category, createdFrom: "generated", …case }`. Forwarded to the runtime (below) |

A case carries `channel` (`whatsapp`, `telegram`, `api`; any other, `web` included, is a `400`) and an optional `principal`
(`{ status?, source?, userId?, displayName?, role?, scopes? }`, `docs/12` §2.1): the speaker's
identity and scopes for the held turn; without it, an unknown speaker with no scopes. An
optional `chat` (`direct`, the default, or `group`) runs the turn in a group chat: only on
`telegram` and without a `principal`, else `400 invalid_eval_case`.

An invalid case (unknown check or field, bad value) answers `400 invalid_eval_case` with
`details.issues[]` = `{ path, code, message }`. Stubs or tool-keyed checks naming a tool the agent
does not have are stored anyway and listed in `warnings[]` (`unknown_stub_tool`,
`unknown_check_tool`); so are workflow stages (`startStage`, `reachesStage`, `transitions`,
`endStage`; `docs/12` §2.2.6) that the agent's active version does not have (`unknown_stage`, with
the node id in `tool`). Unknown agent or case, or one of another org: `404`.

A generated draft is saved by removing `category` and adding `agentId`: the rest is a valid
`POST /api/v1/evals/cases` body, already with `createdFrom: "generated"` (`docs/12` §2.2.3).
`/generate` answers `502 runtime_unavailable` when the runtime does not answer (up to 10 min).

Eval runs (T-091) live on the runtime, which owns models and agents; `apps/web` forwards
`/api/v1/evals/runs*` to these internal routes (`Authorization: Bearer <INTERNAL_API_TOKEN>`):

| Method | Path | Purpose |
|---|---|---|
| POST | `/internal/evals/runs` | `{ orgId, agentId, candidates?, kind? }` → `202 { run }`; runs every live case × candidate in the background. `candidates` default to the active version's model (max 20, `auto` or `<provider>/<model>`). `409 eval_run_active` (`details.runId`) while the agent has a `queued`/`running` run; `409 no_active_version` / `no_eval_cases`; `404 agent_not_found`; `402 plan_required` once the month's `eval_runs_per_month` is spent (T-103) |
| GET | `/internal/evals/runs/:runId` | Header `X-Charla-Org-Id`; `{ run, results[] }` with each result's `status`, `output`, `traceId`, `error` |
| POST | `/internal/evals/runs/:runId/cancel` | `{ orgId }` → `{ run }` `cancelled`; results not started end `cancelled` |
| POST | `/internal/evals/cases/generate` | `{ orgId, agentId, agentVersionId?, locale? }` → `200 { data }` as above. `agentVersionId` defaults to the active version, `locale` to its `config.locale`. `404 agent_not_found` / `agent_version_not_found`; `409 no_active_version`; `502 eval_generation_failed` (`details.attempts`, `details.issues[]`) when no answer validated after the repairs |
| POST | `/internal/templates/try` | T-152, forwarded by `POST /api/webapp/templates/try` (dashboard session, not the public API): `{ orgId, template: { vertical, locale, slug, title, config, tools }, messages[] }` (≤ 10, the last the user's) → `200` NDJSON stream of `{ type: "text" \| "break" \| "tool" \| "done" \| "error" }`; `402 no_credits`, `404 org_not_found`, `400 invalid_request`. Held turn on an in-memory version, stubbed tools, billed (`docs/12` §2.2.5) |
| POST | `/internal/agents/try` | T-173, forwarded by `POST /api/webapp/agents/:agentId/try` (dashboard session, member or above; the agent and version looked up under the org's RLS): `{ orgId, agentId, versionId, tools: "simulated" \| "live", startStage?, messages[] }` (≤ 10, the last the user's) → `200` NDJSON stream of `{ type: "text" \| "break" \| "tool" \| "calls" \| "workflow" \| "done" \| "error" }`; `402 no_credits`, `404 not_found` (not the agent's version, or not the org's), `409 invalid_stage`, `400 invalid_request`. Held turn on the version (eval agents), billed (`docs/12` §2.2.7) |

### 2.8 Webhook destinations
| Method | Path | Purpose |
|---|---|---|
| GET/POST | `/webhooks` · PATCH/DELETE `/webhooks/:id` · POST `/webhooks/:id/rotate-secret` · POST `/webhooks/:id/test` | Destinations |
| GET | `/webhooks/:id/deliveries` · POST `/deliveries/:id/resend` | Delivery inspection |

### 2.9 Dashboard API (`/api/webapp`, internal)

Not public: the dashboard's own routes, same error envelope. The caller is the Better Auth session
cookie (T-130): its active organization and the user's membership of it, read on the server.
`401 unauthorized` without a session, `403 no_active_organization` without an active org,
`403 not_a_member` when the membership is gone, and `403 cross_origin` for a write whose `Origin`
is not the dashboard's. Every query runs under the org's RLS, and roles follow `docs/11` §3
(`viewer` → `403 viewer_read_only` on writes, below admin → `403 owner_or_admin_required` where
owners and admins decide).

Sign-in, organizations and invitations are Better Auth's own endpoints under `/api/auth/*`
(`email-otp/send-verification-otp`, `sign-in/email-otp`, `sign-in/social`, `organization/*`),
called by the dashboard's forms; they are not a stable contract.

| Method | Path | Purpose |
|---|---|---|
| GET | `/handoffs?status=waiting\|taken\|resolved\|stale&limit=` | The org's handoff queue, oldest first (T-070; `limit` ≤ 200, default 50) |
| POST | `/handoffs/:id/claim` · `/release` · `/resolve` | Queue moves (T-070). `409 invalid_transition { status }` from the wrong status; a release of another member's claim is `403 not_claimer` unless the caller is owner/admin |
| GET | `/agents/:agentId/actions?status=&limit=` | The agent's governed actions as `PublicActionRecord`, newest first (T-063; `limit` ≤ 200, default 50; every role reads) |
| POST | `/agents/:agentId/actions/:actionId/decide` | `{ decision: approve \| decline, reason? }` (T-063, ≤ 500 chars). Owner/admin only (`403 owner_or_admin_required`); another org's or agent's action is `404`. Runs in the runtime with `via: dashboard` (proof grade `verified`) → `200 { action, changed }`; `changed: false` when it was already decided. `502 runtime_unavailable` if the runtime does not answer |
| POST | `/agents/:agentId/actions/groups/:groupId/decide` | Approve all / decline all (T-136): same body and roles. `404` unless the group has a `pending` action of that agent in the caller's org. The runtime decides them in proposal order (`docs/09` §4.3; approve stops at the first that does not complete) → `200 { groupId, results: [{ actionId, outcome: decided, action, changed } \| { actionId, outcome: decided, error } \| { actionId, outcome: skipped }] }`. `502 runtime_unavailable` as above |
| POST | `/conversations/:id/messages` | `{ text }` (T-072, ≤ 4,096 chars; optional `Idempotency-Key`, a retry is delivered once). Any role but viewer. Sends the text to the contact as `role: team` and **takes the conversation over**: `status = held`, `held_by_member_id`, `held_until = now + 30 min` (renewed by each team message; none while a handoff is open, and a `waiting` one is claimed by the member); the agent's running turn is cancelled and it stays quiet while held. `200 { conversation: { id, status, heldByMemberId, heldUntil }, tookOver, cancelledTurnId }`; `409 window_closed { windowExpiresAt }` outside WhatsApp's 24 h window (send a template, T-081), `409 conversation_closed`, `409 opted_out`; `404` for another org's conversation |
| POST | `/conversations/:id/handback` | `{ note? }` (T-072, ≤ 1,000 chars). Any role but viewer. `held → open`; a notice turn resumes the agent with the note as an instruction and the messages of the hold quoted by role (none when there is no note and nobody wrote). `200 { conversation, resumed, turnId }`; `409 not_held { status }` |

## 3. Agents as models

| Surface | Base | Endpoints |
|---|---|---|
| OpenAI-compatible | `/api/v1/openai` | `POST /chat/completions`, `GET /models` |
| Anthropic-compatible | `/api/anthropic` | `POST /v1/messages`, `POST /v1/messages/count_tokens` |

- `model` = agent slug or id. Scope `agents:chat`; the agent must have its API gateway on
  (`api_gateway_enabled`, set with `PATCH /api/v1/developer/agents/:agentId`). An agent-bound key
  reaches only its agent. `GET /models` lists the agents with the gateway on, by slug.
- Implemented (T-123, [ADR-0011](adr/0011-openai-compatible-endpoint.md)): `apps/web`
  authenticates and relays to the runtime (`POST /internal/openai/chat/completions`), which runs
  the turn on the agent's implicit `api` channel identity. One contact per API key (and per
  `user`, when sent): conversations and memory are private to the key. The agent knows the
  contact by that `user` (or by no id at all without one), never by the key id it is stored under,
  so replies and handoff summaries do not repeat the key.
- Honoured: `stream`, `stream_options.include_usage`, `tools`, `tool_choice`, `response_format`
  (`json_object` / `json_schema` as an instruction to the turn), `user`. Ignored without error:
  `temperature`, `max_tokens`, `seed` and the other sampling parameters. Not yet:
  `reasoning_effort` / `thinking.budget_tokens`, images and files in `messages`.
- Input: the trailing `user` message, and/or the `tool` results after the last `assistant`
  message. `system` / `developer` messages ride along as context and never replace the agent's
  prompt. Earlier turns the caller sends are used only for a conversation without history of its
  own; otherwise the stored history is the context.
- `x-conversation-id` header (`[A-Za-z0-9._:-]{1,128}`) threads calls; without it each call is a
  new conversation and the answer's `x-conversation-id` names it. One turn per conversation at a
  time → `409 busy`.
- Content: the turn's text as one string; the text of each model step (before and after a tool
  call) is its own paragraph, separated by a blank line, as the transcript stores it as separate
  messages.
- Streaming: `chat.completion.chunk` from the first token, `: ping` every 15 s, a last chunk with
  `finish_reason`, the usage chunk (`choices: []`) when `include_usage`, always `data: [DONE]`. A
  turn that fails after the first byte ends with an `error` frame before `[DONE]`.
- Client tools (`[A-Za-z0-9_-]{1,64}`, ≤ 64; a name the agent already uses keeps the agent's tool)
  end the response with `finish_reason: tool_calls`; the calls are parked 24 h; results come back
  as `tool` messages in the next request with the same `x-conversation-id`, answered once
  (unknown or repeated ids → `400 unexpected_tool_result` / `400 duplicate_tool_result`); a parked
  call left unanswered reaches the model as an error; a result over 32,000 characters is cut.
- Non-streaming responses include `usage` and `charla: { conversation_id, agent_id, trace_id,
  pending_actions }`.
- Identity (#589, `docs/09` §2.2): before each turn the runtime resolves who the contact is, as
  on WhatsApp. With an identity webhook it is asked with `sender.channel: "api"` and
  `sender.userId` = the contact's id, `<key id>:user:<user>` (the key id alone without `user`);
  without one, the contact's dashboard grant gives the scopes. The `user` field names a person
  under the key but proves nothing by itself: a tool with `requiredScopes` (company-knowledge's
  `create_work_item` needs `work:write`) is refused (`refused_scope`) unless the webhook or a grant
  gives that scope to that key and `user`. A webhook `reply` is the whole answer, with no turn:
  `finish_reason: stop`, `charla.trace_id: null` and no `x-charla-turn-id` header.
- Confirmations (`docs/09` §4.3): a tool with `approval: ask` does not run in the turn. Its call
  becomes a `pending` action listed in `charla.pending_actions` (`[]` when none; on a streamed
  answer, in the last chunk's `charla.pending_actions` when there are any): `{ id, group_id, tool,
  description, card, status, decided_via, result, error, created_at, decided_at, expires_at }`,
  never the arguments. Show the `card` to the person and send their answer with
  `POST /api/v1/openai/actions/:actionId/decide` (`agents:chat`), body `{ decision: approve |
  decline, user?, reason? }`, header `x-conversation-id` required: the same key, `user` and
  conversation as the chat that proposed it, else `404 action_not_found`. The stored call runs
  before the answer `200 { action, changed }` (`status: completed | failed | declined | expired`);
  a repeat answers `changed: false` and runs nothing. Other errors: `400 validation_error` /
  `invalid_json` / `invalid_conversation_id`, `403 gateway_disabled`, `403
  requires_speaker_scopes` (`details.missing`, still pending), `409
  approval_requires_verified_surface` (the team approves it on the dashboard), `502
  runtime_unavailable`. Only this request approves: nothing the model writes does. The next turn
  of the conversation knows the outcome (`# Acciones`); no turn runs on the decision itself.
- Errors: `401 invalid_key`, `403 insufficient_scope` / `gateway_disabled`, `404 model_not_found`,
  `400 validation_error` / `invalid_messages` / `invalid_tool_choice`, `402 insufficient_credit`,
  `409 busy` / `agent_unavailable`, `429 concurrent_turns_exceeded`, `500 turn_failed` /
  `turn_cancelled`, `502 runtime_unavailable`.
- Passthrough mode per agent (not yet): caller's system prompt wins, only request tools, no
  memory/guards.

## 4. Turn-scoped API for external harnesses (`/api/v1/turns/:turnId`)

Bearer `ht_…` or `cts1.…`. Routes: `POST /messages`, `POST /stream`, `POST /actions`, `POST
/attachments`, `GET /attachments/:id`, `POST /typing`, `POST /lease`, `GET /arrivals?after=`,
`GET /return-link?text=`, `POST /complete`. Harness inbox: `GET /api/v1/harness/inbox/next?wait=`
and `POST /api/v1/developer/agents/:agentId/harness/signing-secret`. Semantics in
[07-agent-runtime.md §9](07-agent-runtime.md).

## 5. Outbound event webhooks

Envelope:

```json
{ "type": "charla.conversation.opt_status_changed", "version": 1, "eventId": "evt_…",
  "orgId": "org_…", "agentId": "agt_…", "conversationId": "conv_…", "occurredAt": "…",
  "data": { "channel": "whatsapp", "line": "+52…", "scope": "line", "previousOptedOut": false, "optedOut": true, "reason": "keyword", "keyword": "BAJA", "sourceMessageId": "wamid.…" } }
```

`conversation.opt_status_changed` (T-084): one per consent transition on a line (`docs/08` §2.7).
`scope` (ISSUE-1169) is `line` for a change made on that line and `organization` for an org-wide
one (BAJA TOTAL / ALTA TOTAL, or an operator acting on every line), published once for each line
whose state it changed. `reason` ∈ `keyword | verified_restoration | provider | operator | health | import`; `keyword` is
the normalised word (`BAJA`, `NO MAS`) or `null`; `sourceMessageId` is the provider's id of the
contact's message (`wamid`), `null` when no message caused it; `conversationId` is the
conversation of the change (for provider and operator changes, the contact's direct one on the
line). The dashboard's `POST /api/webapp/conversations/:id/consent { optedOut: boolean, scope?:
"line" | "organization" }` (any role but viewer; `scope` defaults to `line`, the conversation's
line; `organization` acts on every line of the org) answers `{ previousOptedOut, optedOut,
changed, scope }` for the conversation's line, `409 provider_opt_out` when WhatsApp's own
marketing stop is in force on it.

Headers: `Charla-Signature: t=<ts>,v1=<hex>` (multiple `v1` during rotation overlap),
`Charla-Event-Id`, `Charla-Event-Type`, `Charla-Delivery-Id`, `Charla-Attempt-Id`. HMAC-SHA256
over `"<ts>.<raw-body>"`. At-least-once; dedupe on `eventId`. Retries up to 72 h with
exponential backoff and jitter; terminal history 30 days; manual resend keeps `eventId`.

Delivery rules (T-083; `@charla/domain` `webhooks/`, worker `apps/runtime/src/workers/webhook-out.worker.ts`):

- Fan-out: `EventBus.publish` (or `publishInTx` inside the producer's transaction) validates
  `data` against the catalog's Zod schema and writes one `webhook_deliveries` row per live,
  enabled destination whose `events` match (exact, `family.*` or `*`) and whose `agent_filter`
  is empty or holds the event's agent. `webhook.test` only goes to the destination that asked.
- Any 2xx acknowledges. Anything else (non-2xx, timeout 15 s, network error, SSRF block, missing
  secret) is retried after ~1 min, doubling, ±20 % jitter, capped at 6 h; an attempt that would
  land past 72 h settles the delivery as `failed`. Requests go through `safeFetch` (public HTTPS,
  no redirects).
- One BullMQ `webhook-out` job per attempt (`jobId webhook-<deliveryId>-<dueMs>`). The row lease
  (`lease_until`, 60 s) makes each attempt single-replica; the `maintenance` task `webhook-sweep`
  (every 30 s) re-queues due rows whose job was lost, deletes history settled > 30 days ago and
  drops previous secrets whose 24 h overlap ended.
- Disabling or deleting a destination cancels its pending deliveries; deletion keeps the history.
- `resend` (manual origin, fresh 72 h window) answers `409 delivery_in_flight` while a lease is
  active, `410 history_expired` past 30 days and `409 destination_disabled`. `test` answers
  `429 test_queue_full` when the destination already has 25 pending `webhook.test` events.
  Other errors: `404 destination_not_found | delivery_not_found`, `422 invalid_destination`.

Event catalog (GA): `conversation.opt_status_changed`, `message.received`, `message.sent`,
`message.delivered`, `message.read`, `message.failed`, `turn.completed`, `turn.failed`,
`action.*` (also to deployment `actions.webhook_url`: one signed POST per transition, 5 s, no
retries, `Charla-Timestamp` + `sha256=` signature, `data: { action, viewUrl }`; `docs/09` §4.6), `handoff.opened | claimed | resolved`
(`handoff.resolved` data: `handoffId`, `reason`, `status` `resolved | stale`, `resolvedBy`
`member | agent | system`, `summary` when the agent closed it; T-073),
`line.quality_changed`, `line.tier_changed`, `template.status_changed`, `payment.created |
paid | failed | expired | cancelled | refunded`, `billing.balance_low`, `billing.balance_exhausted`,
`billing.plan_changed`, `billing.payment_failed`, `person.erased`, `webhook.test`.

`payment.*` `data` (ADR-0019): `{ paymentId, provider, amount, currency, status,
refundedAmount?, paidAfterClose? }`, amounts in minor units, `paymentId` the payment request's
id. Published when a provider notification (verified, then confirmed against the provider's
API) moves a request: `payment.paid`, `payment.expired`, `payment.cancelled`, and
`payment.refunded` with `status: partially_refunded` until the whole amount is back
(`refundedAmount`). `paidAfterClose: true` when the money arrived after the link expired or was
cancelled.

`person.erased` `data` (T-142): `{ contactId, requestId, channel, erasedAt }`, ids only: the tenant
uses `contactId` to erase its own copy.

`billing.*` `data` (T-101): `{ balance, allowance, threshold?, reason, turnId? }` in credits
(1 credit = 1 USD). `reason: charge` when a turn's charge took the balance to 20 % of the last
grant or purchase (`allowance`; `threshold` is that 20 %) or from positive to ≤ 0, once per
crossing, with the `turnId`; `reason: turn_refused` (`balance_exhausted` only, `allowance: null`)
when a contact's message got no turn for lack of credit, at most once an hour per org. T-104: a
`reason: charge` event also emails the owner (`settings.notifications.ownerEmail`) and texts the
agent's team WhatsApp number (escalation route, only while its 24 h window is open); a
`turn_refused` one notifies nobody (the crossing already did).

`billing.plan_changed` `data` (T-102): `{ previous, plan, reason, provider, subscriptionId }`,
`reason` `checkout | invoice_paid | subscription_updated | subscription_deleted | grace_expired`.
`billing.payment_failed` `data` (T-102): `{ provider, invoiceId, subscriptionId, amount (minor
units), currency, attempt, nextAttemptAt, graceEndsAt }`; the plan stays until `graceEndsAt`
(7 days after the first failure of the dunning), then drops to `free` unless an invoice is paid.

`handoff.*` `data`: `{ handoffId, kind?, reason?, summary?, url?, memberId? }`; `summary` is the
agent's note for the team, never the transcript, and `url` the handoff in the dashboard. An agent's
`features.escalation.routes.webhook` (T-071) receives `handoff.opened` through this same queue: the
URL must be one of the org's destinations (it holds the signing secret), and a destination that is
both the route and a subscriber gets the event once.

`line.*` `data` (T-085, hourly `quality-poll`): `line.quality_changed` →
`{ line, previous, current }` with ratings `green | yellow | red | unknown` (`previous: null` on a
number's first reading, which is only published when it is not green). `line.tier_changed` →
`{ line, previous, current, reason, businessInitiated24h, usage? }`: tiers are counts as strings
(`"1000"`, `"unlimited"`); `reason: tier_changed` when Meta changed the tier, `near_limit` (with
`previous = current`) when business-initiated conversations of the last 24 h passed 80 % of the
tier, once per crossing. `usage` is that count divided by the tier.

## 6. MCP server (`https://mcp.<domain>/mcp`)

Streamable HTTP; OAuth with dynamic client registration; scopes `mcp`, `manage`, `channels`.
One tool per REST endpoint (`get_agents`, `post_deployments`, …) plus `talk_to_agent`,
`check_job`, `cancel_job`, `current_context`, `switch_organization`, `deploy_agent`,
`get_deployment`, `delete_deployment`, `list_agent_templates`, `list_channel_types`,
`escalate`. Permissions identical to the dashboard; viewers `403 viewer_read_only`. Calls > 40 s
return `jobId`. Server card at `/.well-known/mcp.json`. Code Mode (`/mcp/codemode` with
`search` and `execute`) Later. Agents themselves are also exposed via Mastra `MCPServer` per
org at `/api/mcp/:agentId/mcp` for tenant tooling.

## 7. SDK (`@charla/agents`, name TBD)

Mirrors Keiki's `@onkeiki/agents` surface at a smaller scope for GA: `create({ apiKey, name,
agent: { model, maxSteps, historyLimit, systemPrompt, tools, capabilities }, harness, plugins,
secrets })`, `defineTool({ name, description, input (Zod), execute, policy })`,
`defineAlert`, `definePlugin`, `kit.sync()`, `kit.serve()` (external harness server with
`/turn`, `/alerts/execute`, `/delivery`, `/events/*` behind the agent key), `@charla/agents/cloud`
fetch-only client (`sync`, `deploy`, `get`, `remove`, `detachChannel`, `completions`,
`verifyWebhook`). Zod instead of Effect Schema. `@charla/ai-sdk` with `createCharlaHandler({
signingSecret, waitUntil, onTurn, onReaction, onOptStatusChanged })`.
