
# App runtime contract

Agent Cloud runs your app's web and worker processes with a fixed set of environment variables, including one set per granted connection, and, for some apps, identity headers. Code that reads only these works unchanged in production, in a rehearsal and on a mirror.

Check what a mirror gives your app with:

```bash
agc exec -- printenv PORT DATABASE_URL AGC_EMAIL_URL AGENTCLOUD_MIRROR
```

Values agc treats as secret print as `[set by agent.cloud]` in `agc exec` output and in the mirror's log:

- every connection value;
- Agent Cloud's own credentials (names ending in `_TOKEN`, `_SECRET`, `_KEY`, `_PASSWORD` or `_PASSPHRASE`);
- `.env.mirror` values, except a positively plain one (a line ending `# plain`, or a value like `true`, `8080` or `debug`) under a name that doesn't look like a credential.

## Reference

### Environment variables

<!-- generated: runtime-env -->
| Variable | Production release | Rehearsal | Mirror (`agc up`, `agc exec`) |
|---|---|---|---|
| `PORT` | The port to listen on (`[service.web] port`) | Same | A free port agc picked (the web proxy in front of it is on the mirror's own port). Empty for the worker. |
| &lt;[data.db] env&gt; | Production's database URL, `sslmode=verify-full` | A fresh, unmasked branch of production | The mirror's masked copy: a local relay URL inside the sandbox, else the copy's URL with `sslmode=verify-full` |
| `AGC_RUN` | `live` | `rehearsal` | not set |
| `AGENTCLOUD_MIRROR` | not set | not set | The mirror's name |
| `AGENTCLOUD_APP_URL` | The app's own Agent Cloud address, `https://<host>`, as of when the pods started (never a custom domain); a changed address arrives with the next release | Production's address | Production's address, when agc knows it |
| `AGENTCLOUD_RELEASED` | not set | not set | The live release's version number, empty before the first release, as of when the mirror's processes started |
| `AGC_EMAIL_URL` | `https://agent.cloud/email/v1/messages`; mail is sent | Same URL; mail is captured under the rehearsal, never sent | Same URL; mail is captured in the mirror's outbox |
| `AGC_EMAIL_TOKEN` | `agce_…`, for this app and production | `agce_…`, works only while the rehearsal runs | `agce_…`, dies with the mirror |
| `AGC_AUTH_URL` | `https://agent.cloud/auth/apps/<app>` (real sign-in), when the deployment has app sign-in | `https://agent.cloud/auth/test/<ticket>` (test mode) | Test mode, returning the browser to 127.0.0.1 |
| `AGC_AUTH_TOKEN` | `agca_…`, for this app and production | `agca_…` for the rehearsal | `agca_…` for the mirror |
| `AGC_AUTH_PROVIDER` | `edge` when the release was shipped with `[auth] provider = "edge"` | Same | Same |
| `AGC_EDGE_DEV_USER` | never | never | never in the app’s environment: agc’s web proxy adds the test identity (`AGC_EDGE_DEV_USER` from your shell, default `dev@mirror.invalid`) to a browser’s requests, edge apps only |
| &lt;secret names&gt; | Each secret a person set, by its name | Same | never; put test values in `.env.mirror` |
| &lt;plain env names&gt; | `[service.web] env` in web pods, `[service.worker] env` in worker pods, from the release's own manifest; a name a secret or Agent Cloud's own variable already sets is left out | Same | The web's for the app, `agc exec` and a seed command, the worker's for the worker; `.env.mirror` and agc's own variables win over it |
| &lt;connection variables&gt; | The granted capability's role (write over read) | Same, except a write role is withheld from a rehearsal that waits for a person’s approval or a first release nobody approves; a ClickHouse store gives its copies endpoint, and a Redis store none (the rehearsal gets an empty Redis of its own) | The mirror role, or the production read role if the owner allows it and it's read-only, else nothing |
| `PGSSLROOTCERT` | `/etc/ssl/certs/ca-certificates.crt`, in Agent Cloud's Python image only | Same | `<AGC_HOME>/ca.pem`, Python (uv) apps only |
| `HTTPS_PROXY` | not set by Agent Cloud | not set | The mirror's allowlisting proxy, `http://127.0.0.1:<port>`; also `HTTP_PROXY`, `https_proxy`, `http_proxy` |
| `NO_PROXY` | not set | not set | `localhost,127.0.0.1,::1` (and `no_proxy`) |
| `NODE_USE_ENV_PROXY` | not set | not set | `1`, so Node's fetch uses the proxy |
| `NODE_ENV` | `production`, in Agent Cloud's Node image only (no Dockerfile) | Same | not set from your shell; set it in `.env.mirror` or `[service.web] env` if the app needs it |
<!-- /generated: runtime-env -->

In production and rehearsals, the variables are assembled in this order, later ones winning: the app's secrets, the database URL, email, sign-in, connections, the edge variables, file storage and analytics variables when the app has them, `AGENTCLOUD_APP_URL`, then `PORT` and `AGC_RUN`. The plain `[service.*] env` only fills names none of those set. So no secret or plain value can override an Agent Cloud variable, and neither can be named `PORT`, `AGC_…`, `AGENTCLOUD_…` or the `[data.db] env` variable in the first place.

### On a mirror only

A mirror's processes (the app, the worker, `agc exec`, a seed command) don't inherit the shell that ran `agc up`. From it they get only `PATH`, `HOME`, `TMPDIR`, `LANG`, `LC_ALL` and the other `LC_*` categories, `TZ`, `TERM`, and the certificate files `NODE_EXTRA_CA_CERTS`, `SSL_CERT_FILE` and `SSL_CERT_DIR`. `agc up` names the variables it held back, never their values. Over those come the manifest's plain `env`, then every `KEY=value` in `.env.mirror` in the app folder, and agc's own variables win over all. `agc init` adds `.env.mirror` to `.gitignore`, and snapshots never include `.env*` files.

Inside the sandbox the app can reach only Agent Cloud, the endpoints of connections granted to the mirror, the hosts in `[mirror] egress_allow`, and its own loopback ports, through `HTTPS_PROXY`. A client that ignores the proxy variables can't reach the internet from a mirror.

### Headers your app receives

| Header | When | Value |
|---|---|---|
| `x-agc-user-email` | `[auth] provider = "edge"` | The signed-in person's email, set by the gate. Any value a client sends is stripped first. On a mirror, `AGC_EDGE_DEV_USER` (default `dev@mirror.invalid`); in a rehearsal, after a `SIGN IN` smoke step. |
| `x-agc-user-name` | Same | Their name, or their email when the provider gives none. |
| `x-agc-user-role` | Same, on Agent Cloud's own gate | `owner` for an owner of the app's organization, `member` for any other member; absent for everyone else, on a mirror, after a smoke flow's `SIGN IN`, and on a target's own sign-in. Rechecked at most once a minute. Treat a missing role as someone outside the organization. Any value a client sends is stripped first. |

Apps on Agent Cloud sign-in or `provider = "none"` get no identity headers; Agent Cloud sign-in apps call the [sign-in broker](/docs/reference/sign-in-broker-api.md#sign-in-broker-api) instead.

### Headers Agent Cloud adds to responses

| Header | Value |
|---|---|
| `X-Agc-Release` | `v<N>`, on every response a release serves. Agent Cloud uses it to confirm the traffic switch from outside. |

### What production refuses before your app sees it

A `POST`, `PUT`, `PATCH` or `DELETE` whose `Origin` (or `Sec-Fetch-Site`) says it came from another site gets 403 with code `cross_origin`, except on `[service.web] cross_origin` paths. A mirror's local proxy does the same:

```json
{"error":{"code":"cross_origin","message":"Changes come from this app’s own pages."}}
```

### Processes

| | Production | Rehearsal | Mirror |
|---|---|---|---|
| Web | `web-v<N>`, from the built image, `[service.web] command` | One web pod from the same image | `dev` (or `command`) on your machine, inside the OS sandbox, behind a local proxy on the mirror's port |
| Worker | `worker-v<N>` × `instances`, same image and same environment (including `PORT`); SIGTERM, then 60 s to finish | One worker, then a second run that kills it mid-job and starts a second worker | `[service.worker] dev` or `command` through the shell, `PORT` empty, restarted when it exits (backoff up to 30 s) |

Agent Cloud's own images set `NODE_ENV=production` (Node, no Dockerfile) or `HOME=/tmp`, `PYTHONUNBUFFERED=1` and `PGSSLROOTCERT` (Python). With your own Dockerfile, its `ENV` lines apply instead.

## Connection variables

When an owner makes a connection available and it's granted to your app, Agent Cloud puts its settings and credential into the app's environment under names derived from the connection's name. A connection named `sales-lake` gives variables starting `SALES_LAKE_`: the name uppercased, hyphens turned into underscores. `agc connections` prints the exact names for your app:

```bash
agc connections
```

```json
{"ok":true,"product":"agent.cloud","command":"connections","data":{"org":{"name":"Acme","slug":"acme"},"connections":[{"name":"lake","kind":"ducklake","mirror_access":"role","capabilities":{"read":"granted","write":"available"},"variables":["LAKE_CATALOG","LAKE_DATA_PATH","LAKE_KEY_ID","LAKE_SECRET","LAKE_REGION","LAKE_SNAPSHOT"]}]},"next":[{"cmd":"agc status","why":"nothing to ask for"}]}
```

### Snowflake

<!-- generated: vars-snowflake -->
| Variable (connection `snowflake`) | What it holds | Set |
|---|---|---|
| `SNOWFLAKE_ACCOUNT` | Snowflake account identifier | always |
| `SNOWFLAKE_WAREHOUSE` | Warehouse | always |
| `SNOWFLAKE_DATABASE` | Database | always |
| `SNOWFLAKE_ROLE` | Role of the granted capability (or the mirror role) | always |
| `SNOWFLAKE_USER` | User for that role | always |
| `SNOWFLAKE_PRIVATE_KEY` | PEM private key | key-pair credential |
| `SNOWFLAKE_PRIVATE_KEY_PASSPHRASE` | Its passphrase | key-pair credential with a passphrase |
| `SNOWFLAKE_CLIENT_ID` | OAuth client id | OAuth credential |
| `SNOWFLAKE_CLIENT_SECRET` | OAuth client secret | OAuth credential |
| `SNOWFLAKE_TOKEN_URL` | OAuth token endpoint | OAuth credential |
<!-- /generated: vars-snowflake -->

A role has either a key pair or an OAuth client, never both, so an app gets one of the two credential sets. Agent Cloud doesn't serve a Snowflake code snippet.

### DuckLake

<!-- generated: vars-ducklake -->
| Variable (connection `lake`) | What it holds | Set |
|---|---|---|
| `LAKE_CATALOG` | `postgresql://…?sslmode=verify-full` URI of the catalog, with the role's password: the secret-bearing one | always |
| `LAKE_DATA_PATH` | `s3://bucket/prefix/` or `gs://bucket/prefix/` | always |
| `LAKE_KEY_ID` | Storage HMAC key id | always |
| `LAKE_SECRET` | Storage HMAC secret | always |
| `LAKE_REGION` | Storage region | when the connection has one (S3) |
| `LAKE_SNAPSHOT` | Catalog snapshot the mirror is pinned to | mirrors only, once pinned |
<!-- /generated: vars-ducklake -->

The connection code Agent Cloud gives for DuckLake, shown for a connection named `lake` on S3 (on GCS, the secret is `TYPE gcs` with only the key id and secret):

<!-- generated: snippet-ducklake -->
```python
import os, duckdb
e = os.environ
lit = lambda s: "'" + s.replace("'", "''") + "'"   # a SQL literal: ATTACH takes neither parameters nor expressions
con = duckdb.connect()                            # or the app's own database
con.execute("LOAD ducklake; LOAD postgres; LOAD httpfs;")   # installed in the image at build time
con.execute("CREATE SECRET lake_storage (TYPE s3, KEY_ID ?, SECRET ?, REGION ?)", [e["LAKE_KEY_ID"], e["LAKE_SECRET"], e["LAKE_REGION"]])
pin = f", SNAPSHOT_VERSION {int(e['LAKE_SNAPSHOT'])}" if e.get("LAKE_SNAPSHOT") else ""   # set in a mirror only
con.execute(f"ATTACH {lit('ducklake:postgres:' + e['LAKE_CATALOG'])} AS lake (DATA_PATH {lit(e['LAKE_DATA_PATH'])}, READ_ONLY{pin})")  # drop READ_ONLY with a write grant
```
<!-- /generated: snippet-ducklake -->

A mirror is pinned to the catalog snapshot it first read (`LAKE_SNAPSHOT`), so its view doesn't move under you. The pin is cleared when the mirror is deleted (`agc down --delete`, `agc db reset`).

### Flight SQL

<!-- generated: vars-flightsql -->
| Variable (connection `trades`) | What it holds | Set |
|---|---|---|
| `TRADES_URI` | `grpc+tls://host:port` | always |
| `TRADES_CATALOG` | Catalog name | always |
| `TRADES_USER` | User | always |
| `TRADES_TOKEN` | Token, used as the password | always |
| `TRADES_CA` | PEM root CA, when the endpoint's certificate isn't publicly trusted | when the connection has one |
<!-- /generated: vars-flightsql -->

The connection code for a Flight SQL connection named `trades`. There is no setting to skip TLS verification; an endpoint with a private certificate comes with `TRADES_CA`.

<!-- generated: snippet-flightsql -->
```python
import os
from adbc_driver_flightsql import DatabaseOptions
from adbc_driver_flightsql.dbapi import connect
e = os.environ
conn = connect(e["TRADES_URI"], db_kwargs={
    "username": e["TRADES_USER"], "password": e["TRADES_TOKEN"],                    # the Handshake: the token is the password
    DatabaseOptions.WITH_COOKIE_MIDDLEWARE.value: "true",                       # the server's session cookie rides along
    **({DatabaseOptions.TLS_ROOT_CERTS.value: e["TRADES_CA"]} if e.get("TRADES_CA") else {}),
})
catalog = '"' + e["TRADES_CATALOG"].replace('"', '""') + '"'             # quoted, so a name like fanatics-lake or select parses
cur = conn.cursor()
cur.execute(f"SELECT * FROM {catalog}.main.weekly_trading_cube LIMIT 10")   # DuckDB SQL; the catalog is the prefix
rows = cur.fetch_arrow_table()
```
<!-- /generated: snippet-flightsql -->

### HTTP API

<!-- generated: vars-http-api -->
| Variable (connection `api`) | What it holds | Set |
|---|---|---|
| `API_URL` | The address of the target's API gateway for this connection; never a credential | releases and rehearsals on the organization's own target |
| `API_CA_PEM` | The public CA certificate that signs the gateway's TLS certificate, given when the gateway serves verified TLS; trust it for `<NAME>_URL`. Never a credential | releases and rehearsals on the organization's own target, when the gateway serves verified TLS |
<!-- /generated: vars-http-api -->

An `http-api` connection gives `<NAME>_URL`, plus `<NAME>_CA_PEM` when the target's gateway serves verified TLS. Send each call to `$<NAME>_URL<path>` (for a connection named `api`, `fetch(process.env.API_URL + '/v1/projects')`) and never add a token or an `Authorization` header: you don't have one, and the gateway strips any you send. With `<NAME>_CA_PEM` set, verify the gateway's certificate and hostname against it; never turn verification off or fall back to HTTP. The gateway adds the organization's credential, lets through only the operations granted to the app (anything else is a 403 that never reaches the API), and logs method, path and status, never a body.

When the connection calls the API as the signed-in person, copy the `x-agc-identity` header of the request you're handling onto each call. For a background call on someone's behalf, only where an owner allowed it, send `X-Agc-Subject: <email>` and no `x-agc-identity`. Only releases serve those calls: a rehearsal has no signed-in person.

It works only for an app on its organization's own target, whose API gateway serves it. A mirror never gets the variable, and an app on Agent Cloud's own runtime can't ship with one (`connection.gateway_unavailable`).

### Which role, where

| Environment | Variables carry |
|---|---|
| Production release | The granted capability's role: write if the app holds write, else read. |
| Rehearsal | The same, except that a rehearsal of a release still waiting for a person's approval gets only roles verified read-only. A store outside Agent Cloud isn't forked, so writes there would be real. |
| Mirror (`agc up`, `agc exec`, a seed command) | The connection's mirror role when the owner gave it one (`mirror_access: "role"`); the production read role when the owner allows laptops to reuse it and it's read-only (`"read"`); otherwise nothing, and the app must cope (seed data, a stub). |

On a mirror agc fetches the values from Agent Cloud each time it starts the app or worker and for each `agc exec`. They're held in memory, never written to disk, and printed as `NAME=[set by agent.cloud]`. Every fetch is recorded on Agent Cloud.

### Capability states in `agc connections`

| State | Meaning | What to do |
|---|---|---|
| `granted` | The app has it. | Ship. |
| `available` | Granted at once on request. | `agc connections request <name> --why "<reason>"` |
| `needs approval` | An owner decides. | Request it; relay `data.approval.url` (exit 10). |
| `pending` | Requested, waiting for an owner. | Wait; `agc connections` shows the outcome. |
| `disabled` | The organization doesn't offer it. | Ask the person. |

## Errors

| Code | Exit | Cause | Fix |
|---|---|---|---|
| `connection.not_granted` | 12 | `agentcloud.toml` names `[connection.<name>] access` the app hasn't been granted; `agc ship` refuses. | `agc connections request <name> --why "<reason>"`, then ship. |
| `connection.disabled` | 12 | The organization doesn't offer that capability. | Ask the person. |
| `connection.not_in_org` | 12 | The app is in an organization this agent hasn't joined. | Ask the person for a Start an app prompt with a join code. |
| `connection.approval` | 10 | The request waits for an organization owner. | Relay `data.approval.url` exactly. |
| `connections.no_reason` | 2 | `request` without a name or `--why`. | Add both. |
| `connection.subject_unavailable` | 12 | An HTTP API connection that calls as the signed-in person, from an app not behind its target's sign-in. | Set `[auth] provider = "edge"`, or drop the connection. |
| `connection.gateway_unavailable` | 12 | An HTTP API connection where the app runs has no API gateway to serve it. | Remove the `[connection.<name>]`, or run the app on its organization's own target. |
| `connection.gateway_unready` | 12 | The target's API gateway lacks a step only a person can take; `agc ship` refuses. | Relay the fix; `agc doctor` says when it's ready. |
| `connection.path_not_allowed`, `connection.not_granted` | HTTP 403 | A call through `<NAME>_URL` to an operation the app isn't granted. | `agc connections` lists what's allowed. |
| `connection.identity_required` | HTTP 401 | A call as the signed-in person carried neither `x-agc-identity` nor an allowed `X-Agc-Subject`. | Copy the request's `x-agc-identity`. |
| `connection.grant_required` | HTTP 403 | The API didn't issue a token for that person. | Show the person the message; it says what to do. |
| `connection.gateway_insecure` | HTTP 503 | The target's gateway isn't serving yet: its TLS isn't confirmed, or its plain-HTTP exception doesn't hold. The message gives the reason. | Ask an owner; the code doesn't change. |

## Agent notes

- Don't hard-code a port. On a mirror `PORT` differs from `[service.web] port`; an app that ignores it fails with `mirror.app_not_ready` or a port collision.
- Rehearsals run on a copy of production's real data with production's secrets. Use `AGC_RUN` to keep outside effects (posting to another service, charging a card) to `live`. Platform email is already safe: a rehearsal's mail is captured, never sent.
- `AGENTCLOUD_MIRROR` is set only on mirrors; don't use it to enable debug features that would also need to work in a rehearsal.
- `agc check` warns when the organization granted the app a connection that `agentcloud.toml` doesn't declare. Add the `[connection.<name>]` table so the need is in the repo.
- Connections aren't forked. A mirror's queries reach the real system through the mirror role; treat them as production reads, and a connection's write role is withheld from a rehearsal that is waiting for a person's approval because writes there would be real.
- Write the code against the variable names, then let the mirror prove it. If the mirror gets nothing, have the app fall back to seed data rather than fail.

## Related

- [Platform APIs: sign-in and email](/docs/reference/sign-in-broker-api.md)
- [`.env.mirror` and the shell environment](/docs/build/env-mirror-and-shell-environment.md#envmirror-and-the-shell-environment)
- [The edge gate](/docs/build/the-edge-gate.md)
- [Connections (owners)](/docs/owners/connections.md)
- [agentcloud.toml reference](/docs/reference/agentcloud-toml-reference.md)

<!-- feedback:start -->
---
Wrong, outdated or unclear? Run `agc feedback docs "reference/app-runtime-contract: <what is wrong>" --body <file>` with the sentence quoted in the file. No code or app data is sent.
<!-- feedback:end -->
