# The Ampbase API

Everything the dashboard does to your channels, configs, rollouts and agents goes through one API, and an API token calls the same methods. This page covers how to call it, which methods a token can reach, how errors, limits and pages behave, and where the schema lives.

For minting and managing the tokens themselves, see [API tokens](https://ampbase.io/docs/api-tokens.md).

## Calling the API

The API speaks [Connect](https://connectrpc.com) over HTTPS. Every method is a `POST` to its own path, with a JSON body:

```
https://ampbase.io/ampbase.api.v1.<Service>/<Method>
```

```bash
curl https://ampbase.io/ampbase.api.v1.ConfigService/ListConfigs \
  -H "Authorization: Bearer $AMPBASE_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Ampbase-Run: ci-4812" \
  -d '{"channel_id": "clickhouse"}'
```

A Connect client generated from the schema (see [The schema](#the-schema)) works too, over JSON or binary protobuf.

**Name a channel by its slug.** Wherever a request names a channel, `channel_id` takes the channel's slug, the one in its agents' endpoint (`clickhouse` in `wss://acme.ampbase.io/channels/clickhouse/v1/opamp`), or its id. See [Channels by slug](https://ampbase.io/docs/ids.md#channels-by-slug).

**JSON is `snake_case`.** Every response names its fields as the schema does: `org_id`, `next_page_token`, `version_ulid`. Requests may use either `snake_case` or `camelCase`. Ids have a text form of their own, described on [IDs in the API](https://ampbase.io/docs/ids.md).

**JSON answers omit zero-valued fields.** A field at its zero value (`0`, `false`, an empty string or list) is left out of the response, so treat a missing field as that zero value.

## Authentication

Send an API token as a bearer token on every call:

```
Authorization: Bearer amp_live_...
```

A token acts in the one org it was minted in, with the role it was minted at, and only in the channels it names, if it names any. A call outside any of those is refused with `permission_denied`.

**A call with a token may leave `org_id` out.** Ampbase fills it in with the token's org. A call that does send `org_id` must name the token's org, or it is refused with `permission_denied`.

A missing, malformed, expired or revoked token is refused with `unauthenticated`, as HTTP 401.

### The `Ampbase-Run` header

Each call may also carry your own label for the task that is acting:

```
Ampbase-Run: <1 to 128 bytes of A-Z a-z 0-9 . _ : / ->
```

Use it for whatever names the work: a CI run id, a coding-agent session id, a ticket number. Ampbase records it, beside the token and its owner, on every change the call makes and on every audit-log entry the call writes, so the audit log can show which run made a change. It is a label, not a credential: it is not checked beyond its shape and need not be unique. A call without it records no run. A value outside that shape is refused with `invalid_argument`.

## Methods a token can call

A token can call the methods below. The role column is the least role a token needs for the call. A token is minted at Viewer, Editor or Admin, and each can do everything the roles below it can. A method missing from these tables is not open to tokens: its call is refused with `permission_denied`, however the token was minted.

### AgentKeyService

| Method | Least role | What it does |
|---|---|---|
| `CreateAgentKey` | Admin | Mint an agent key for a channel. |
| `ListAgentKeys` | Viewer | List a channel's agent keys. |
| `RevokeAgentKey` | Admin | Revoke an agent key. |

### AgentService

| Method | Least role | What it does |
|---|---|---|
| `ListAgents` | Viewer | List a channel's agents, filtered by status if you ask. |
| `GetAgent` | Viewer | Read one agent. |
| `GetAgentFlagTrace` | Viewer | Step through how a channel's rules evaluated for one agent. |
| `GetAgentComponentRequirements` | Viewer | What the agent's assigned config needs its build to contain. |
| `DeleteAgent` | Admin | Delete an offline agent's record. A live agent is refused with `failed_precondition`. |

**`last_seen_at` can trail a healthy host's check-ins by up to 5 minutes;** `status` says whether a host is checking in. This holds wherever an agent is returned, `ListAgents` and `GetAgent` alike.

### AuditService

| Method | Least role | What it does |
|---|---|---|
| `ListAuditEvents` | Admin | Read the org's audit log. |

### ChannelService

| Method | Least role | What it does |
|---|---|---|
| `ListChannels` | Viewer | List the org's channels the token can see. |
| `CreateChannel` | Admin | Create a channel. |

### CodingUsageService

| Method | Least role | What it does |
|---|---|---|
| `GetChannelUsageSummary` | Viewer | A channel's coding-agent spend and adoption over a time range. |
| `GetChannelGovernance` | Viewer | A channel's enrolled workstations and the policy they receive. |

### ConfigService

| Method | Least role | What it does |
|---|---|---|
| `ListConfigs` | Viewer | List a channel's configs. |
| `GetConfig` | Viewer | Read a config and its current version. |
| `ListConfigVersions` | Viewer | List a config's versions, newest first. |
| `GetConfigVersion` | Viewer | Read one version's content. |
| `GetComposedConfig` | Viewer | Read a version as its agent runs it: its files and, for an agent that merges them, the one document they merge to. |
| `PreviewConfigVersion` | Viewer | Diff proposed changes against your own latest version, or against `parent` when you send one, without saving. The answer carries `files` and, as the files' sums, `added`, `deleted` and `hunks`. |
| `CompareVersions` | Viewer | Diff any two saved versions in a channel, file by file. |
| `GetConfigVersionCoverage` | Viewer | What a version needs of an agent's build, and how much of the fleet can run it. |
| `GetComponentCoverage` | Viewer | How much of the fleet can run what one routing target resolves to. |
| `GetChannelBuildRequirements` | Viewer | What a build must contain to run everything the channel currently serves. |
| `GetDefaultRoute` | Viewer | The config the channel serves by default, and who deployed it. |
| `GetMutes` | Viewer | Whether the versions named are muted, and why. |
| `ListCueMoves` | Viewer | A config's broadcast history, newest first: each change to what it serves, who made it, and how. |
| `ListTracks` | Viewer | List a channel's tracks. |
| `GetTrack` | Viewer | Read one track, with the head of everything it has saved. |
| `CreateConfig` | Editor | Create a config with its first version. On a channel with no default, making it the default needs Admin; an Editor's create leaves the default unset and says so in `first_default`. |
| `CreateConfigVersion` | Editor | Save a new version of a config. |
| `DeriveObserveVariant` | Editor | Save the observe-only variant of an enforcing version as a new version of its config. |
| `UpdateConfigMetadata` | Editor | Rename a config or change its description. |
| `DeleteConfig` | Editor | Delete a config. Refused while a rollout moves it, a rule names it, a soundcheck serves it, or an open or ready track has saved a version of it. Once deleted it is not in `ListConfigs`, and the methods that act on a config answer `not_found` for it; its versions stay readable by id. |
| `CreatePolicy` | Editor | Create a coding-agent policy. On a channel with no default, making it the default needs Admin; an Editor's create leaves the default unset and says so in `first_default`. |
| `CreatePolicyVersion` | Editor | Save a new version of a coding-agent policy. |
| `DeployConfig` | Admin | Deploy a config version as the channel's default. |
| `Broadcast` | Admin | Broadcast now the tracks you name, or every ready one. Each config they change moves to the tracks' newest version, all of them or none. It changes no rule. |
| `DeployPolicy` | Admin | Deploy a coding-agent policy version. |
| `MuteVersion` | Admin | Mute a version, so nothing can ship it until the mute is cleared. |
| `ClearMute` | Admin | Clear a version's mute. |
| `OpenTrack` | Editor | Open a track: a lane of work whose saves serve nothing until it ships. |
| `SetTrackReady` | Editor | Queue a track for the next rollout, or take it out. |
| `SetSoundcheck` | Editor | Serve a track's heads to a few hosts you name, ahead of a rollout. An enforcing soundcheck needs Admin. |
| `CloseTrack` | Editor | Close a track without shipping it. |

### CredentialService

| Method | Least role | What it does |
|---|---|---|
| `GetChannelCredentialSettings` | Viewer | A channel's credential mode. |
| `SetChannelCredentialMode` | Admin | Switch a channel between shared and managed credentials. |
| `SetChannelEnrollment` | Admin | Open or pause new enrollments in a channel. |
| `SetChannelEnrollmentModes` | Admin | Choose which supervisor modes may connect to a channel. |
| `RotateInstanceCredential` | Admin | Re-issue one agent's credential without disconnecting it. |
| `RevokeInstanceCredential` | Admin | Cut off one agent's credential. It may enroll again. |
| `RotateChannelCredentials` | Admin | Cut off every agent credential in a channel at once. Agents re-enroll. |
| `BanInstance` | Admin | Cut off an agent and refuse its enrollment from then on. |
| `UnbanInstance` | Admin | Lift a ban, so the agent may enroll again. |
| `RotateOrgSigningKey` | Admin | Rotate the org's signing key. Every agent credential and every API token in the org stops working at once. |

### IntelligenceService

| Method | Least role | What it does |
|---|---|---|
| `GetIntelligenceExport` | Viewer | A channel's intelligence export settings. |
| `SetIntelligenceExport` | Admin | Turn a channel's intelligence export on or off. |
| `RunCardinalityAnalysis` | Admin | Run a cardinality analysis and return its findings. |
| `RunCostAttribution` | Admin | Run a cost analysis and return its findings. |
| `RunSamplingAnalysis` | Admin | Run a sampling analysis and return its recommendations. |

### RolloutService

| Method | Least role | What it does |
|---|---|---|
| `PreviewRollout` | Viewer | The stages a rollout would run, without starting it. |
| `GetRollout` | Viewer | Read a rollout's state. |
| `ListRollouts` | Viewer | List a channel's rollouts. |
| `ListRolloutAgents` | Viewer | The agents in a rollout and the stage each is at. |
| `ListRolloutActivity` | Viewer | A rollout's history, oldest first. |
| `StartRollout` | Admin | Start a rollout. |
| `AdvanceRollout` | Admin | Advance a rollout to its next stage. |
| `PauseRollout` | Admin | Pause a rollout. |
| `ResumeRollout` | Admin | Resume a paused rollout. |
| `RollbackRollout` | Admin | Roll a rollout back. |
| `MuteRollout` | Admin | Mute every version a rolled-back rollout shipped. |

### RoutingService

| Method | Least role | What it does |
|---|---|---|
| `ListRules` | Viewer | A channel's routing rules in order, with the revision `SaveRules` needs. |
| `GetRule` | Viewer | Read one rule. |
| `ListRuleRolloutsByType` | Viewer | How many agents of each type each rule serves. |
| `GetRuleComponentRollup` | Viewer | The agents a rule targets, grouped by whether their builds can run it. |
| `SaveRules` | Admin | Replace a channel's rules, against the revision you read. |

## Pages

Every list a token can call returns its items a page at a time, except `RoutingService`'s `ListRules` and `ListRuleRolloutsByType`. A channel's rules are one set you read and save back whole, so those two answer the whole set at once.

Paged lists take `page_size` and `page_token` and answer `next_page_token`:

- `page_size` is the most items to return, at most 200. Zero, or leaving it out, asks for the server's default.
- Pass the `next_page_token` you were given, unchanged, as `page_token` to read the next page. An empty `next_page_token` means you have read the last page.
- A page can hold fewer items than you asked for and still be followed by another, so read until the token is empty.
- A `page_token` the list did not give you is refused with `invalid_argument`.

```bash
CHANNEL=clickhouse
token=""
while :; do
  page=$(curl -s https://ampbase.io/ampbase.api.v1.ConfigService/ListConfigs \
    -H "Authorization: Bearer $AMPBASE_TOKEN" \
    -H "Content-Type: application/json" \
    -d "{\"channel_id\": \"$CHANNEL\", \"page_token\": \"$token\"}")
  echo "$page" | jq -r '.configs[]?.name'
  token=$(echo "$page" | jq -r '.next_page_token // ""')
  [ -z "$token" ] && break
done
```

## Errors

A refusal is a Connect error: an HTTP status, and a JSON body with a `code`, a `message` written for a person, and sometimes `details`:

```json
{
  "code": "failed_precondition",
  "message": "a rollout holds this channel",
  "details": [{
    "type": "google.rpc.ErrorInfo",
    "value": "ChVST0xMT1VUX0hPTERTX0NIQU5ORUwSCmFtcGJhc2UuaW8a...",
    "debug": {
      "reason": "ROLLOUT_HOLDS_CHANNEL",
      "domain": "ampbase.io",
      "metadata": {"rollout_id": "rol-01JBQ0Z5M6V3T8K2R4N7P9W1XA"}
    }
  }]
}
```

**Switch on the reason, not the message.** A refusal your code is expected to act on carries a `google.rpc.ErrorInfo` detail in the domain `ampbase.io`, with a reason from the table below and the metadata it names. `debug` is the detail in JSON; `value` is the same detail as base64 protobuf, which a generated client decodes for you. Messages are written for people and may change. Reasons and their metadata keys do not.

| Reason | Metadata | When |
|---|---|---|
| `ALREADY_ROTATED` | `successor` | A token is rotated that already has a live successor. Revoke the successor, or use it. |
| `ROLLOUT_HOLDS_CHANNEL` | `rollout_id` | A deploy, or a second `StartRollout`, while a rollout holds the channel. `rollout_id` names it when known. |
| `ROLLOUT_HOLDS_TARGET` | `rollout_id` | Deleting a config that a running rollout is moving: its target, or one of the versions its rules move from or to. Roll the rollout back or let it finish first. |
| `RULE_HOLDS_CONFIG` | `rules` | Deleting a config that a rule names, in any variant, enabled or not, the channel default among them. `rules` is the rule keys, comma-separated in rule order, the default as `channel-default`. Point each at another config, or deploy another config for the default, then delete. |
| `SOUNDCHECK_HOLDS_CONFIG` | `tracks` | Deleting a config that a soundcheck is serving to hosts. `tracks` is the soundchecked tracks, comma-separated. Clear the soundcheck first. |
| `TRACK_HOLDS_CONFIG` | `tracks` | Deleting a config that an open or ready track has saved a version of. `tracks` is every such track, comma-separated. Ship each track or close it, then delete. A delete held for more than one reason is refused for the first of a running rollout, a rule, a soundcheck, then a track. |
| `RULE_SET_FROZEN` | `rollout_id` | A change to a channel's rules while a rollout has them frozen. |
| `SOUNDCHECK_CAP` | `cap` | `SetSoundcheck` names more hosts than `cap` allows. A larger share of the fleet is a rollout. |
| `SOUNDCHECK_HOST_OUTSIDE_TRACK` | `track`, `configs`, `host` | `SetSoundcheck` names `host`, which runs none of the configs the track has changed. `configs` is a comma-separated list. Soundcheck the track on hosts that run one of them. |
| `SOUNDCHECK_HOST_TAKEN` | `hosts`, `tracks` | `SetSoundcheck` names hosts that another track's soundcheck holds. `hosts` lists each such host once, in the order the request named them, and `tracks` names the track holding each; the two lists are paired by position. Nothing changes on the refusal. Pick other hosts, or send `take_over` to move them into this track's soundcheck. |
| `TRACK_BASE_MOVED` | `track`, `config`, `base`, `broadcast` | `StartRollout`, `PreviewRollout`, `Broadcast` or `DeployConfig` ships a track whose `base` is no longer the `broadcast` of `config`, the config it changes, and no other track in the same call leads to it. Save the track's next version with `parent` set to `broadcast`, then ship it again. |
| `TRACKS_OVERLAP` | `tracks`, `config`, `rebase_onto` | Two tracks shipped together change `config`, and neither's head descends from the other's. The tracks are taken in queue order: ready ones by when they were marked ready, then open ones, ties by id. The track to move is the one rebased onto the other, its base a version the other saved, which the other has since moved past; otherwise it is the later of the two, which covers two tracks rebased onto one shared version; `tracks` names it first, then the one it conflicts with. Save its next version with `parent` set to `rebase_onto`, the head it must build on. |
| `TRACK_CONFIG_DELETED` | `track`, `config` | `StartRollout`, `PreviewRollout`, `Broadcast` or `DeployConfig` names a track that changes `config`, which has since been deleted, or takes the ready tracks with `include_ready` when every one of them is such a track. The track can never ship. Close it with `CloseTrack`; to keep its changes to other configs, copy them from the track's versions into a new track. |
| `TRACKS_ALREADY_BROADCAST` | `tracks` | `StartRollout` or `PreviewRollout` of tracks whose every change is already broadcast: a call moved the broadcasts and did not mark the tracks shipped, so a rollout has nothing to stage. `Broadcast` the tracks to mark them shipped. `tracks` is the tracks named, comma-separated. |
| `ROLLOUT_HAS_BROADCAST` | `rollout_id` | `RollbackRollout` on a rollout whose promotion has already moved the broadcast. The rollout finishes; to go back, Broadcast now the previous version. |
| `FILE_CHANGED` | `config`, `name`, `parent` | A save changes a file that is no longer the one the change was made from: `replaces` does not match the file `name` of `config` in the version the save builds on. `name` is left off for a configuration's one unnamed file. Read the file at version `parent`, apply your change to it, and save again. |
| `FILE_REFUSED` | `rule`, `name` | A save's files break a rule of the configuration's agent type, or a size limit. `rule` is one of `NAME_NOT_ACCEPTED`, `NAME_MISSING`, `UNNAMED_NOT_ACCEPTED`, `NAME_NOT_PLAIN_FILENAME`, `NAME_WRONG_EXTENSION`, `FILE_TOO_LARGE` and `CONFIG_TOO_LARGE`; `name` is the file, when the rule is about one. |
| `TRACK_HEAD_MOVED` | `track`, `head` | A save names a `track_head` that is no longer the track's head for that configuration, or moves the track onto another `parent` without naming one. Read version `head`, apply your change to it, and save again with `track_head` set to `head`. |

A refusal without a reason is a Connect code and a message. The codes you will see most:

| Code | HTTP | Means |
|---|---|---|
| `invalid_argument` | 400 | A field failed validation. The message names it. |
| `failed_precondition` | 400 | The request is valid but the state does not allow it now. |
| `unauthenticated` | 401 | The token is missing, malformed, expired or revoked. |
| `permission_denied` | 403 | The token's org, role or channels do not cover the call. |
| `not_found` | 404 | The id names nothing the token can see. |
| `aborted` | 409 | A record changed between your read and this write. Re-read and try again. |
| `resource_exhausted` | 429 | The token is over its rate limit. See below. |
| `unavailable` | 503 | Try again shortly, with backoff. |

## Rate limits

Each token has its own allowance, so an org splits its traffic across workloads by minting a token for each:

| Plan | Requests per minute, per token |
|---|---|
| Trial, Starter | 120 |
| Professional | 600 |
| Business, Scale, Enterprise | 3,000 |

Every call a token makes is charged, including one refused for its permissions or its fields. Every answer to a token call carries three headers:

| Header | Value |
|---|---|
| `X-RateLimit-Limit` | The token's requests per minute. |
| `X-RateLimit-Remaining` | Requests left in the current allowance. |
| `X-RateLimit-Reset` | When the allowance is whole again, as a Unix time in seconds. |

Over the limit, a call is refused with `resource_exhausted` and a `Retry-After` header giving the seconds to wait. The allowance refills continuously rather than once a minute, so waiting `Retry-After` seconds frees one request, not a whole minute's.

Ampbase serves the API from several machines, and each counts a token's calls on its own. A client whose calls spread across them can briefly go past the limit before each one refuses it. Plan for the limit in the table, not for the overshoot.

## Shipping tracks

`StartRollout`, `PreviewRollout`, `DeployConfig` and `Broadcast` take `tracks`, the tracks to ship, and `include_ready`, which adds every ready track that changes the same config. On the first three, leave the version unset and the call ships the newest head of the tracks; set it and it must be that version. `Broadcast` takes no version: it always ships the newest head of its tracks.

- **Tracks on one config combine** when their heads form one chain: each track saved on top of the one before it. Two that diverge are refused with `TRACKS_OVERLAP`.
- **Each track must start from the current broadcast**, or from another track shipped in the same call. A track that does not is refused with `TRACK_BASE_MOVED`, unless its head is already the broadcast: shipping that track again moves nothing and marks it shipped. With `include_ready`, a ready track whose base has moved is not refused: it goes back to open, and `GetTrack` shows `handed_back` with the version to save against.
- **A version deployed by id ships its track.** When the version is the head of an open or ready track, the call ships that track and checks it as above. A version that is no track's head deploys as it is, which is how you broadcast an older version again. A track that changes more than one config is not shipped this way: its head deploys as a version no track holds, and the track stays open.
- **A track ships whole or not at all.** A track that has changed two configs ships both, and a call that names only tracks ships every config they change. If one of them cannot ship, a named track refuses the call and a ready one taken by `include_ready` goes back to open; the refusal names the config. `include_ready` adds a ready track only when every config it changes is already in the call.
- **A track on a deleted config can never ship.** A config with an open or ready track on it cannot be deleted, but a save landing just as the delete does can leave one. Named, such a track refuses the call with `TRACK_CONFIG_DELETED`; taken by `include_ready`, it goes back to open with `handed_back` reason `TRACK_HAND_BACK_REASON_CONFIG_DELETED` and the rest of the call ships. Close it, and copy its other changes into a new track.

`PreviewRollout` refuses a set of tracks in the same words `StartRollout` would, and hands nothing back.

A config whose broadcast is already the version its tracks ship is not one of a rollout's `targets`: `PreviewRollout` lists it under `already_broadcast`, and the rollout marks its tracks shipped when it promotes. When that is every config the tracks change, the rollout is refused with `TRACKS_ALREADY_BROADCAST`.

- **Confirms are per config.** A call that ships several configs takes `confirms`, one entry for each config that asks for a confirm, naming it by `config_id`. `PreviewRollout` lists what each asks for under `targets`. A `StartRollout` of one config may use `confirms` or its own confirm fields, not both; one of several must use `confirms`. An entry for a config the call does not ship is refused. When a call of several is refused for one of them, the message names that config.
- **`Broadcast` changes no rule.** It moves the broadcast of each config its tracks change, and an agent gets the new version only through a rule that follows that config. To make a config the channel's default, use `DeployConfig`.

## Retries

**A read is always safe to repeat.** For a write, the API is built so that repeating one after a lost answer cannot do the work twice:

- **Compare-and-swap writes** take the revision you read, and a stale one is refused rather than overwriting someone else's change. `SaveRules` takes the rule set's `revision` from `ListRules`, and a stale one is refused with `failed_precondition`. Re-read, then decide again.
- **`StartRollout` takes a `request_id`** of your choosing. A repeat with the same id answers with the rollout the first call started, rather than starting a second. Use one id per rollout you mean to start.
- **A `Broadcast`, `DeployConfig` or `DeployPolicy` that did not finish answers `unavailable` and is finished by repeating it.** The repeat moves only what has not moved yet, marks the tracks shipped and records the deploy.
- **A `Broadcast`, `DeployConfig` or `DeployPolicy` refused because another deploy to the same target is running answers `unavailable`.** It moved nothing; the same call repeated shortly starts once that deploy ends.
- **The rest are harmless to repeat.** `OpenTrack` repeated opens a second track, which you can close.

When a refusal names a rollout, the answer also carries an `Ampbase-Rollout-Id` header with the rollout's id, so you can tell whether it is the one you started.

Retry `unavailable` with exponential backoff. Retry `resource_exhausted` after its `Retry-After`. Do not retry the other codes unchanged: the same request will be refused the same way.

## The schema

The API's protobuf schema is the source of truth for every message and field. It is published on the Buf Schema Registry as [`buf.build/ampbase/api`](https://buf.build/ampbase/api).

- **Generated clients.** Any Connect code generator works against the schema, in any language it supports.
- **Fields are named as the schema names them.** JSON uses those names, in `snake_case`, and ids take the forms on [IDs in the API](https://ampbase.io/docs/ids.md).

## Changes

Version 1 of the API, `ampbase.api.v1`, only grows. A field, value, message or method may be added. None is removed or renumbered. Retiring something starts with a deprecation, recorded here, and the deprecated item keeps working.

- **Webhook event type `CONFIG_ROLLEDBACK`** is deprecated. It was never sent, so a webhook subscribed to it receives nothing. It is no longer offered when you create a webhook, and a request that names it is still accepted.
