# Enrollment and devices

> Create a self-hosted bot, mint its single-use enrollment token, enroll the pod, replace or revoke the device, and offboard: API calls, roles and audit events.

Canonical URL: https://docs.botyard.io/docs/self-hosted/enrollment

A self-hosted bot runs on a **device**: the `botyardd` pod in your cluster, identified by a key
pair it keeps on its persistent volume. A device joins a bot by redeeming an **enrollment token**.
This page covers that lifecycle, from creating the bot to revoking the device. For how a
self-hosted bot connects and what it needs, see the [Self-hosted runtime](/docs/self-hosted)
overview.

> [!NOTE]
> Self-hosted bots are enabled per organization by Botyard. Until your organization is enabled,
> creating a self-hosted bot and minting a token for one both fail with
> `422 Unsupported bot hosting combination`. Contact Botyard to request access.

## Who can do what

| Action                       | Permission       | Held by default                                           |
| ---------------------------- | ---------------- | --------------------------------------------------------- |
| Create a bot                 | `bot:bot.create` | Organization owners, and API keys with the **Owner** role |
| Mint an enrollment token     | `bot:bot.create` | Same as creating a bot                                    |
| Invalidate enrollment tokens | `bot:bot.create` | Same as creating a bot                                    |
| Revoke a device              | `bot:bot.update` | Organization owners, and API keys with the **Owner** role |
| List a bot's devices         | `bot:bot.read`   | Anyone who can see the bot                                |

These are permissions, not roles. The table shows who holds them through the built-in roles. An
explicit organization-wide grant of the permission also allows the action. Owning a bot does not:
a member who owns a bot still can't revoke its device.

Minting a token carries the same permission as creating a bot. Whoever redeems the token enrolls
their machine as that bot, so treat a token as a live credential.

To call the API with a key, create one under **Settings > API keys** and choose the **Owner** role.
Keys default to **Member**, which by default holds none of the write permissions above. See
[API authentication](/docs/api/authentication).

## 1. Create the bot

