# Self-hosting

fctl is open source, so you can host all of it yourself.
[app.fctl.sh](https://app.fctl.sh) is a managed control plane; this page
sets up your own, on your machines or on Cloudflare.

An fctl instance is a control plane (the API and the web app, with the
Durable Objects and the D1 database that hold its state) and the runners
that connect to it: your machines, each with the `fctl host` service on it.
Nothing in the code is tied to fctl.sh: everything instance-specific is
configuration. The control plane runs in one of two ways, with the same
features, settings, runners and apps:

| | On your own machine or cluster | On Cloudflare |
|---|---|---|
| What runs | one container, `ghcr.io/hyperstructure/fctl-control`: the Worker on workerd, Cloudflare's open-source Workers runtime | one Worker with Durable Objects and a D1 database, on your account |
| What you need | a machine with Docker, or a Kubernetes cluster; no account anywhere | a Cloudflare account with a domain on it |
| HTTPS | a reverse proxy of your choice, or plain http on a network you trust | Cloudflare's, on your domain |
| Backups | copies of its data directory | D1's 30 days of point-in-time history |
| Made for | trying fctl out, a spare machine, a homelab, a cluster you run | a team's everyday instance, as app.fctl.sh |

Set up the control plane one of the two ways. The rest of this page is the
same for both, in the order to follow:

1. [The first account and your team](https://fctl.sh/docs/self-hosting.md#the-first-account-and-your-team).
2. [GitHub](https://fctl.sh/docs/self-hosting.md#connect-github-optional-recommended): a GitHub App that
   agents clone, push and open pull requests as, and whose webhook keeps
   sessions' pull requests current. Without it, projects have no
   repositories.
3. Optionally, [a review app](https://fctl.sh/docs/self-hosting.md#a-review-app-optional): a second GitHub App
   that review agents post as, so that their reviews stand apart from what
   the agents that opened the pull requests answer.
4. Optionally, [Linear](https://fctl.sh/docs/self-hosting.md#connect-linear-optional): an OAuth app with which
   teams delegate Linear issues to fctl.
5. Optionally, [Slack](https://fctl.sh/docs/self-hosting.md#connect-slack-optional): an app with which people
   start and steer agents from Slack.
6. Optionally, [Google sign-in](https://fctl.sh/docs/self-hosting.md#google-sign-in-optional) and
   [email](https://fctl.sh/docs/self-hosting.md#email-optional).
7. [Runners](https://fctl.sh/docs/self-hosting.md#bring-runners-online), the machines agents run on.

Each app takes a few minutes in GitHub's, Linear's or Slack's settings,
then its IDs and secrets go to the control plane: as environment variables
on your own machine, in the instance file and with `cargo xtask secrets`
on Cloudflare.

Running it for an organization's people?
[fctl for organizations](https://fctl.sh/docs/organizations.md) shows the settings to change,
how your directory provisions accounts, and how your own portals, bots and
tools start agents and hear what they do.

## On your own machine or cluster

The image runs the Worker and the web app that run on Cloudflare, on
workerd through Miniflare, with all its state (the database, every
session's event log, attached files) in `/data`
([ADR 0026](https://github.com/hyperstructure/fctl/blob/main/docs/adr/0026-the-control-plane-runs-without-cloudflare-on-workerd.md)).
It listens on port 8787, runs on amd64 and arm64 machines alike, and each
release of fctl publishes it.

### With Docker

```sh
docker run -d --name fctl --restart unless-stopped \
  -p 8787:8787 -v fctl-data:/data \
  -e FCTL_PUBLIC_URL=http://192.168.1.20:8787 \
  ghcr.io/hyperstructure/fctl-control
docker logs fctl
```

`FCTL_PUBLIC_URL` is the address people open the app at and hosts connect
to: the machine's address on your network here, `http://localhost:8787`
to keep it to this machine, or the https address of a
[reverse proxy](https://fctl.sh/docs/self-hosting.md#https-and-reverse-proxies) in front. The log has the link
that creates the first account, the primary instance owner's, after what
plain http gives up:

```text
Made a master key in /data/master-key. It encrypts stored credentials and secrets: keep it with the data (or set FCTL_MASTER_KEY to it).
Applied 18 database migrations
fctl control plane 0.11.0 at http://192.168.1.20:8787, listening on 0.0.0.0:8787, data in /data
Over plain http, anyone on the network in between can read sign-ins and tokens, and browsers offer passkeys, notifications and installing the app only over https (or on localhost): keep it to a network you trust, or put a reverse proxy with TLS in front.
Create the primary instance owner's account (the link works once):
  http://192.168.1.20:8787/setup#token=…
```

Open it, then carry on with [your team](https://fctl.sh/docs/self-hosting.md#the-first-account-and-your-team).
`fctl-data` is a volume Docker makes; a directory of yours works too
(`-v /srv/fctl:/data`) once user 1000, which runs the server in the image,
can write to it.
[`deploy/standalone/compose.yaml`](https://github.com/hyperstructure/fctl/blob/main/deploy/standalone/compose.yaml) does
the same with Docker Compose. To build the image yourself, in a clone:
`docker build -f deploy/standalone/Dockerfile -t fctl-control .`

### On Kubernetes

[`deploy/standalone/kubernetes.yaml`](https://github.com/hyperstructure/fctl/blob/main/deploy/standalone/kubernetes.yaml)
has a StatefulSet of one, with a volume for its data, a Service and an
Ingress. Set `FCTL_PUBLIC_URL` and the Ingress's host in it to your address,
then:

```sh
kubectl create namespace fctl
kubectl -n fctl create secret generic fctl \
  --from-literal=FCTL_MASTER_KEY="$(openssl rand -base64 32)"
kubectl -n fctl apply -f kubernetes.yaml
kubectl -n fctl logs statefulset/fctl-control
```

Keep it to one replica. Its state is SQLite files on the volume, and two
servers on them would each run the same sessions: a second one waits for
the first to stop, and gives up after 45 seconds. The Ingress has to pass
WebSockets, as ingress-nginx, Traefik and the cloud providers' do, and
bodies of up to 25 MB, for attachments. The pod reads the `fctl` Secret as
environment variables: add the [GitHub App's](https://fctl.sh/docs/self-hosting.md#connect-github-optional-recommended),
[Google's](https://fctl.sh/docs/self-hosting.md#google-sign-in-optional) and [Resend's](https://fctl.sh/docs/self-hosting.md#email-optional)
secrets there when you use them.

### From a clone, without Docker

With Rust and Node.js 22 or newer, as for [development](https://fctl.sh/docs/development.md#setup):

```sh
git clone https://github.com/hyperstructure/fctl && cd fctl
cargo xtask serve --public-url http://192.168.1.20:8787
```

It builds the Worker and the web app, then runs the server the image runs,
with its state in `.fctl-serve/` (`--data` for another directory). It
listens on every address unless the URL is on this machine.

### Settings

The server takes the settings the Worker takes on Cloudflare, as
environment variables. Each can come from a file instead, `<NAME>_FILE`, as
Docker and Kubernetes secrets do.

| Variable | Default | What it is |
|---|---|---|
| `FCTL_PUBLIC_URL` | `http://localhost:8787` | The address people open the app at and hosts connect to |
| `FCTL_INSTANCE_NAME` | `fctl` | Shown in the app and in emails |
| `FCTL_MASTER_KEY` | made in the data directory | 32 random bytes in base64 (`openssl rand -base64 32`) that encrypt stored credentials and secrets |
| `FCTL_SETUP_TOKEN` | made at each start | The token in the setup link, which works until the first account exists |
| `FCTL_DATA_DIR` | `/data` in the image | Where the state lives |
| `FCTL_PORT`, `FCTL_LISTEN` | `8787` (or `PORT`), `0.0.0.0` | Where it listens |
| `FCTL_SEARCH_ENGINES` | `0` | `1` lets search engines index the sign-in page ([search engines](https://fctl.sh/docs/self-hosting.md#search-engines)) |
| `FCTL_TRUST_PROXY` | `0` | How many [reverse proxies](https://fctl.sh/docs/self-hosting.md#https-and-reverse-proxies) in front add `X-Forwarded-For` |
| `FCTL_WEBHOOK_PRIVATE_HOSTS` | none | IP ranges and host names on your network that webhooks may post to ([webhooks to your own network](https://fctl.sh/docs/self-hosting.md#webhooks-to-your-own-network)) |
| `FCTL_WEBHOOK_HTTP` | `0` | `1` lets webhooks post over plain `http://` ([webhooks to your own network](https://fctl.sh/docs/self-hosting.md#webhooks-to-your-own-network)) |
| `FCTL_ADMIN_TOKENS` | `0` | `1` lets instance admins make admin tokens, which create and change people's accounts ([admin tokens](https://fctl.sh/docs/self-hosting.md#provision-people-with-admin-tokens)) |
| `FCTL_METRICS_TOKEN` | none | The bearer token Prometheus scrapes runner pools' demand with at `/api/v1/metrics`; none, no metrics ([runner pools in Prometheus](https://fctl.sh/docs/self-hosting.md#runner-pools-in-prometheus)) |
| `GITHUB_APP_ID`, `GITHUB_APP_SLUG`, `GITHUB_CLIENT_ID`, `GITHUB_DEFAULT_OWNER`, `GITHUB_APP_PRIVATE_KEY`, `GITHUB_CLIENT_SECRET`, `GITHUB_WEBHOOK_SECRET` | | [The GitHub App](https://fctl.sh/docs/self-hosting.md#connect-github-optional-recommended) |
| `GITHUB_REVIEW_APP_ID`, `GITHUB_REVIEW_APP_SLUG`, `GITHUB_REVIEW_APP_PRIVATE_KEY` | | [The app review agents post as](https://fctl.sh/docs/self-hosting.md#a-review-app-optional) |
| `LINEAR_CLIENT_ID`, `LINEAR_CLIENT_SECRET`, `LINEAR_WEBHOOK_SECRET` | | [Linear](https://fctl.sh/docs/self-hosting.md#connect-linear-optional) |
| `SLACK_CLIENT_ID`, `SLACK_CLIENT_SECRET`, `SLACK_SIGNING_SECRET`, `SLACK_APP_TOKEN` | | [Slack](https://fctl.sh/docs/self-hosting.md#connect-slack-optional) |
| `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | | [Google sign-in](https://fctl.sh/docs/self-hosting.md#google-sign-in-optional) |
| `RESEND_API_KEY`, `FCTL_EMAIL_FROM` | | [Email](https://fctl.sh/docs/self-hosting.md#email-optional) |

Without `FCTL_MASTER_KEY`, the server makes a master key the first time it
starts and keeps it in `master-key` in the data directory, next to what it
encrypts, so a copy of the directory has both. To keep them apart, as the
Kubernetes example does, set it from a secret. Once the server has made
one, set that one: replacing the key makes every stored Claude credential
and project secret unreadable, so the server refuses another.

### HTTPS and reverse proxies

Plain http works on a network you trust. Over it, though, anyone on the
network in between reads sign-ins and tokens, and browsers offer passkeys,
notifications and installing the app only over https (or on `localhost`).
For those, put a reverse proxy with TLS in front, which passes WebSockets
and bodies of up to 25 MB, and set `FCTL_PUBLIC_URL` to its https address.
[Caddy](https://caddyserver.com), for one, gets the certificate itself:

```
fctl.example.com {
	reverse_proxy localhost:8787
}
```

On a [Tailscale](https://tailscale.com) network,
`tailscale serve --bg 8787` gives the machine an https address
(`https://<machine>.<tailnet>.ts.net`) without making it public.

Behind a proxy, set `FCTL_TRUST_PROXY=1` (`2` behind two of them, and so
on). The control plane limits sign-in attempts and records addresses in
the audit log by the address each request comes from, which a proxy puts
in the `X-Forwarded-For` header it adds: without the setting, every request
seems to come from the proxy. With it, the server takes the address the
outermost proxy saw, and ignores what a client wrote there itself. It
counts proxies rather than knowing them, so the server's port must be
reachable only through them: a client that connects to it directly would
choose its own address.

### A private instance

An instance can stay on your own network: people reach it over the
company's network or VPN, runners dial out to it from there, and from
the internet only four paths answer, each only where you use what calls
it. Whoever runs your network's edge sets it up, in about an hour, with
the instance's container already behind a reverse proxy inside.

| Path | Who calls it from the internet | Without it |
|---|---|---|
| `/api/v1/github/webhook` | GitHub's deliveries, signed with `GITHUB_WEBHOOK_SECRET` | Sessions learn of merges and checks hours late, reviews start only when someone asks, and follow-ups and schedules that run on GitHub's events never come |
| `/api/v1/linear/webhook` | Linear's deliveries, signed with `LINEAR_WEBHOOK_SECRET` | Delegating a ticket in Linear starts nothing |
| `/oidc/` | AWS, Google Cloud and Azure, which fetch each workspace's issuer's documents and keys before they take its agents' [identity tokens](https://fctl.sh/docs/identity-tokens.md) | The clouds refuse agents' tokens |
| `/api/v1/published/` | GitHub's image proxy, which fetches the screenshots agents publish in pull requests | Pull requests show broken images |

Sign-ins with GitHub, Linear, Slack and Google come back through people's
browsers, which are inside, and so need no path of their own. Slack needs
none either: a private instance takes its events over Socket Mode, a
connection it opens to Slack ([Connect Slack](https://fctl.sh/docs/self-hosting.md#connect-slack-optional)).

```text
inside: people, runners                         internet: GitHub, Linear, clouds
fctl.acme.dev → the internal proxy              fctl.acme.dev → the edge
        │                                       the four paths, else 404
        └──────────▶ fctl-control :8787 ◀─────────────┘
```

Both sides use the same address, `https://fctl.acme.dev`: your network's
DNS answers it with the internal proxy, the public DNS with the edge. It
has to be one address, scheme, host and port alike: it is
`FCTL_PUBLIC_URL`, which every issuer and published link is under, and
the app refuses changes from pages of another. The internal proxy's
certificate can't come from an HTTP challenge, which would reach the
edge: use a DNS challenge, or your own certificate authority.

**Paths with `..` in them.** fctl resolves `.` and `..` in a path, and
`%2e` as a dot, so `/oidc/../api/v1/sessions` reaches
`/api/v1/sessions`. An edge that matches the path as it came lets such a
request through as one for `/oidc/`: each setup below turns them away
first, and the check at the end makes sure.

#### With a Cloudflare Tunnel

Where `acme.dev` is on Cloudflare, `cloudflared` on the instance's
machine connects out to Cloudflare, which sends it the requests for the
paths its rules let in:

```sh
cloudflared tunnel login
cloudflared tunnel create fctl                 # prints the tunnel's id, and writes its credentials
cloudflared tunnel route dns fctl fctl.acme.dev
```

`/etc/cloudflared/config.yml`, with the tunnel's id:

```yaml
tunnel: 6ff42ae2-765d-4adf-8112-31c55c1551ef
credentials-file: /etc/cloudflared/6ff42ae2-765d-4adf-8112-31c55c1551ef.json
ingress:
  - hostname: fctl.acme.dev       # any . or .. segment: never to the instance
    path: '(^|[/\\])\.\.?([/\\]|$)'
    service: http_status:404
  - hostname: fctl.acme.dev
    path: ^/api/v1/(github|linear)/webhook$
    service: http://localhost:8787
  - hostname: fctl.acme.dev
    path: ^/oidc/
    service: http://localhost:8787
  - hostname: fctl.acme.dev
    path: ^/api/v1/published/
    service: http://localhost:8787
  - service: http_status:404
```

```sh
sudo cloudflared tunnel ingress validate --config /etc/cloudflared/config.yml
sudo cloudflared --config /etc/cloudflared/config.yml service install
```

Rules match the path decoded, but with its dots as they came, and the
first one that matches wins. Also turn on **Normalize URLs to origin**
under the zone's **Rules → Settings**, so that Cloudflare resolves dot
segments before the tunnel sees them. Cloudflare adds the client's
address to `X-Forwarded-For` and `cloudflared` adds none, so
`FCTL_TRUST_PROXY=1` holds for requests from both sides. Your network's
DNS answers `fctl.acme.dev` itself, with the internal proxy.

#### With an AWS load balancer

On AWS, an internet-facing Application Load Balancer takes the four
paths and answers the rest with a 404, while an internal one serves
everything to your network. Each has a target group of its own, as an
ALB takes no other's, with the instance's port 8787 in it; a Route 53
private hosted zone answers `fctl.acme.dev` inside with the internal
one, and the public zone with the internet-facing one. On the
internet-facing one's HTTPS listener, with a certificate for
`fctl.acme.dev`:

```sh
aws elbv2 modify-listener --listener-arn "$EDGE_LISTENER" --default-actions \
  '[{"Type":"fixed-response","FixedResponseConfig":{"StatusCode":"404","ContentType":"text/plain","MessageBody":"Not found"}}]'
aws elbv2 create-rule --listener-arn "$EDGE_LISTENER" --priority 10 --actions Type=forward,TargetGroupArn="$EDGE_TARGETS" \
  --conditions '[{"Field":"path-pattern","PathPatternConfig":{"Values":["/api/v1/github/webhook","/api/v1/linear/webhook"]}},
                 {"Field":"http-request-method","HttpRequestMethodConfig":{"Values":["POST"]}}]'
aws elbv2 create-rule --listener-arn "$EDGE_LISTENER" --priority 20 --actions Type=forward,TargetGroupArn="$EDGE_TARGETS" \
  --conditions '[{"Field":"path-pattern","PathPatternConfig":{"Values":["/oidc/*","/api/v1/published/*"]}},
                 {"Field":"http-request-method","HttpRequestMethodConfig":{"Values":["GET","HEAD"]}}]'
```

Let only the two load balancers' security groups reach port 8787. Each
adds one address to `X-Forwarded-For`: `FCTL_TRUST_PROXY=1`. ALBs match
rules after normalizing the path, which AWS doesn't say in full: if the
check at the end lets a dot segment through, put AWS WAF in front of
the internet-facing one, with a rule that blocks the other paths after
its `NORMALIZE_PATH` transformation.

#### Not with Tailscale Funnel

Funnel makes a port of a machine public or private as a whole, and
only under its `ts.net` name: with the app on port 443 for your tailnet
and the four paths on 8443 for the internet, the issuer and published
links would have to be under the 8443 address, where people's browsers
find no app. Use a tunnel or a load balancer instead.

#### Check it

From outside your network (a phone off the VPN, say), the paths you
opened answer and nothing else does:

```sh
curl -s -o /dev/null -w '%{http_code}\n' https://fctl.acme.dev/api/v1/health                    # 404
curl -s -o /dev/null -w '%{http_code}\n' --path-as-is https://fctl.acme.dev/oidc/../api/v1/health  # 404
curl -s -o /dev/null -w '%{http_code}\n' https://fctl.acme.dev/oidc/%2e%2e/api/v1/health          # 404
curl -s https://fctl.acme.dev/oidc/wsp_01JC3F5W5Q0Q7A2N9X4D1V6ZBK/.well-known/openid-configuration  # the issuer's document
```

The sign-in page answers 404 too, while inside it opens and
`/api/v1/health` answers `{"ok":true,…}`. `fctl projects identity -p
web` prints a workspace's issuer. On GitHub, the app's **Advanced →
Recent Deliveries** show `200` for each delivery, and Linear's webhook
page shows them delivered.

- **Narrowing the webhooks to their senders.** fctl turns away any
  webhook that its secret didn't sign, so this is a second fence, not
  the first. GitHub lists the addresses its webhooks come from under
  `hooks` in `https://api.github.com/meta`, which changes now and then
  (it grew on 2026-10-29), and Linear lists its own in its security
  docs. An ALB rule takes few addresses: an AWS WAF IP set, or a
  Cloudflare WAF rule, takes them all. Published screenshots can't be
  narrowed: GitHub's image proxy has no published addresses.
- **Google Cloud alone** can trust an issuer it doesn't reach, with its
  keys uploaded (`--jwk-json-path` on the provider). The instance makes
  a new key every 30 days, two days before it signs with it, so the
  upload has to follow each one. AWS and Azure fetch the keys
  themselves.

### Webhooks to your own network

[Webhooks](https://fctl.sh/docs/automation.md#webhooks) post to `https://` addresses on the
public internet alone, so that whoever manages one, a workspace's admin or
a project's owner or maintainer, can't have the server reach machines on
its own network. A receiver of yours on that network (a chat bot, a deploy
script, a CI server without TLS) needs you to let them there:

```sh
FCTL_WEBHOOK_PRIVATE_HOSTS="10.20.0.0/16, 192.168.1.20, hooks.lan, *.corp.internal"
FCTL_WEBHOOK_HTTP=1
```

- `FCTL_WEBHOOK_PRIVATE_HOSTS` lists, separated by commas or spaces, IP
  ranges (`10.20.0.0/16`, `fd00::/8`), addresses (`192.168.1.20`), host
  names (`hooks.lan`, `jenkins`) and the names under a domain
  (`*.corp.internal`: `ci.corp.internal`, not `corp.internal` itself).
  The server doesn't start with an entry it can't read.
- `FCTL_WEBHOOK_HTTP=1` lets webhooks post over plain `http://`, to any
  address they may reach. What they post then travels unencrypted, and
  the address field says so as someone types one.

List the receivers' ranges, not whole networks: anyone who manages a
webhook can have the server post to whatever you list. Leave out the
server's own address, cloud metadata (`169.254.169.254`) and networks
with admin interfaces. The server posts webhooks through a network of
their own, which connects only to public addresses and the IP ranges you
list, checking where a host name resolves as it connects: a public name
that resolves into your network reaches nothing there, unless you list
its range. A host name you list goes wherever it resolves, so list
names only you control ([Security](https://fctl.sh/docs/security.md)). The address field and
`fctl webhooks events` show what the instance takes. The server checks
each address again before it posts, so after a restart with narrower
settings a webhook that points past them fails, with the reason in its
log, and turns itself off after three days. On Cloudflare, a Worker
reaches only the public internet, and app.fctl.sh sets neither.

### Operating it

- **Upgrades.** Pull the new image (or change the tag) and start the
  container again: the server applies the database migrations as it starts.
  Running sessions carry on, and their hosts reconnect. Hosts and agents
  tolerate a control plane one version ahead, and hosts update themselves
  to its version within minutes, from fctl.sh unless their `host.toml`
  sets another `download_base`
  ([Host updates](https://fctl.sh/docs/architecture.md#host-updates)); a version that isn't
  published there, such as a build of your own, leaves them where they are.
- **Disk.** Sessions' snapshots take most of the data directory: each
  session stopped in the last 30 days keeps its conversation and the work
  its agent hadn't pushed, encrypted, a few MB, and at most
  `max_snapshot_mb` (200 MiB unless `fctl admin set --max-snapshot-mb`
  says otherwise). Workspaces keep them fewer days with `fctl workspaces
  set --snapshot-days`, and none with `--snapshots off`; `fctl admin set
  --snapshots off` turns them off for the whole instance
  ([Session snapshots](https://fctl.sh/docs/architecture.md#session-snapshots)).
- **Backups.** Everything is in the data directory. Stop the server and
  copy it, or snapshot its volume: `docker run --rm -v fctl-data:/data -v
  "$PWD":/backup busybox tar czf /backup/fctl-data.tgz /data`. Unless you
  set `FCTL_MASTER_KEY`, the copy holds the master key too: keep it as
  safe as the key.
- **Logs.** `docker logs fctl`, or `kubectl -n fctl logs
  statefulset/fctl-control`: what the control plane logs, and its errors.
  `fctl host logs`, on a runner, shows its host service's.
- **Housekeeping.** The server runs the hourly job of
  [Deletion](https://fctl.sh/docs/architecture.md#data) at 17 minutes past each hour, while it
  runs.
- **What it takes.** About 500 MB of memory and little CPU at rest. The
  data grows with sessions' transcripts and attached files.
- **Removing it.** `fctl host uninstall` on each runner first, while the
  control plane can still stop their sessions (`--force` stops the ones
  that run), then remove the container and its volume.

## On Cloudflare

An instance on Cloudflare is one Worker (the API, the web app and its
Durable Objects) and a D1 database, on your Cloudflare account and domain.

### What you need

- A Cloudflare account with a domain (zone) on it. The **Workers Paid** plan
  ($5 a month) is recommended for its higher limits; a small team stays well
  inside what it includes.
- Rust (via [rustup](https://rustup.rs); the repository pins its toolchain)
  and Node.js 22 or newer.
- Wrangler signed in to that account: run `npx wrangler login` in the
  repository, or export `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID`.
  An API token needs **Workers Scripts: Edit**, **D1: Edit**,
  **Workers KV Storage: Edit**, **Account Settings: Read**, and, on the zone,
  **Workers Routes: Edit** and **DNS: Edit** (for the custom domain).

### 1. Describe the instance

```sh
git clone https://github.com/hyperstructure/fctl && cd fctl
cp deploy/instances/example.toml deploy/instances/acme.toml
```

Edit `deploy/instances/acme.toml`:

```toml
worker = "fctl"                         # the Worker's name in your account
instance_name = "Acme factory"          # shown in the app and in emails
public_url = "https://fctl.acme.dev"    # its host becomes the Worker's custom domain

[d1]
database_name = "fctl"
database_id = ""                        # filled in by --create
location = "weur"                       # optional primary location
```

Nothing in this file is secret; commit it to your fork if you like.
To let search engines index the sign-in page, add `search_engines = true`
([search engines](https://fctl.sh/docs/self-hosting.md#search-engines)).

Cloudflare serves the instance over https, and over plain http too. To
redirect every plain-http request to https, for a page, a file or the API,
add `https_only = true`. The Worker then runs for every request, the web
app's files included, and Cloudflare counts each as a Worker request.

To let instance admins make admin tokens, with which your own programs
create people's accounts and add them to workspaces and projects, add
`admin_tokens = true` ([admin tokens](https://fctl.sh/docs/self-hosting.md#provision-people-with-admin-tokens)).

### 2. Deploy

```sh
cargo xtask deploy acme --create
```

This creates the D1 database (recording its id in the instance file), builds
the web app and the Worker (Rust compiled to WebAssembly), renders
`crates/fctl-control/wrangler.deploy.toml`, applies the database migrations,
and deploys to your domain. Run it again, without `--create`, for every
upgrade. When Cloudflare's API throttles a step (it answers 429 for a while
once a token or an address has made too many requests), the step runs again
once the wait the API asks for is over, up to four times. So does a step
that a server in front of the API failed, answering it with a 5xx that
isn't JSON (wrangler says "Received a malformed response from the API"),
5, 15 and 45 s later; creating the database doesn't, since it may have
been made before the answer failed.

### 3. Set the secrets

```sh
cargo xtask secrets acme
```

This sets, once:

- `FCTL_MASTER_KEY` — 32 random bytes that encrypt stored credentials and
  sign state. Keep it: replacing it makes every stored Claude credential and
  project secret unreadable.
- `FCTL_SETUP_TOKEN` — a one-time token. The command prints the setup link,
  `https://fctl.acme.dev/setup#token=…`. Open it to create the account of
  the primary instance owner; after that, the link does nothing.
  `--new-setup-token` prints a fresh one.

Other secrets go in with `--set`, the GitHub App's key with
`--github-key` and the review app's with `--github-review-key` (below).

### Operating it

- **Upgrades.** `git pull && cargo xtask deploy acme`; migrations apply first.
  Hosts and agents tolerate a control plane one version ahead, and hosts
  update themselves to its version within minutes
  ([Host updates](https://fctl.sh/docs/architecture.md#host-updates)).
- **Backups.** D1 keeps 30 days of point-in-time history (Time Travel):
  `npx wrangler d1 time-travel restore`. For a copy, `npx wrangler d1 export`.
  Session event logs live in Durable Object storage, and so does each
  workspace's search index, which the sessions can build again: after
  `UPDATE sessions SET search_indexed = 0` the hourly job has them do it.
- **Logs.** `npx wrangler tail fctl` streams the Worker's logs; observability
  is enabled in the rendered config. `fctl host logs`, on a runner, shows
  its host service's.
- **Costs.** The control plane is request- and storage-priced on Cloudflare;
  the work happens on your hardware and your Claude subscriptions. fctl never
  makes Anthropic API calls. Sessions' snapshots are most of what it
  stores: a few MB for each session stopped in the last 30 days, in
  Durable Object storage (`fctl workspaces set --snapshot-days`, `fctl
  admin set --max-snapshot-mb` and `--snapshots off` bound them,
  [Session snapshots](https://fctl.sh/docs/architecture.md#session-snapshots)).
- **Removing it.** `fctl host uninstall` on each runner first, while the
  control plane can still stop their sessions (`--force` stops the ones
  that run), then `npx wrangler delete fctl` and
  `npx wrangler d1 delete fctl`.

## The first account and your team

Open the setup link to create the account of the primary instance owner,
then sign in and create your first workspace. Then invite your team under
**Admin → People** (each address on its own, and to your workspaces at the
same time), or allow them under **Admin → Access**: exact emails (which
also creates invite links) or whole domains (`*@acme.dev`), whose people
then sign up with Google and join the workspaces that invite them. To
have your people sign in with your Google Workspace alone, require it for
your domains ([Requiring Google for your domains](https://fctl.sh/docs/self-hosting.md#requiring-google-for-your-domains)).
To require two-factor sign-in of everyone, turn it on under **Admin →
Sign-in** (or `fctl admin set --require-two-factor on`); it seals each
authenticator app's secret with `FCTL_MASTER_KEY`. Passkeys belong to the
host name in `FCTL_PUBLIC_URL`: moving the instance to another host name
leaves them behind, and people add new ones. As the primary instance
owner, you can also make sensitive actions, such as deleting projects,
making access tokens and inviting admins, take a passkey or a code first,
under **Admin → Settings → Sensitive actions** (or `fctl admin set
--verify-sensitive-actions on`). It is off by default, which may suit an
instance only you or a few people use; turning it off again asks you to
confirm it's you. To hold addresses for later, such as `/w/home` and
`/p/home`, reserve them under **Admin → Settings → Reserved addresses** (or
`fctl admin reserve home`): a new instance holds none but those fctl's own
pages use, and a workspace or project whose name makes a reserved one gets
a random ending instead (`home-829d34`).

People who haven't uploaded a picture show their Gravatar: the control
plane asks gravatar.com for each one by the SHA-256 hash of their primary
address, as they sign up and once a day after, and keeps a copy. Each
person can turn that off in their profile. To turn it off for everyone,
as for an instance that must not reach gravatar.com or whose privacy
policy doesn't name Gravatar, use **Admin → Settings → Profile pictures**
(or `fctl admin set --gravatar off`), which also removes the copies.

Each person can export their data once a week: an export reads everything
they have, every transcript too. To let them export more often, or less,
choose under **Admin → Settings → Data exports** (or `fctl admin set
--export-interval 1d`; `off` lets them export at any time, and a year is
the longest wait).

An organization that runs fctl for its own people may want a portal or a
bot of its own to start agents for them, with a workspace's [service
accounts](https://fctl.sh/docs/automation.md#service-accounts). By default a service account
starts sessions only for the people who allowed it, and fctl asks each of
them. Where everyone on the instance works for the organization, its
admins can decide for them: turn off **Admin → Settings → Service accounts
→ People allow them first** (or `fctl admin set --service-account-consent
off`), which takes confirming it's you where the instance asks for that.
Service accounts then start sessions for any member of their workspace,
on that member's Claude subscription, also for those who said no; each
member still sees which act for them, and what they answered counts again
once you turn it back on.

Anyone who signs in creates workspaces of their own, as their primary
admin. An organization that puts its people in its own workspaces, under
**Admin → People** or with [admin
tokens](https://fctl.sh/docs/self-hosting.md#provision-people-with-admin-tokens), can keep that to its admins:
turn off **Admin → Settings → Workspaces → Everyone creates workspaces**
(or `fctl admin set --members-create-workspaces off`). Only instance
admins and the primary instance owner then create workspaces; everyone
else joins the ones they are invited or added to, and the app offers them
none to create. The workspaces that exist stay as they are.

Each person can be a member of five workspaces, those they create and
those they join, and you, as the primary instance owner, of any number. To
let people be in more, or fewer, choose under **Admin → Settings →
Workspaces** (or `fctl admin set --max-workspaces 50`; `any` lets everyone
be in any number). Lowering it takes nobody out of a workspace: those in
more create and join no more until they have left some.

## Provision people with admin tokens

To create people's accounts from your identity provider, your HR system or
a script, put them in your workspaces and projects, and delete them when
they leave, let instance admins make admin tokens: set
`FCTL_ADMIN_TOKENS=1` on your own server, or add `admin_tokens = true` to
your instance's file on Cloudflare and deploy again. (app.fctl.sh takes
none.) An instance admin then makes one under **Admin → Settings → Admin
tokens**, or with `fctl admin tokens create "Okta provisioning"`, and
copies it: it is shown once.

The token acts as the admin who made it, on the admin API's people
endpoints alone ([the list](https://fctl.sh/docs/api.md#people-with-an-admin-token)), until it
expires, someone revokes it, or they stop being an active admin:

```sh
export FCTL_SERVER=https://fctl.acme.dev FCTL_TOKEN=fctl_adm_…
curl -sS -X POST "$FCTL_SERVER/api/v1/admin/users" -H "Authorization: Bearer $FCTL_TOKEN" \
  -H "Content-Type: application/json" -d '{"email": "ada@acme.dev", "given_name": "Ada", "family_name": "Lovelace"}'
curl -sS -X PUT "$FCTL_SERVER/api/v1/admin/users/ada@acme.dev/workspaces/acme" -H "Authorization: Bearer $FCTL_TOKEN" \
  -H "Content-Type: application/json" -d '{"role": "member"}'
curl -sS -X PUT "$FCTL_SERVER/api/v1/admin/users/ada@acme.dev/projects/web" -H "Authorization: Bearer $FCTL_TOKEN" \
  -H "Content-Type: application/json" -d '{"role": "editor"}'
```

The CLI does the same with the token as `FCTL_TOKEN`: `fctl admin users
create`, `show`, `set`, `add` and `remove`
([The CLI](https://fctl.sh/docs/cli.md#provisioning-people-with-an-admin-token)).

- **Signing in.** A new account has no password until someone sets one:
  `password` as you create it, or the link
  `POST /api/v1/admin/users/{user}/reset-link` makes, which works for an
  hour (emailed to them where the instance sends [email](https://fctl.sh/docs/self-hosting.md#email-optional)).
  Where the instance has
  [Google sign-in](https://fctl.sh/docs/self-hosting.md#google-sign-in-optional) and Google hosts the address
  (a Google Workspace account's, or Gmail), the person can sign in with
  Google instead: while the account has no way in at all (no password,
  passkey or linked Google account), its first Google sign-in links
  Google to it. The allowlist admits the address from then on, as an
  invitation's, and they join the workspaces it was invited to. Where
  [Google is required for the address's domain](https://fctl.sh/docs/self-hosting.md#requiring-google-for-your-domains),
  leave `password` out: the token's request with one is refused, as a
  password wouldn't sign them in.
- **Leaving.** Disable an account first (`{"status": "disabled"}`): that
  signs them out and stops the sessions that run on their Claude
  subscription. Deleting it then works as deleting their own would: the
  workspaces only they are in go with it, and what others use stays.
- **What it can't do.** It changes no roles, nor the allowlist,
  invitations or the instance's settings, sees nothing inside projects but
  who is in them, and makes no other token. No token changes the primary
  instance owner's account, and only the primary instance owner's tokens
  change admins'. A workspace's primary admin stays its primary admin.
- **Limits.** Someone is in at most five workspaces, or as many as the
  instance's admins chose (the primary instance owner in any number). A
  workspace that requires two-factor sign-in stays
  closed to someone until they set it up, and an instance that requires it
  holds the admin's tokens to it too.
- **Confirming.** Where sensitive actions ask people to confirm it's them
  (**Admin → Settings → Sensitive actions**), making a token asks, and what
  the token does after doesn't.
- **Keep it secret.** Whoever holds it can change a member's address and
  so take their account over: keep it with your identity provider's
  secrets, make it expire, and revoke it (**Admin → Settings → Admin
  tokens**, or `fctl admin tokens revoke`) when it may have leaked. The
  audit log records what each token did, as its admin, with an admin
  token. Turning `FCTL_ADMIN_TOKENS` off stops every token at once, and
  leaves them listed to revoke.

## Connect GitHub (optional, recommended)

With a GitHub App, projects link repositories, agents get short-lived tokens
for their project's repositories only, and fctl can create new repositories.
An instance has one app; each workspace works in the accounts it is
installed on that are connected to the workspace. A second app, for review
agents to post as, is optional ([A review app](https://fctl.sh/docs/self-hosting.md#a-review-app-optional)).

The steps below use `https://fctl.acme.dev` as `FCTL_PUBLIC_URL`; put
yours in its place. GitHub delivers the app's webhook from the internet,
so it needs to reach that address. An instance it can't reach, such as one
served over plain http on a home network, still works with the app, but
sessions learn of merges and checks hours late, through the hourly lookup
([Pull request state and checks](https://fctl.sh/docs/self-hosting.md#pull-request-state-and-checks)).
Reviews start only when someone asks for one (`fctl review start`), and
follow-ups, which need the webhook, don't come at all.

### 1. Create the app

Under the organization that will own it, open **Settings → Developer
settings → GitHub Apps → New GitHub App** and fill in the form from the
top:

| Field | Value |
|---|---|
| **GitHub App name** | Your choice, such as `acme-fctl`: agents' commits, pull requests and comments show it. The end of its public link (`github.com/apps/acme-fctl`) is its slug |
| **Homepage URL** | `https://fctl.acme.dev`, or a page about your instance |
| **Redirect URI** (**Callback URL** in older forms) | `https://fctl.acme.dev/api/v1/github/authorized`. A workspace's admin signs in to GitHub there to connect an account, which shows fctl what they may connect |
| **Request user authorization (OAuth) during installation** | Off: fctl starts the sign-in itself |
| **Enable Device Flow** | Off |
| **Setup URL** | `https://fctl.acme.dev/api/v1/github/installed` |
| **Redirect on update** | On, so that people who install the app from a workspace, or give it more repositories, come back to the workspace to choose what it works in |
| **Webhook: Active** | On |
| **Webhook URL** | `https://fctl.acme.dev/api/v1/github/webhook` |
| **Secret** | A secret of your own (`openssl rand -hex 32`), which you give the control plane in step 3 |
| **SSL verification** | Enabled |
| **Permissions** | The repository permissions below; no organization or account permissions |
| **Subscribe to events** | The events below |
| **Where can this GitHub App be installed?** | **Only on this account** when workspaces work only in your organization. **Any account** lets workspaces use other accounts too (someone's own, a friend's organization), which can install it only then; you can change it later under **Advanced → Make public** |

Leave the other fields as GitHub sets them. Repository permissions:

| Permission | Access | Why |
|---|---|---|
| Contents | Read and write | clone, commit, push |
| Pull requests | Read and write | open and update pull requests |
| Issues | Read and write | agents can read and comment on issues |
| Workflows | Read and write | agents may edit `.github/workflows` |
| Checks | Read and write | agents can see CI results; review agents' checks |
| Actions, Commit statuses | Read | agents can see CI results |
| Administration | Read and write | only for **New repository** |
| Metadata | Read | required (GitHub ticks it itself) |

Events, which GitHub offers once the permissions above are chosen:

| Event | What fctl does with it |
|---|---|
| **Pull request** | keeps sessions' pull requests current (opened, merged, closed), starts reviews, brings agents back when their pull requests merge or close, and starts the runs of schedules that wait for pull requests to open or merge |
| **Check run**, **Check suite** | shows checks as they change, brings agents back when one fails, and starts the runs of schedules that wait for a branch's checks to fail |
| **Status** | the same for CI that reports commit statuses rather than checks |
| **Issue comment**, **Pull request review**, **Pull request review comment** | brings agents back when people mention them ([Follow-ups](https://fctl.sh/docs/self-hosting.md#follow-ups)) |
| **Issues** | starts the runs of schedules that wait for issues to be opened or labeled ([Automation](https://fctl.sh/docs/automation.md#run-on-events)) |
| **Release** | starts the runs of schedules that wait for releases to be published |

fctl uses no other permission or event. An app that has more works the
same: the tokens fctl gives sessions carry only the permissions under
[What sessions get](https://fctl.sh/docs/self-hosting.md#what-sessions-get), whatever the app has, and it
answers deliveries of other events without acting on them. (app.fctl.sh's
own app, `fctl-sh`, has more, for work beyond fctl's.) Among its events,
**Workflow run** and **Merge queue entry** aren't in use yet, but a
future version of fctl may use them.

For an app made before schedules ran on events, subscribe it to
**Issues** and **Release** under **Permissions & events**: installations
accept nothing new, since the app reads issues and contents already.
Until it is, the project's Schedules tab and `fctl schedules` say that
fctl doesn't hear of those events, and schedules that wait for them
start no runs.

### 2. Install it

Install the app on the organization (all repositories, or the ones agents
may touch, including those they only read, such as private dependencies),
from its public link or **Install App** in its settings. Installing it
lets the instance mint tokens for that account, but no workspace uses it
until one of its admins connects it (step 4).

### 3. Tell the control plane about it

Collect these from the app's settings on GitHub (**General**):

| Setting | Where it comes from |
|---|---|
| `GITHUB_APP_ID` (`app_id`) | **App ID**, at the top |
| `GITHUB_CLIENT_ID` (`client_id`) | **Client ID**, under it |
| `GITHUB_APP_SLUG` (`app_slug`) | the end of the **Public link** |
| `GITHUB_DEFAULT_OWNER` (`default_owner`) | the organization **New repository** creates repositories in |
| `GITHUB_APP_PRIVATE_KEY` | **Private keys → Generate a private key**, which downloads a `.pem` file |
| `GITHUB_CLIENT_SECRET` | **Client secrets → Generate a new client secret** |
| `GITHUB_WEBHOOK_SECRET` | the webhook's secret from step 1 |

The client secret signs workspace admins in to GitHub to connect
accounts; reading their installations and repositories needs only the
Metadata permission above, so the app asks for no more.

On your own machine, set the seven variables (with Kubernetes, the key in
the `fctl` Secret:
`--from-file=GITHUB_APP_PRIVATE_KEY=acme-fctl.private-key.pem`) and start
the server again.

On Cloudflare, fill in the instance file:

```toml
[github]
app_id = "123456"
app_slug = "acme-fctl"
client_id = "Iv23li…"
default_owner = "acme"     # where "New repository" creates repositories
```

Then store the key and the two secrets and redeploy:

```sh
cargo xtask secrets acme --github-key ~/Downloads/acme-fctl.private-key.pem
echo "$GITHUB_CLIENT_SECRET" | cargo xtask secrets acme --set GITHUB_CLIENT_SECRET
echo "$GITHUB_WEBHOOK_SECRET" | cargo xtask secrets acme --set GITHUB_WEBHOOK_SECRET
cargo xtask deploy acme
```

The key is stored as PKCS#8, which WebCrypto imports (`cargo xtask secrets`
and the server convert it); it never reaches a host or a sandbox. fctl
reads it also on one line, as a form can store it, its line breaks turned
into spaces, dropped or written as `\n`. Without the client secret, a
workspace keeps the accounts it has but can't connect a new one, and its
Integrations → GitHub says so.

### 4. Connect it to a workspace

A workspace's admin connects the account under the workspace's **GitHub**
tab (or `fctl workspaces connect`) and chooses the repositories it works
in ([Which workspace uses which account](https://fctl.sh/docs/self-hosting.md#which-workspace-uses-which-account)).
Projects then link those repositories. **Admin → GitHub** shows the app's
installations, and the app's **Advanced → Recent Deliveries** on GitHub
show each webhook delivery with the control plane's answer: the `ping`
GitHub sent as the app was created got 501 if the control plane didn't
have the secret yet; **Redeliver** it to see `{"ok":true}`.

### Pull request state and checks

With the webhook's secret set, the control plane takes the deliveries
GitHub signs with it, and answers others with 401 (without the secret,
501). For each pull request a session lists that one concerns, it asks
GitHub what became of it, so session lists and pages show its state (open,
draft, queued, merged or closed) and its checks as they change, whatever
the session is doing. It also asks about each pull request a session
finds, and once an hour about up to 500 open ones it hasn't heard of for six
hours, which brings sessions from before the webhook up to date at the
first run after you set the secret. It asks about 50 at a time, for one
point of the installation's GraphQL rate limit (5,000 an hour, which your
agents share). In repositories whose pull requests have so many checks
that GitHub gives up on 50 at once, it asks about 10 at a time, or one at
a time, for a point each. It leaves the rest for the next hour while the
installation has fewer than 1,000 points left, and after five minutes of
lookups. Without the secret, sessions show what their agents last looked
up, without checks.

The webhook also starts the reviews of projects whose review agents are
on ([Architecture](https://fctl.sh/docs/architecture.md#review-agents)): a pull request opened,
pushed to or marked ready gets one. Their checks need the app's **Checks**
permission to be **Read and write**: for an app made before, change it
under **Permissions & events**, and each installation's owners accept it
(GitHub asks them). Until then reviews post, without a check, and the
project's Reviews tab says why.

To turn the webhook on for an app made before, edit it on GitHub: under
**General**, tick **Active** under **Webhook** and fill in its URL and
secret; under **Permissions & events**, subscribe to **Pull request**,
**Check run**, **Check suite** and **Status**. Installations accept
nothing new: the app reads pull requests, checks and commit statuses
already. **Advanced → Recent Deliveries** shows
each delivery and the control plane's answer: `{"ok":true,"sessions":1}`
when a session heard of it.

Subscribe to those four events before you rely on the webhook. When a pull
request merges or closes while **Pull request** isn't subscribed, or the
webhook is off, GitHub sends nothing about it, and its sessions keep
showing it as it was until the hourly job looks it up again. The job skips
pull requests the control plane looked up in the last six hours, and a
delivery about a pull request's checks counts as a lookup: one that merges
soon after its last check run shows as open for six to seven hours after
that run.

To bring such a pull request up to date at once, make GitHub send a
delivery that names it, which makes the control plane look it up: add a
label to the pull request and remove the label again (with **Pull request**
subscribed), or redeliver an earlier delivery under
**Advanced → Recent Deliveries** (GitHub keeps them for three days). On
Cloudflare you can also have the next hourly run look up every pull
request that isn't merged or closed, by clearing when the control plane
last did (`fctl` is the `database_name` in your instance file):

```sh
npx wrangler d1 execute fctl --remote --command \
  "UPDATE pull_request_sessions SET checked_at = NULL
   WHERE state IS NULL OR state NOT IN ('merged', 'closed')"
```

### Follow-ups

Projects can bring their agents back to the pull requests they opened
([Architecture](https://fctl.sh/docs/architecture.md#follow-ups)): when someone who can write
to the repository mentions `@fctl` or `@agent` in a comment, when a check
fails, when a pull request conflicts with its base branch, when it merges
or closes. New projects start with all of them on, and each project turns
them on or off in its Settings, or with `fctl projects set --follow-ups`
(projects made before they did keep what they stored); they need the webhook's secret, and for
comments the app subscribed to **Issue comment**, **Pull request review**
and **Pull request review comment**. For an app made before, subscribe to
them under **Permissions & events**: installations accept nothing new,
since the app reads and writes issues and pull requests already. Failed
checks, conflicts and merges come with the events above: GitHub says
nothing when a pull request starts to conflict, so after each merge into a
repository the control plane asks it about the other pull requests there
whose projects follow up on conflicts, for a point of the installation's
rate limit, and again, a point at a time, while GitHub works out its
answer. **Advanced → Recent Deliveries** answers `{"ok":true,"follow_ups":1}`
for a comment that reached an agent, and fctl puts an 👀 reaction on it.

### Which workspace uses which account

A workspace's admins connect accounts under the workspace's
**Integrations → GitHub**, or with `fctl workspaces connect`. Connecting sends them to GitHub to sign
in with the app, which shows fctl what they may give the workspace: every
repository of their own account, or of an organization whose every
repository the app reaches and they administer all of (as its owners do);
otherwise the repositories they administer. Back on the tab, they choose
which of those the workspace works in. So nobody connects another account's
repositories to their workspace — GitHub won't let them — and an instance
admin, who holds the app's key, connects nothing into a workspace either.
Installing the app on an account from the tab, or giving it more
repositories there, brings them back to the same choice through the same
sign-in. Repositories named with `--repo` are connected without the
choice, where GitHub says they may be. New repositories go into
`default_owner` when the workspace works in all of it, otherwise into an
organization the workspace works in all of; the app can create repositories
in organizations, not in people's own accounts.

Under **Admin → GitHub** (`fctl admin github list`), an instance admin sees the
app's installations and the workspaces that use each, and can take an
account from a workspace (`fctl admin github remove <account>
<workspace>`), which its running sessions lose within the hour. Only the
workspace's own admins connect it again.

### What sessions get

A project has a primary repository and may list more, each read only or
read and write, or let agents read every repository of the account that the
app can reach (`owner/*`, within what its workspace may use); they all
belong to one account, whose installation mints the tokens. Each session gets up to two, valid for an
hour and refreshed through its host:

| Token | Repositories | Permissions |
|---|---|---|
| Write | the primary repository and those listed as read and write | contents, pull requests, issues and workflows: write; checks, actions, commit statuses: read. For an agent that comments: pull requests and issues: write; contents, checks, actions, commit statuses: read |
| Read only | those listed as read only, or the account's (`owner/*`); for an agent that only reads, all of them | contents, pull requests, issues, checks, actions, commit statuses: read |

Issues are on them only where the project's ticket tracker says
([Architecture](https://fctl.sh/docs/architecture.md#ticket-trackers)): GitHub Issues of the
repositories its agents write to, as above; of one repository, issues
only on a write token for that repository alone; no tracker, or Linear,
none at all. For a project that keeps its agents to one repository's
issues among several it writes to, the control plane reads and writes
that one's for them (`fctl ticket`), with a token for its issues alone
that it revokes once used. A session a maintainer starts to reach
GitHub's issues (`fctl run --github-issues`) gets them as above, whatever
the tracker says.

What a session's agent may do on GitHub, push, comment, triage or read,
is its own choice within its project's setting
([Architecture](https://fctl.sh/docs/architecture.md#github-access)). The app needs no more
permissions for it: to resolve review threads for agents that comment,
the control plane mints a token that can write the thread's repository's
contents and keeps it, and for agents that triage, one that writes the
issues of the repository they label and comment in.

A review agent's session gets one token, which only reads, for the
reviewed repository and the project's others. The control plane posts
its review with a token of its own, for that repository alone: pull
requests and checks: write, contents: read; and resolves fctl's earlier
threads with one that can write contents. Both are the [review
app](https://fctl.sh/docs/self-hosting.md#a-review-app-optional)'s where it's installed. Neither leaves the
control plane, and both are revoked once used.

Agents may write only to repositories that are named: reading a whole
account is as far as an owner-wide grant goes. A listed repository the
installation no longer reaches (removed from it, renamed or deleted) is left
out of the tokens, and the session says so; a session whose primary
repository is out of reach does not start. People manage the list under the
project's **Repositories** tab or with `fctl projects repos`.

### A review app (optional)

Review agents post their reviews as the GitHub App, which agents write
their own comments and replies as. With a second app, they post as that
one where it's installed, so that a pull request shows a review agent's
findings apart from what the agent that opened it answers (app.fctl.sh's
are `fctl-review` and `fctl-sh`). Where it isn't installed on an account,
or doesn't reach a repository, reviews post as the GitHub App, as before.
Skip it, and review agents work all the same.

1. Create a second app under the same organization, as in
   [step 1](https://fctl.sh/docs/self-hosting.md#1-create-the-app) above, with a name and logo of its own.
   It signs nobody in and hears nothing from GitHub (the GitHub App's
   webhook tells fctl everything), so most of the form stays empty:

   | Field | Value |
   |---|---|
   | **GitHub App name** | Your choice, such as `acme-fctl-review`: reviews show it |
   | **Homepage URL** | `https://fctl.acme.dev`, or a page about your instance |
   | **Redirect URI** | None |
   | **Request user authorization (OAuth) during installation** | Off |
   | **Enable Device Flow** | Off |
   | **Setup URL** | `https://fctl.acme.dev/api/v1/github-review/installed` |
   | **Redirect on update** | On, so that people who install it from a workspace come back there |
   | **Webhook: Active** | Off, with no URL or secret |
   | **Permissions** | The repository permissions below; no organization or account permissions |
   | **Subscribe to events** | None (GitHub offers none while the webhook is off) |
   | **Where can this GitHub App be installed?** | As for the GitHub App, so that the same accounts can install it |

   Repository permissions:

   | Permission | Access | Why |
   |---|---|---|
   | Pull requests | Read and write | post reviews and their summaries, mark findings fixed, sum pull requests up in their descriptions |
   | Checks | Read and write | the `fctl review` check |
   | Contents | Read and write | resolve fctl's earlier threads, as GitHub asks; without it, the GitHub App resolves them |
   | Metadata | Read | required (GitHub ticks it itself) |

2. Generate a **private key** (**General → Private keys**), and tell the
   control plane about the app: its **App ID** and the slug at the end of
   its **Public link**. On your own machine, set `GITHUB_REVIEW_APP_ID`,
   `GITHUB_REVIEW_APP_SLUG` and `GITHUB_REVIEW_APP_PRIVATE_KEY`, and start
   the server again. On Cloudflare, add it to the instance file's
   `[github]`:

   ```toml
   [github.review]
   app_id = "234567"
   app_slug = "acme-fctl-review"
   ```

   Then store the key and redeploy:

   ```sh
   cargo xtask secrets acme --github-review-key ~/Downloads/acme-fctl-review.private-key.pem
   cargo xtask deploy acme
   ```

3. Install it on the accounts the GitHub App is installed on. Nobody
   connects it: fctl uses it only on repositories a workspace connected
   through the GitHub App, so installing it is all it takes. Each
   workspace's **Integrations → GitHub** says which app posts the reviews
   on each of its accounts, and its admins install the review app there
   from it, on the repositories the workspace connected (`fctl workspaces
   review-app` prints the links); a project's **Reviews** tab says which
   app its reviews post as. When fctl can't sign in to GitHub as the
   review app, because it can't read `GITHUB_REVIEW_APP_PRIVATE_KEY` or
   GitHub refuses the key, every review posts as the GitHub App, and
   **Integrations → GitHub** says why.

Which app writes a review is settled as the review starts, since only the
app that created a check may change it: a review that started before the
app was installed finishes as the GitHub App. The findings either app
posted are fctl's to mark fixed, resolve and sum up later, each comment
edited by the app that wrote it.

## Connect Linear (optional)

With a Linear app, teams that track their work in Linear delegate issues
to fctl there: assigning one to fctl's agent, or mentioning it in a comment,
starts a session of the project that takes the issue's team, as the person
who asked, which reports back in the issue
([Architecture](https://fctl.sh/docs/architecture.md#linear)). An instance has one app, which
each workspace's admins install in their Linear workspace from fctl.
Delegations reach fctl only through the app's webhook, so Linear needs to
reach your instance from the internet.

1. Create an OAuth application in a Linear workspace you administer
   (**Settings → API → OAuth applications**), and fill it in:

   | Field | Value |
   |---|---|
   | **Application name** | Your choice: people assign issues to it and mention it by this name (app.fctl.sh's is `fctl-sh`) |
   | **Developer name**, **Developer URL** | Who runs the instance, shown as Linear asks to install the app |
   | **Callback URLs** (Redirect URIs) | `https://fctl.acme.dev/api/v1/linear/installed`: workspaces install the app there, and people link their Linear accounts |
   | **Public** | On (Publicly available), so that Linear workspaces other than yours can install it; off, only yours can |
   | **Webhooks** | On |
   | **Webhook URL** | `https://fctl.acme.dev/api/v1/linear/webhook` |
   | **Events** | **Agent session events** (delegations, mentions, replies and stops), **OAuth authorization events** (Linear says fctl's app was uninstalled from a Linear workspace) and **Permission changes** (its admins changed the teams it sees) |

   fctl uses no other events: they only send it every change in every
   Linear workspace that installs the app, which it answers without
   acting on. (app.fctl.sh's app subscribes to more, such as issues and
   comments, for work beyond fctl's.)

   Or create it from a manifest with these, whose resource types are the
   three events above:

   ```json
   {
     "$schema": "https://linear.app/.well-known/oauth-app-manifest.schema.json",
     "schemaVersion": "1.0.0",
     "distribution": "public",
     "oauth": {
       "client_name": "acme-fctl",
       "redirect_uris": ["https://fctl.acme.dev/api/v1/linear/installed"],
       "grant_types": ["authorization_code"]
     },
     "webhook": {
       "url": "https://fctl.acme.dev/api/v1/linear/webhook",
       "resourceTypes": ["AgentSessionEvent", "OAuthAuthorization", "PermissionChange"]
     }
   }
   ```

   fctl asks for its scopes as workspaces install it: `read`, `write`,
   `app:assignable` (people assign it issues, which delegates them) and
   `app:mentionable` (people mention it), as Linear's own agent (`actor=app`);
   and `read` alone, revoked at once, when someone links their account.
   The app needs no developer token.
2. Tell the control plane about it: the **Client ID** and **Client
   secret** under **OAuth credentials**, and the **Signing secret** under
   **Webhooks**. On your own machine, set `LINEAR_CLIENT_ID`,
   `LINEAR_CLIENT_SECRET` and `LINEAR_WEBHOOK_SECRET` (the signing secret)
   and start the server again. On Cloudflare, add the client ID to the
   instance file and the secrets to the Worker:

   ```toml
   [linear]
   client_id = "8f6a…"
   ```

   ```sh
   echo "$LINEAR_CLIENT_SECRET" | cargo xtask secrets acme --set LINEAR_CLIENT_SECRET
   echo "$LINEAR_WEBHOOK_SECRET" | cargo xtask secrets acme --set LINEAR_WEBHOOK_SECRET
   cargo xtask deploy acme
   ```
3. A workspace's admin connects their Linear workspace under the
   workspace's **Integrations → Linear**, or a project's **Settings →
   Tickets**: Linear asks one of its admins to install the app and to
   choose the teams it sees.
   Each project then chooses its teams. People link their Linear accounts
   (Settings, the project's Settings → Tickets, or Linear's own button the first
   time they delegate an issue), and fctl starts sessions only for people
   it knows there, as them.

The webhook takes deliveries signed with its secret within a minute of
their time, and answers others with 401 (without the secret, 501). Each
delivery is answered at once, as Linear wants within five seconds, and
fctl answers in the agent session within ten. Linear's **Recent
deliveries**, under the app's webhook, show what fctl answered:
`{"ok":true}`.

Let Linear's GitHub integration link the Linear workspace to your GitHub
organizations too: sessions' branches carry their ticket's key, so it
links their pull requests to the tickets. fctl moves the tickets to In
Progress, In Review and Done itself as their sessions work, which each
project's Settings → Tickets can turn off where a team's own automation in Linear
moves them otherwise. fctl hears of merges through the GitHub App's
webhook ([Pull request state and checks](https://fctl.sh/docs/self-hosting.md#pull-request-state-and-checks)).

## Connect Slack (optional)

With a Slack app, people start and steer agents from Slack: mentioning
fctl in a channel, writing to it in its messages, `/fctl` or **Send to
fctl…** on a message starts a session as the person who asked, and its
card, replies and questions come back to the thread, where replies steer
it ([Start agents from Slack](https://github.com/hyperstructure/fctl/blob/main/docs/slack.md), [Architecture](https://fctl.sh/docs/architecture.md#slack)).
An instance has one app, which each workspace's admins install in their
Slack workspaces from fctl. Yours is your organization's own, an internal
app to Slack: Slack's full rate limits apply to it, and it may use Slack's
Real-time Search, which an app distributed outside the Slack Marketplace,
as app.fctl.sh's is until Slack lists it there, may not. Slack's events
reach the instance over HTTP, at addresses Slack reaches from the
internet, or, for an instance Slack can't reach, over Socket Mode: a
WebSocket the instance opens to Slack itself.

1. **Create the app from its manifest.** Under **Admin → Slack**,
   **Create the Slack app** opens Slack's form with the manifest filled in
   with your instance's name and addresses (`fctl admin slack --manifest
   yaml` prints it): choose the Slack workspace to create it in, check it
   and create it. For an instance named `fctl` at
   `https://fctl.acme.dev`, it is:

   ```yaml
   _metadata:
     major_version: 2
     minor_version: 1
   display_information:
     background_color: "#171717"
     description: "Start and steer fctl's agents from Slack."
     long_description: "Mention fctl in a channel, or write to it in its messages, and an agent starts on the work in a sandbox, as you, on your Claude subscription. Its card in the thread shows how it goes: what it's doing, its plan, its pull requests with their checks. Your replies in the thread steer it, its questions come with a button for each answer, and its replies come back where you asked. Agents read the thread they started from, and only the public channels your workspace's admins make readable."
     name: "fctl"
   features:
     agent_view:
       agent_description: "Starts fctl's agents on your projects: say what to do, and an agent works on it in a sandbox, as you, and reports back here."
       suggested_prompts:
         - message: "Fix the bug where "
           title: "Fix a bug"
         - message: "How does this work: "
           title: "Explain some code"
         - message: "What are my sessions doing?"
           title: "What's running?"
     app_home:
       agent_tasks_enabled: false
       home_tab_enabled: true
       messages_tab_enabled: true
       messages_tab_read_only_enabled: false
     bot_user:
       always_online: true
       display_name: "fctl"
     shortcuts:
       - callback_id: "fctl_send_message"
         description: "Start an fctl session from this message"
         name: "Send to fctl"
         type: "message"
       - callback_id: "fctl_start_session"
         description: "Start an fctl session on one of your projects"
         name: "Start an fctl session"
         type: "global"
     slash_commands:
       - command: "/fctl"
         description: "Start an fctl session, or see yours"
         should_escape: true
         url: "https://fctl.acme.dev/api/v1/slack/commands"
         usage_hint: "[what to do] | status"
   oauth_config:
     redirect_urls:
       - "https://fctl.acme.dev/api/v1/slack/installed"
       - "https://fctl.acme.dev/api/v1/slack/linked"
     scopes:
       bot:
         - "app_mentions:read"
         - "assistant:write"
         - "channels:history"
         - "channels:join"
         - "channels:read"
         - "chat:write"
         - "commands"
         - "groups:history"
         - "groups:read"
         - "im:history"
         - "im:read"
         - "im:write"
         - "reactions:write"
         - "search:read.public"
         - "team:read"
         - "users:read"
         - "users:read.email"
       user:
         - "openid"
         - "profile"
         - "email"
   settings:
     event_subscriptions:
       bot_events:
         - "agent_session_stopped"
         - "app_home_opened"
         - "app_mention"
         - "app_uninstalled"
         - "message.channels"
         - "message.groups"
         - "message.im"
         - "tokens_revoked"
       request_url: "https://fctl.acme.dev/api/v1/slack/events"
     interactivity:
       is_enabled: true
       request_url: "https://fctl.acme.dev/api/v1/slack/interactivity"
     org_deploy_enabled: false
     socket_mode_enabled: false
     token_rotation_enabled: false
   ```

   Where the instance has `SLACK_APP_TOKEN`, or an address Slack can't
   reach (plain `http://`, or a private host), the manifest turns
   `socket_mode_enabled` on and leaves the three request URLs out (the
   command's `url`, and the events' and interactivity's `request_url`):
   Slack then sends everything over Socket Mode (step 3). The app's name
   is the instance's (at most 35 characters): people mention it by that
   name. Org-wide installs and token rotation stay off, as fctl takes
   neither yet.

   What fctl does with each bot scope:

   | Scope | For |
   |---|---|
   | `app_mentions:read` | Mentions of fctl in channels |
   | `assistant:write` | Its messages in Slack's agent view, where each thread of someone's messages with it is a session |
   | `channels:history` | Public channels' messages: replies in its threads there, a thread's earlier messages, and the channels admins make readable for agents |
   | `channels:join` | Joining the public channels admins map to projects or make readable |
   | `channels:read` | Looking a public channel up before reading or posting there, and listing public channels for admins |
   | `chat:write` | Posting and changing the card, replies, questions and notes, each thread's agent session, and streams in direct messages |
   | `commands` | `/fctl`, **Send to fctl** and **Start an fctl session** |
   | `groups:history` | Private channels it was invited to: replies in its threads there, and a thread's earlier messages |
   | `groups:read` | Looking a private channel up |
   | `im:history` | People's direct messages with it |
   | `im:read` | Looking direct messages up |
   | `im:write` | Opening someone's direct messages with it, for notifications and the sessions its forms start |
   | `reactions:write` | 👀 on what it took up |
   | `search:read.public` | Searching readable channels with Slack's Real-time Search, for agents |
   | `team:read` | The Slack workspace's name and icon |
   | `users:read` | Who wrote what, their time zone, and whether they are guests |
   | `users:read.email` | People's addresses, for knowing them by address where the instance allows it |

   The user scopes, `openid`, `profile` and `email`, are for Sign in with
   Slack, with which people link their accounts: fctl reads who they are
   and revokes the sign-in's token at once. The app needs no other
   token: agents never hold one, and fctl reads and posts for them.
2. **Tell the control plane about it**: the **Client ID**, **Client
   Secret** and **Signing Secret** under the app's **Basic Information →
   App Credentials**. On your own machine, set `SLACK_CLIENT_ID`,
   `SLACK_CLIENT_SECRET` and `SLACK_SIGNING_SECRET` and start the server
   again. On Cloudflare, add the client ID to the instance file and the
   secrets to the Worker:

   ```toml
   [slack]
   client_id = "1234567890.1234567890123"
   ```

   ```sh
   echo "$SLACK_CLIENT_SECRET" | cargo xtask secrets acme --set SLACK_CLIENT_SECRET
   echo "$SLACK_SIGNING_SECRET" | cargo xtask secrets acme --set SLACK_SIGNING_SECRET
   cargo xtask deploy acme
   ```

   Slack checks the events address as the manifest is saved, which the
   instance answers only once it has the signing secret: where Slack says
   the address isn't verified, have it check again under the app's **Event
   Subscriptions** now.
3. **Socket Mode**, for an instance Slack can't reach: under **Basic
   Information → App-Level Tokens**, generate a token with the
   `connections:write` scope, and set it as `SLACK_APP_TOKEN` (`xapp-…`),
   on Cloudflare as a secret (`cargo xtask secrets acme --set
   SLACK_APP_TOKEN`). An app made from the manifest of an instance Slack
   can't reach has Socket Mode on already; otherwise turn it on under the
   app's **Socket Mode**. The instance needs no signing secret with it. A
   Durable Object keeps the connection open and opens a new one as Slack
   refreshes it, on Cloudflare and on your own machine alike; **Admin →
   Slack** and `fctl admin slack` say whether it's connected, and what
   went wrong last.
4. **Install it.** A workspace's admin connects their Slack workspace on
   the workspace's **Integrations** tab under **Slack** (**Add to Slack**),
   or with `fctl workspaces slack connect`: Slack asks someone who may add
   apps there to install it, and where its admins approve apps, one of
   them. To install it in a Slack workspace other than the one you created
   it in, choose **Activate Public Distribution** under the app's
   **Manage Distribution** first: Slack lets no other Slack workspace
   install it until then. Each person links their Slack account once, as
   they first ask fctl there or in **Settings → Slack**.
5. **Knowing people by their address** (optional). Where your people sign
   in to Slack and to fctl through the same provider, **Admin → Slack**
   lets workspaces know them by their verified address in Slack, without a
   link (`fctl admin slack --match-email on`), and each workspace's admins
   then turn it on for their Slack workspace. It's off by default, and
   off on app.fctl.sh: an address in Slack proves nothing to fctl where
   Slack's admins can set anyone's.

What Slack sends over HTTP (`/api/v1/slack/events`, `/interactivity` and
`/commands`) counts only signed with the signing secret, within five
minutes of its time: the instance answers anything else with 401
(without the secret, 501). It answers each at once, as Slack wants within
three seconds, and does the work after. Slack uninstalls an
app whose installer leaves the Slack workspace or becomes a guest there:
the workspace's Slack page then says its access was revoked, and an admin
connects it again.

## Google sign-in (optional)

Create an OAuth client of type **Web application** in the Google Cloud
console, with the authorized redirect URI
`https://fctl.acme.dev/api/v1/auth/google/callback` (your `FCTL_PUBLIC_URL`
followed by `/api/v1/auth/google/callback`; Google takes http ones only for
`localhost`).

On your own machine, set `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` and
start the server again. On Cloudflare:

```toml
[google]
client_id = "1234-abc.apps.googleusercontent.com"
```

```sh
echo "$GOOGLE_CLIENT_SECRET" | cargo xtask secrets acme --set GOOGLE_CLIENT_SECRET
cargo xtask deploy acme
```

People can then link Google under **Settings**, and allowlisted people can
sign up with it. An account with no way to sign in yet, as an admin
token makes one, links Google at its first Google sign-in
([Provision people with admin tokens](https://fctl.sh/docs/self-hosting.md#provision-people-with-admin-tokens)).
**Admin → Sign-in** shows the redirect URI to give Google, and how many
people sign in with it.

### Requiring Google for your domains

Where your people's addresses are your Google Workspace's, they can sign
in with it alone: under its two-step verification and device checks,
unable to sign in again once you close their Google account, and with no
password of fctl's to forget or leave behind. Closing a Google account
doesn't end the sign-ins its person has already: disable their account
here too as they leave (or with your [admin
token](https://fctl.sh/docs/self-hosting.md#provision-people-with-admin-tokens)'s sync), or keep sign-ins
short ([How long people stay signed in](https://fctl.sh/docs/self-hosting.md#how-long-people-stay-signed-in)). Under **Admin → Sign-in → Domains that sign in
with a provider**, choose **Require a provider** and give your domains
(`acme.com, acme.dev`), or:

```sh
fctl admin sign-in require acme.com acme.dev
```

Before it saves, it shows whom it concerns ("38 people sign in with a
password today: their next sign-in goes through Google, and their
passwords stop working. 4 people at other domains sign in as before."),
and the CLI asks to confirm unless `--yes`. Then, for everyone with an
address at those domains, a connected one too:

- **Google, as that address, is the way in.** Their passwords stop
  working, and so do their passkeys alone, unless you allow those
  (`--passkeys`): quick, but a passkey still signs in someone whose Google
  account you closed. Passkeys still confirm it's them after Google and
  before sensitive actions. Saving the rule deletes the browser sessions,
  CLI sign-ins, access tokens and admin tokens they made another way,
  those from before the rule too: they sign in again, and make access
  tokens again, once. The admin token your directory sync uses stops if
  an admin the rule covers made it another way: make it after signing in
  with Google, or as the primary instance owner.
- **Their next Google sign-in moves them over.** It links their Google
  Workspace account to their fctl account by its address, whatever else
  the account has, unless another Workspace account at those domains signs
  in to it already (a recycled address's new holder doesn't get the
  account). Once its second factor checks out, where it asks for one, it
  takes the account's password, which signs nobody in any more. Signing
  in as a personal Google account (a Gmail one) is refused: the page says
  which address to choose.
- **They hear of it**, by email where the instance [sends
  it](https://fctl.sh/docs/self-hosting.md#email-optional), and the sign-in page says which domains sign in
  with Google and turns its form into Google's button for an address
  there.
- **Their addresses stay**: they can't disconnect an address at those
  domains, as that would let them sign in another way. An instance admin
  or an admin token can.
- **A Google account that's gone keeps its place**: when you recreate
  someone's Workspace account at the same address, the old one, still
  linked, keeps the new one from linking (so that whoever gets a recycled
  address doesn't get its account). Unlink it under **Admin → People →
  Unlink Google**, or with `fctl admin unlink ada@acme.com`: that signs
  them out everywhere, and their next sign-in links the new one. When the
  address went to someone else, disable the old account instead
  (`fctl admin disable`): unlinking would hand it to them.
- **You keep a way in while Google is down**: the primary instance owner's
  password and passkeys sign in whatever the rules say (**Primary instance
  owner? Sign in with your password** on the sign-in page). Nobody else's
  do.
- **You don't sign yourself out**: if the rule would cover you and you
  signed in another way, it waits until you sign in with Google as an
  address there, which shows it works for you.

`fctl admin sign-in` shows the rules and whom each covers, and `fctl admin
sign-in unrequire acme.dev` lets a domain's people sign in as they like
again (it asks you to confirm it's you where the instance asks for that);
passwords that went at their first Google sign-in don't come back, and
each sets one from **Settings** or **Forgot?** on the sign-in page.

To keep accounts to your directory as well, so that signing in with
Google through a `*@acme.com` allowlist entry makes none, turn off
**Admin → Sign-in → Accounts → Signing in makes accounts** (or `fctl admin
set --self-sign-up off`): only invitations, addresses you allow one by
one and [admin tokens](https://fctl.sh/docs/self-hosting.md#provision-people-with-admin-tokens) make accounts,
and the sign-in page tells people without one to ask an admin.

fctl signs people in through Google alone today. SAML, Okta, Microsoft
Entra ID and other OpenID Connect providers aren't supported yet.

### How long people stay signed in

By default a browser stays signed in while it's used, until 30 days
unused; a CLI until 180 days unused; and an access token as long as its
maker chose, for ever included. Under **Admin → Sign-in → Staying signed
in**, or with `fctl admin sign-in policies`, an instance admin sets:

- **Browsers sign in again after** a set time, however much they're used
  (`--browser-max 12h`), and **sign out unused for** less than 30 days
  (`--browser-idle 1h`, at least 5 minutes). A tab left open on a page
  that updates itself counts as use.
- **CLIs sign in again after** a set number of days (`--cli-max 30d`), with
  `fctl login`.
- **Access tokens last at most** a set number of days (`--token-max 90d`):
  new ones can't be made to last longer, and older ones end once they're
  that old.
- **Members make access tokens**, or only admins (`--member-tokens off`):
  members' tokens stop working, and they use the CLI, signed in as
  themselves.

```sh
fctl admin sign-in policies --browser-max 12h --browser-idle 1h --cli-max 30d --token-max 90d
```

Before it saves, it shows what it ends at once ("Saving signs out 14
browsers and 3 CLIs at once: their people sign in again. It ends 5 access
tokens: scripts and CI that use them need new ones."), and the CLI asks
unless `--yes`. Every request checks its sign-in against the policy,
those made before it too, and **Settings** tells people how long theirs
last. Where your domains require Google, signing in again goes through
Google, which checks they still may: someone whose Google account you
closed is out of fctl once their browser's and CLI's sign-ins end. Their
access tokens don't go through Google, so limit those, or keep members
from making them, too. Letting sign-ins or tokens last longer again asks
you to confirm it's you, where the instance asks for that. Admin tokens
and service accounts' secrets last as long as their makers chose.

### Signing in only from your networks

Under **Admin → Sign-in → Networks**, or with `fctl admin sign-in policies
--networks`, an instance admin names the IP ranges people sign in and send
requests from (your office's, your VPN's), as CIDR:

```sh
fctl admin sign-in policies --networks 203.0.113.0/24,2001:db8::/32
fctl admin sign-in policies --networks any   # from anywhere again
```

Browsers, CLIs, access tokens, admin tokens and service accounts elsewhere
are refused: a browser outside them shows the sign-in page, which says
why, and keeps its sign-in for when it's back inside. Runners' connections,
GitHub's and Linear's webhooks and published screenshots' links come from
anywhere, so runners in your cloud need no range of their own, but a
script that calls the API from CI does. The primary instance owner signs
in from anywhere with a browser or the CLI, the way in when your network's
addresses change; their access tokens and admin tokens are held to the
ranges. An admin can't save ranges their own address is outside of
(**Admin → Sign-in** shows it, with **Add it**), and letting people in from
more places asks you to confirm it's you, where the instance asks for
that. The control plane sees each request's address as `CF-Connecting-IP`
says, which your own server sets from the proxies in front of it
([`FCTL_TRUST_PROXY`](https://fctl.sh/docs/self-hosting.md#https-and-reverse-proxies)).

## Email (optional)

Without email, admins copy invite and password-reset links from the app. To
send them, use [Resend](https://resend.com) with a verified domain. With
email, the links go only to the addresses they are for, and admins don't see
them: a reset link signs in as its person, and an invitation's link joins
the workspaces that invited its address.

On your own machine, set `RESEND_API_KEY` and `FCTL_EMAIL_FROM`
(`Acme factory <fctl@acme.dev>`) and start the server again. On Cloudflare:

```toml
[email]
from = "Acme factory <fctl@acme.dev>"
```

```sh
echo "$RESEND_API_KEY" | cargo xtask secrets acme --set RESEND_API_KEY
cargo xtask deploy acme
```

## Search engines

An instance asks search engines to keep out: its `/robots.txt` disallows
everything but `/llms.txt`. To have its sign-in page found, set `search_engines = true` in
its file in `deploy/instances` on Cloudflare, or `FCTL_SEARCH_ENGINES=1`
for the server. `/robots.txt` then allows the sign-in page (and the early
access page where there is one), `/llms.txt`, `/sitemap.xml`, `/favicon.ico`,
`/favicon.svg`, `/icon-maskable-512.png` (the favicon search results show)
and `/apple-touch-icon.png`, and names `/sitemap.xml`, which lists the
pages, for Google Search Console and the like.
Everything else stays disallowed, and needs signing in anyway.

## Bring runners online

A runner is a machine that runs sessions, with the `fctl host` service on
it. On each machine that runs agents (the one that runs the control plane
can be one of them), follow
[Getting started → Bring a machine online](https://fctl.sh/docs/getting-started.md#5-bring-a-machine-online):

```sh
curl -fsSL https://fctl.sh/install | sh
fctl login fctl.acme.dev            # or with its scheme: fctl login http://192.168.1.20:8787
fctl host install
```

Machines that autoscaling makes, or that nobody signs in on, enroll with a
workspace's enrollment token instead, which its admins make on its Runners
tab
([Many machines and autoscaling](https://fctl.sh/docs/getting-started.md#many-machines-and-autoscaling)):

```sh
FCTL_SERVER=https://fctl.acme.dev FCTL_ENROLL_TOKEN=fctl_et_… fctl host install
```

The control plane enrolls them, holds the ones that wait for approval and
removes the ones that go, in its own code and D1, the same with this image
as on Cloudflare: nothing to set up for it. The runners a token enrolls
are a pool, with the token's labels, which projects choose, and what it
needs now, which an autoscaler reads
([Runner pools](https://fctl.sh/docs/architecture.md#runner-pools)).

### Runner pools in Prometheus

Set `FCTL_METRICS_TOKEN` to a long random string (`openssl rand -hex 32`)
and the server serves every workspace's pools to Prometheus at
`/api/v1/metrics`, with that token as the bearer token; without it, the
endpoint answers 404:

```yaml
scrape_configs:
  - job_name: fctl
    metrics_path: /api/v1/metrics
    scheme: https
    authorization:
      credentials_file: /etc/prometheus/fctl-metrics-token
    static_configs:
      - targets: [fctl.acme.dev]
```

Each pool's gauges have the labels `workspace` (its slug), `pool` (its
enrollment token's name) and `pool_id`: `fctl_pool_runners` by `state`
(`online`, `draining`, `pending`, `starting`, `offline`),
`fctl_pool_busy_runners`, `fctl_pool_slots` by `state` (`capacity`,
`busy`, `free`), `fctl_pool_waiting_sessions`,
`fctl_pool_oldest_wait_seconds` and `fctl_pool_wanted_runners`, the same
numbers as `fctl runners demand`. Each workspace's
`fctl_waiting_sessions` counts its sessions that wait by `reason`, and
`fctl_unpooled_sessions` those no pool could run. They are counts only,
with workspaces' slugs and pools' names: give the token to what scrapes
them alone. On Cloudflare, set it as a secret (`wrangler secret put
FCTL_METRICS_TOKEN`) to serve the same.

Hosts download their release from `https://fctl.sh/releases` by default; set
`download_base` in `host.toml` to mirror them elsewhere (`fctl host image
build` installs fctl in the default image from there too). They pull the
sandbox image from `ghcr.io/hyperstructure/sandbox`; set `image` to use a
copy in your own registry ([Sandbox images](https://fctl.sh/docs/sandbox-images.md)). A runner runs
any image a project chooses until its owner lists the ones it allows
(`allowed_images`), and builds images from no repository until they list
some (`allowed_builds`): set both on machines that run other people's
projects ([Which images a host runs](https://fctl.sh/docs/sandbox-images.md#which-images-a-host-runs)).

### Hosts in Kubernetes

A host that runs in a pod, enrolled with an enrollment token from a
secret, as one of a Deployment's replicas that something scales (KEDA,
say), needs what its driver needs there: the `docker` driver a Docker
daemon it reaches (`DOCKER_HOST`), for example. It keeps its pod's
`controller.kubernetes.io/pod-deletion-cost`
annotation at the number of sessions it runs, so that the Deployment,
scaling down, removes the pods that run none first. That takes its
service account permission to patch its own pod, and its name from the
downward API (else it takes its hostname, which a pod's is):

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata: { name: fctl-host, namespace: fctl }
rules:
  - apiGroups: [""]
    resources: [pods]
    verbs: [get, patch]
---
# in the Deployment's pod template
env:
  - name: POD_NAME
    valueFrom: { fieldRef: { fieldPath: metadata.name } }
  - name: POD_NAMESPACE
    valueFrom: { fieldRef: { fieldPath: metadata.namespace } }
lifecycle:
  preStop:
    exec: { command: [fctl, host, drain, --timeout, 25m] }
terminationGracePeriodSeconds: 1800
```

Bind the role to the pod's service account. A host whose service account
may not patch its pod says so once in its log and stops trying;
`pod_deletion_cost = false` under `[kubernetes]` in `host.toml` turns it
off. The `preStop` hook drains the runner when the pod is to go, gives the
turns under way 25 minutes, then stops what still runs, whose agents push
their work, within the pod's 30.

### Session snapshots in a bucket of your own

A session's snapshot, its conversation and the work its agent hadn't
pushed, goes to the control plane as its sandbox stops, encrypted
([Session snapshots](https://fctl.sh/docs/architecture.md#session-snapshots)). To keep them in
your own cloud instead, give your runners a bucket in `host.toml`; the
control plane then keeps only where each is, its size and its checksum:

```toml
[snapshots]
url = "s3://acme-fctl/sessions"   # the bucket, and where in it
# region = "eu-north-1"           # unset: AWS_REGION, the machine's own on EC2, else us-east-1
# endpoint = "https://<account>.r2.cloudflarestorage.com"   # an S3-compatible service; unset: AWS S3
# access_key_id = "…"             # with secret_access_key_file: keys of its own, for a service without roles
# secret_access_key_file = "/etc/fctl/s3-secret"
# max_mb = 2048                   # the largest snapshot it keeps there
```

`fctl host restart` takes it up; `fctl host install --snapshot-bucket
s3://acme-fctl/sessions` sets the URL as it installs, for boot scripts.
The host signs its requests with the
machine's own credentials, where AWS's tools look for them: the
instance's role on EC2, a web identity (IRSA) or the container's
credentials (Pod Identity) on EKS, the `AWS_*` variables. They need
these on the prefix, and `s3:ListBucket` on the bucket, without which S3
answers a request for a snapshot that its lifecycle rule deleted with
403 rather than 404, and the runner shows it as the bucket refusing it:

```json
[
  { "Effect": "Allow", "Action": ["s3:PutObject", "s3:GetObject", "s3:DeleteObject", "s3:AbortMultipartUpload"],
    "Resource": "arn:aws:s3:::acme-fctl/sessions/*" },
  { "Effect": "Allow", "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::acme-fctl" }
]
```

A session's snapshot is at `sessions/<session>/<snapshot>`, and a
host that saves a new one deletes the one before, when that one is in its
bucket too. A session resumes with its snapshot only on a runner whose
host has the same bucket and prefix, and waits up to ten minutes for one
that is busy before it starts on another from its branch. Requests that
S3 asks to slow down, or that fail on the way, go again up to three
times.
The control plane forgets a snapshot once its workspace's days have
passed, but it can't delete it from your bucket: give the prefix a
lifecycle rule that expires objects after as many days (30 unless the
workspace says otherwise). Uploads that a machine never finished go with
a rule that aborts incomplete multipart uploads after a day. On Google
Cloud Storage, use its XML API with HMAC keys
(`endpoint = "https://storage.googleapis.com"`); R2 and MinIO take their
endpoints as they are.

A host that can't read its `[snapshots] url` doesn't start, so that
snapshots meant for your bucket never go to the control plane by
mistake. One whose bucket fails it (no credentials, a policy that
refuses it, a bucket that doesn't answer) says why on the workspace's
Runners tab and in `fctl runners` until a snapshot goes through again. A
snapshot the bucket didn't take is saved nowhere: the session resumes
elsewhere from its branch, as without snapshots.

## Notifications, published screenshots and identity tokens

- **Notifications** need no setup and no push provider account: the control
  plane makes its Web Push (VAPID) key the first time someone opens
  Settings → Notifications, and keeps it in D1, sealed with the master key.
  Browsers allow notifications only from `https://` origins (and
  `http://localhost`).
- **Published screenshots** stay off until an admin allows them (Admin →
  Settings, `fctl admin set --publish-screenshots on`) and a project turns
  them on. Its agents then publish screenshots for pull requests at links
  on your instance's domain, which anyone who has one can open until they
  expire (30 days unless the project chooses 24 hours to 60 days). If your
  instance has a privacy policy, say so there. GitHub shows them in pull
  requests only when its image proxy can fetch them, so only from an
  instance it can reach.
- **Identity tokens** need no setup either: the control plane makes its
  signing key the first time an issuer is asked for its keys or an agent
  mints a token, keeps it in D1 sealed with the master key, and makes a
  new one every 30 days ([Identity tokens](https://fctl.sh/docs/identity-tokens.md)). Each
  workspace's issuer is `FCTL_PUBLIC_URL` with `/oidc/` and the
  workspace's id, so set `FCTL_PUBLIC_URL` to the address services reach
  the instance at, and pass `/oidc/` through your proxy as the rest. AWS,
  Google Cloud and Azure fetch an issuer's documents themselves before
  they trust its agents: they take only `https://` with a certificate they
  trust, on the public internet. A service on your own network checks
  tokens against an instance on it.
