# `alphaavatar host`

Run the Host management service, and manage the Host that runs for an application home.

```bash
alphaavatar host start [--bind ADDRESS] [--port PORT]
alphaavatar host status [--json]
alphaavatar host stop
alphaavatar host pair [--approve REQUEST | --reject REQUEST]
alphaavatar host devices [--revoke DEVICE]
alphaavatar stop
```

The management service is the Host's outermost layer. It runs without any Avatar configuration,
and stays while Avatars start, fail and stop: an App, and these commands, reach configuration,
credentials, Doctor and the Avatar through it. The Avatar itself runs inside the same Host
process, as [`alphaavatar start`](https://docs.alphaavatar.io/en/v0.7.0/cli/start.md) has always run it: one at a time, with its sessions,
execution processes and shared inference.

## Who starts what, and what stops it

| Command | Starts | Ctrl+C or SIGTERM stops |
| --- | --- | --- |
| `alphaavatar host start` | The Host, no Avatar until one is asked for | The Host, and its Avatar first |
| `alphaavatar start <config>`, a Host running | That Host's Avatar | That Avatar; the Host keeps running |
| `alphaavatar start <config>`, none running | A Host of its own, then its Avatar | Both; that Host also ends when its Avatar stops or fails |
| `alphaavatar stop` | — | The running Host's Avatar; the Host keeps running |
| `alphaavatar host stop` | — | The running Host, and its Avatar first |

- One Host runs per application home. A second `host start` refuses, naming the one running.
- A Host that `start` began behaves as `start` always has: it runs in the foreground, ends with its
  Avatar and answers with start's exit codes. To keep a Host for an App to configure and restart
  Avatars, run `alphaavatar host start` (for instance as the service unit) and start Avatars on
  it.
- Stopping an Avatar releases what its run owns: its sessions, execution processes and shared
  inference. The application home, saved configuration and Avatar workspaces stay as they are.
- [`alphaavatar dev`](https://docs.alphaavatar.io/en/v0.7.0/cli/dev.md) runs the runtime alone, without the management service.

## `host start`

Runs the management service in the foreground. It listens in two places:

- **A local socket**, in a private directory that `run/host.json` in the application home names.
  Whoever reaches it is the Host's own user: the CLI commands below use it.
- **A network listener**, `127.0.0.1:8091` by default. Anyone reaching it learns only who the Host
  is and how to pair; everything else needs a [paired](#pairing-devices) device's token.

`--bind` and `--port` override the settings below for this run; port `0` takes a free one.

| Exit code | Meaning |
| --- | --- |
| 0 | Stopped normally |
| 1 | Failed while running |
| 2 | Its settings are invalid, or it could not listen |
| 3 | A Host already runs for this application home |

### Settings

The `management` section of the application home's `settings/settings.yaml`, read before any
Avatar configuration:

```yaml
management:
  bind: 127.0.0.1        # The network listener's address
  port: 8091             # 0: a free port
  url: https://host.example:8091  # Where clients reach it, if not its listening address
  tls:                   # PEM files, for clients that reach the Host over a network
    certificate: /path/to/host.crt
    key: /path/to/host.key
  origins: []            # Web App origins a browser may call the API from
```

A `bind` other than loopback needs `tls`: device tokens and credentials cross that network. A TLS
proxy in front of a loopback bind serves as well. `url` is the address `host pair` and `/v1/host`
give clients, such as a proxy's or this machine's name; unset, it is the listening address, and
unknown when the Host listens on every address (`0.0.0.0`, `::`), which no client can connect to. A `start` whose Host cannot open the network
listener (the port in use) runs without it, the local socket still there; `host start` stops
instead.

## `host status`, `host stop` and `stop`

- `host status` shows the running Host: its version, home, network URL, fingerprint, its Avatar's
  state and, after a failure, the failure's stage and reason. `--json` prints what the API's
  `/v1/host/status` answers.
- `stop` stops the Avatar and waits until its run has released what it owns. With no Avatar
  running it says so and exits 1.
- `host stop` stops the Host and waits until it has released the application home.

These exit 1 when no Host runs for the home.

## Pairing devices

A device, such as the App on a phone, pairs once and then holds a token of its own:

1. On the Host's machine, `alphaavatar host pair` creates a one-time code and shows it with the
   Host's network URL and fingerprint. The code lasts 10 minutes; a new one replaces it.
2. The device sends the code with a name and a key of its own making. The terminal shows the
   request: the device's name, its fingerprint and the scopes it asks for.
3. Compare the fingerprint with the one the device shows, then approve or reject. Without a
   terminal, `host pair` prints the code and exits; decide with `--approve REQUEST` or
   `--reject REQUEST`.

Approving gives the device its token, which it fetches once with its key; the code is then used
up. Rejecting invalidates the code, as do ten wrong codes. Codes and undecided requests end with
the Host. Paired devices are kept in `settings/management.json`, each with its token's hash only,
until `alphaavatar host devices --revoke DEVICE`.

| Scope | Allows |
| --- | --- |
| `manage` | Configuration, credentials, Doctor, the Avatar, operations; the default |
| `pair` | Pairing codes, pairing decisions and the paired devices |

The Host's own lifecycle (`host stop`) stays with its local user.

## The management API

Version 1, JSON over HTTP, the same on the local socket and the network listener. Over the network,
send `Authorization: Bearer <token>`. A refusal answers
`{"error": {"code", "message", "details"}}`, with 400, 401, 403, 404, 409 or 422 as its code says:
`avatar_running`, `revision_conflict` and `operation_in_progress` are 409, for instance.

| Route | Scope | Does |
| --- | --- | --- |
| `GET /v1/host` | anyone | Who the Host is: ID, API and AlphaAvatar version, URL, TLS, fingerprint, whether pairing is open |
| `GET /v1/host/status` | manage | The Host, its build, its Avatar and the operations running |
| `GET /v1/avatar` | manage | The Avatar's state, its run (what it loaded, the revision of each file read, its failure), the runtime's status while it runs, and `restart_required` when a file it read has been saved since |
| `POST /v1/avatar/start`, `/v1/avatar/stop` | manage | Start (`target`, `overrides`) or stop the Avatar, as an operation; a start's operation names its `run`, and a stop given `run` stops that run only |
| `GET /v1/configs` | manage | Bundles and profiles with their revisions, and the default bundle |
| `GET`, `PUT /v1/configs/{bundles\|profiles}/{name}` | manage | A file as written, or saved over the `base_revision` it was read at |
| `POST /v1/configs/bundles` | manage | Create a bundle and its profiles, as `config init` does |
| `PUT /v1/configs/default` | manage | Choose the default bundle |
| `POST /v1/configs/check` | manage | `config check` of a configuration, as an operation |
| `GET`, `PATCH /v1/credentials` | manage | Where each credential comes from; store (`set`) or remove (`remove`) stored ones in one commit |
| `GET /v1/doctor/checks`, `POST /v1/doctor` | manage | Doctor's checks; run Doctor (`metrics`, `rounds`, `authorize`), as an operation |
| `GET /v1/operations`, `GET /v1/operations/{id}`, `POST .../cancel` | manage | Long operations: list, read (`?wait=` seconds for the next change), cancel |
| `POST /v1/pairing/codes`, `GET /v1/pairing` | pair | A new code; the current one and its requests |
| `POST /v1/pairing/requests`, `GET /v1/pairing/requests/{id}` | anyone | A device's request; its state, and its token once approved (`X-Device-Key`) |
| `POST /v1/pairing/requests/{id}/approve`, `.../reject` | pair | Decide a request |
| `GET /v1/devices`, `DELETE /v1/devices/{id}` | pair | The paired devices; revoke one |
| `POST /v1/host/stop` | the local user | Stop the Host |

- **Operations.** Starting or stopping the Avatar, a check and Doctor answer `202` with an
  operation: `queued`, `running`, then `succeeded`, `failed` or `canceled`. Canceling marks
  `cancel_requested` until the work settles. Its `phase` says where it is; its `result` holds the
  run, the check's answer or Doctor's report with the revision of each configuration file it read.
  A canceled Doctor keeps the report of what finished. An `Idempotency-Key` header returns the
  same operation for a repeated request. One Avatar start or stop, and one Doctor, at a time.
- **A configuration** is a bundle by its name or a file by its absolute path: a relative one is
  refused, as the Host would read it from its own directory. `alphaavatar start` makes a relative
  path absolute before it asks.
- **Revisions** are the SHA-256 of a file's bytes, line endings and all. An Avatar's run records
  the files its load read, as it read them; a check's and Doctor's result records them as they were
  before and after the command, `files` null and `files_changed` true when they changed
  meanwhile, as the command may have read either.
- **Saved is not running.** Saving a file checks only that it is a YAML mapping; whether it is
  valid is the check's answer, and a running Avatar keeps what it loaded until it starts again.
- **Credentials** are never answered: a name, where its value comes from (`environment`,
  `env_file` or `stored`, in that order, as loading reads them), and when the stored ones changed.
  A file that holds a credential's value (written in it under a key such as `api_key`, or one this
  Host stores or reads from its environment) is shown with it masked and cannot be saved through
  the API. A file that is not valid YAML is not shown, as where its credentials are cannot be told:
  reading it answers `config_not_yaml` (422) with where it fails and its revision, over which a
  replacement can still be saved. Doctor's consent to call services (`authorize`) is the person's, given in the App; no
  terminal asks.
- **A failure** says its stage, as start prints it, and for a configuration that did not load, the
  settings at fault and the next step, as `config check --json` does.
