# Your own Isolink relay

The public version of this guide is at <https://isolink.app/relay.html>.

A relay server lets Isolink reach you over the internet when nobody is nearby. You run it
yourself, for example on a home PC or a small server, and reach it through your router's
dynamic DNS name (such as `myrouter.tplinkdns.com`).

- **Your devices stay connected to it.** Contacts reach you through it from anywhere. Isolink
  still tries Wi-Fi and Bluetooth first. The relay is only used when no nearby route works,
  and that relay link is dropped as soon as a nearby one comes back.
- **It keeps sealed messages while you're offline,** for up to 7 days, and hands them over
  when you reconnect.
- **One relay can serve a whole family.** Each person joins with their own invite. Everything
  that passes through is end-to-end encrypted between the people talking, so members can't
  read each other's messages and neither can the relay. The relay does see which devices talk
  to each other, when, and how much.
- **Contacts don't need a relay of their own.** Once you've met a contact nearby, their app
  knows your relay. It connects to your relay as a guest to reach you. A guest can only reach
  members or leave sealed mail for them; it can't receive anything through the relay. You can
  turn guests off, or allow only the people you choose (see [Settings](#settings)).

## Set it up

You need a machine that stays on, plus one forwarded TCP port on your router. The examples use
port 8443.

### Linux

```sh
curl -fsSL https://isolink.app/relay/install.sh | sudo sh   # binary, system user, systemd unit
isolink-relay setup     # a few questions, then it starts the service and makes your first invite
```

`setup` asks for your dynamic DNS name and port, a name and a line about the relay, and who
may use it as a guest. Setting up the certificate is optional: skip it and the relay makes a
self-signed one, or let it guide you to Let's Encrypt, your own files or a proxy. Change it
later with `isolink-relay certs`.
It runs the same code as `init`, then offers the first invite as a QR code. That invite makes
you an owner. Run `setup` again at any time to change the answers: it keeps the certificate
when the address stays the same, so invites already out keep working. `init` takes the same
answers as flags, for scripts:

```sh
isolink-relay init --url https://myrouter.tplinkdns.com:8443 --name "Our house"   # also starts it
isolink-relay invite --admin --name "Kyle"   # prints a QR code and a code to paste
```

`isolink-relay` with no command prints the help, grouped as setup, people, access, bots and
maintenance. Under it is one line on how the relay is doing: running or not, its address,
members and devices online. Before it is set up, the line says `Not set up yet. Run:
isolink-relay setup`. It never starts the relay: the service runs `isolink-relay serve`.

The installer checks the download against the SHA-256 in the update feed. To install by hand,
unpack `isolink-relay-<version>-linux-x86_64.tar.gz` and run `sudo ./install.sh` from it.
The `isolink-relay` command runs the binary (in `/usr/local/lib/isolink-relay/bin`) as the
`isolink-relay` user on `/var/lib/isolink-relay`, asking for sudo when it needs to.

A release keeps the relay in `bin/` and the engine that runs cards' scripts (QuickJS) in `lib/`
beside it: move them together. Without `lib/`, the relay still runs, but bots' cards with scripts
don't. `isolink-relay --check-engine` says whether the engine runs. Updates put both in place;
on Windows, a relay installed before releases carried the engine needs the installer run once
more to get it.

### Windows

In an **administrator** PowerShell:

```powershell
irm https://isolink.app/relay/install.ps1 | iex   # Program Files, Windows service, firewall, PATH
isolink-relay setup                               # starts the service too
```

To install by hand, unzip `isolink-relay-<version>-windows-x64.zip` somewhere it can stay and
run `.\isolink-relay-service.exe install` (WinSW) from it. The relay keeps its data in
`%ProgramData%\IsolinkRelay`. Logs are next to the service executable.

### Your own service manager

The install scripts set up systemd or WinSW for you. Anything else, such as a container, must run `isolink-relay serve`: the bare command only prints the
help. Give a container a restart policy, such as `--restart unless-stopped`, so a restart
from the app or `isolink-relay restart` brings it back.

## Join from the app

Go to **You → Settings → Relays**, then either **Scan the relay invite** or **Paste the relay
invite**. Each invite works once and expires after 3 days (change this with `--days`). One
invite covers one person: all their linked devices join with it. **Scan a code**, at the top
of the You tab, reads invites too, along with every other Isolink code.

An invite is also a link to the relay's own join page, `https://…/join/<invite>`. Sharing an
invite from the app with **Other apps**, or copying the link the admin page shows, sends
that. Opening it shows the relay's name and picture, and **Open in Isolink**, which opens the
app on Android, iPhone, iPad and Mac to join, or the code to scan and how to get the app.
Once the invite is used or runs out, the page says so. The app also takes the link itself:
scanned, pasted under **Paste an invite**, or sent in a chat.

**You → Settings → Relays** lists every relay you've joined, with its picture, whether you
are connected and your role. Tap one for its name, picture and description, and how long it
has been up. Below are the greeting, how many members
and devices it has, what it holds for you, and **About this relay**: who runs it, its
version, who may be a guest, how long it keeps messages, your space, its certificate pin and
your backup. Then **News**, with a switch to show it in Chats, the bots, the card library and
**Leave this relay**. The relay's forums are in the **Forums** tab.

## Admins manage from the app

What a member may do on the relay is a set of **permissions**, which they get through **roles**
or one by one. There are five areas:

| Area | Permissions |
| --- | --- |
| People | `members.view`, `members.remove`, `members.roles` (give roles and permissions), `members.devices` (sign a device out), `invites.make`, `invites.cancel`, `join.review`, `guests.view`, `guests.manage` |
| Content | `news.post`, `news.moderate`, `forums.make`, `forums.moderate`, `cards.moderate`, `cards.templates`, `reports.handle` |
| Relay | `settings.view`, `settings.change`, `relay.brand` (name, picture, description), `relay.status` (the public status note), `maps.manage`, `policy.change` |
| Automation | `bots.view`, `bots.manage`, `bots.programs`, `bots.send`, `api.keys`, `api.grants` |
| Operations | `logs.view`, `errors.view`, `relay.update`, `relay.restart`, `relay.maintenance`, `relay.diagnostics`, `backups.view` |

Seven roles are built in, and owners can make up to 50 more of their own:

| Role | For |
| --- | --- |
| `admin` | Everything but giving roles. The top role. |
| `moderator` | News, Forums, the card library and reports. |
| `support` | Invites, join requests, guests, devices and reports. |
| `operator` | Updates, restarts, maintenance, logs and error reports. |
| `bot-manager` | Bots, their programs and API keys. |
| `member` | Every member, without being given it. No permissions until owners give it some. |
| `guest` | Every device that isn't a member. Limits only, never permissions; the bottom role. |

Roles sit in one list, highest first: Admin, the other built-in roles, the relay's own in the
order owners place them, then Member and Guest. Move the relay's own with `isolink-relay role
move night-shift --above support`, the arrows on the admin page, or `PUT /roles/{id} {rank}`.

**Member and Guest are base roles**: every member holds Member and every guest holds Guest, and
neither is ever given by hand. A relay changes what they give by editing them: `isolink-relay
role change member --perm news.post` lets every member post to News. Guest takes limits and AI
limits only, because guests have no member record to check a permission against.

**Joining roles** are given roles every new member gets when they join, whether with an invite,
by asking or by being let in: `isolink-relay config set default_roles free,newcomer` (empty for
none), or **New members get this** on a role. A member who joins with an invite gets the
joining roles and the invite's roles. They're kept in the member's file like any given role, so
changing the list later doesn't change anyone who already joined. Bots get none. Removing a
role takes it out of the list too. Only owners set it.

### Limits by role

Every role, built-in ones included, can also carry **limits** for whoever holds it, in place of
the relay's own settings: `devices_per_account`, `drops_per_hour`, `file_pieces_per_minute`,
`mail_items_per_device`, `mail_bytes_per_device`, `file_bytes_per_device`, `opens_per_minute`,
`circuits_per_device`, `circuits_per_target`, `cards_per_account`, `themes_per_account`,
`backup_bytes_per_account`, `backup_versions`, `forum_file_bytes` and `forum_bytes_per_account`.
A member gets each limit from the highest role they hold that sets it: Admin first (owners
count as holding it), then the other built-in roles and the relay's own in order, and Member
last. Guests get Guest's limits. A limit no role sets keeps the relay's setting. Space held
for a device (messages and files waiting for it) follows its owner's roles; how fast a device
sends follows the sender's.

A role can also limit **bots' AI models**: messages, tokens or minutes over a length of time,
as on a bot, counted on each bot. When a role someone holds sets these they stand in for each
bot's own limits; "no limit" lets them use models freely, and leaving them unset falls back to
lower roles and then each bot.

Set limits on the admin page under **Roles**, in the app under **Manage › Roles**, through the
API's `PUT /roles/{id}` `{limits, ai}`, or on the machine:

```sh
isolink-relay role limits admin drops_per_hour=5000 backup_bytes_per_account=1GB
isolink-relay role limits member backup_versions=3 drops_per_hour=default
isolink-relay role ai member "100 messages a month" "200k tokens a month"
isolink-relay role ai admin --none
isolink-relay role limits guest drops_per_hour=50
```

An **owner** holds everything, and only the relay machine makes owners: `isolink-relay admin
<account>`, or an invite made with `invite --admin`. Nothing in the app changes or removes an
owner. A member holds at most 10 roles. Nobody gives what they don't hold or changes someone
who holds more than they do, and only owners give or take `members.roles` and make roles.

Give roles and permissions on the machine with `isolink-relay grant <account> moderator
relay.maintenance`, and take them with `grant --off` or `revoke-scope`. `isolink-relay role
list` shows the roles, `role permissions` every permission, and `role add --name "Night shift"
--perm reports.handle --perm members.view` makes one. In the app or on the admin page, someone
with `members.roles` picks roles in the member's sheet; owners edit roles on the admin page
under **Roles**. Invites can carry roles too: `invite --role support`.

Relays before roles gave **scopes** (`invite`, `members`, `guests`, `settings`, `bots`,
`announce`, `cards`, `forums`, `maintain`, `grant`). Members keep what their scopes gave: each
turns into the permissions it stood for the first time the relay reads them. `grant` and
`--scope` still take scope names, and the relay still tells older apps the scopes a member's
permissions add up to.

A member with any permission sees **Manage relay** on the relay's page under Settings → Relays. It shows the
devices online, guests, the space mail, files and backups take, and a health word. When a
newer release is out, it offers **Update** to members with `relay.update`, and the app shows
"Updating…" until the relay is back on the new version. Under Maintenance, **Update by
itself** turns on `auto_update`. Each row shows only with its permission:
**Members**, **Invites**, **Guests**, **Settings**, **Bots** and **Card
library**.

The relay checks every request itself and never trusts the app. A guest gets `members only`;
a member without the permission gets `not allowed`. Every change goes to the relay's log with who
made it. Changes reach the member's connected devices at once.

Settings changed from the app count at once, with no restart. A setting fixed with a `serve`
flag can only change on the machine. Updating from the app needs the relay to run as the
installed service:

- **Windows:** the service may replace its own file, so it updates and restarts itself.
- **Linux:** the binary belongs to root and the service runs as `isolink-relay`, so it can't
  replace it. Instead it leaves an `update-request` file in its data folder. The installer's
  `isolink-relay-update.path` unit sees it and runs `isolink-relay update` as root, which
  checks the feed and the download itself (the file only asks, it carries nothing trusted),
  then restarts the relay. A relay installed before this unit existed needs the installer run
  once more (`curl -fsSL https://isolink.app/relay/install.sh | sudo sh`), and the app says
  so. After that, every `update` keeps the units up to date too.
- **Docker, or run by hand:** update the image or the binary yourself.

With `auto_update` on (`isolink-relay config set auto_update true`, or **Update by itself**
in the app, which needs `relay.update`), the relay installs a new release as soon as its check
finds one, and restarts. It looks at start and then every `update_every` (1 hour by default; `0` stops it looking). It is off by default.

The relay has its own version numbers (1.0.0 and up), apart from the app's. With
`beta_updates` on (**Early versions** under Maintenance in the app, for members with
`relay.update`), it takes beta releases too, such as `1.1.0-beta.1`, when one is newer than the
stable release. Turning it off never goes back: the relay keeps the beta it runs until a newer
stable release comes out. Every update is signed, and the relay refuses one that isn't.

**Restart relay** (under Maintenance, with `relay.restart`) asks first, then shows
"Restarting…" until the app is linked to the relay again, and "Back online" once it is. If the
relay isn't back within a minute, it says so. See [Restarting](#restarting) for what the relay
does.

## Maintenance mode

Maintenance mode is a switch for when you work on the relay. Turn it on from the admin page's
Overview, from the API (`PUT /api/v1/maintenance`), or on the machine:

```sh
isolink-relay maintenance on --level limited --note "New disk, back by 2pm" --minutes 90
isolink-relay maintenance off
```

| Level | What happens |
| --- | --- |
| `notice` | Members see a banner with the note. Nothing else changes. |
| `limited` (the default) | Messages between members keep flowing. Joining, invites, posting to News, Forums and the card library, the bots, and changes from anyone without `relay.maintenance` wait, with `maintenance` as the reason. The API answers changes with `503` and `Retry-After`. |
| `closed` | Only members with `relay.maintenance` connect. Everyone else's app is turned away with the note, shows "Down for maintenance", and tries again every minute or so, or when the note says it ends. |

It is kept in the relay's data folder (`maintenance.json`), not its settings file, so it
survives a restart, and it ends by itself after `--minutes` (at most 30 days). Every connected
device hears of each change at once, and every change goes to the log with who made it.

## The admin page

The relay serves an admin page at `/admin/`, for example
`https://myrouter.tplinkdns.com:8443/admin/`. It manages the relay the way **Manage relay**
in the app does: status, updates and restarts, members and what they may do, invites, people
asking to join, guests and the allow list, the name, picture and description, settings and
policies, bots with their rules, card actions and logs, programs, the card library and theme
gallery, error reports and the relay's log. It asks the relay the same requests the app
does, as your account, so the same permissions, policy and limits apply, and every change goes to
the log with your name. It can't post to News or forums: those are end-to-end encrypted
with a key only members' devices hold.

There is no password. To sign in the first time:

1. When the relay starts it prints a one-time login, a link that works once within 24
   hours: `admin page, one-time login for 24 hours: https://…/admin/#login=…`. Find it with
   `journalctl -u isolink-relay` on Linux, in the service log on Windows, or in your
   hosting's logs. `isolink-relay admin-login` makes another at any time. It is never
   written to the relay's own log, which admins read from the app.
2. Open it. The page shows a code: in Isolink, go to **You → Relay server → Scan the relay
   invite** and scan it, or copy it and use **Paste the relay invite**.
3. The app signs in to the relay with the code. The relay ties the page to your account and
   makes you an owner, as `isolink-relay admin` would, joining you to the relay first if you
   weren't a member. A one-time login stands for the relay machine, so treat it like the
   machine's password.

Then add a **passkey** under **Your account**. It is saved against your Isolink account on
the relay, and signs you in again with **Sign in with a passkey**. A sign-in lasts 24 hours.
Removing a member removes their passkeys and signs them out.

Or sign in with the app: the sign-in page shows a code under **Sign in with the Isolink
app**. Scan it with **Scan a code** and approve it, and the page signs in as your account.
Any member can, from a device of their account as it stands: admins see what their
permissions reach, and members who manage nothing see their own API tokens, cards and
account. The code never makes anyone an admin, works
once, and the page shows a new one every three minutes. Only approve a page you opened
yourself: whoever shows you the code gets your access for a day.

Passkeys need the page on HTTPS with a certificate your browser trusts, such as one from
Let's Encrypt (`isolink-relay certs letsencrypt`, see [Certificates](#certificates)) or your
proxy. With the self-signed certificate the relay makes, browsers don't offer passkeys, so
sign in with a one-time login each time.

## The REST API

Scripts and services can use the relay over HTTPS at `/api/v1/`, with a token:

- **A personal token** (`isp_…`): any member makes one on the admin page under **API**, for up
  to 90 days. It acts as them: `me:` scopes for their own devices, presence, News and Forums, and
  whatever their roles reach.
- **An admin key** (`isk_…`), for 1 to 365 days, acting as the admin who made it.
- **A service key** (`iss_…`): an owner makes one for the relay itself, for something like a home
  hub. It acts as the relay's owners, keeps working when the one who made it leaves, and may
  never expire (`--forever`).

```sh
isolink-relay api key add --name "Parcel locker" --scope messages:send --bot House --days 90
isolink-relay api key add --kind service --name "Home hub" --scope maintenance:write --forever
curl -X POST https://relay.example.com/api/v1/messages -H "Authorization: Bearer isk_…" \
  -H "Content-Type: application/json" -d '{"to": "Sam", "text": "Locker 4, code 7731."}'
```

Every token has scopes (`members:read`, `roles:write`, `maintenance:write`, `forums:moderate` and
the rest), may be limited to some addresses, and never does more than whoever it acts as can do
at the time. Bots get tokens of their own for an hour: programs their rules run find one in
`ISOLINK_BOT_TOKEN`, and anything holding a bot's account key gets one by signing a challenge. A
rule with `--grant me:read,me:notify` asks the member who calls it, on a card, to let the bot act
for them for an hour; its program then gets `ISOLINK_GRANT_TOKEN`, and `/revoke` ends it.

The relay can't write in anyone's chat, so messages sent this way come from a bot, which seals them
to the member's devices with its own keys: end-to-end encrypted from the bot, to members who added
it. News and Forum posts come out sealed, as the app gets them. The whole API, its scopes and
errors are in [docs/relay-api.md](../docs/relay-api.md), and as OpenAPI at `/api/v1/openapi.json`.

## MCP: letting an AI assistant look after the relay

The relay is also an MCP server at `/mcp`, so Claude Code, Claude Desktop or any other MCP client
can read and change its settings, members, invites, bots and maintenance, read and moderate News
and Forums, and send and read messages as one of its bots. It signs in with the
same tokens as the REST API and can do only what the token's scopes and its maker can:

```sh
isolink-relay api key add --name "Claude" --scope settings:read --scope settings:write \
  --scope bots:read --scope bots:write --days 30
claude mcp add --transport http my-relay https://relay.example.com/mcp \
  --header "Authorization: Bearer isk_…"
```

A token lists only the tools its scopes reach. Removing a member, changing what someone may do,
removing a bot, maintenance, restarting and updating are never done on the first call: it answers
what would happen and a code, good for ten minutes, that the assistant sends back once you agree.
Every change goes in the relay's log under the key's name, and revoking the key ends it. More in
[docs/relay-api.md](../docs/relay-api.md#mcp).

The easy way: **Set up MCP** in the app (Manage relay) or on the console's API page makes a 30-day
key for what you may do (look after, read only or everything), then gives the line for Claude Code,
the config for the Claude app, and a prompt that has the assistant set itself up.

## MCP connections: tools from other services for the relay's bots

The relay can also connect out to MCP servers, such as a home hub, a calendar or another relay's
`/mcp`, so its bots' models can use their tools. The owner adds a connection, and each bot uses
the ones it is given:

```sh
isolink-relay mcp add home https://hub.example.com/mcp --token
isolink-relay mcp test home
isolink-relay mcp use Claude home
```

The token goes in the env store, never in `bots.json` or the log. A connection's tools are only
for members who manage the relay unless it was added with `--everyone`. Only the tools the server
marks read-only are offered unless it was added with `--changes`. They reach the model as
`mcp_<connection>_<tool>`. `https://` is required, except for `http://localhost`.

## The home page and asking to join

The relay's address on its own, such as `https://myrouter.tplinkdns.com:8443`, shows a home
page with the relay's name, description and picture (unless the policy keeps them from
guests) and a code to scan or paste in the app:

- On a relay that takes members by invite (`join invite`, the default), the code **asks to
  join**. The app says the request was sent. Admins with the `invite` scope see it under
  **Join requests** on the admin page, and let them in or turn them down. Once let in, the
  person scans or pastes the same code again to finish joining. Requests are kept for 30 days,
  200 at most, and `joins_per_ip` limits how often one address asks.
- On a relay anyone may join (`join open`), the code joins at once.
- While joining is paused, there is no code.

The name a request shows is what the person's device calls itself, so check with them before
letting them in.

## Restarting

`isolink-relay restart` on the relay machine, or **Restart relay** in the app, restarts the
running relay. The command reaches it through its data folder: it leaves a `restart-request`
file there, which the relay picks up within a second. The relay then stops its bots, closes
every link with code 4012 so devices try again every 2 seconds rather than backing off, and
starts again:

- **As a service** (systemd, WinSW, any systemd unit, or a container): it exits with code 75.
  The unit's `Restart=on-failure` starts it again after 5 seconds; WinSW's `onfailure` after
  10 seconds; a container's restart policy at once.
- **Run by hand** (`isolink-relay serve` in a terminal): it starts itself again in place, in
  the same terminal, with the same arguments.

The command waits up to a minute and prints "Back online." when the relay is running again.
Messages sent meanwhile wait on the phones and go once the relay is back. After `update`,
a relay run by hand is restarted the same way, so the new version runs.

## Moving to a new address

A relay that changes its address takes its members with it. Point the new address at the
relay machine first (its DNS name, and its certificate or proxy), then run
`isolink-relay move https://new.example.com`, or **Manage community → Move to a new address**
in the app as its owner. The relay restarts and answers at both addresses for 30 days
(`--keep-days` changes that).

Each relay has its own signing key, made the first time it starts and kept in its data folder
as `identity.json`. Apps learn it when they connect, and invites carry it. The move is a
notice signed with that key. The relay hands it to every device that signs in at the old
address, and apps pass it on to their contacts in the same community, so a member whose app
can't reach the old address any more still hears of it. An app switches only when the notice
checks out against the key it already holds, and the relay at the new address proves it holds
that same key. A notice can't be forged by someone who takes over the old domain, and it
can't send members to another relay. While the new address doesn't answer, apps try the old
one.

What moves along: News and forums (still sealed under the host they began at, so posts from
before the move open), the relay key, greetings, bots and backups. Certificates:

- **Self-signed:** the certificate and its pin stay, so devices trust it at the new address too.
- **Let's Encrypt:** the relay gets one certificate for the old and new names until the old
  address stops answering.
- **Your own certificate, or a proxy:** make it cover both names for the 30 days.

A member offline the whole time joins again with a new invite: the app sees the same key and
keeps everything, rather than adding a new community. Keep the data folder when you move
machines: a relay with a new key is a new relay to its members' apps, and they warn about it.
The admin page's passkeys are tied to the old host name: add them again at the new one.

## The relay's profile

A relay has a name, a short description (up to 280 characters) and an icon: a PNG, JPEG or
WebP picture of up to 64 KB, or an emoji, with a colour behind the emoji or the name's
initials. Members see them on the relay's page under Settings → Relays and wherever the app names the relay,
in place of its address.

```sh
isolink-relay profile --name "Our house" --description "The Hill Street family relay."
isolink-relay profile --icon house.png      # or --icon-clear, --emoji 🏡, --color "#3366ff"
isolink-relay profile                       # shows them
```

Members with the `settings` scope change them from **Manage relay**. Devices get the name,
the description and a hash of the icon when they connect, and fetch the picture only when
the hash changes.

## Certificates

`isolink-relay certs` shows the certificate and guides you through changing it; `certs
letsencrypt`, `certs self-signed`, `certs own` and `certs proxy` go straight to one guide.
`certs status` shows where it's from and until when, and `certs renew` gets a new Let's
Encrypt certificate now.

**Self-signed (the default).** `init` makes a self-signed certificate for your hostname. Every
invite carries the certificate's fingerprint, and the app trusts that fingerprint, not a
certificate authority. That means no port 80 and no DNS records. A browser checks HTTPS
using its own trusted certificates. An invite's fingerprint alone cannot make it trust
a self-signed relay. To keep the same relay and support browser members, set up a trusted
certificate with `isolink-relay certs letsencrypt`, your own trusted CA or a TLS reverse
proxy. Give members a fresh invite if the address changes.

**Plain HTTP on your LAN.** If the relay already uses plain HTTP, issue an invite with
its private IP address or a `.local` hostname. Browser members on the same network paste
it into Communities and allow local network access when prompted. A loopback address
is for a relay on the browser's own machine. HTTP exposes relay traffic to that network.
For browsers that block local HTTP WebSockets, and for access over the public internet,
use HTTPS with a certificate the browser trusts.

**Let's Encrypt.** The relay gets a free certificate every browser trusts, renews it about a
month before it runs out, and serves the new one without a restart. The address must be a
host name (a dynamic DNS name is fine), not an IP address. Let's Encrypt first checks the name
is yours, in one of two ways:

- *Over HTTP:* it connects to the name on **port 80**, whatever port the relay uses, so a relay
  on `:8449` still gets a certificate that works on 8449. Forward TCP port 80 on the router to
  a port on this machine (80, or e.g. 8080 when 80 is taken here: `--acme-http-port 8080`) and
  leave it forwarded for renewals. The relay listens there only while it renews.
- *Over DNS:* when port 80 can't come in, a program you give sets the TXT record
  `_acme-challenge.<name>`: it is run as `program set <name> <value>`, then `program clear
  <name> <value>`, and must finish only once the record is published. That needs a DNS
  provider with an API (or DuckDNS); tplinkdns.com, No-IP and most dynamic DNS can't.

```sh
isolink-relay init --url https://myrouter.tplinkdns.com:8449 --acme --acme-http-port 8080 --force
isolink-relay init --url https://me.duckdns.org:8443 --acme --acme-dns-hook /usr/local/bin/duckdns-txt --force
```

Until the first certificate comes, the relay serves a stand-in and tries again hourly; its
log says what to forward. Members who joined with the self-signed certificate keep connecting
with Isolink 0.21.0 or later, which trusts the relay once its certificate is publicly trusted
for its name; new invites carry no pin. `--acme-directory staging` tries Let's Encrypt's
staging service first, without its rate limits.

**Your own certificate.**

```sh
isolink-relay init --url https://relay.example.com --cert fullchain.pem --key privkey.pem
```

Devices then check that certificate against public certificate authorities, so renewing it
needs no new invites; the relay picks up renewed files within the hour. You can also run behind
a reverse proxy that handles TLS: use `--plain` and point the proxy at the port.

## Signed updates

When the relay updates itself it checks the download's SHA-256 against the update feed. That
proves the bytes arrived intact, but not *who* made them. Signed updates add that proof: each
release is signed with a key only Isolink holds, and a relay whose build carries Isolink's update
key refuses an update that isn't signed by it. A relay without one keeps working on the checksum
alone and says so in its log.

## Look after it

When the relay is running, the commands that manage members, invites, the allow list and
settings (`admin-login`, `admin`, `grant`, `revoke-scope`, `invite`, `invites`, `revoke`,
`members`, `remove`, `revoke-device`, `unrevoke-device`, `revoked`, `config`, `allow`,
`disallow` and `allowed`) run inside it rather than on its files: what they change counts
at once, and members' connected devices hear of it straight away. They find it through
`control.json` in the data folder, which only the relay's own user can read and which
names a port on the loopback address and a token. With no relay running, or with
`--config` naming another settings file, they work on the files as before.

| Command | What it does |
| --- | --- |
| `isolink-relay` | Prints the help and how the relay is doing. It doesn't start it. |
| `isolink-relay setup` | Asks a few questions and sets the relay up, or changes it. Offers the first owner invite. |
| `isolink-relay certs [letsencrypt\|self-signed\|own\|proxy]` | Shows the certificate and guides you through changing it. |
| `isolink-relay certs status` / `certs renew` | Where the certificate is from and until when; a new Let's Encrypt one now. |
| `isolink-relay serve` | Runs the relay. The service does this for you. |
| `isolink-relay profile` | Shows or changes the relay's name, description and icon. See [The relay's profile](#the-relays-profile). |
| `isolink-relay members` | Lists the accounts that joined, with their devices, and what each may manage. |
| `isolink-relay remove <account>` | Removes an account (a prefix of its id is enough). Its devices become guests. |
| `isolink-relay invite --admin` | An invite whose member becomes an owner. `--role R` (repeat it) gives roles instead, and `--scope S` the older scopes. |
| `isolink-relay admin <account>` | Makes a member an owner, who may do everything, in the app too. `--off` takes it away. With the relay running, it counts at once; otherwise when their devices next connect. |
| `isolink-relay grant <account> <role\|permission\|scope>…` | Gives roles, permissions or older scopes. `--off` takes them away. See [Admins manage from the app](#admins-manage-from-the-app). |
| `isolink-relay revoke-scope <account> <…>…` | Takes them away. |
| `isolink-relay role list` | The roles and what each gives. `role permissions` lists every permission; `role add`, `role change` and `role remove` look after the relay's own; `role limits` and `role ai` set any role's limits. See [Limits by role](#limits-by-role). |
| `isolink-relay maintenance [on\|off]` | Shows or sets [maintenance mode](#maintenance-mode): `--level notice\|limited\|closed`, `--note`, `--minutes`. |
| `isolink-relay invites` | Lists invites nobody has used yet, who made them and whether they make an admin. |
| `isolink-relay revoke <id>` | Cancels an unused invite. |
| `isolink-relay config` | Shows every setting, its value and its default. |
| `isolink-relay config set <key> <value>` | Changes a setting in `relay.json`. It is checked first. With the relay running, it counts at once, as from the app; a setting `serve` was given as a flag keeps the flag's value until the relay restarts without it. |
| `isolink-relay config unset <key>` | Puts a setting back to its default. |
| `isolink-relay allow <account> [--name N]` | Lets an account (all its devices) in as a guest when `guests` is `allowlist`. |
| `isolink-relay allow --device <device> [--name N]` | Lets one device in as a guest, not the rest of its account. |
| `isolink-relay disallow <id>` | Takes an account or device off the allow list. A prefix of its id is enough. |
| `isolink-relay allowed` | Lists the allow list, and guests refused in the last week with their ids. |
| `isolink-relay restart` | Restarts the running relay and waits for it to come back. Devices reconnect within seconds. See [Restarting](#restarting). |
| `isolink-relay move <address> [--keep-days 30]` | Moves the relay to a new address and restarts it there. Members' apps follow by themselves, and the old address keeps working until then. See [Moving to a new address](#moving-to-a-new-address). |
| `isolink-relay update` | Installs the latest release (checked against its SHA-256, and its signature when [signed updates](#signed-updates) are on) and restarts the service. Run it as root or administrator (on Linux, `isolink-relay` asks for sudo). Running the installer again does the same. `--check` only reports whether there is one. Members with `relay.update` update from the app when it runs as the installed service. |
| `isolink-relay announce "text"` | Posts to News. It isn't end-to-end encrypted: the relay machine has no relay key. With no text, shows the newest post. `--clear` deletes the newest post. |
| `isolink-relay news` | Lists News with each item's id. |
| `isolink-relay news delete <id>` | Deletes an item from News. The start of its id is enough. |
| `isolink-relay forum add --name N [--about A] [--emoji E]` | Makes a forum. Like `announce`, it isn't encrypted. |
| `isolink-relay forum list` | Lists the forums, with their posts and how many joined. Encrypted names show as `(encrypted)`. |
| `isolink-relay forum remove <forum>` | Deletes a forum with its posts and files. Name it by its id or the start of a name made here. |
| `isolink-relay forum lock <forum> [--off]` | Locks a forum: only members with `forums` post and comment in it. `--off` unlocks it. |
| `isolink-relay bot add --name N` | Adds a chat bot. `--house` makes it the relay's main bot. `--media audio,video` lets it take voice notes and videos. Members are told it joined. |
| `isolink-relay bot media <bot> audio,video\|none` | Turns voice notes (`audio`) and videos (`video`) on or off for a bot. Both are off until turned on. |
| `isolink-relay bot groups <bot> on\|off` | Lets a bot answer in group chats. Off until turned on. See [Bots in groups](#bots-in-groups). |
| `isolink-relay bot roles <bot> cards themes assistant\|none` | What a bot helps members with in the app: building cards in Card Studio, designing themes in Theme Studio, or anything as an assistant. None until turned on. See [Bots that help in the app](#bots-that-help-in-the-app). |
| `isolink-relay bot web <bot> on\|off` | Lets a bot's models fetch web pages through the relay, while `bot_web` is on too. Off until turned on. See [Web pages from a model](#web-pages-from-a-model). |
| `isolink-relay bot tools <bot> <tool>,…\|all\|none` | Chooses the tools on members' devices a bot may ask for. See [Tools on members' devices](#tools-on-members-devices). |
| `isolink-relay bot list` | Lists the bots, how many rules each has and its account. |
| `isolink-relay bot remove <bot>` | Removes a bot, its keys and its chats. Name a bot by its name or the start of its id. |
| `isolink-relay bot card install <bot> <card.json>` | Installs the named actions a card declares, so its `ctx.bot(name)` calls run through the relay (the endpoint and keys never reach the device). Any key values an admin packaged in the card move into the env store and are stripped from the stored action. `bot card list <bot>` shows the actions and any env key still to set; `bot card remove <bot> <action>` takes one away. |
| `isolink-relay bot rule add <bot> --command /hours --reply "…"` | Adds a rule. Instead of `--command`, use `--exact`, `--contains`, `--regex`, `--has-file image\|video\|audio\|file\|any` or `--any`. Instead of `--reply`, use `--llm <profile>` or `--run <program> [args…]` (last). `--account <id>` limits it to a member. Add `--card file.json` to send an interactive card with the reply, or `--file F` to send a file from the data folder. `--env NAME` gives a `--run` program one value from the env store. |
| `isolink-relay bot rule list <bot>` | Lists a bot's rules with their ids. |
| `isolink-relay bot programs allow <path> --name N` | Allows a program for rules made in the app. `--about "…"` says what it does. `--arg A` (repeat it) gives arguments it always gets first. `--env NAME` gives it one value from the env store. `--timeout 20` sets its seconds. Allowing a name again changes it. See [Programs the app may use](#programs-the-app-may-use). |
| `isolink-relay bot programs list` \| `bot programs disallow <name>` | Lists the allowed programs, with their paths, or takes one away. Rules that run it stop working. |
| `isolink-relay bot rule remove <bot> <rule>` | Removes a rule. The start of its id is enough. |
| `isolink-relay rule add --relay …` | Adds a rule every bot follows, after its own. Same flags as `bot rule add`. |
| `isolink-relay rule list --relay` \| `rule remove --relay <rule>` | Lists or removes the relay's rules. |
| `isolink-relay llm add <name> --provider anthropic\|openai\|gemini` | Adds an AI model for bots to use. `--accepts image,pdf,text,audio,video` says which files it takes. See [Bots that think or run things](#bots-that-think-or-run-things). |
| `isolink-relay env set NAME` | Keeps a secret, such as an API key, in the relay's env store. The value comes from a prompt that doesn't show it, or from stdin, never from the command line. See [The env store](#the-env-store). |
| `isolink-relay env list` \| `env unset NAME` \| `env import <file>` | Lists the names and when each was set (never the values), removes one, or reads a `.env` file. |
| `isolink-relay llm list` \| `llm remove <name>` | Lists the models (never their keys), or removes one no rule uses. |
| `isolink-relay llm test <name> "hello"` | Asks the model once and prints its answer. |
| `isolink-relay llm level [<level> <model> \| <profile> \| default] [--effort E] [--advisor M]` | Shows or sets which model each level means. See [Model levels](#model-levels). |
| `isolink-relay bot level <bot> [low \| medium \| high \| xhigh \| own]` | The level the bot's AI rules answer with; `own` for the model each rule names. |
| `isolink-relay bot greeting <bot> "text"` | What the bot says to each new contact. No text puts back the default. |
| `isolink-relay bot greeting <bot> --prompt "…"` | Its chat model (its first `--llm` rule's) writes each new contact's greeting from the prompt. The text goes when the model can't answer. `--no-ai` goes back to the text. |
| `isolink-relay bot welcome-card <bot> card.json` \| `--off` | A card that goes with the bot's greeting, such as a menu of what it does. Checked as a rule's `--card` is. |
| `isolink-relay bot style add <bot> --name "Halloween Special" --prompt "…"` | A picture style of the bot's own, at most 12. Members see its name in the picture maker, next to the usual styles, once the bot makes pictures (`bot images`). The relay draws with your prompt, and the member's own words go after it. `--for restyle` offers it only to change a photo, such as a profile picture, and `--for background` only for chat backgrounds. `--icon` names an icon for its chip. |
| `isolink-relay bot style list <bot>` \| `bot style remove <bot> <style>` | Lists its styles with their prompts, or removes one. |
| `isolink-relay bot instructions <bot> ["text" \| default]` | How its AI models should behave. Without its own, a bot follows the `bot_instructions` setting. No text shows them. |
| `isolink-relay bot disclosure <bot> ["text" \| default] [--banner on\|off\|default] [--header on\|off\|default]` | What a bot that uses AI tells people about it: a banner at the start of its chat and an info button in its chat header. Without its own, a bot follows the `bot_disclosure` settings. With nothing to change, shows it. |
| `isolink-relay bot stop [<bot>]` | Stops what a bot, or every bot with none named, is working on now: its models and programs. Their chats see "Stopped." Members can send `/stop` to stop the bot's answer to them, and admins can stop a bot from Relay admin in the app. |
| `isolink-relay bot code <bot>` | Shows the bot's contact code and QR code, once the relay has run it. |
| `curl -k https://localhost:8443/healthz` | Health check: prints `ok <devices connected>`. |
| `isolink-relay status` | Running or not, version, devices online, each bot's state, updates. `--json` for scripts. See [Finding faults](#finding-faults). |
| `isolink-relay doctor` | Checks what usually goes wrong and says how to fix it. Exits with 1 when something fails. |
| `isolink-relay logs [-n 100] [-f]` | The relay's recent log, scrubbed of keys and tokens. `-f` follows it. |
| `isolink-relay bot log <bot> [-n 100] [-f]` | What a bot did with each message, and why it answered or didn't. |
| `isolink-relay errors list` \| `errors show <id>` \| `errors export [-o file.json]` | The problems members' apps reported. See [Error reports](#error-reports). |
| `isolink-relay devices [<account>]` | Each member's devices: online now, when last seen, revoked. |
| `isolink-relay report [-o file.json]` | One file with the status, the doctor's checks, settings, bots, error reports and recent logs, to share when asking for help. |

## Bots

A bot is a real Isolink account. Its keys live in `bots/<id>/` in the data folder, and the
relay runs it inside its own process. It connects to the relay as a member, through a socket
in memory. Its chats are end-to-end encrypted like anyone else's. The relay never reads
other members' messages: anything it says in a chat comes from a bot. A bot's keys sit in the
data folder, so whoever runs the relay can read what people send to its bots.

```sh
isolink-relay bot add --name "House" --house
isolink-relay bot rule add House --command /hours --reply "The shop opens at 9."
isolink-relay bot rule add House --contains wifi --reply "The password is on the fridge."
isolink-relay bot greeting House "Hi! Send /help to see what I can do."
```

Members see the relay's bots under **You → Settings → Relays** and add one with one tap. A bot's
chat shows a **Bot** badge. `/help` lists a bot's commands. Rules match without caring about
case: `--command` matches the first word, `--exact` the whole message, `--contains` any part,
and `--regex` a regular expression. The first rule that matches answers. An unknown command
gets a hint to send `/help`.

Bots never carry messages for other people. A bot holds no sealed items for anyone and hands
none on, whatever its settings say, and members' devices never give one anything to carry or
fetch anything from one. Bots stay out of carry trails, stats and the mesh map.

**Verified by the relay.** Members reach the relay over a connection whose certificate they
pinned when they joined, and the relay lists each bot with its account and contact code. A
bot whose keys match the code the relay lists shows as verified by the relay, with no need to
compare safety numbers in person. It is worked out from the relay's latest list every time:
once the relay stops listing the bot, or lists other keys, it is no longer vouched for. A bot
whose keys change while the relay still vouches for the new ones gets no *verify again*
warning; any other change gets the usual one. In the core this is
`Messenger.vouchingRelayName(accountId)`, the relay's name or null.

Bots take contacts from whoever the policy key `bot.contact` lets in: members by default. Add
Guest to it (or set `bot_guests` to `true`) to let guests add them too, or name roles to keep
bots to some members.
Each contact gets at most 10 replies a minute and 120 an hour. A bot accepts at most 20 new
contacts a day, like any Isolink account.

When a bot joins, from `bot add` or from the app, every member is told: *House joined the
relay*. It shows in News too, as a line from the relay. Connected members hear at once, the
rest when they next connect, for as long as the relay keeps mail. The app raises one
notification, which opens the bot with **Add**.

### Photos, files, voice notes and videos

Bots take photos and files up to `bot_file_bytes` (10 MB by default), and say so to anything
bigger. Voice notes and audio (`audio`) and videos (`video`) are off for every bot until
turned on with `bot add --media audio,video` or `bot media <bot> audio,video`, or from the
bot's page in the app. A bot that doesn't take them says *This bot doesn't take voice
notes.* or *This bot doesn't take videos.*, and nothing goes on to a rule. A bot can also
write out voice notes for its models: see [Voice notes, written out](#voice-notes-written-out).

A message with only a file matches `--any` rules and `--has-file` rules: `--has-file image`,
`video`, `audio` or `file` for that kind, `--has-file any` for any. `/help` says what a bot
takes. A fixed `--reply` rule can send a file from the data folder with `--file`.

### Bots that help in the app

A bot can help members inside the app as well as in its own chat. `bot roles Pixel cards themes`
(or the bot's page in the app, or Bots in the web console) says what it helps with:

- `cards`: it shows under **Bots** in Card Studio. A member asks it to build or change the card
  they have open; it shows a short plan and writes each part of the card while they watch, then
  fixes what Card Studio's checks find. The member keeps or undoes what it did.
- `themes`: it shows under **Bots** in Theme Studio. A member describes a look, and its changes
  show in the preview straight away, to keep or undo.
- `assistant`: it is offered as an assistant to ask anything.

`bot roles Pixel none` turns it off. The member's message goes to the bot in its own encrypted
chat, with the card's code and the checks' findings, or the theme, attached for its model; its
model works through tools only the app it was asked from takes, while that studio stays open.
It needs a rule that asks a model (`--any --llm`). A member with several bots for the same job
picks one, and the app remembers it.

### Bots in groups

A bot answers only in its own chats until it's allowed in groups, with `bot groups House on`
(or `off`), or from the bot's page in the app. Until then, apps leave it out of the people
offered for a new group or for adding to one, and a group it is already in says it won't
answer there.

In a group, a bot answers a message only when it is for the bot: one that mentions it with
`@House`, replies to one of its messages, or starts with one of its own commands. `/help`
takes a mention, since every bot knows it. Anything else is the members talking among
themselves, and the bot leaves it be. An @mention brings what was said just before it, up to
10 messages from the 30 minutes before, so "@House what do you think of it?" comes with what
"it" is. It answers members of the relay (and guests with
`bot_guests`), and never adds anyone as a contact or greets them there.

A reply needs no mention: Reply on one of the bot's messages and it answers, while a reply
to anyone else's message stays among the members. Wherever a reply is for the bot, in a group
or its own chat, a model hears the message it quotes ahead of it, like
`[Replying to your message: "…"]`, and a program gets it as `ISOLINK_REPLY_TEXT`.

A model hears each message with the sender's name in front, and keeps the group's turns
apart from each member's own chat with the bot. Tools on members' devices stay in those
own chats: a model in a group has only `post_card` and `answer_card`, and a `--tool` rule
says it only works in a chat with the bot on its own. Bots never take calls, in a group or
anywhere.

### Disappearing messages

A chat with a bot can have a disappearing timer like any chat. The bot gets the change and
answers in kind: its replies carry the same expiry, and it deletes its copy of the messages
on time. Turns it kept for a model are forgotten when the timer passes.

Changes to `bots.json` count at the bot's next message. A bot added or removed starts or
stops within half a minute while the relay runs.

### Cards

`--card file.json` sends an interactive card with a fixed reply. The file holds the card
in either form below, and `rule add` checks it as the app does: a card with no blocks, or a
block the app wouldn't show, is refused with the reason, such as *blocks[1].type 'buttons' is
not one of text, button, choice, checklist, input, rating, link*.

```json
{"title": "Wi-Fi", "emoji": "📶", "blocks": [
  {"type": "text", "text": "The password is **on the fridge**."},
  {"type": "choice", "id": "worked", "text": "Did it work?", "options": ["Yes", "No"]}
]}
```

| Block `type` | Fields |
|---|---|
| `text` | `text`: words, simple Markdown, up to 2000 characters. |
| `button` | `text`: the label. `action`: `respond` (the tap is an answer; the default), `link` (opens `url`) or `reply` (starts a reply). |
| `choice` | `text`: the question. `options`: 2 to 12 different ones. `multi`: more than one may be picked. |
| `checklist` | `text`: a heading. `options`: 1 to 30 items everyone in the chat can tick. |
| `input` | `text`: the question, answered in words. `hint`: the greyed text. |
| `rating` | `text`: the question, answered with 1 to 5 stars. |
| `link` | `url`: an http or https address. `text`: its title. |

A card has a `title` (up to 80 characters), at most 30 blocks, and may have an `emoji`, an
`accent` like `#6366F1` and an `id`. Block ids are letters, digits, `_` or `-`; they are made
up when left out. Labels are up to 120 characters. Pictures can't come from a bot: they
travel as bytes in the card, so use a link. The app's own short form (`k`, `t`, `o`…) works too.

**Answers to the bot's cards.** When a member answers, ticks or taps a card the bot sent,
the bot hears it. A `--card-answer <card id>` rule (or `--card-answer any`) answers it with
its fixed `--reply`, where `{answer}` is what was picked or typed. Without one, an `--any` rule
that asks a model passes it to the model as a turn of its own (see below). Fixed `--any`
replies don't answer card taps.

```sh
isolink-relay bot rule add House --card-answer worked --reply "Thanks. You said: {answer}."
```

### Which rule answers

A bot tries its own rules in order, then the relay's (`rule add --relay`). `--any` rules
match every message, so they come last: the bot's own, then the relay's. `/help` is built in
and always answers.

`--about "…"` says what a command does, in a few words. In a bot's chat, typing `/` lists its
commands with these, `/help` first; without `--about`, the reply's first words show. Commands
limited with `--account` stay out of that list.

`--account <id>` limits a rule to one member; repeat it for more. The start of an id is
enough: `isolink-relay members` lists them. A limited rule doesn't answer anyone else, and
`/help` only lists the commands the person asking can use.

```sh
isolink-relay rule add --relay --command /wifi --reply "The password is on the fridge."
isolink-relay bot rule add House --command /door --run /usr/local/bin/open-door --account 3f9a2c
```

### Command arguments

A command can say what it takes after its name. Write each argument in angle brackets, after
the command or with `--params`:

```sh
isolink-relay bot rule add House --command "/shout <person> <when?>" --reply "HEY {person}! {when}"
isolink-relay bot rule add House --command /remind --params "<who> <when?=tonight> <note...?>" \
  --run /usr/local/bin/remind
```

| Written | Means |
|---|---|
| `<person>` | Required. |
| `<when?>` | Optional: it may be left out. |
| `<when?=now>` | Optional, and `now` when left out. A default makes it optional. |
| `<note...>` | Takes every word left on the line. Add `?` to make it optional. |

Names are a letter, then letters, digits or `_`, up to 32, and ignore case. `text`, `name`,
`chat`, `result` and `answer` already mean something in a reply, so no argument may be called
those. A command takes at most 12. **Required ones come first**: `rule add` refuses an optional
argument before a required one, and a `<x...>` that isn't last, and says what to change.

Members give arguments in order, or by name in any order. Giving one by name is how an
optional one is given without the ones before it:

```text
/shout John now
/shout "John Smith" 'next week'
/shout person="John Smith" when=now
/shout when=later John
```

Quotes keep spaces in, `\` escapes inside double quotes, and a quoted `"when=now"` is a value,
not a name. Arguments are checked before anything runs. A message that doesn't fit gets what
to send instead, and nothing runs: *`/shout` needs `<person>`. Send it as `/shout <person>
<when?>`.*, *`/shout` has no argument called `who`.*, *Too many words from "c" on*, or *A quote
isn't closed.* A command with no arguments works as before: everything after it is
`ISOLINK_ARGS`, unchecked.

What the command got reaches whatever answers it:

- **A fixed reply** fills in `{person}` for each argument, and nothing for an optional one not
  given. `rule add` refuses a `{x}` the command doesn't take.
- **A program** (`--run`, or an allowed program) gets `ISOLINK_ARG_PERSON` for each argument
  given, in capitals, and all of them as JSON in `ISOLINK_ARGS_JSON`, such as
  `{"person":"John Smith","when":"now"}`. Without `--shell`, a word of the command line that
  holds `{person}` is filled in too, still one argument of its own: `--run /usr/local/bin/remind
  --to {who}`. A word that is only an optional argument not given is left out. What a member
  typed is never read as another placeholder, and a `--shell` line never has it in it: read the
  variables there.
- **A model** hears the message, then a line such as `[/shout takes <person> <when?>: person =
  "John Smith", when not given]`.

The app's `/` list shows each command with its arguments. Once a command and a space are
typed, a line over the message field shows its usage with the next argument picked out,
offers `name=` for a word that starts one, and says what's wrong as it is typed. `/help` lists
the usage too: `/shout <person> <when?>`.

## Bots that think or run things

A rule can answer with an AI model (`--llm`) or with a program (`--run`) instead of fixed
text.

> **Warning.** These end the privacy of a bot's chats. A bot's chats are end-to-end
> encrypted only as far as the relay. With `--llm`, the relay sends each message, the
> sender's earlier turns and your system prompt to that model's service. With `--run`, the
> program runs as the relay's own service user, with that user's rights over its files and
> network. Only run programs you trust, and only add models you'd trust with what members
> send.

Members are told. A bot with an `--llm` rule, a `--run` rule marked `--external host`, or a
speech-to-text service, lists those hosts in the app: *Sends your messages to
api.anthropic.com*. A model on the same machine (`localhost`) isn't listed.

### An AI model

Add a model once, then use it in any bot's rules:

```sh
# Anthropic. The key stays out of bots.json: give an environment variable or a file.
isolink-relay llm add claude --provider anthropic --key-env ANTHROPIC_API_KEY \
  --system "You answer questions for the Hill Street house. Keep it short."
isolink-relay llm test claude "hello"
isolink-relay bot rule add House --any --llm claude

# Ollama, or any OpenAI-compatible service (LM Studio, OpenRouter, OpenAI).
isolink-relay llm add local --provider openai --model llama3.2 --url http://localhost:11434/v1
isolink-relay bot rule add House --command /ask --llm local
```

| Flag | Meaning |
|---|---|
| `--provider` | `anthropic`, `gemini` (Google's Gemini API), or `openai` for any OpenAI-compatible Chat Completions service. |
| `--accepts` | The files the model takes: `image`, `pdf`, `text`, `audio`, `video`. By default `anthropic` takes image, pdf and text; `openai` image and text (it can take WAV and MP3 audio too); `gemini` all five. |
| `--model` | The model. For Anthropic the default is `claude-opus-5-5`, asked with `low` effort. |
| `--url` | The service's base address. Anthropic's and OpenAI's own by default. For Ollama, `http://localhost:11434/v1`. |
| `--key-env VAR` | Read the key from `VAR` in the relay's [env store](#the-env-store), or else from that environment variable of the relay's service. |
| `--key-file PATH` | Read the key from this file. Make it readable only by the relay (`chmod 600`). |
| `--system "…"` | The system prompt. |
| `--max-tokens N` | The longest answer, in tokens (default 8000). |
| `--history N` | For older apps only: earlier turns the relay keeps and sends along (default 10). |
| `--compact-at KB` | How much chat a model gets before it sums up the older part, 8 to 96 KB (default 32). |
| `--effort` | Anthropic only: `low`, `medium`, `high`, `xhigh` or `max`. |
| `--web-search` | Anthropic only: the model may search the web with Anthropic's own search tool, at most 3 searches an answer. Off by default. Members see `web-search` among the bot's hosts. |
| `--advisor M` | Anthropic only: a stronger Claude model, such as `claude-opus-5-5`, the model may ask for advice through Anthropic's advisor tool (`advisor_20260301`), at most 3 times an answer. |

`bots.json` only holds the variable's name or the file's path, never the key. `llm list` never
prints a key. With `--key-env`, keep the key in the env store (`isolink-relay env set
ANTHROPIC_API_KEY`), or set the variable where the relay runs, for example with
`Environment=ANTHROPIC_API_KEY=…` in a systemd drop-in. Local services need no key.

**Files to a model.** Photos go to the model as images (Anthropic image blocks, `image_url`
data for OpenAI-style services, inline data for Gemini). PDFs go as documents to Anthropic
and Gemini. Text files (txt, md, csv, json, code) go inline, with their name. Voice notes
and videos go only to a model whose `--accepts` lists them, and only when the bot takes them:
Gemini gets them inline, or through its File API when they are big, up to `bot_file_bytes`.
Anything a model doesn't take gets a plain answer, *I can't read that kind of file yet.* or
*I can't take voice notes or videos.*, and nothing goes to the model. Pictures over 3.75 MB
are refused for Anthropic and OpenAI-style models: the relay doesn't shrink them. A model
can answer with files too: see [Files from a model](#files-from-a-model).

Live voice with a bot (e.g. Gemini Live) is planned.

**What every model is told.** Each request starts with a short prompt of Isolink's own, then
your `--system` text after a blank line. It says:

- who the model is: the bot's name, in an Isolink chat on the relay (its name from `init
  --name`, or its host), talking with one person at a time;
- the date, the day and the time in the relay's time zone, to use for times;
- that replies show as Markdown (bold, lists, links, code), with no tables and no HTML, and
  should stay short;
- the tools it has, and when to use each, and never to claim a tool worked unless it did;
- how cards and answers to cards reach it, and to answer `NO_REPLY` when an answer to its card
  needs no reply. The bot then sends nothing;
- to label code with its language, how to send files with `send_file`, what a voice note
  looks like, and the [docs](#docs-for-models) it can read.

The relay never changes what a model writes: Markdown reaches the app as it is. Only very
long code moves into a file (see [Files from a model](#files-from-a-model)).

**Web search.** With `--web-search`, an Anthropic request carries Anthropic's server-side web
search tool: `web_search_20260209` for the models that take it (Opus 4.6 and later, Sonnet 4.6
and later), `web_search_20250305` for the rest. Searches run at Anthropic. The bot keeps the
text after the last search result as the answer, and sends a paused turn (`pause_turn`) back
to finish. Searches cost extra on Anthropic's bill.

**Model levels.** Bots and cards ask for a level instead of a model: `low`, `medium`, `high`
or `xhigh`. `llm level <level> <model>` sets a level to a model name, run with the provider,
key and settings of the model the bot would otherwise use; `llm level <level> <profile>` uses
one of the relay's models whole; `default` clears it. A bot's level (`bot level`, or Level in
its settings) moves all its `--llm` rules and its greetings onto that level's model. A card's
bot slot asks with `model: 'low'` in `card({ bots: { slot: { grants, model } } })`: the bot
plays that card on the level's model and keeps its own elsewhere. Levels you haven't set mean,
for Claude models: `low` `claude-haiku-5-5`, `medium` `claude-sonnet-5-5` with
`claude-opus-5-5` as advisor, `high` the bot's own model, `xhigh` `claude-opus-5-5` at `xhigh`
effort. For other providers an unset level is the bot's own model. The levels live in
`bots.json` as `levels`; the console sets them on the Models page.

**Advisor.** With `--advisor`, or a level's advisor, an Anthropic request carries the advisor
tool and the `advisor-tool-2026-03-01` beta header. The model answers and, when it needs it,
asks the advisor, which reads the whole chat and sends back a short plan. Advice is capped at
4096 tokens a call. Only `anthropic` (Claude) models get the tool: OpenAI, Gemini and local
models never do, and the relay refuses `--advisor` on them. Advisor tokens
count toward bots' usage limits.

### Cards and models

A model has the bot's own tools as well as the member's device tools:

| Tool | Who sends it | Use |
|---|---|---|
| `post_card` | The bot, as its own message | The default for "send me a card": questions with options, lists to tick, ratings, buttons. Needs no permission: it's the bot's own chat message. Answers come back to the model. Returns `message_id`. |
| `answer_card` | The bot | Answers, taps or ticks a card in its chat as the bot: `message_id`, `block_id` and `answer` (a button: `true`; a choice: option text or a list; words; 1 to 5 stars; checklist item numbers or texts, with `done: false` to untick). |
| `send_card` | The member's device, as the member | Only when the member asks for a card from them. Asks the member first. |
| `save_card` | The member's device, into **My cards** | For a card "for me", "to keep" or "to reuse", or one to send somewhere else. |

`post_card`, `send_card` and `save_card` take the same `card`, as above. Every card a model
writes is checked before it goes anywhere. A broken card goes back to the model as a tool
error naming what's wrong, so it can fix it and try again; the member never sees it, and a
card is never sent with no blocks.

**Scripted cards** stay off: a model's card with a `script` is refused unless the bot allows
it, with `bot scripts House on` (or `off`), or from the bot's page in the app. Then the
schema offers `script`, and a script must parse before the card goes. It runs in the app's
sandbox like any scripted card. `--card` files from the relay's owner may carry scripts.

**Cards to a bot.** A card a member sends to a bot reaches its model (or its program, in
`ISOLINK_TEXT`) as words: the title, the card and message ids, each block with its id, type,
options and the answers so far. An answer to one of the bot's cards reaches the model as a
turn of its own: *[card answer] Alice picked "Not mine" on "Whose are they?" (block owner) on
your card "Whose keys are these?"*, then the card. The model can answer, use `answer_card`, or
stay quiet with `NO_REPLY`. A failure there is only logged.

Under a card a bot posts, the app shows **Save to My cards**.

While a model or a program works on an answer, the chat shows the bot as typing. It stops while
the bot waits for the person to answer a tool request.

**Memory.** The chat on the person's phone is the bot's memory. With each message, and each
answer to a bot's card, the app sends the chat before it, end-to-end encrypted like the
message. The model gets that as its history. The relay keeps no history of its own for these
apps, only the latest chat for an hour, for an answer to a card. When the person clears the
chat (**Clear chat** in the chat's menu), the bot forgets it. The app sends at most 300 turns
and 120 KB.

Once the chat passes `--compact-at` (32 KB by default), the bot asks the same model, after
answering, to sum up the earlier summary and all but the newest turns (those in a quarter of
`--compact-at`, at least 4). The summary, at most about 2000 characters, rides on the reply
as a hidden field. The person's devices keep it with that message and never show it. From
then on the app sends the summary and only the turns after it, so a long chat keeps folding
into the summary. If the summary fails, the reply goes without it and the relay logs why.
`--history` doesn't cut what the app sends.

Older apps send no chat. For them the relay keeps the last `--history` turns in memory only,
forgotten after an hour of quiet or a restart. A model gets 60 seconds. Answers are cut at 4000
characters. If it fails, the bot says "That didn't work." and the details go to the relay's
log. On Anthropic's own API, a request its safeguards decline is answered by a fallback model.

### Voice notes, written out

A bot can turn voice notes into text for its `--llm` rules. Add a speech-to-text profile
once, then give it to a bot:

```sh
# OpenAI's Whisper, or any service with the same /v1/audio/transcriptions
# (faster-whisper-server, LocalAI, Speaches).
isolink-relay env set OPENAI_API_KEY
isolink-relay stt add openai --openai-compatible https://api.openai.com/v1 \
  --model whisper-1 --key-env OPENAI_API_KEY
isolink-relay stt add local --openai-compatible http://localhost:8000/v1 --model Systran/faster-whisper-small

# A program on this machine, such as whisper.cpp. It gets the audio file's path last
# and prints the text. -nt leaves out timestamps.
isolink-relay stt add cpp --run /usr/local/bin/whisper-cli -m /opt/whisper/ggml-base.en.bin -nt

isolink-relay stt test openai voice.m4a
isolink-relay bot transcribe House openai        # or: bot add --name House --transcribe openai
isolink-relay bot transcribe House none
isolink-relay stt list
isolink-relay stt remove cpp
```

| Flag | Meaning |
|---|---|
| `--openai-compatible URL` | The service's base address. The relay posts to `URL/audio/transcriptions`. |
| `--model` | The model (default `whisper-1`). |
| `--key-env NAME` | Read the key from `NAME` in the [env store](#the-env-store), or else from that environment variable. Local services need none. |
| `--run` | The program and its arguments, last on the line. It runs without a shell, like a rule's `--run`. |
| `--timeout N` | Seconds it may take (default 120, up to 600). |

Turning it on turns voice notes (`audio`) on for the bot. A voice note to an `--llm` rule is
written out first. The bot sends the text back as a reply to the voice note, *🎤 "Is the
shop open on Sunday?"*, then the model's answer. The model gets the text, marked as a
voice note, and not the audio. Other rules get the voice note as it is.

The app records voice notes as AAC in an `.m4a` file. They go to the service as they are:
Whisper takes m4a, mp3, ogg, wav and webm. Voice notes over `stt_max_seconds` (5 minutes by
default) get *That voice note is too long for me.* and go nowhere. If the service fails, the
bot says *Couldn't make out that voice note.* and the reason goes to the relay's log. A key
never goes on the command line, into `bots.json`, the log or the app.

### Files from a model

A model can send files with the relay's `send_file` tool: `name`, `content` and an optional
`mime`. It is for text: Markdown (`.md`) and code (`.py`, `.dart`, `.js`, `.json`, `.sh`,
`.csv`, `.txt` and more). The app shows a `.md` file rendered in the chat, and other files
as a file to open. The relay cleans the name and adds an extension when there is none. Each
file is at most `bot_file_bytes`, five an answer. They follow the answer's text.

Code in an answer stays in the message, in a fenced block labelled with its language
(```` ```python ````). A block over 150 lines, or one that would push the message past
4000 characters, goes into a file instead, such as `code.py`. The message says where it
went: *The code is in code.py (212 lines).*

### Web pages from a model

A model can read web pages with the relay's `fetch_page` tool, with the relay as the client:
the request comes from the relay machine, never the member's device. It needs two switches,
both off until turned on: the relay's `bot_web` setting (`isolink-relay config set bot_web true`,
or under Bots in the relay's settings), and the bot's own (`bot web House on`, or *Fetch web
pages* on the bot's page). With either off the model doesn't get the tool.

- **Public pages only.** `http` and `https` on ports 80, 443, 8000, 8080 and 8443. The relay
  looks up the name and refuses it if any address is loopback, private (10/8, 172.16/12,
  192.168/16, fc00::/7), link-local (169.254/16, where cloud metadata lives, and fe80::/10),
  shared, multicast or reserved, then connects to the address it checked. Each redirect (up
  to five) is checked the same way. No proxy, cookies or names and passwords in the address.
- **Limits.** 15 seconds a page, the first 2 MB read, text types only (HTML, plain text,
  JSON, XML), 20 new pages a bot a minute, and at most 8 relay tool calls an answer.
- **Few tokens.** A page comes back as text: scripts, styles, menus, footers and forms go,
  the page's `<main>` or `<article>` stands in for the rest when it has one, headings become
  `#` lines and list items `-`. It returns 6,000 characters at a time (`max_chars` up to
  20,000) with `more_from` to read on, and lists links only when asked (`links: true`).
- **Cached.** The relay keeps the last 64 pages for 10 minutes, shared by its bots. Reading
  on, or asking again, doesn't fetch the page again.

With the same two switches a model can also send a picture or file from the web in the chat
(`send_web_file`), such as a meme someone asked for. `fetch_page` with `images: true` lists a
page's pictures (its share picture first) to pick from. The fetch goes the same checked way,
and the file must be one of a few safe kinds, told by its first bytes rather than its name or
the server's word: PNG, JPEG, GIF, WebP, PDF, MP3, OGG, M4A, MP4, WebM or plain UTF-8 text.
Programs, archives, web pages and SVGs (which can hold scripts) are refused. Up to 10 MB, and
within `bot_file_bytes`; it counts toward the 20 fetches a minute and 5 files an answer.

> **Warning.** What a page says reaches the model as it is, and a page can be written to
> steer a model. Turn it on for bots whose tools you would be happy for a stranger's page
> to ask for.

### A model uses the bot's commands

A model behind a bot with commands gets a `use_command` tool: `command` and `args`, the
arguments by name. It uses one of the bot's own commands as if the member had sent it, and
gets back what it answers, to use in its reply: a fixed reply with its `{x}` filled in, or what
a program printed. Its arguments are checked as a member's are, and a wrong one comes back
with what the command takes. Only commands the member may use count, and never one that asks
a model or a member's device. A program runs with its own timeout, env names and limits, and
stops when the answer is stopped.

### Docs for models

The relay keeps docs its models can read with a `read_doc` tool. Each model gets a short
list of their names and first lines, and reads one only when it helps. The relay has these
built in:

| Doc | What it covers |
|---|---|
| `cards` | Interactive cards: the JSON, every block, answers and limits. |
| `card-scripts` | Card scripts: the language, state, buttons, reaching web sites. |
| `formatting` | How messages show: `*bold*`, `_italic_`, `~strike~`, code, quotes, bullets. |
| `markdown` | Markdown files: what shows and how to send one. |
| `bot-tools` | The bot's own tools, on the relay and on members' devices. |

Add your own, in Markdown, up to 64 KB each and 20 in all:

```sh
isolink-relay bot docs add house-rules.md          # called house-rules
isolink-relay bot docs add notes.md --name bins
isolink-relay bot docs list
isolink-relay bot docs remove bins
isolink-relay bot docs use House house-rules,cards  # or: all (the default), none
```

They live in `bot-docs/` in the data folder. Every bot reads every doc unless you choose
some with `bot docs use`.

### A program

`--run` takes the program and its arguments, last on the line. The relay starts it directly,
without a shell. The message never goes into its arguments: it arrives on stdin and in these
environment variables:

| Variable | Value |
|---|---|
| `ISOLINK_TEXT` | The whole message. |
| `ISOLINK_COMMAND` | The first word, when it starts with `/`, in lower case. Otherwise empty. |
| `ISOLINK_ARGS` | The rest of the message after the command, or all of it when there is none. |
| `ISOLINK_ARG_<NAME>` | For a command that takes [arguments](#command-arguments): each one given, its name in capitals, like `ISOLINK_ARG_PERSON`. Defaults are filled in; an optional one not given is unset. |
| `ISOLINK_ARGS_JSON` | The same, as one JSON object: `{"person":"John"}`. |
| `ISOLINK_FROM` | The sender's account id. |
| `ISOLINK_NAME` | The sender's name, as the bot knows it. |
| `ISOLINK_BOT` | The bot's id. |
| `ISOLINK_CHAT` | The chat's id. |
| `ISOLINK_REPLY_TEXT` | When the message is a reply: the message it quotes. Unset otherwise. |
| `ISOLINK_REPLY_FROM` | Who wrote the quoted message: their account id, or the bot's own when it is the bot's. |
| `ISOLINK_REPLY_NAME` | Their name, as the bot knows it. |
| `ISOLINK_FILES` | The paths of the files the message brought, one a line, saved in the run folder. |
| `ISOLINK_FILE_NAMES` | Their names as sent, one a line. |
| `ISOLINK_OUT` | A fresh folder for this run. Every file the program writes there goes back as an attachment, photos as photos, each up to `bot_file_bytes`. |
| *your `--env` names* | Each value from the env store the rule names with `--env NAME`. Only those. |

A tiny program that answers `/shout`:

```sh
#!/bin/sh
# /usr/local/bin/shout: prints the message after /shout in capitals.
printf '%s\n' "$ISOLINK_ARGS" | tr a-z A-Z
```

With arguments, it reads each one by name instead:

```sh
#!/bin/sh
# /usr/local/bin/shout, for /shout <person> <when?=now>
printf 'HEY %s, %s!\n' "$ISOLINK_ARG_PERSON" "$ISOLINK_ARG_WHEN" | tr a-z A-Z
```

```sh
isolink-relay bot rule add House --command "/shout <person> <when?=now>" --run /usr/local/bin/shout
isolink-relay bot rule add House --command /shout --run /usr/local/bin/shout
isolink-relay bot rule add House --command /weather --timeout 10 --external wttr.in \
  --run /usr/local/bin/weather
```

What it prints is the answer, cut at 4000 characters. Printing nothing sends no answer. A
program gets 20 seconds (`--timeout`, up to 300). It runs in `bots/<id>/run/` in the data
folder, with only `PATH`, `LANG`, `LC_ALL`, `TZ` and `HOME` (that folder) from the relay's own
environment. If it exits with an error or runs too long, the bot says "That didn't work." and
the end of its stderr goes to the relay's log. A bot runs two programs at once at most;
another ask meanwhile gets "I'm busy. Try again in a moment." The usual reply limits apply.

`--shell` runs the line through `sh -c` (`cmd /c` on Windows) instead, for pipes. Quote the
whole line. The message still only reaches it on stdin and in the variables. Never put
`$ISOLINK_TEXT` unquoted into the line.

Add `--external host` when the program sends messages somewhere, so members are told.

Only `isolink-relay` on the relay's machine can add rules that ask a model or run a command
line, LLM and speech-to-text profiles, docs and keys. Nothing in the app or in the relay's
protocol can. Admins see those rules in the app with a lock, as *Runs door.sh (set on the
relay machine)*: the file's name, never its folder. They can move other rules around them,
but never change or remove them.

### Programs the app may use

The app can't type a command line. It picks from a list of **allowed programs** instead.
Each one has a name, a fixed path, fixed first arguments, the env store names it gets, and a
short description. The list lives in `bot-programs.json` in the data folder.

The relay machine allows a program anywhere:

```sh
isolink-relay bot programs allow /usr/local/bin/weather --name weather \
  --about "Today's weather" --arg --units --arg metric --env WEATHER_KEY
isolink-relay bot programs list
isolink-relay bot programs disallow weather
```

**A program's own arguments.** A program can say what it takes once, with `--params`, written
as for a [command](#command-arguments). Every rule that runs it takes those arguments too,
unless the rule gives its own, so `/weather Paris` and `/weather city=Paris units=imperial`
work without repeating them on each rule. `{city}` in its `--arg` words is what was given,
each still one argument of its own, and the program gets `ISOLINK_ARG_CITY` and
`ISOLINK_ARGS_JSON` as well. `--arg` may only name arguments it takes.

```sh
isolink-relay bot programs allow /usr/local/bin/weather --name weather \
  --params "<city> <units?=metric>" --arg --city --arg "{city}" --arg --units --arg "{units}"
```

Owners set the same in the app and the relay console, under **Arguments**. `bot programs
list`, the app and the console show them, and the `/` list shows them on each command that
runs the program.

Owners can also allow programs from the app, under **Manage relay › Bots › Programs**. Only
a file in the **programs folder** counts: `programs` in the data folder, or `programs_dir`
(set on the machine only; the app shows it as fixed). Put the file there on the machine,
then tap **Allow**. The relay checks it every time, and before each run:

- Its real path, with links and `..` followed, must be inside the folder.
- It must be a file you can run (`chmod +x`), and nobody else may write to it.
- It must belong to the relay's user or root. On Windows it must be an `.exe`, `.bat` or
  `.cmd`, and the owner isn't checked.

An owner picks the program's name, description, first arguments and env store names in the
app. The app sees only the names in the env store, never the values. Programs allowed on the
machine show *Set on the relay machine* and can't be changed in the app. Members with only
`bots` see the list but can't change it. Every change goes to the relay's log with who made
it, and a line in News tells every member who allowed, changed or disallowed what.

**Adding files from the relay console.** On the console's **Programs** page an owner can
also upload a program or write a script into the folder, read and edit a script, put a new
copy of a file in place, and delete a file. Adding a file doesn't allow it: that is still its
own step, which the console offers in the same form. The relay keeps the folder safe as it
writes:

- A new file's name is up to 64 letters, digits, `.`, `_` or `-`, starting with a letter or
  digit, so it can't name a folder, a path or a hidden file. On Windows it must end in `.exe`,
  `.bat` or `.cmd`.
- An upload comes in pieces under a hidden name, and only takes its own name once it is
  whole, as a file of the relay's user that only that user can read, write or run (`700`).
  A bot never runs half a program. Uploads are up to 64 MB; scripts edited as text up to
  192 KB.
- It never writes through or replaces a link, never touches a file a program allowed on the
  relay machine points at, and won't write over a file unless asked to replace it.
- A file an allowed program runs can't be deleted until it is disallowed. Replacing or editing
  it changes what that program runs, so News tells every member, as it does when a program is
  allowed.
- The relay's log records each file written, with the start of its SHA-256, and who wrote it.
  Only owners can read or change files; members with `bots` don't see them.

Turn this off with `program_files_from_app = false` on the relay machine. Owners can then
still allow files you put in the folder, but not add, edit or delete them.

> **Warning.** An owner's account can now put a program on the relay machine and run it as the
> relay's user. Keep owners to people you'd give a shell on that machine, sign in to the
> console with a passkey, and turn `program_files_from_app` off if you'd rather add programs
> on the machine yourself. Keep the folder writable by the relay's user and root only.

A rule made in the app names an allowed program. After the program's own arguments it may
add up to 8 more, each one argument of its own, never through a shell:

| Word | What it becomes |
|---|---|
| `{text}` | The message after the command. |
| `{name}` | The sender's name. |
| `{chat}` | The chat's id. |
| `{city}` | One of the command's [arguments](#command-arguments), or the program's. The rule is refused when neither takes it. |
| a plain word | Itself: letters, digits and `. , : = + -`, not starting with `-`. |

The relay refuses anything else, and checks that the program is on the list. The message
still arrives on stdin and in the `ISOLINK_` variables, as with `--run`. The timeout, output
limits and run folder are the same too. A message can start with `-`, so put `--` last in
`--arg` if the program reads options. If a program is disallowed, or its file stops passing
the checks, its rules answer "That didn't work." and the log says why.

## Tools on members' devices

A bot can ask a member's device to do a few fixed things: share where it is, ask a question,
set a reminder. The app has a fixed set of tools. A bot names one and gives its arguments. It
can never send code to run.

| Tool | Arguments | What comes back |
|---|---|---|
| `get_location` | none | `lat`, `lon`, `accuracy_m`. Rounded to about 1 km unless the member chose *Exact* for that bot. |
| `set_reminder` | `text`, and `at` or `in_minutes` | A note with the text in the bot's chat, and a reminder on it then. It shows in the member's **Reminders**. `reminder` (its id) and `at`. |
| `list_reminders` | none | `reminders`: `id`, `text` and `at` of each reminder waiting in this bot's chat. Never other chats. |
| `cancel_reminder` | `id` | Cancels one of the reminders in this bot's chat; `cancelled`. Any other id is `no such reminder`. |
| `ask_choice` | `question`, `options` (2 to 10) | `choice`: the option tapped. |
| `ask_text` | `question` | `text`: what the member typed. |
| `send_card` | `card` | An interactive card sent from the member into the chat; `message` is its id. |
| `save_card` | `card` | The card shows in the chat with a live preview and **Save to My cards**, **Edit first** and **No thanks**. `outcome`: `saved` (with `card`, its id in My cards), `edited` (saved from the editor) or `declined`. |
| `pick_file` | `prompt`, `kinds` | The member picks a file. It arrives as a normal attachment; `name` and `message` say which. |
| `open_link` | `url` | The link shows first, and opens when tapped; `opened`. |
| `schedule_message` | `text`, `at` | A message from the member to this bot, sent at `at`. |
| `run_command` | `name`, `args?` | Computers only: one of the commands the member added under **You → Bot commands**, with its arguments by name (`{"city": "Paris"}`) or as one line. `exit` and `stdout` (up to 4 KB). A wrong or missing argument comes back as an error with the command's usage. |

Times are ISO 8601 with a time zone, e.g. `2026-10-19T09:00:00+01:00`.

**Commands on a computer with arguments.** A member adds a command under **Bot commands** with
a name, a command line and, if it takes any, **Arguments**, written as for a
[relay command](#command-arguments): `weather <city> <units?>`. `{city}` in the line is
what the bot gave, as one word of its own (`weather --city={city} {units}`), and the program
gets `ISOLINK_ARG_CITY` and `ISOLINK_ARGS_JSON` as well. A **Run in a shell** line never has
the values in it: it reads the variables. The app refuses a line that uses an argument the
command doesn't take. A bot sends `{"name": "weather", "args": {"city": "Paris"}}`; one with a
missing, unknown or extra argument gets the usage back, and nothing runs. The small line in
the chat says what it ran with: *House ran weather city="Paris", exit 0*.

**Which tools a bot offers.** New bots offer `set_reminder`, `list_reminders`,
`cancel_reminder`, `ask_choice`, `ask_text`, `send_card` and `save_card`. Bots made before
these defaults keep the four they had (`ask_choice`, `ask_text`, `send_card`, `set_reminder`)
until an admin chooses. Location, files, links, scheduled messages and commands are opt-in
per bot:

```sh
isolink-relay bot tools House                      # what it offers now
isolink-relay bot tools House get_location,ask_choice
isolink-relay bot tools House all                  # or: none
```

Admins with the `bots` scope set the same from the bot's page in the app, under **What it may
ask devices for**. Members see what a bot offers on its contact page before it ever asks.

**From a model.** An `--llm` rule gives the model the bot's tools: Anthropic `tools`, OpenAI
`tools` and Gemini `functionDeclarations`, each with a JSON schema. When the model calls one,
the bot asks the member's device and waits up to 2 minutes. The model goes on with what came
back (`tool_result`, a `tool` message, or a `functionResponse`). Several calls in one turn go
one after another, at most 5 in one answer. A model that keeps asking after that gets *That
didn't work.*

**From a fixed rule.** `--tool` asks the device first, with `--args` as a JSON object. The
`--reply` goes after it, with `{result}` replaced by what came back:

```sh
isolink-relay bot rule add House --command /day --about "Pick a day" \
  --tool ask_choice --args '{"question": "Which day?", "options": ["Sat", "Sun"]}' \
  --reply "See you on {result}."
```

A single value goes in as it is; anything else as JSON. If the member says no, or doesn't
answer, the bot sends nothing and the relay's log says why.

**From a program.** Not yet: a `--run` program can't call tools. Printing `@tool <name> <json>`
is planned.

### What the member decides

Each device keeps its own list for each bot and each tool: **Ask** (the default), **Always** or
**Never**. `run_command` starts at **Never**. A call set to Ask shows a small card in the chat:
*House wants to see your location*, with **Don't allow**, **Once** and **Always**. A question
(`ask_choice`, `ask_text`), a card to save (`save_card`), a link and a file picker are their
own prompt: the member answers, or says no, so they are only **Ask** or **Never**. Every use shows as a small line in the chat, such as *House saw your location*.
The list follows the account to its other devices, like pinned and archived chats; commands
stay on the computer that has them.

### The threat model

Bots can ask; devices decide.

- A call goes to the device the member last wrote from, and is checked there, against that
  device's list, every time. Nothing on the relay can turn a tool on for a member.
- Devices take calls only from bots their relays list, and only for tools that bot offers.
  A call from a person is ignored. An unknown tool is answered `unknown tool`.
- A device takes at most 10 calls a minute from one bot. A call nobody answers ends after 2
  minutes with `no answer`.
- Results go back in the encrypted chat to the bot that asked, and to nobody else. Calls and
  results never show as messages.
- Commands are desktop-only and user-defined. Phones never run them. A bot names a command;
  it never sends one. The command line runs without a shell, split into the program and its
  arguments, unless the member ticked **Run in a shell** for it. Its output shows in the chat.
- Location is rounded to about 1 km unless the member chose Exact for that bot.
- What a device sends back reaches the relay's bot, and so whoever runs the relay, and a
  model's service when an `--llm` rule asked.

## The env store

Secrets for bots, such as API keys, live in `env.json` in the relay's data folder. Only the
relay's user can read it: mode 0600, owned by `isolink-relay` on Linux (the command runs as
that user), and on Windows only the service account (LocalSystem) and Administrators.

```sh
isolink-relay env set ANTHROPIC_API_KEY      # asks for it without showing it
printf '%s' "$KEY" | isolink-relay env set GEMINI_API_KEY
isolink-relay env import keys.env            # NAME=value lines
isolink-relay env list                       # names and when each was set
isolink-relay env unset GEMINI_API_KEY
```

A value never goes on the command line, so it stays out of the shell's history. Values never
cross the relay's protocol, never reach the app, and never show in the log, `config`, `llm
list` or `env list`. An LLM or speech-to-text profile's `--key-env NAME` reads `NAME` here
first. A `--run`
program gets only the names its rule lists with `--env NAME`, never the whole store.

> **Warning.** Anyone with root or administrator rights on the machine can read the store.

## Greeting, News and forums

Set `greeting` to welcome people: `isolink-relay config set greeting "Welcome to our relay."`
Members see it on the relay's page under Settings → Relays. With a house bot, someone who joins also finds it
at the top of the bot's chat.

**News** is one read-only chat per relay. It holds posts from admins with the `announce`
scope (text, and one photo or file) and short lines from the relay itself: a bot or someone
joined, the relay was updated or renamed, a forum was made. Members can't reply or react. The
app shows it as a row at the top of Chats and raises one notification for each new post.
`isolink-relay announce "text"` posts to News from the relay machine. `news_keep` sets how many
items it keeps. Older apps see the newest post as the relay's announcement; an encrypted one
reads *A new post is in News. Update Isolink to read it.*

**Forums** are boards on the relay. Every member sees every forum, joins the ones they like,
posts (a title, text, and up to 10 photos, videos or files of up to `forum_file_bytes` each)
and comments (one file each; replies go one level deep). Each account has one up or down vote
on each post and comment. Posts sort by Hot, New or Top. Members with `forums` make forums;
with `forums_by_members` set to `true`, every member may. Who may is the policy key
`request.forumCreate`, so it can name roles too. A forum's maker edits and deletes
it. Authors edit and delete their own posts and comments; members with `forums` remove any,
pin posts and lock forums. Guests see neither News nor forums. A post goes `forum_ttl` after
its last comment. Files take `forum_bytes_per_account` and `forum_bytes_total`.

### End-to-end encrypted, with one key per relay

What people write in News and forums is end-to-end encrypted with a **relay key**: 32 random
bytes that only members' devices hold. The relay keeps and passes on ciphertext. It sees who
posted, when, how big things are, votes and counts. Files are sealed with a key of their own,
which travels inside the encrypted post.

The first member to post makes the key. A member's device without it asks the relay, and the
relay asks up to three online devices that hold it. One of them checks the asking device's
signed keys and seals the relay key to it. Until it arrives, the app shows *Waiting for a
member's device to share the key*. The key is in members' chat backups.

What this protects against, honestly:

- A stolen disk, a backup copy of the data folder, a hacked relay process or a curious admin
  reading files can't read News or forums.
- Anyone the relay admits as a member can read them: members' devices hand the key to new
  members, and the relay decides who is a member. So someone who runs the relay can join, or
  make a member up, and read them, as in any group anyone can join.
- Removed members keep the key they had. The relay stops serving them anything.
- Posts and forums made on the relay machine (`announce`, `forum add`), News posts from older
  apps and the relay's own lines are not encrypted. The app marks them *From the relay*.

## Card library

Members share cards on the relay, and anyone on it can browse and save them. A card is a JSON
object of up to 768 KB, as JSON, with an `id` and a `title`. The relay stores it with who published it
and when, and reads nothing else in it. Publishing the same id again replaces your card.
Someone else's id is taken. Only the publisher, or someone with the `cards` scope, can remove a card. The library is
for members only: there is no web address for it. `cards_per_account` and `cards_total` set
its size.

## Card templates

A relay can host its own card templates: starting points every member sees, in a section
named after the relay, when they make a new card. Members with the `cards` scope choose them:
in the app, from a card in My cards with **Make it a relay template**, or under **Manage →
Card templates**; on the admin page, under **Card templates**, by pasting a card code. Each
template has a name, a line about it and what it's for (plans, polls, lists, games or tools).
Key values are taken out before a template is kept, and a member's copy is a card of its own.
`templates_total` sets how many it holds.

## Smart pills

Members' apps draw bits of a message as small pills: links, phone numbers, colours, dates,
parcel numbers and more. A relay can add its own kinds, such as its game's friend codes or a
courier's tracking numbers. Its rules follow the same schema as the app's own
([docs/smart-pills.schema.json](../docs/smart-pills.schema.json)) and pass the same checks,
and members get them with the relay's info when they connect. Each shows as its own switch in
the app under **Settings → Chats → Smart pills**. Guests don't get them.

They live in `pills.json` in the data folder, read again when it changes:

```sh
isolink-relay pills add switch --name "Switch friend codes" \
  --pattern '\b[A-Z]{3}-\d{3}-\d{3}\b' --case-sensitive --icon 🎮 \
  --program user-add-info --open 'https://example.com/u/{0}'
isolink-relay pills test switch "add me ASD-123-455"   # what it finds, and what the program says
isolink-relay pills list
isolink-relay pills import rules.json                   # a whole file, checked first
isolink-relay pills remove switch
```

A rule's `ask` names an allowed program (`bot programs`) or a bot and one of its commands.
The app asks the relay about each match as the pill shows, and the answer draws the pill and
fills its sheet. A program gets the match in `ISOLINK_TEXT` (and the member in
`ISOLINK_FROM` and `ISOLINK_NAME`) and prints JSON:

```json
{ "label": "Joe", "detail": "10 mins ago", "image": "avatar.png",
  "title": "Joe", "subtitle": "Online 10 mins ago",
  "fields": [{ "label": "Friend code", "value": "ASD-123-455" }],
  "actions": [{ "label": "Profile", "open": "https://example.com/u/ASD-123-455" }],
  "ttl": 600 }
```

The pill then reads "(Joe's picture) Joe · 10 mins ago". `image` names a PNG, JPEG or WebP
of up to 64 KB the program wrote to `ISOLINK_OUT`. Every key is optional, and output that
isn't JSON shows as text in the sheet. A bot command gets the match as its arguments, and
its fixed reply or program's output is read the same way; commands that use a model or a
member's tools can't answer pills. Actions with `program` or `bot` run when the member taps
them, and their answer fills the sheet.

What keeps this safe: the relay only runs a program on words its own rule finds (up to 200
characters), for members, at most 30 a minute for each connection and 4 at once across the relay. A relay's
rules can open only `https:`, `tel:`, `sms:` and `mailto:` links, with the site fixed, and
can't use the app's `open` action on the match itself. Patterns that could take forever
(repeated repeats, back-references) are turned down. `request.pill` in the policy sets who
may ask. At most 30 rules, and a broken `pills.json` hands out none (`pills list` says why).

## Map tiles

A relay can hand its members map tiles, so shared locations draw on a real map and members
can save **Offline map areas** before a trip without each setting up a tile server of their
own. Set `tile_server` to a tile URL with `{z}`, `{x}` and `{y}`:

```sh
isolink-relay config set tile_server 'https://tiles.example.org/{z}/{x}/{y}.png?key=YOURKEY'
isolink-relay config set tile_credit '© OpenStreetMap contributors © Example Maps'
```

Owners can set it from the app (**Manage relay → Settings**, under Maps) or on the admin page too. The
app picks it up the next time it connects, or when someone opens **Offline map areas**.

- **Licensing is yours to check.** Use a tile server whose terms let you pass its tiles on to
  your members and let them keep tiles for offline use: your own (such as one serving
  OpenStreetMap data with [TileServer GL](https://tileserver.readthedocs.io/) or
  [OpenMapTiles](https://openmaptiles.org/)), or a provider whose plan allows it.
  OpenStreetMap's own `tile.openstreetmap.org` forbids both, and the relay refuses it. Put
  whatever credit the terms ask for in `tile_credit`; the app shows it on every map, and
  shows OpenStreetMap's credit when it is empty.
- **The URL stays on the relay.** Members' apps ask for tiles over their relay connection,
  so the tile server sees only the relay and a key in the URL never reaches a phone. The
  relay's log names only the tile server's host.
- **Bandwidth and caching.** The relay keeps the tiles it fetches in `tiles/` in its data
  folder, up to `tile_cache_bytes` (1 GB by default), so members share one download; the
  least used go first, and a tile is fetched again after 30 days. It fetches at most four at
  once. Each device can get `tiles_per_minute` tiles (600 by default), enough to save an
  area at the app's pace. The app keeps at most 20,000 tiles in an area and 200 MB of areas
  in all, so that's the most one member's saving can fetch.
- **What the relay learns.** Like any tile server, the relay sees which tiles members look
  at, so roughly where. Tiles are for members only.
- **How the app chooses.** A tile server set in the app (**Offline map areas → Tile
  server**) wins. Without one, the app uses the first relay it's a member of that hands out
  tiles, and saves areas from it. Tiles and areas from it stay on the phone when the relay
  can't be reached.

Change `tile_server` and the relay starts a fresh cache; empty it to stop. `request.tile`
in [Policies](#policies) can limit tiles to admins or turn them off without forgetting the
server.

## The Isolink store

The app's **Browse** tabs (Theme Studio → Library, and My cards) list theme packs and cards
from the [Isolink store](https://github.com/orimovo/isolink-store). Apps never fetch it
themselves: their relay does, and hands it to members over the connection they already have.
So the store's host sees only the relay, never a member's address or what they pick.

It is on by default. `theme_stores` lists the stores the relay pulls, separated by spaces (at
most 8). The default is Isolink's own. Another store must be named with the account that signs
its index, after a `#`, so the relay and the app can check it:

```
isolink-relay config set theme_stores 'https://raw.githubusercontent.com/orimovo/isolink-store/store/ https://packs.example.org/#0123456789abcdef0123456789abcdef'
isolink-relay config set theme_stores ''   # off
```

- **Checked twice.** The relay fetches a store's `index.json` at most once an hour (an admin
  can fetch it now from Manage relay → Maintenance → **Refresh store**) and keeps it
  only when its signature checks out and its `seq` hasn't gone back. It fetches a pack, card or
  thumbnail only when a member first asks for it and the index lists it, and keeps it only when
  its size and SHA-256 match. The app checks the index, the hash and the pack's own signature
  again before keeping anything.
- **Kept on disk** under `packs/` in the relay's folder, up to `store_cache_bytes` (1 GB by
  default), least recently used first out. Taking a store out of `theme_stores` drops its files.
- **In pieces.** Files go to members 256 KB at a time, so the app shows progress and can stop.
  `store_files_per_minute` (600 by default, about 150 MB) limits pieces per device. Past it the
  relay says how many seconds to wait, and the app waits that long and carries on, so a big pack
  or a screen of pictures is slower rather than refused.

`request.storeIndex` and `request.storeFile` in [Policies](#policies) can limit the store to
admins or turn it off for members.

## Backups on your relay

Members can keep their latest chat backup on their relay. In the app, go to **You → Chat
backup** and turn on **Keep a copy on my relay**. The app shows a relay backup code. It holds
the relay's address, its certificate pin, a random slot id and a secret. Save it somewhere
away from the phone.

The backup is the same file as a backup saved to the phone, locked with your passphrase. The
relay stores only that ciphertext. Each account has one slot of up to
`backup_bytes_per_account`. Leaving the relay, or being removed from it, deletes it.

The slot keeps up to `backup_versions` versions, so you can roll back. The relay keeps every
version from the last 24 hours, then the newest of each day for 7 days, then the newest of
each week for 5 weeks. All versions together stay within `backup_bytes_per_account`; the
oldest go first. The newest is always kept.

Once a passkey, password manager or saved passphrase holds the backup's passphrase, phones
and desktop apps back up automatically about 15 minutes after the last change, at most hourly,
and at least daily while anything changes. A browser with a recovery passkey starts backing
up changed chats after about 15–30 seconds and spaces further uploads or retries a minute
apart. It also tries to finish a pending backup when the tab is hidden. The phone app
checks on start and from the always-on service. It
skips the upload when nothing changed, and holds off on battery saver below 20%. To roll
back, go to **You → Chat backup → Earlier versions**. Your current chats go up as a new
version first, so a roll back can be undone.

To restore on a new phone, set up Isolink, then go to **You → Chat backup → Restore from my
relay** and enter the code and the passphrase. The relay hands the backup over only to a
device that proves it holds the secret. The new phone needs no invite, and this works on a
relay that takes no guests.

### Passkeys and password managers

Under **Protect it with** the app can keep the code and passphrase for you, in one or more
ways. Keep at least two.

- **Passkey.** The app makes a passkey for `isolink.app` in your phone's password manager,
  using the WebAuthn PRF extension. The passkey gives 32 secret bytes. HKDF-SHA256 turns them
  into a key, which seals the backup's passphrase with AES-256-GCM. The sealed passphrase goes
  to the relay as the slot's `meta`. The passkey's user handle holds the slot, its secret, a
  4-byte hash of the relay's URL and the first 10 bytes of its certificate pin. To restore,
  pick the passkey. If the new phone has not joined the relay, type its address: the app
  checks it against the hashes before it sends anything. The passkey's name shows the relay's
  address. Deleting the passkey means this backup can't be opened with it.
- **Password manager.** One entry, named "Isolink backup · relay address", holds the relay
  backup code and the passphrase as `<code>#<passphrase>`.
- **Passphrase.** The code and a passphrase you keep yourself, as above.

Once any of these is set up, the passphrase stays the same from one backup to the next. If you
pick a passkey or password manager first, the app makes a random passphrase. The relay never
sees the passphrase or the passkey's output.

### Recovering the account with a passkey

A backup holds chats, never the account, so restoring onto a new phone normally lands in a
new account: contacts see a new person to verify, and groups need a new invite. Under the
backup's passkeys, **Recover my account with this passkey** changes that. It is off unless
chosen, because whoever holds the passkey can then be you.

Turning it on asks for the passkey. The app makes a random 32-byte recovery key, seals it
under the passkey's PRF output (HKDF-SHA256 with its own label, then AES-256-GCM), and seals
the account key, its chain, the name, the account's devices and its relays under the recovery
key. Both go into the slot's `meta` next to the sealed passphrase, and the account is sealed
again with every backup, so a rotated key or a new device is in the next one. Passkeys added
later recover it too. Turning it off takes the account out of the `meta`.

On a new phone, picking that passkey to restore offers **Recover my account**. The phone
becomes another device of the same account, as if it had been linked: contacts and the
account's other devices hear of it, and it rejoins the account's relays. Mail held for the
old phone is lost, being sealed to its keys. Only a phone with no chats of its own yet can be
taken over. The relay's `meta` limit is 16 KB, so a relay older than this release refuses it.

## Error reports

When something goes wrong in a member's app (a crash, or a Bluetooth link that fails), the app
leaves an anonymous report on each relay its account is a member of, the next time it's
connected. Members with the `maintain` scope read them under **Manage relay → Error reports**,
copy one into a bug report, and clear them.

A report holds what broke (the error's message, cut to 300 characters), where (the part of the
app, and the stack's frames: lines that name code, up to 120 of them), the app's version, the
platform (`android`, `ios`, `windows` and so on) and its OS version, and what the app was doing:
the short debug report's connection state and its newest events, up to 16,000 characters,
taken when the problem happened. Before it leaves the phone, the app swaps contact and account
ids, names, emails, addresses and anything key-shaped for placeholders, exactly as the debug
report does; drops quoted text from the message, since an error may quote what it was reading;
drops the user's name from home folder paths; and keeps no stack line that isn't code. No
message text, keys, account, device or phone model go with it. A relay from before reports
carried the OS and context gets the report without them, and a stack of up to 40 lines.

In **Error reports**, a report shows its app version, platform and OS, the stack trace and what
the app was doing. **Copy all**, **Save**, **Share** and **Send in a chat** pass the whole report
on as text or as a `.txt` file; the debug report has the same four.

The relay doesn't note which member sent a report, in its files or its log. It groups reports
of the same problem (by its kind, where, message and top frames, with numbers left out) and
keeps the newest report of it with a count, the app versions and platforms it came from, and when it was first
and last reported, to the hour. Each connection counts once for a problem and may send 30
reports an hour. It keeps 200 problems at most, dropping the one seen longest ago, and forgets
a problem `error_ttl` after it was last reported. They live in `errors.json` in the data folder.
On the relay machine, `isolink-relay errors list` lists them, `errors show <id>` prints one in
full, and `errors export -o errors.json` writes them all out: add `--from 2026-11-01`
and `--to 2026-11-03` for only the problems reported on those days, and `--text` for plain text
rather than JSON. The web console's **Error reports** page and the app's error reports screen
export the same way. The running relay writes new reports to `errors.json` every 30 seconds.
The hosted relay at relay.isolink.app takes error reports unless `RELAY_SETTINGS` turns
`error_reports` off.

On a small relay a report can still hint at who sent it: a problem only one member's platform
has, for example. Members turn reports off in the app under **Settings → Advanced →
Error reports to relays**, which also forgets any waiting. Owners turn them off for the whole
relay with `error_reports` set to `false`. The app sends the same problem to a relay at most once
a day, keeps at most 20 waiting, and sends only to relays that say they take them.

## Finding faults

When something doesn't work, start with:

```sh
isolink-relay doctor        # what's wrong, and how to fix it
isolink-relay status        # running, version, devices online, each bot's state
isolink-relay bot log House # what a bot did with each message
isolink-relay logs -f       # the relay's log as it happens
```

`doctor` checks that the relay is running and can read every file in its data folder, that
its settings and `bots.json` load, that each bot started, has rules, and that each rule's
model or program is there. It checks that the relay can see each model's key: in the env
store, in its key file, or set by the systemd service (an update rewrites
`isolink-relay.service`, so an `Environment=` line put straight in that file is lost: use
`env set`, or a drop-in). It points out a bot that had errors in the last day, or took
messages and answered none, and reported problems and updates.

**The relay log.** Everything the relay prints also goes to `logs/relay.log` in the data
folder, rolling over at 1 MB into `relay.log.1`. `isolink-relay logs` prints the newest
lines, `-n` how many, `-f` follows. Lines older than `log_ttl` (30 days unless set) are
dropped, from bots' logs too. Members with `maintain` read it in the app under
**Manage relay → Relay log**, and in the console under **Log**; both have a live view that
follows new lines as they come, with a filter and a choice of levels (problems, warnings,
everything).

**A bot's debug log.** Each bot keeps `logs/bot-<id>.log` (256 KB, then `.1`): each message
it took (who, by the start of their account id, and its kind and length, never its words),
which rule answered or why none did (not a member, a group chat, the rate limit, no rule
matched, voice notes off), which model or program ran, how long it took, and what failed,
such as `HTTP 401: invalid x-api-key` or `no answer within 60 s`. Members with `bots` read it
in the app on the bot's page, under **Debug log**, which also says when a bot could not start.

**Nothing secret goes in.** Every line is scrubbed before it is written or printed, in the
journal too: values from the env store, LLM key files and key variables come out by name
(`[redacted ANTHROPIC_API_KEY]`), and so does anything shaped like an API key, a bearer token,
a password or a private key.

**A report to share.** `isolink-relay report -o report.json` puts the status, the doctor's
checks, changed settings, the bots and their rules (what they answer and what runs them, not
the words of fixed replies), the models (provider, model, where the key comes from, never the
key), member and device counts, error reports, and the last 500 lines of each log in one
file. It goes through the scrubber as a whole.

The running relay writes how it is doing to `status.json` in the data folder every 30
seconds, for `status` and `doctor`.

## How it works

1. **Connecting.** A device opens one WebSocket to `/v1/relay`. The relay sends a random
   challenge. The device answers with its signed bundle and an Ed25519 signature over the
   challenge and the relay's host name. The host name is included so a malicious relay can't
   pass the answer on to another relay.
2. **Members and guests.** If the device's account matches a member record, and its chain of
   account keys extends the stored one, the device is a member. Otherwise it is a guest. A
   device certified by an older account key, such as a device that was removed, is a guest.
3. **Circuits.** `open {c, to}` asks for a circuit to an online device. The relay allows it only
   if one end is a member. Binary frames carry a 4-byte circuit number followed by the bytes.
   Each circuit carries an ordinary Isolink link, which the hub authenticates end to end. In
   the hub the transport is called `server`; it has priority 60 and is fallback only.
4. **Invites from admins.** `invite {id, name?}` from a device with the `invite` scope gets
   back `invite {id, code}`, a one-time invite for 3 days that gives no scopes; anyone else
   gets `inviteFailed`. The `welcome` message says `admin: true` when the account holds every
   admin scope, `owner: true` to owners, and `scopes` lists what the account may manage.
5. **Mail.** `drop {to, item}` leaves the same sealed, tag-addressed envelope that contacts
   carry for each other. The relay pushes it to the member when it connects and deletes it
   when the member acknowledges it.
6. **Finding a contact's relay.** Over an authenticated link, devices send a `relays` frame with
   the URL and certificate pin of every relay their account belongs to. The newest list wins
   across your own devices.
7. **What members learn.** A member's `welcome` also carries `greeting`, `bots` (each with
   `id`, `name`, `account`, `code`, `house` and `external`, the hosts it sends messages to) and `announcement` (`id`, `text`, `at`, `by`),
   the newest News post for older apps.
   A new one reaches connected members as `announcement {a}`, with `a` null when none is left.
   `relay` describes the relay: `name`, `description`, `iconHash`, `emoji`,
   `color`, `version`, `since` (when it started), `members`, `online`, `guests`, `mailTtl`
   (seconds), `space` and `used` (this device's mail space), `held` (items waiting for the
   account), `owners` (their names) and `backup` (`size`, `at`). `botNews` lists bots that
   joined lately (`id`, `bot`, `at`); a new one reaches connected members as `botJoined
   {news}`. When someone changes what an account may do, its connected devices get `you
   {member, admin?, owner?, scopes}`. News and forums add `news` (the newest 50 items, oldest
   first), `newsMore`, `forums`, `replies` (the newest 20 to this account, newest first),
   `forumsByMembers` and `relayKey` (the id of the relay key, or null); see step 12.
8. **Requests.** The card library and older apps' announcements use requests with an `id`.
   The relay answers `done {id, …}` or `failed {id, why}`. `cardPublish {card}`, `cards
   {from}` (a page, with `next` for the one after), `cardRemove {card}` (your own, or any with
   the `cards` scope) and `announce {text}` (the `announce` scope: a News post in the clear;
   empty text deletes the newest post). Guests get `members only`.
9. **Backups.** A device that says `for: backup` in its `hello` gets a side connection. It is
   never reachable, replaces no other connection, skips the guest policy and can do nothing
   but backups. Members upload with `backupStart {slot, key}`, then `backupChunk {i, data}`
   pieces of the size the relay gives, then `backupEnd {size, sha}`. `key` is an HMAC of the
   secret in the relay backup code. To fetch, a device asks for `backupNonce`, then sends
   `backupOpen {slot, proof}`, with `proof` an HMAC of the nonce and slot under `key`. Then
   `backupRead {i}` returns each piece. Five wrong proofs close the connection. An unknown
   slot and a wrong proof get the same answer. `backupStat` and `backupDelete` look after a
   member's own backup. `backupStart` may carry `meta`, a string of up to 4096 characters
   the relay keeps with the slot without reading it; `backupMeta {meta}` replaces it (null
   clears it) without a new upload. The answer to `backupOpen` includes `meta`, so only a
   device with the slot's secret sees it. It goes when the slot does, and is one for the slot,
   whatever the version.

   **Versions.** `backupStart {slot, key, meta?, version: true}` makes a new version, numbered
   by the relay from 1 and returned in `backupEnd`'s answer as `version`; older versions are
   then pruned as the retention rule above says. Without `version` (a device from before
   versions) the upload replaces every version with one numbered 0, as a single slot did.
   `backupList` returns `versions: [{version, at, size}]`, newest first, for the slot the
   connection opened with `backupOpen`, or a member's own. `backupOpen` and `backupRead` take
   an optional `version`, the newest by default, and `backupOpen`'s answer says which it
   opened. `backupDelete {version?}` deletes one version, or all of them. `backupStat` lists
   the versions too. Only wrong proofs count towards the five, so one connection can open
   several versions. A relay from before versions answers `backupList` with `failed bad`;
   the app then shows the one backup `backupOpen` gave.
10. **Bots.** A bot is a device inside the relay's process. It signs in like any other device,
    through a socket in memory, and its member record says `bot: true`.
11. **Relay information and admin requests.** These use the same `{t, id, …}` requests and
    `done`/`failed` answers. Guests get `members only`; members without the permission get
    `not allowed`. Bad input gets `bad`, often with a `detail` a person can read. While
    [maintenance mode](#maintenance-mode) pauses changes, those from members without
    `relay.maintenance` get `maintenance`, with `maintenance` describing it.

    The table names the older scope each request needed; it now needs a permission that scope
    stands for, such as `members.view` for `adminMembers` or `relay.restart` for `adminRestart`.
    `welcome` and `you` also carry `roles` (the role ids the account was given), `base`
    (`member` or `guest`, the base role it holds besides) and `perms` (every permission it
    holds, roles and all), and `welcome` carries `maintenance` while it is on. A change to any
    role re-sends `you` to every connected device, guests included. A
    change reaches connected devices as `maintenance {maintenance}`, null when it ends; at
    `closed`, devices without `relay.maintenance` get `refused {why: maintenance,
    maintenance}`.

    | Request | Scope | Answer (`done`) |
    | --- | --- | --- |
    | `relayInfo` | any member | `relay`, as in `welcome` |
    | `relayIcon` | any member | `icon` (base64url), `iconHash` |
    | `adminStatus` | any scope | `online`, `maxDevices`, `guestsOnline`, `held`, `heldMax`, `backups`, `backupMax`, `forums`, `forumsMax` (space News and forum files take), `health` (`good`, `busy`, `full`), `update`, `canUpdate`, `canRestart`, `version`, `since`, `owner`, `scopes`, `schema`, `manage` (Manage relay's settings sections, each `id`, `label`, `list` as in `adminSettings`; Maintenance moves to Settings on a hosted relay) |
    | `adminMembers` | `members` | `list` of `account`, `name`, `joined`, `owner`, `bot`, `scopes`, `devices` (`id`, `online`, `seen`), `held`, `backup` |
    | `adminRemove {account}` | `members` | Removes a member: devices become guests, the backup is deleted. Never an owner (`owner`), a bot or yourself. |
    | `adminScopes {account, scopes}` | `grant` | Sets a member's permissions from older scopes. Only owners give or take `grant`; owners can't be changed. |
    | `adminAccess {account, roles, perms}` | `members.roles` | `roles`, `perms`, `scopes`. Replaces what a member holds. Nobody gives what they don't hold or changes someone who holds more; only owners give or take `members.roles`. |
    | `adminRoles` | any permission | `roles` highest first (`id`, `name`, `about`, `perms`, `builtIn`, `held`, `base` on Member and Guest, `noPerms` on Guest, `joining`, `rank` on the relay's own), `defaultRoles`, `areas` (every permission by area), `heldMax`, `limits` |
    | `adminRoleSave {role?, name, about?, perms, limits?, ai?, rank?, joining?}` \| `adminRoleDelete {role}` | owners | `role`. Without `role`, makes one. Built-in roles get `fixed` for other permissions, except Member, whose permissions change. `rank` places one of the relay's own, from 0 at the top; `joining` puts it in `default_roles` or takes it out. |
    | `adminDeviceRevoke {account, device}` | `members.devices` | Signs a device out: it connects as a guest until it is linked again. |
    | `adminMaintenance` | any permission | `maintenance` (`level`, `note`, `until`, `since`, `by`), or null |
    | `adminMaintenanceSet {level?, note?, until?}` | `relay.maintenance` | `maintenance`. Without `level`, turns it off. `until` is at most 30 days away. |
    | `adminInvites` | `invite` | `list` (unused: `id`, `name`, `by`, `owner`, `scopes`, `created`, `expires`), `used` (`name`, `account`, `by`, `at`) |
    | `adminWhichMembers` | `invite` | `accounts` (up to 1000) in; `members`: the ones among them that are members, bots left out |
    | `adminInvite {name?, days, roles?, perms?, scopes?}` | `invite` | `code`, `expires`. `days` is 1 to 30. Roles, permissions and scopes need `members.roles`, and only what the inviter holds. |
    | `adminRevoke {invite}` | `invite` | Cancels an unused invite by its id. |
    | `adminGuests` | `guests` | `policy`, `fixed`, `allowed` (`id`, `kind`, `name`, `added`), `refused` (`account`, `device`, `name`, `at`) |
    | `adminAllow {allow, kind, name?}` \| `adminDisallow {allow}` | `guests` | Adds an account or device to the allow list, or takes it off. |
    | `adminSettings` | `settings` | Takes `lang` (the app's language). `editable`, `schema` (1), `lang`, `sections` (`id`, `label`, `page`: `manage`, `settings` or `own`, in order), `list` (`key`, `kind`, `value`, `default`, `set`, `fixed`, `label`, `help`, `summary`, `icon`, `shape`, `choices`, `section`, `order`, `common`, `limits` (`min`, `max`, `maxLength`), `format`, `long`, `change` (the permission, or `owner`), `can` (this caller may change it)), `policy` (each key with its `roles`, `groups`, `perms`, `off`, nearest `level`, `custom`, `defaultSet`, `default`, `set`) |
    | `adminUi` | any scope | Takes `page` (`manage`, `programs`, `log`), `lang`, `kinds` and `screens` (what the app draws). `ui` (1), `title`, `sections` (`id`, `label`, `items`: `kind` `screen`, `page`, `action`, `stat`, `setting` (with `setting` as in `adminSettings`), `files` (`list`, `read`, `write`, `remove`, `upload` requests), `log` (`source`) or `web` (`view`: a console page), with `id`, `label`, `summary`, `icon`). Only rows the member may see and kinds and screens the app named. |
    | `adminWebSignIn` | any scope | Takes `view` (a console page such as `models`). `url`: the console at that page with a one-time sign-in for this member (2 minutes, then a 1 hour session) and without its own bars, for the app to show. |
    | `adminSet {key, value, exact?}` \| `adminUnset {key}` | `settings` (`guests` for the `guests` key, `policy.change` for `policy`, owners for `default_roles`) | Checked with the relay's own parser, written to `relay.json`, and in effect at once. A key fixed by a `serve` flag gets `fixed`. A `policy` value names only the keys it changes. Without `exact`, a key sent as its nearest level keeps its roles; the reply's `custom` lists keys whose roles aren't a level. |
    | `adminRename {name}` | `settings` | `name`. Empty falls back to the host. |
    | `adminProfile {description?, icon?, emoji?, color?}` | `settings` | `relay`. `icon` is base64url, or null to take it away. |
    | `adminBots` | `bots` | `running`, `bots` (`id`, `name`, `house`, `greeting`, `welcome`, `account`, `added`, `media`, `rules`), `relayRules`. A rule that asks a model shows only `locked: llm`. A `--run` rule shows `locked: run` and `runs`, the program's file name. A rule that runs an allowed program shows `program` and `programArgs`. |
    | `adminBotAdd {name, house?}` \| `adminBotRemove {bot}` | `bots` | `bot` (its id). Adding needs the relay to run its bots (`unavailable` otherwise). |
    | `adminBotRename {bot, name}` | `bots` | `name`. Its account takes the name, and members' apps show it in place of any nickname. |
    | `adminBotGreeting {bot, text, ai?, prompt?}` \| `adminBotMedia {bot, media}` | `bots` | Sets the greeting (with `ai`, its chat model writes each one from `prompt`, and `text` goes when it can't), or which of `audio` and `video` it takes. |
    | `adminBotInstructions {bot, text}` | `bots` | `instructions`. How its AI models should behave; empty text follows the relay's `bot_instructions`. `adminBots` gives each bot's `instructions`, `greetingAi` and `greetingPrompt`, and `defaultInstructions`. |
    | `adminBotDisclosure {bot, text?, banner?, header?}` | `bots` | What a bot that uses AI tells people, and whether it shows as a banner and in the chat header. A part left out stays; null or empty text follows the relay's `bot_disclosure` settings. `adminBots` gives each bot's own `disclosure`, `ai` for bots that use AI, and `defaultDisclosure`. |
    | `adminBotStyleSet {bot, name, prompt, for?, icon?, thumb?, style?}` \| `adminBotStyleRemove {bot, style}` | `bots` | `styles`. A picture style of the bot's own (at most 12): members' apps show its `name` in the picture maker, and the relay draws with its `prompt`, which apps never see. `for` is `restyle` or `background` (both when left out). `style` changes the one with that id. `thumb` is its chip's thumbnail, a base64 PNG, JPEG or WebP up to 256 KB (`false` takes it off, left out keeps it); apps get its hash as `thumb` and fetch it with `botAvatarFile`. `adminBots` gives each bot's `styles`, and the title of its `welcomeCard`. |
    | `adminBotWelcomeCardOff {bot}` | `bots` | Takes off the card that goes with its greeting. Cards are set on the server: `isolink-relay bot welcome-card <bot> card.json`. |
    | `adminRuleAdd {bot, kind, match, reply \| program, programArgs?, accounts?}` | `bots` | `rule`. A fixed reply, or an allowed program with words from `{text}`, `{name}`, `{chat}` and plain words (`bad` with a `detail` otherwise). A request with `llm`, `run`, `shell`, `external`, `env`, `timeout`, `card` or `file` gets `not allowed`. |
    | `adminRuleRemove {bot, rule}` \| `adminRuleMove {bot, rule, to}` | `bots` | `rules`. A locked rule gets `locked`. Moving shifts the other rules among themselves; locked rules keep their place. |
    | `adminPrograms` | `bots` | `owner`, `folder`, `programs` (`name`, `about`, `env` names, `machine`; for owners also `file` and `args` of one allowed in the app). Owners also get `files` in the folder (`file`, `size`, `modified`, `allowed`, `problem`, `link`), `envNames`, `maxBytes`, `maxScriptBytes`, `chunkBytes`, and `canWrite` when they may add files. Never a path or an env value. |
    | `adminProgramAllow {name, file, about?, args?, env?}` | owners | `program`. `file` is a file in the programs folder; anything outside it, after links and `..`, gets `bad` with a `detail`. So does a file that isn't executable, is open to anyone's changes, or belongs to someone else. |
    | `adminProgramChange {name, file?, about?, args?, env?}` \| `adminProgramDisallow {name}` | owners | Changes or disallows a program an owner allowed. One allowed on the machine gets `machine`. |
    | `adminProgramUpload {file, at, size, data, replace?}` | owners | `at`, and `file` (as in `files`) once the last piece is in. `data` is base64url, up to 256 KB a piece, starting at `at` 0 and following on from the piece before; `size` up to 64 MB. Only the first piece counts against the rate of changes. A file already there gets `bad` unless `replace`. `fixed` when `program_files_from_app` is off. |
    | `adminProgramWrite {file, text, replace?}` | owners | `file`. Writes a script of up to 192 KB, executable by the relay's user only. |
    | `adminProgramRead {file}` | owners | `file`, `size`, and `text`, or `binary` for a file that isn't UTF-8 text or is over 192 KB. |
    | `adminProgramDelete {file}` | owners | Deletes a file, or a link, from the programs folder. A file an allowed program runs gets `bad` until it is disallowed; one allowed on the machine gets `machine`. |
    | `adminUpdate {install?}` | `maintain` | `update` (the newer version, if any). With `install`, the relay installs it and restarts; `unavailable` when it can't replace itself. |
    | `adminRestart` | `maintain` | The relay restarts (see [Restarting](#restarting)); it answers first. Older relays say `unavailable` when they don't run as a service. |
    | `adminStoreRefresh` | `maintain` | Fetches each store's index now rather than within the hour (see [The Isolink store](#the-isolink-store)). Answers `stores` (how many it got) and `storeAt`; `off` with no stores, `unreachable` when none answered. `adminStatus` gives `store: {at}`. |

12. **News, forums and the relay key.** The same requests and answers, for members only.
    Besides the usual refusals: `not yours` for someone else's post or comment, `locked` for
    posting in a locked forum without `forums`, `taken` for an id already used, `size` for
    too much, `full` when there is no room, `busy` past an hourly limit, and `unknown`.

    What people write travels as `enc`: base64url of a 12-byte nonce and AES-GCM under the
    relay key, over JSON. The additional data is `isolink-relay-content-v1`, the relay's host
    name in lower case, the kind (`forum`, `post`, `comment` or `news`) and the id, joined by
    NUL bytes, so nothing opens under another id. Devices make the ids (32 hex characters).
    Inside: a forum `{name, about?, emoji?}`, a post `{title, text?, files?}`, a comment or
    News post `{text?, file?}`. A file there is `{id, name, mime, size, key, thumb?, w?, h?,
    ms?}`, its own key sealing it piece by piece. The relay caps `enc` at 4 KB for a forum,
    64 KB for a comment or News post and 512 KB for a post. The key's id is the first 16
    characters of base64url(SHA-256(`isolink-relay-key-v1` and the key)).

    | Request | Who | Answer (`done`) |
    | --- | --- | --- |
    | `news {before?}` | any member | `list` (up to 50 older items, oldest first), `more` |
    | `newsPost {item, enc, file?}` | `announce` | `item` |
    | `newsEdit {item, enc}` \| `newsDelete {item}` | `announce` | `item`, or nothing |
    | `forums` | any member | `list` |
    | `forumCreate {forum, enc}` | whoever `request.forumCreate` lets in (`forums.make` by default) | `forum` |
    | `forumEdit {forum, enc?, locked?}` | its maker, or `forums` (`locked`: `forums` only) | `forum` |
    | `forumDelete {forum}` | its maker, or `forums` | nothing |
    | `forumJoin {forum, join}` | any member | `forum` |
    | `forumPosts {forum, sort, from}` | any member | `list` (up to 25), `next`. `sort` is `hot`, `new` or `top`. |
    | `forumPost {forum, post}` | any member | `post`, `comments` (oldest first) |
    | `forumSubmit {forum, post, enc, files}` | any member (`forums` when locked) | `post`. `files` are up to 10 upload ids. |
    | `forumEditPost {forum, post, enc}` | its author | `post` |
    | `forumRemovePost {forum, post}` | its author, or `forums` | nothing |
    | `forumPin {forum, post, pinned}` | `forums` | `post` |
    | `forumComment {forum, post, comment, parent?, enc, file?}` | any member (`forums` when locked) | `comment` |
    | `forumEditComment {forum, post, comment, enc}` | its author | `comment` |
    | `forumRemoveComment {forum, post, comment}` | its author, or `forums` | nothing. One with replies stays as `removed`, empty. |
    | `forumVote {forum, post, comment?, vote}` | any member | `score`. `vote` is 1, -1 or 0. |
    | `forumUpload {size}` | any member | `upload`, `chunk`. `size` is the file's size unsealed. |
    | `forumUploadChunk {upload, i, data}` | the uploader | `i`. Every sealed piece is exactly `chunk` bytes. |
    | `forumUploadEnd {upload, sha}` | the uploader | `file` (`id`, `size`, `chunk`, `sha` of the sealed bytes). A post must take it within an hour, once. |
    | `forumFile {file, i}` | any member | `data`, one sealed piece |
    | `keyClaim {keyId}` | any member | `keyId`: the first claim wins and stays. |
    | `keyHave {keyId}` | any member | `keyId`. The device holds the key, so it may be asked for it. |
    | `keyAsk` | any member | nothing. The relay keeps the newest ask per device. |
    | `keyGive {ask, sealed}` | a device that said `keyHave` | nothing. The relay passes `sealed` on. |

    A post is `{id, forum, enc, files, by, byName, at, edited?, score, comments, pinned?, vote,
    last}`, `vote` being the asking account's. A comment is `{id, post, parent?, enc?, file?,
    by, byName, at, edited?, score, vote, removed?}`. A forum is `{id, enc, by, byName, at,
    locked?, posts, members, last, joined?}`; one made on the relay machine has `name`,
    `about` and `emoji` instead of `enc`. A News item is `{id, at, kind, enc?, text?, by?,
    account?, file?, edited?, data?}`, `kind` being `post`, `bot`, `member`, `update`, `forum`
    or `renamed`.

    Connected members get `newsItem {item}` (new or changed), `newsGone {id}`, `forum {forum}`
    (new or changed, `joined` as it is for each), `forumGone {id}`, `relayKey {keyId}` when a
    key is first claimed, and `forumReply {reply}`: `{id, forum, post, comment, toComment?,
    byName, at}`, to the author of the post or of the comment replied to. The relay can't read
    what was written, so a reply says who and where only.

    Handing out the key: a device without it sends `keyAsk`. The relay sends `keyWanted {ask,
    account, device, bundle}` to up to three online devices that said `keyHave`, never the
    asker itself, and to each such device that connects while the ask is open. `bundle` is the
    asker's signed bundle as it signed in. A holder checks the bundle's signatures, that its
    device and account match, and that it hasn't blocked the account. It seals `{key, keyId}`
    to the bundle's X25519 key with a one-off key (HKDF info `isolink-relay-key-give`; the
    additional data names the relay, the key id and the asking device) and sends `keyGive`.
    The asker gets `key {sealed}`, checks the key's id and sends `keyHave`. Asks are limited
    to 30 an hour per device, gifts to 120, claims to 10.

## Settings

The relay's limits and guest policy live in `relay.json` in its data folder. Use
`--config <path>` to read another file. With no file, every setting has its default. The
limits keep one misbehaving device from filling the relay.

Change settings with `isolink-relay config set <key> <value>`, or edit the file. `serve`
also takes each one as a flag, which beats the file: `--mail-ttl 3d`, `--guests members`.
The relay reads the file when it starts, so restart it after editing the file yourself;
`config set` on a running relay counts at once. Members
with the `settings` scope change settings from the app, where the relay checks them and they
count at once; a setting fixed by a flag can only change on the machine. A bad key or value
stops `serve` with a message saying which one.

Sizes take `KB`, `MB` or `GB` (`32MB`), or a plain number of bytes. Times take `s`, `m`,
`h` or `d` (`7d`), or a plain number of seconds. Every number must be above 0.

| Key | Default | What it does |
| --- | --- | --- |
| `guests` | `open` | Who may connect without being a member. See below. |
| `max_devices` | `2000` | Devices connected at once. More are turned away as busy. |
| `auth_timeout` | `10s` | Time a device has to sign in after it connects. |
| `hello_bytes` | `16KB` | Largest message accepted before a device signs in. Anything bigger, or any data, ends the connection unread. |
| `waiting_per_ip` | `8` | Connections one address can have open before signing in. More are turned away (HTTP 429). |
| `connects_per_ip` | `60` | New connections one address can make a minute. |
| `trust_proxy` | `false` | Take the address from `X-Forwarded-For`. Turn on only behind your own reverse proxy (`--plain`): anyone can set that header. |
| `ping_interval` | `25s` | How often idle connections are pinged to keep them open. |
| `max_frame_bytes` | `5MB` | Largest piece of data passed along a connection. |
| `circuits_per_device` | `64` | Connections one device can have open at once. |
| `opens_per_minute` | `120` | Connections one device can open a minute. |
| `drops_per_hour` | `1200` | Messages one device can leave an hour. |
| `mail_item_bytes` | `256KB` | Largest single message, or piece of a file, held. |
| `mail_items_per_device` | `500` | Messages held for one member device. |
| `mail_bytes_per_device` | `32MB` | Space held for one member device. |
| `mail_bytes_total` | `1GB` | Space held for all devices together. |
| `mail_ttl` | `7d` | Longest a message or file is held. |
| `file_bytes_per_device` | `256MB` | Space for files held for one member device, on top of its messages. A file is refused whole when it would not fit; phones carry it instead. |
| `file_bytes_total` | `4GB` | Space for files held for all devices together. |
| `file_abandon_after` | `6h` | How long a file left part way waits for its next piece before it is dropped. A sender that stops or deletes a file takes its pieces back at once. |
| `greeting` | none | A welcome members see when they join, up to 1000 characters. Write `\n` for a new line. |
| `bot_guests` | `false` | Let guests add the relay's bots, not just members. Kept for older apps: it reads and sets the policy key `bot.contact`. |
| `bot_instructions` | A short code of conduct in Markdown, in the relay's `language` | How every bot's AI model should behave, unless a bot has its own instructions. It follows Isolink's own prompt and comes before the model's `--system`. Up to 8000 characters. Empty for none. |
| `bot_disclosure` | "This is generative AI and can make mistakes. Check important facts.", in the relay's `language` | What every bot that uses AI (a chat or picture model) tells people about itself, unless a bot has its own. Apps show it in the bot's chat. Empty for none. |
| `bot_disclosure_banner` | `true` | Show the AI disclosure as a banner at the start of an AI bot's chat, unless a bot says otherwise. |
| `bot_disclosure_header` | `true` | Show an info button with the AI disclosure in an AI bot's chat header, unless a bot says otherwise. |
| `bot_file_bytes` | `10MB` | Largest file a bot takes or sends. |
| `bot_web` | `false` | Let bots fetch public web pages, with the relay making the request. Each bot also needs `bot web <bot> on`. See [Web pages from a model](#web-pages-from-a-model). |
| `programs_dir` | none | Folder owners may allow bot programs from, in the app. Empty means `programs` in the data folder; a relative path is in the data folder. Set on the machine only: the app shows it as fixed. See [Programs the app may use](#programs-the-app-may-use). |
| `program_files_from_app` | `true` | Let owners add, edit and delete files in the programs folder from the relay console. Set on the machine only. See [Programs the app may use](#programs-the-app-may-use). |
| `cards_per_account` | `50` | Cards one account can publish to the card library. |
| `cards_total` | `2000` | Cards the card library holds in all. |
| `templates_total` | `100` | Card templates the relay hosts for its members. |
| `backup_bytes_per_account` | `64MB` | Space for one account's encrypted backup. Pieces of it are sent no bigger than `max_frame_bytes`. |
| `backup_bytes_total` | `4GB` | Space for all encrypted backups together. |
| `backup_versions` | `10` | Earlier backups kept for each account, to roll back to. All of them share `backup_bytes_per_account`. |
| `news_keep` | `500` | News items kept. The oldest go first, with their files. |
| `forums_by_members` | `false` | Let every member make forums, not just those with the `forums` scope. Kept for older apps: it reads and sets the policy key `request.forumCreate`. |
| `forum_file_bytes` | `25MB` | Largest photo, video or file in News or a forum. |
| `forum_bytes_per_account` | `500MB` | Space for one account's files in News and forums. |
| `forum_bytes_total` | `5GB` | Space for all files in News and forums together. |
| `forum_ttl` | `3650d` | How long a post is kept after its last comment. Checked at start and once a day. |
| `error_reports` | `true` | Take anonymous error reports from members' apps. See [Error reports](#error-reports). |
| `error_ttl` | `30d` | How long an error report is kept after the problem was last reported. |
| `log_ttl` | `30d` | How long lines in the relay's log and its bots' debug logs are kept. |
| `stt_max_seconds` | `300` | Longest voice note a bot writes out, in seconds. |
| `bot_answer_seconds` | `300` | Longest a bot works on one answer before it stops and says it took too long, in seconds. Time spent waiting for the person doesn't count. |
| `auto_update` | `false` | Install new releases by itself, and restart, when it can update itself. Members with maintain change it. |
| `update_every` | `1h` | How often the relay looks for a new release, to show it in the app or install it with `auto_update`. |
| `beta_updates` | `false` | Take beta releases too, to try the next relay version early. |
| `tile_server` | none | A tile URL with `{z}`, `{x}` and `{y}` the relay gets map tiles from for its members. Owners change it. See [Map tiles](#map-tiles). |
| `tile_credit` | none | Who the map comes from, shown on members' maps. Empty shows OpenStreetMap's credit. |
| `tile_cache_bytes` | `1GB` | Space for map tiles the relay keeps, so members share one download. The least used go first. |
| `tiles_per_minute` | `600` | Map tiles one device can get a minute. |
| `preset` | `home` | Which defaults the relay starts from: `home` for a family relay, `global` for one anyone may join. Set on the machine only. See [A relay anyone may join](#a-relay-anyone-may-join). |
| `hosting` | `self` (`service` under `global`) | How the app shows the relay to members: `self` for one people run for themselves, with every detail; `service` for one run for customers, which shows their account, the service's status and where to get help instead of how the relay is set up. |
| `language` | `en` | The language of the relay's own texts: the default `bot_instructions` and `bot_disclosure` come in it. `en`, `ar`, `de`, `es`, `fr`, `pt` or `zh`. `init` and `setup` take the machine's language; texts the owners wrote stay as they are. |
| `plan` | none | The members' plan a service shows, such as `Free`. |
| `support_url`, `status_url`, `privacy_url`, `terms_url` | none | `https://` links the app shows under Help: where to get help, the status page, the privacy policy and the terms. |
| `join` | `invite` | How someone becomes a member: `invite`, `open` (any device that asks) or `paused` (nobody new; members carry on). |
| `joins_per_ip` | `5` | Accounts one address can join an hour, while joining is open. |
| `member_prune_after` | `3650d` | How long a member that joined by asking may stay unseen before it is removed. |
| `min_app` | none | The oldest app version that should be offered this relay, given in `/v1/status`. |
| `status_note` | none | A line `/v1/status` gives for the app to show, such as planned downtime. |
| `policy` | none | Who may see or use each event, request and property, as `key=roles` pairs over the preset. See [Policies](#policies). |
| `default_roles` | none | Roles every new member gets on joining, besides Member and what their invite gives. Owners set it. See [joining roles](#admins-manage-from-the-app). |
| `wake_every` | `30s` | Least time between two pushes that wake the same device for mail. |
| `call_wait` | `25s` | How long a call waits for a pushed device to connect. |
| `pushed_mail_ttl` | `24h` | How long mail that went out inside a push is kept, in case the device never says it arrived. |

Before a device signs in, the relay knows only its address, so the `hello_bytes`,
`waiting_per_ip` and `connects_per_ip` limits keep strangers from tying it up. They also
keep the code that reads a sign-in as small a target as it can be. A family behind one
home router shares an address; signing in takes well under a second, so the defaults leave
plenty of room.

### Policies

Everything a relay sends or takes has a key, and `policy` sets who may see or use each one as a
set of **roles**. A device passes if it holds any of them:

- a role, such as `moderator`, `supporter` or `guest` (any role, including the relay's own);
- `everyone`: any signed-in device, guests included;
- `members`: any member's device;
- a permission, such as `forums.make`: anyone holding it, through a role or on its own;
- `admins`: anyone holding any permission at all (in the app, "Anyone who manages").

An empty set means owners only (`owners`). Owners always pass unless the key is `off`, which
turns it off for everyone and keeps its roles for when it's turned back on. A set only says who
may try: a request that needs a permission still needs it. Keys come in groups:

- `news.*`: lines in News, such as `news.member` ("Sam joined") or `news.bot`.
- `event.*`: things the relay tells devices, such as `event.botJoined`.
- `prop.*`: parts of what the relay says about itself, such as `prop.relay.members` (the
  member count) or `prop.welcome.botNews`.
- `request.*`: every request a device can make, such as `request.forumCreate`. Making a forum
  needs nothing else: its default is `forums.make`.
- `bot.contact`: adding the relay's bots and talking to them, checked on each message (a
  member's roles, or Guest for anyone else). Members by default.
- `push.*`: `push.register` (handing the relay a push token), `push.payload` (small messages
  inside the push) and `push.call` (waking a device for a call).

Set them as `isolink-relay config set policy "news.member=off, request.forumCreate=moderator,supporter"`
(the words after a key's `=` up to the next key are its roles), `key=default` to put one back,
or in `relay.json` as `{"policy": {"request.forumCreate": {"roles": ["moderator"], "groups":
["members"], "perms": ["forums.make"], "off": false}}}`. The old level words (`everyone`,
`members`, `admins`, `owners`, `off`) still work. An unknown key or role word stops `serve`
with a message.

`bot_guests` and `forums_by_members` are policy keys now: `bot_guests=true` is `bot.contact`
with Members and Guest, and `forums_by_members=true` is `request.forumCreate` with
`forums.make` and Members. Setting either still works and writes its key. The first time a
relay with roles in policy starts, it writes `relay.json` over that way, levels as role sets,
and keeps the old file as `relay.json.before-roles`.

Older apps see each key's nearest level. When one sends a key's level back unchanged, a key
with roles keeps them, so saving their screen never widens a set. A relay with the `global` preset starts from a quiet policy: no "XYZ
joined" or other member news, member and online counts for admins only, forums, the card
library, bots and key claims off, and messages inside pushes allowed for members.

### A relay anyone may join

With `join` set to `open`, a device that says it wants to join becomes a member of its own
account: no scopes, the relay's quotas, and removed once unseen for `member_prune_after`.
`joins_per_ip` keeps one address from making many. `paused` stops new members without
touching the ones there. `GET /v1/status` answers `{v, joining, minApp?, note?, push}` to
anyone, so the app offers the relay only while it takes people and leaves it out when the
relay is down.

The `global` preset is for a relay that serves everyone, such as Isolink's own at
`relay.isolink.app` (set up in [`infra/`](../infra/README.md)). It opens joining, raises
`max_devices`, trims each device's mail and file space, keeps 3 backup versions of up to
32 MB, turns error reports and auto updates off, starts from the quiet policy above, and sets
`hosting` to `service`.

### Push wakes

A relay with push set up lets phones disconnect in the background. The app hands it a push
token when it connects (sealed at rest with `PUSH_TOKEN_KEY`, so a copy of the records alone
can't push anyone). When mail comes for a device that isn't connected, the relay sends a
push saying only "wake" and its own host name, at most every `wake_every`; the phone connects,
fetches and goes back to sleep. A call waits up to `call_wait` for the device to connect.
With **Messages in notifications** on, and `push.payload` allowing it, a message small enough
(3000 characters, sealed as ever) rides inside the push itself, and stays on the relay until
the phone next connects and acks it, or for `pushed_mail_ttl`. Tokens the push service
rejects are dropped; the phone registers again when it next connects.

Push needs credentials, from the environment: `FCM_SERVICE_ACCOUNT` (a Firebase service
account's JSON key) for Android, and `APNS_KEY` (the `.p8` key), `APNS_KEY_ID`,
`APNS_TEAM_ID` for iPhone. Without them the relay works as before and phones stay connected.
iPhone pushes are alerts that the app's notification extension rewrites; until it does they say
"Isolink" and "New message". Apps that embed Isolink and use this relay can name their own in
`APNS_ALERTS`, a JSON object of bundle id to `{title, message?, call?}`:
`{"com.example.setgetter": {"title": "Setgetter", "message": "Your go"}}`.

### Records in a database, and more than one node

`isolink-relay hosted` runs a relay from the environment, for hosting on a container platform:
`RELAY_URL`, `PORT`, `RELAY_NAME`, `RELAY_SETTINGS` (JSON over the global preset, behind a
proxy), and where it keeps things:

- `RELAY_DATABASE_URL`: Postgres for members, invites, mail and push registrations, with
  `RELAY_DATABASE_CA` to check the server's certificate. Without it, files in `RELAY_DATA`.
- `SPACES_ENDPOINT`, `SPACES_BUCKET`, `SPACES_KEY`, `SPACES_SECRET`: an S3-compatible bucket
  for backups and forum files, which a container's disk would lose.

Every node keeps the records in memory and writes changes behind, in batches; Postgres tells
the other nodes what changed. Nodes sharing a database form one relay: each says which
devices it holds, mail reaches a device whichever node it is on, and a circuit to a device on
another node is sent to that node's own address (`RELAY_NODE`, `RELAY_NODE_URL`). A node
that stops for 70 seconds is taken as gone.

### Who may use it as a guest

Members' devices always connect. The `guests` setting decides who else may:

| Value | Who connects |
| --- | --- |
| `open` | Any Isolink device. Guests can only reach members or leave mail for them. |
| `members` | Members' own devices only. |
| `allowlist` | Members, plus the accounts and devices on the allow list. |

The relay checks this when a device signs in, before it can open a connection or leave mail.
It uses the account and device ids the device has just proven with its keys. A refused device
gets `members only` or `not on the allow list`, and the relay logs its ids.

Add someone with `isolink-relay allow <account>` for all their devices, or
`isolink-relay allow --device <device>` for one device. `isolink-relay allowed` lists the
guests refused in the last week, so you can ask a friend to try once and then allow them by
the start of their id. Changes to the allow list count at the next sign-in, without a
restart. A device that is already connected stays until it reconnects.

**Locking the relay to your own hardware.** Use `allow --device`. A MAC address never reaches
a relay on the internet, and phones don't share their serial numbers. Instead, every Isolink
device has its own signing key, and its device id comes from that key. The key lives in the
device's secure storage and can't be copied off it, so a device id can't be borrowed by
another phone.