> [!WARNING]
> The app does not yet have a flow to create a self-hosted native bot. Create it through the API.
> Tracked as
> [#4872](https://app.botyard.io/orgs/botyard/workforces/platform-development/task/4872).

Call [`POST /v1/orgs/{org_id}/bots`](/docs/api/bots/create_bot_v1_orgs__org_id__bots_post) with
`hosting_type` `self_hosted` and `harness` `botyard_native`:

```bash
curl -X POST "https://api.botyard.io/v1/orgs/$ORG_ID/bots" \
  -H "Authorization: Bearer $BOTYARD_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "cluster-bot",
    "hosting_type": "self_hosted",
    "harness": "botyard_native",
    "config": { "bot_type": "native" }
  }'
```

The response includes the bot's `id` and `slug`. A self-hosted bot counts toward your plan's bot
limit like any other bot.

[`GET /v1/orgs/{org_id}/bots/hosting-options`](/docs/api/bots/get_bot_hosting_options_v1_orgs__org_id__bots_hosting_options_get)
lists the hosting combinations your organization may use. If `self_hosted` + `botyard_native` is
missing, your organization is not enabled yet.

Once the bot exists, its page in the app has a **Device** tab, where you mint tokens, watch the
device's status and revoke it.

## 2. Mint an enrollment token

An enrollment token is:

* **Single use.** Redeeming it registers one device, and it can't be used again.
* **Valid for 7 days.** Mint it right before you install.
* **Bound to one bot.** It can only complete that bot's enrollment.
* **Shown once.** Botyard stores only a hash. If you lose it, mint a new one.
* **One at a time.** Minting again invalidates the bot's previous unspent token immediately.

You can only mint while your organization is enabled for self-hosted bots.

### With the API (recommended for Kubernetes)

Call
[`POST /v1/orgs/{org_id}/bots/{bot_slug}/enrollment-tokens`](/docs/api/bot-devices/mint_enrollment_token_v1_orgs__org_id__bots__bot_slug__enrollment_tokens_post).
There is no request body. Pipe the `token` field from the response straight into the Kubernetes
Secret the chart reads, so the token never appears in a command line or the clipboard:

```bash
kubectl create namespace botyard   # if it doesn't exist yet
curl -fsS -X POST \
  "https://api.botyard.io/v1/orgs/$ORG_ID/bots/$BOT_SLUG/enrollment-tokens" \
  -H "Authorization: Bearer $BOTYARD_API_KEY" \
  | jq -j .token \
  | kubectl -n botyard create secret generic botyard-enrollment --from-file=token=/dev/stdin
```

The call returns `201`. The response also carries `enrollment_token_id`, `expires_at` (7 days
ahead), and `regenerated: true` when this call replaced an earlier unspent token. Avoid
`kubectl create secret … --from-literal=token=<token>`: it puts the token in your shell history.

### In the app

On **User menu** › **Settings** › **Bots** › *‹your bot›* › **Device**, click **Generate install command**. The app shows a command for
installing on a laptop:

```text
curl -fsSL https://get.botyard.io/install | sh -s -- --token <token>
```

> [!CAUTION]
> **Do not run this command for a Kubernetes install**
>
> Running it installs the laptop daemon on the machine you run it on and **spends the
> single-use token**. Your pod then can't enroll. Copy only the value after `--token` into the
> Secret. A Kubernetes-specific option is tracked as
> [#4871](https://app.botyard.io/orgs/botyard/workforces/platform-development/task/4871).

**Regenerate** under the command mints a new token and invalidates the one shown.

## 3. Enroll the pod

Install the chart with `enrollment.existingSecret` pointing at the Secret (the key defaults to
`token`, set by `enrollment.secretKey`). [Install on Kubernetes](/docs/self-hosted/install-kubernetes)
covers the chart in full.

The container's entrypoint enrolls non-interactively before it starts the daemon:

| `botyardd enroll` result | Meaning                                                                                                           | What happens                                                                                             |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| Exit `0`                 | Enrolled. Or Botyard confirmed this volume's key is already the bot's active device, and the token was not spent. | The daemon starts.                                                                                       |
| Exit `3`                 | The state directory is already bound to a device. The token is not presented, so it is not spent.                 | The daemon starts and reconnects. This is every restart after the first.                                 |
| Any other exit code      | Enrollment failed. For example, the token was spent, expired or invalidated.                                      | The container exits and Kubernetes restarts it. Mint a new token, update the Secret and restart the pod. |

On a restart, the logs say so explicitly. The exit code itself is not printed:

```text
refusing to enroll: this machine is already bound and --replace was not given
botyard-selfhosted: state directory already enrolled; the enrollment token was not used
```

The entrypoint removes the token from the environment before the daemon starts, so neither the
container's init process nor `botyardd` holds it. The token stays in the Secret, where it is inert
after first use. Because the pod spec still references the Secret, a shell you open with
`kubectl exec` **does** have `BOTYARD_ENROLLMENT_TOKEN` in its environment. Delete the token from
the Secret once the device is enrolled if you don't want it kept.

The device appears on **User menu** › **Settings** › **Bots** › *‹your bot›* › **Device** under the name in `enrollment.deviceLabel`, or the
pod name if that is unset.

### The volume is the device

The device's private key lives on the pod's persistent volume, under `/var/lib/botyard/state`. So:

* **Restarting or rescheduling the pod** keeps the device. No new token is needed.
* **Deleting the PVC** destroys the device's key. The pod can't reconnect as that device, and it
  needs a new enrollment (see below).
* `helm uninstall` keeps the PVC. Delete it deliberately.
* A bot has at most one active device, so the chart always runs one replica.

## 4. Add an LLM credential before the first chat

A self-hosted bot's model calls are brokered by Botyard, using LLM credentials stored in Botyard,
not on your cluster. A credential existing in your organization is not enough: bind one to the bot
before you chat with it.

1. Add the credential under **Credentials** > **LLM Providers**, if your organization doesn't have
   one yet. See [Provider credentials](/docs/provider-credentials).
2. Open **User menu** › **Settings** › **Bots** › *‹your bot›* › **General**. In the **LLM Provider** card, click **Add LLM provider**, pick the
   credential, then pick a model and click **Confirm**.
3. Click **Apply changes** in the bar at the bottom of the page, and wait for it to save.
   **Confirm** only stages the change: until you apply it, the bot has no credential bound.

Through the API, call
[`PUT /v1/orgs/{org_id}/bots/{bot_slug}/credentials`](/docs/api/credentials/assign_credentials_v1_orgs__org_id__bots__bot_slug__credentials_put)
with the credential in the `llm` scope:

```json
{
  "credentials": [
    { "credential_id": "<credential-id>", "scope": "llm", "ordinal": 0, "default_model": "<model-id>" }
  ],
  "scopes": ["llm"]
}
```

The bot's config still shows `provider: "botyard"` for its model. That is expected for native
bots: the real provider comes from the bound credential.

> [!WARNING]
> **Known issue: the bot can look ready without a credential**
>
> Without an LLM credential bound to the bot, its first turn fails with "No credential is configured for
> provider scope 'llm'". The app and the bot's `chat-readiness` endpoint can still report the bot
> as ready. Tracked as
> [#4877](https://app.botyard.io/orgs/botyard/workforces/platform-development/task/4877).

## Device status in the app

The bot's **Device** tab and the **Device** field in the bot's header show the device's state:

| State                  | Meaning                                                                       |
| ---------------------- | ----------------------------------------------------------------------------- |
| **Pending enrollment** | A token was minted in this browser session and no device has enrolled yet.    |
| **Enrollment expired** | No device has enrolled, and no live token was minted in this browser session. |
| **Never connected**    | The device is enrolled but has not connected yet. Check the pod is running.   |
| **Online**             | Seen in the last 5 minutes.                                                   |
| **Offline**            | Enrolled and authorized, but not seen recently. The bot itself is unaffected. |
| **Revoked**            | The device is denied on every request.                                        |

The app doesn't remember tokens across page loads. So a bot that has never had a device reads
**Enrollment expired** when you open it later, even if its token is still valid. If you minted the
token through the API, this is what you see until the pod enrolls.

The Device tab also shows the key custody the device reported (**Software file — reported by
device** for the Kubernetes image) and, once connected, the local host policy and runtime version
it reported.

> [!WARNING]
> **Known issue: bot lists show Running before enrollment**
>
> The bot list, the **Overview** page and the launchpad show the bot as **Running** and healthy
> from the moment it is created, even before any device enrolls. Use **User menu** › **Settings** › **Bots** › *‹your bot›* › **Device** for
> the real state. Tracked as
> [#4822](https://app.botyard.io/orgs/botyard/workforces/platform-development/task/4822).

To read the device registry through the API, call
[`GET /v1/orgs/{org_id}/bots/{bot_slug}/devices`](/docs/api/bot-devices/list_bot_devices_v1_orgs__org_id__bots__bot_slug__devices_get).
It lists every device ever enrolled to the bot, newest first, revoked ones included.

## Replace a device

A bot can't take a second active device. Redeeming a token while one is active fails with "This
bot already has an active device". Replacing a device is always revoke, then mint, then enroll. Do
it in that order: revoking a device also invalidates the bot's unspent token, so a token minted
before the revoke stops working.

1. Revoke the current device (see below).
2. Mint a new enrollment token and update the Secret.
3. Delete the PVC and the pod. The StatefulSet recreates both, and the new pod generates a new key
   and enrolls with the new token.

Keys are never reused, including after revocation, which is why the old volume can't be brought
back.

To move a pod to a **different bot**, follow the same steps with a token minted for the other bot.
A restart with a different bot's token in the Secret does not move it: an already-bound volume
keeps its binding.

## Revoke a device

On **User menu** › **Settings** › **Bots** › *‹your bot›* › **Device**, click **Revoke**, then **Revoke device**. Through the API, call
[`POST /v1/orgs/{org_id}/bots/{bot_slug}/devices/revoke`](/docs/api/bot-devices/revoke_bot_devices_v1_orgs__org_id__bots__bot_slug__devices_revoke_post)
with up to 100 device IDs:

```bash
curl -X POST "https://api.botyard.io/v1/orgs/$ORG_ID/bots/$BOT_SLUG/devices/revoke" \
  -H "Authorization: Bearer $BOTYARD_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "device_ids": ["<device-id>"] }'
```

Revoking a device:

* **denies it immediately.** Every later connection attempt from it is refused;
* **invalidates the bot's unspent enrollment token**, so no machine can enroll as the bot again
  without a new mint;
* **does not touch the bot.** Its conversations, memory and history stay, and you can enroll a new
  device at any time;
* **does not uninstall anything.** The pod keeps running, but can't connect. Uninstall the chart
  and delete the PVC yourself.

Revoking an already-revoked device changes nothing but is still recorded in the audit log. The
response reports `revoked_count` and `invalidated_token_count`.

## Invalidate enrollment tokens

To kill outstanding tokens without minting new ones, call
[`POST /v1/orgs/{org_id}/enrollment-tokens/invalidate`](/docs/api/bot-devices/invalidate_enrollment_tokens_v1_orgs__org_id__enrollment_tokens_invalidate_post)
with up to 100 bot IDs (the bot `id`, not its slug):

```bash
curl -X POST "https://api.botyard.io/v1/orgs/$ORG_ID/enrollment-tokens/invalidate" \
  -H "Authorization: Bearer $BOTYARD_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "bot_ids": ["<bot-id>", "<bot-id>"] }'
```

* It reaches bots that never enrolled a device, which a revoke can't.
* Enrolled devices are not affected. Revoke them separately.
* It is all-or-nothing: if any ID is not a bot in your organization, nothing is invalidated and the
  call returns `404`. Duplicate IDs are collapsed.
* It works whether or not your organization is still enabled for self-hosted bots.

## Offboard

To take self-hosted bots out of service completely:

1. Invalidate the enrollment tokens of every self-hosted bot, so no new device can enroll.
2. Revoke every active device, so no running pod can connect.
3. Uninstall the chart and delete the PVCs in your cluster.

If your organization's self-hosted access is being withdrawn, Botyard removes your organization from
the enablement list. After that, new self-hosted bots and new tokens are refused, but existing
devices and unspent tokens are not affected. Do steps 1 and 2 to cut those off.

## Audit events

Every step above is recorded in your organization's [audit log](/docs/audit-logs), under the
`bot_device` domain:

| Event type                                | Recorded when                                                                  | Severity |
| ----------------------------------------- | ------------------------------------------------------------------------------ | -------- |
| `bot_device.enrollment_token.minted`      | A token is minted or regenerated.                                              | Info     |
| `bot_device.enrolled`                     | A token is redeemed and a device registered.                                   | Info     |
| `bot_device.revoked`                      | A device revoke is requested, including a repeat.                              | Info     |
| `bot_device.enrollment_token.invalidated` | Tokens are invalidated, one event per bot, including bots that had none live.  | Info     |
| `bot_device.enrollment_token.replayed`    | Someone presented a token that was already spent, invalidated or expired.      | Warning  |
| `bot_device.assertion.denied`             | A device's connection attempt was refused, for example because it was revoked. | Warning  |

A **replayed** event is either someone re-running an install with an old token, or someone else
holding the token. Botyard can't tell which, so it records the attempt for you to judge.
