Skip to content

Self-Hosting Guide

This guide walks you through deploying Simple Agent Manager to your own infrastructure. Deployment runs through the Deploy Production GitHub Actions workflow in your own fork, with Pulumi provisioning the Cloudflare resources.

If you’d rather not fork and configure a repository, the installer builds and deploys a complete SAM in your Cloudflare account from your browser, and updates it later (check who can use the hosted installer today). This guide is the fork-based path: more steps, and full control over every setting.

The single-box deployment is being landed in separate slices. Its reverse-tunnel API foundation is build-specific: lease allocation and frps authorization live under apps/api/src/selfhost/ and are absent from the Cloudflare Worker entry. Setting VM_AGENT_TRANSPORT=reverse-tunnel on a Cloudflare deployment does not install that transport and fails before VM allocation.

The self-host build supplies the frpc boot renderer and installs its transport adapter before requests or Durable Object dispatch. It appends the migration manifest from apps/api/src/selfhost/reverse-tunnel-migrations.ts to the same database’s flat migration projection after the shared migrations, rejecting filename collisions. Cloudflare databases do not receive the reverse-tunnel lease table. Existing boxes keep the additive table created by the earlier migration number.

Product analytics on the box use the same pattern. The self-host entry installs a D1 analytics sink (installAnalyticsD1Sink() in apps/api/src/selfhost/analytics/), and the build appends apps/api/src/selfhost/observability-migrations.ts to the observability database’s flat projection (appendSelfhostObservabilityMigrations() in scripts/selfhost/). Cloudflare observability databases never receive the analytics_events table.

The transport setting admits new leases. Existing allocations adopt their original lease only while its exact stored owner remains live. Cleanup and the backstop follow the installed self-host driver, so changing the setting cannot strand an old lease. A build without that driver performs no reverse-lease SQL.

Lease credentials and frps session IDs use separate HKDF-derived HMAC keys. One pinned frps instance owns session replacement. Its Login plugin must apply the server-selected run_id with unchange: false, and every subsequent operation checks that session against the lease. Credential-key rotation recovery is tracked separately. Changing the root key rejects stale resume derivation and old session IDs, but a credential matching the stored lease hash can still log in and obtain the new session ID; root-key rotation alone does not revoke that lease. Installer packaging follows this foundation.

The node boot document for this transport comes from @simple-agent-manager/cloud-init. A non-empty reverseTunnelCredential selects reverse-tunnel mode (isReverseTunnelMode in packages/cloud-init/src/reverse-tunnel.ts). The node then gets the Cloudflare Tunnel firewall (no public agent or SSH ingress), no Origin CA certificate and no cloudflared. It installs a pinned frpc release, checked against a per-architecture sha256, and runs it as the unprivileged sam-frpc unit (packages/cloud-init/src/template-reverse-tunnel.ts). frpc dials the control plane host over wss on its public HTTPS port, verifies its certificate against the system CA store, and exposes only the agent’s loopback tunnel listener as one TCP proxy on the leased port. The credential is written only to the root-only /etc/sam/frpc/credential.env; frpc.toml reads it through frp’s environment template. A failed frpc install reports the frpc_install boot-failure reason. Cloudflare nodes never set these variables and render exactly as before.

The self-host entry wraps the shared Worker with withReverseTunnel(worker, render) from apps/api/src/selfhost/reverse-tunnel/entry.ts. That call installs the transport driver, serves the gateway endpoints under /api/self-host/gateway/ before the shared app sees the request, and runs the lease backstop after the shared handler on the five-minute sweep cron. The backstop logs cron.reverse_tunnel_lease_sweep with its release count, or why it skipped, and it honours the operational cron switch. Its node-transport endpoints:

  • POST /api/self-host/gateway/frps-plugin: the frps server plugin. frps authenticates with HTTP basic auth, user frps, password REVERSE_TUNNEL_GATEWAY_SECRET. A Login allow is answered {reject:false, unchange:false, content}, so frps applies the server-selected run_id. Every other allow is {reject:false, unchange:true}.
  • GET /api/self-host/gateway/node-websocket: Caddy forward_auth for node WebSockets, authenticated with the X-SAM-Gateway-Secret header. The original request runs through the normal ws-_ or node log-stream authentication. The answer is either that handler’s refusal or X-SAM-Upstream/X-SAM-Upstream-_ headers naming the loopback lease port and the credentials Caddy forwards.
  • GET /api/self-host/gateway/app-route: Caddy forward_auth for every request to a deployment app hostname (*.apps.<BASE_DOMAIN>), same header. It answers 404 (or 503 while the node’s tunnel is down) or the node’s lease upstream, the agent’s /deployment/app-ingress/<host>/... URI and a short-lived token for that node and hostname, which Caddy sends as X-SAM-Node-Authorization (authorizeAppRouteRequest in apps/api/src/selfhost/reverse-tunnel/app-route.ts).

Without a gateway secret of at least 32 characters, every endpoint answers 404; a wrong secret gets 401. The Cloudflare Worker never imports this entry.

Control-plane requests, the task liveness probe and WebSocket decisions reach a reverse-tunnel node through the active lease of its current incarnation (resolveNodeAgentRoute in apps/api/src/services/node-agent-route.ts). A released or superseded lease is never routed to, so revocation applies to control-plane traffic on the next request. frps drops the node’s control session within one heartbeat timeout, because a refused Ping does not refresh it. A reverse-tunnel node is never chosen as a snapshot-upload relay, since it has no public hostname.

The self-host build supplies these bootstrap settings; they are not Cloudflare Worker bindings:

Setting Default and contract
REVERSE_TUNNEL_GATEWAY_SECRET Required random secret, at least 32 characters, shared with the frps/plugin gateway.
REVERSE_TUNNEL_GATEWAY_SECRET_ALTERNATE Unset; optional second gateway secret during a coordinated rotation.
REVERSE_TUNNEL_PORT_RANGE_START / REVERSE_TUNNEL_PORT_RANGE_END 20000 / 29999; ports 1024–65535, at most 20,000 ports; must match frps allowPorts.
REVERSE_TUNNEL_HEARTBEAT_TIMEOUT_SECONDS 90; 60–3600 seconds; the build must supply the same timeout to frps.
REVERSE_TUNNEL_PORT_REUSE_MIN_AGE_SECONDS 180; cannot be shorter than twice the heartbeat timeout; maximum 86400 seconds.

Allocation considers the whole bounded port range in one atomic SQL statement, with indexed history lookups. Release checks all active leases in one local statement, without network calls or pagination. At the outer normal limit of 20,000 active leases, one backstop pass releases all eligible leases; the self-host entry runs that backstop every five minutes. A newly freed port still waits for its cooling interval. A full range and a cooling range have distinct errors so operators can distinguish capacity exhaustion from a wait for safe reuse.

This is a build integration foundation for the single-box runtime. Its entry must call installSpeechEndpoints() before serving requests and apply the shared database migrations, including 0259_speech_synthesis_rate_limits.sql. The Cloudflare fork and browser-installer paths described below use Workers AI instead: they do not install these endpoint settings. A runtime without Workers AI or this installed backend cannot offer server speech.

Once your single-box build includes that integration:

  1. Choose an OpenAI-compatible speech provider or run a compatible server reachable from SAM’s API process. It must support multipart POST /audio/transcriptions for voice input and/or JSON POST /audio/speech returning real audio bytes for read-aloud. Check that provider’s documentation for its supported model IDs and synthesis voice IDs. Speech recordings and read-aloud text leave SAM for the selected provider; configure only an endpoint you trust.

  2. Sign in as a superadmin and open Admin → Settings, category AI models. Configure either feature independently with the exact names below. Use a base URL such as https://speech.example.com/v1; SAM appends the audio route, so do not include /audio/transcriptions or /audio/speech, credentials, a query, or a fragment.

    Voice input setting Read-aloud setting Value
    speech.transcription.baseUrl speech.synthesis.baseUrl The provider’s API base URL.
    speech.transcription.model speech.synthesis.model A model ID supported by that endpoint.
    — speech.synthesis.voice A voice ID supported by the synthesis model; required.
    speech.transcription.apiKey speech.synthesis.apiKey Optional Bearer API key; required when the provider requires authentication.
    speech.transcription.allowPrivateNetwork speech.synthesis.allowPrivateNetwork Defaults to false; opt in only for a trusted private endpoint.
  3. Enter keys in the secret setting fields, never in the URL, repository, or GitHub Actions logs. SAM stores them encrypted in its credential store and sends them as Bearer tokens. An endpoint that requires no key can leave its key unset. Changing risky endpoint settings requires the normal admin confirmation. HTTPS is required for public hosts. Plain HTTP is allowed only for private hosts with that feature’s allowPrivateNetwork enabled. Loopback and Docker names resolve from the API process/container, so localhost must actually run the provider there. Cloud metadata and link-local destinations remain refused after opt-in.

  4. Keep TTS_ENCODING=mp3 in the runtime configuration for chunked read-aloud. Other supported encodings work only for a single chunk; SAM refuses multi-chunk container formats before spending provider calls. Raw pcm output is unsupported and refused before a provider call, because the browser audio route cannot play it. Single-chunk Ogg Opus output is stored and served as audio/ogg. Keep TTS_ENABLED enabled for read-aloud.

  5. Refresh the app after saving. Capability queries may remain fresh in the existing browser query cache for up to five minutes. Check /api/config/platform-capabilities for speechToText and textToSpeech, then record a short known sentence in project chat and play read-aloud on a response. Verify the actual transcript and audible result: configured capabilities indicate a complete configuration, not that provider credentials are valid. Failed endpoint calls return a generic unavailable response; check server diagnostics without publishing credentials. Clear that feature’s base URL to disable its endpoint backend.

The AI models category also exposes speech.endpointTimeoutMs (60,000 ms per provider call), speech.transcription.maxResponseBytes (1 MiB JSON), speech.synthesis.maxAudioBytes (8 MiB combined audio per read-aloud request), and speech.synthesis.maxRequestsPerHour (120 requests per user per clock hour). The hourly limit uses an atomic database counter and includes cache hits and failed requests; database-counter failures refuse synthesis. A 429 response includes Retry-After seconds until the next window. Provider billing, models, voices, availability and quotas remain the endpoint operator’s responsibility.

A Cloudflare deployment sends SAM’s email through Cloudflare Email Sending (the AGENT_EMAIL binding) and receives agent email through Email Routing; nothing below changes that. The transport is chosen in one place, emailTransportKind() in packages/agent-email/src/provider.ts, and the binding wins whenever it exists.

A single-box build has no binding. It can send sign-in codes, owner security alerts and account-link confirmations through an SMTP relay instead. These are bootstrap settings in the box configuration, because the first account may sign up by email before any administrator exists. The Cloudflare pipeline does not forward them.

Setting Default Description
SMTP_HOST (unset) Relay host. Unset means no SMTP transport.
SMTP_TLS starttls starttls, tls (implicit TLS) or none. none is accepted only for a loopback host (a mail collector on the same machine).
SMTP_PORT 587 for starttls, 465 for tls Required with none.
SMTP_USERNAME (unset) Sent with AUTH PLAIN, only after TLS (or over loopback). Set with SMTP_PASSWORD (a secret) or not at all.
SMTP_FROM (required) The address SAM’s email comes from. It must be one the relay accepts.

resolveSmtpConfig() (packages/agent-email/src/smtp-config.ts) refuses an invalid set as a whole and logs the reason once; email sign-in is then not offered. A server that does not offer STARTTLS in starttls mode is refused rather than used in plaintext, and the certificate chain is verified by the runtime. The whole exchange is bounded by the agentEmail.smtpTimeoutMs admin setting (15 seconds by default). Every other email sign-in rule (codes only for existing accounts or the installer’s owner, identical responses, rate limits) is the same as on Cloudflare.

Before first-run setup can finish on email alone, SAM checks the relay (emailSignInReadiness() in apps/api/src/services/email-sign-in.ts): it connects, starts TLS, authenticates, and offers SMTP_FROM as sender and the owner email as recipient, then abandons the transaction so nothing is sent. If the relay refuses any step or does not answer, setup asks for a sign-in provider instead, and the reason is logged as email_sign_in.smtp_relay_unusable. The check cannot prove the mailbox receives mail, only that the relay would accept it.

Inbound agent email. The box can also run sam-mx (deploy/selfhost/sam-mx), an SMTP receiver for agent+<key>@agents.<BASE_DOMAIN>. It requires the From domain to be authenticated (aligned SPF or DKIM) and hands each message, during the SMTP session, to the loopback-only route POST /api/self-host/gateway/inbound-email (apps/api/src/selfhost/reverse-tunnel/inbound-email.ts), which runs the same inbound handler as Cloudflare Email Routing. Replies from reply_to_email go through the SMTP relay above, from SMTP_FROM with Reply-To set to the trigger’s address (selfHostAgentEmailSender() in apps/api/src/services/agent-email/self-host-inbound.ts). Agent email is on only when AGENT_EMAIL_INBOUND_SMTP=true (the receiver is installed), the gateway secret is set and an SMTP relay works. The admin loopback test needs Email Routing and is refused on a box; send a test email from an allowed sender instead.

A Cloudflare deployment keeps its DNS records in its Cloudflare zone, and nothing below changes that: the DNS functions in apps/api/src/services/dns-core.ts, dns-app-routes.ts, dns-node-backend.ts and dns-workspace.ts make the same Cloudflare API calls as before.

A single-box build can answer DNS for its own domain instead. The self-host entry installs a box backend (installBoxDns() in apps/api/src/selfhost/dns/), active only when the box sets SAM_DNS_PROVIDER=box. The box deploy sets it when its dns compose profile is on. Then:

  • the records SAM writes, such as app deployment routes (r<n>-<service>-<port>-<env>.apps.<BASE_DOMAIN>, pointing at the box), go to a table in the box’s own database instead of the Cloudflare API (upsertBoxARecord() in apps/api/src/selfhost/dns/records.ts);
  • the cleanup that deletes app-route records left pointing at a deleted deployment server reads and deletes them in that table too (listBoxARecords() in the same file), so stopping an environment leaves no record behind on a box either;
  • a deployment server deleted in the box’s GCP project outside SAM is found by the same provider-existence check as on any install (runDeploymentNodeProviderExistenceSweep() in apps/api/src/services/deployment-node-provider-existence.ts): two “not found” answers through the box’s own GCP credential, 10 minutes apart, release the server and its records here too;
  • the box’s DNS server, sam-dns (deploy/selfhost/sam-dns), syncs them over a loopback-only, secret-checked route (GET /api/self-host/gateway/dns-records), and answers for the whole domain: every other name points at the box;
  • Caddy gets the wildcard certificate by DNS-01 against sam-dns over RFC 2136, signed with a TSIG key SAM generates (SAM_TLS_MODE=dns-rfc2136). No cloud DNS account is involved.

One-time setup. Delegate the domain to the box in its parent zone, and open inbound UDP and TCP port 53 to the box. For BASE_DOMAIN=sam.example.com on a box at 203.0.113.5, the parent zone example.com gets:

sam.example.com. 3600 IN NS ns1.sam.example.com.
ns1.sam.example.com. 3600 IN A 203.0.113.5

If your DNS host does not allow the second record (glue below a delegated name), set SAM_DNS_NAMESERVER to a name outside the domain, such as sam-ns.example.com, and give that name the A record instead. The step-by-step guide, the settings and the switch from Cloud DNS are in deploy/selfhost/README.md (“DNS on the box”).

Verify. dig +short api.sam.example.com returns the box address; dig @203.0.113.5 example.org is REFUSED (no recursion); dig @203.0.113.5 sam.example.com AXFR fails (no zone transfers). A deployment node’s <node-id>.vm. record resolves to the node.

App deployments on a box. Deployment nodes use the box’s reverse tunnel, like workspace nodes, so they need no Cloudflare Origin CA certificate and open no public port: their firewall drops 80 and 443 too. App routes resolve to the box: with DNS on the box, one record per route pointing at SAM_DNS_PUBLIC_IPV4; with your own DNS, a *.apps.<BASE_DOMAIN> wildcard record pointing at the box. *.<BASE_DOMAIN> alone stops matching app names while the *.apps certificate’s DNS-01 challenge record exists. The box’s Caddy serves them with its own *.apps.<BASE_DOMAIN> wildcard certificate. For each request it asks SAM which node may answer (authorizeAppRouteRequest() in apps/api/src/selfhost/reverse-tunnel/app-route.ts): the hostname must be a route of its environment’s latest release, on that environment’s live node. The request then travels through the tunnel to the node, whose agent re-checks the route and passes it to the node’s loopback-only Caddy. Custom domains on app deployments are not served on a box yet. deploy/selfhost/README.md (“App deployments on a box”) has the checks.

What the box accepts. sam-dns is authoritative only: it answers for its domain and refuses every other name, never recurses, refuses zone transfers, NOTIFY and UPDATE on port 53, gives ANY the minimal RFC 8482 answer, truncates UDP answers above 1232 bytes, and rate limits each client network (/24 for IPv4, /56 for IPv6). Updates are accepted only on 127.0.0.1, only with the TSIG key, and only for _acme-challenge TXT records, which live in memory. The egress fence keeps Worker code away from that port. Answers carry a one-hour TTL, so names resolvers recently looked up keep resolving through a short box outage; a second name server is planned.

This applies only to the single-box build; a Cloudflare deployment is not affected. A box keeps its data (database, Durable Objects, files, SAM-hosted repositories) in its fleet bucket, but its sealed secrets, the platform keys that data is encrypted under, were on its own disk. With SAM_REPLACEABLE_BOX=true the box also copies them to the bucket, as ciphertext sealed by its cloud key (scripts/selfhost/replaceable-box.ts), so a dead box can be rebuilt on a new VM from the bucket and the key alone.

  • It needs a key held off the box: Cloud KMS, AWS KMS, Azure Key Vault or a Vault/OpenBao transit key. A key file on the box, plaintext secrets and the bundled object store are refused, because they would die with the box.
  • Replacing a dead box: create a VM with the same identity (allowed to use the key) and, ideally, the same static IP address; put the old .env in place; run pnpm selfhost:rebuild, then pnpm selfhost:deploy --init, start Docker Compose and deploy. Users, sign-in, stored credentials and repositories come back as they were, and nodes reconnect by themselves.
  • What it trusts: your .env (bucket, domain, which key) and the VM’s access to that key. The rebuild never takes the key from the bucket, and refuses anything in the bucket that does not open under that key.

The full runbook, including what a rebuild loses, is in deploy/selfhost/README.md (“Replaceable box”).

Requirement Purpose Tier
Cloudflare account API hosting, DNS, storage Workers Paid ($5/mo)
GitHub account Authentication, CI/CD Free tier
Domain on Cloudflare Workspace URLs Any registrar

Workers Paid is required because SAM uses Durable Objects for real-time chat, task execution, and node lifecycle, and Cloudflare Containers for the default instant-session runtime. Go to Workers & Pages in the Cloudflare dashboard to upgrade. You also need R2 enabled for Pulumi state and Analytics Engine enabled (free): Workers & Pages → Analytics Engine → Enable.

You do not need a shared cloud provider account. Users provide their own Hetzner API token, Scaleway API key, Vultr API key, Infomaniak application credential, DigitalOcean token, UpCloud API subaccount, or GCP configuration through the Settings UI. GCP Workload Identity Federation (WIF) uses an optional infrastructure OAuth client; the service-account JSON mode is OAuth-free.

Step 1: Choose Your Domain and Cloudflare Account

Section titled “Step 1: Choose Your Domain and Cloudflare Account”

Use a top-level domain as BASE_DOMAIN (e.g., example.com), not a subdomain (sam.example.com). Cloudflare’s free Universal SSL covers *.example.com but not nested wildcards like *.sam.example.com. The root domain is not used by SAM — only api., app., and *. subdomains are created.

SAM derives a resource namespace from this domain for Worker names, storage resources, and generated hostnames. For a single installation, use the generated RESOURCE_PREFIX; do not choose a generic prefix by hand. If you run multiple SAM installations in the same Cloudflare account and DNS zone, give each installation its own validated namespace so app, API, workspace, port, VM, and deployment hostnames do not collide.

Copy your Cloudflare account ID from the dashboard URL. In a URL like https://dash.cloudflare.com/<account-id>/<domain>, the account ID is the 32-character value immediately after dash.cloudflare.com/.

Open your domain overview at https://dash.cloudflare.com/<account-id>/<domain> and copy the Zone ID from the right sidebar.

Fork simple-agent-manager on GitHub.

In the Cloudflare account from Step 1, enable R2 first if it is not already active. Then open https://dash.cloudflare.com/<account-id>/api-tokens → Create Custom Token:

Permission Type Resource Access
Account Cloudflare Workers: D1 Edit
Account Workers KV Storage Edit
Account Workers R2 Storage Edit
Account Workers Scripts Edit
Account Workers Observability Read
Account Cloudflare Pages Edit
Account AI Gateway Edit
Account Containers Edit
Account SSL and Certificates Edit
Zone DNS Edit
Zone Workers Routes Edit
Zone SSL and Certificates Edit
Zone Zone Read

Set Zone Resources to your specific domain and Account Resources to your account.

The default deploy configures AI Gateway and writes Analytics Engine data, so keep the AI Gateway permission and enable Analytics Engine even if every user brings their own model keys. SAM also enables the Cloudflare Container instant-session runtime by default, so Containers: Edit is required for the default Worker deploy. The same deploy automatically builds and versions the container vm-agent; no prebuilt image, registry credential, or manual vm-agent version is required. The Account → SSL and Certificates → Edit permission is required for issuing per-node Origin CA certificates used for VM-agent TLS — without it, new nodes cannot obtain a TLS certificate and will fail to boot.

Optional — VM Cloudflare Tunnels: To use outbound-only VM agent connections for newly provisioned workspace and deployment VMs, grant the runtime token Account → Cloudflare One Connector: cloudflared → Edit (the API catalog calls this Cloudflare One Connector: cloudflared Write) and set the GitHub Environment variable VM_AGENT_TRANSPORT to cloudflare-tunnel. Manual deployments use CF_API_TOKEN for runtime operations, so update that token before enabling the setting. The hosted installer includes this permission in newly created runtime tokens; existing installations need their runtime token permission updated. DNS Edit is also required. No per-machine token setup is needed: SAM creates, configures, and removes the tunnels. Existing VMs and instant containers keep their current transport, and deployment VMs keep serving app routes on their public IP. See VM transport configuration.

Optional — Account Analytics read: Add Account → Account Analytics → Read so superadmins see what the Cloudflare account costs. It powers the Cloudflare card on Admin → Health & cost (a daily usage-derived estimate of this month’s Cloudflare cost and a projection) and the Analytics Engine charts on Admin → Analytics. Without it, the Cloudflare card says the token cannot read account analytics and what to add; the Admin → Analytics charts and the optional daily analytics forward fail with a generic error. Runtime tokens created by the hosted installer do not include this permission yet. You can add it to an existing token in the Cloudflare dashboard; no redeploy is needed. See Health & cost.

Optional — Workers AI read: AI models for agents works without extra permissions. Model calls and the model list use the Worker’s own Workers AI binding and go through your AI Gateway. Adding Account → Workers AI → Read also lets agents fetch a model’s full input schema with list_ai_models. Without it, agents get the model’s documentation link instead. Model calls are billed to this Cloudflare account, and each project has a monthly limit.

Optional — email sign-in and agent email: Give the deployment token Zone → Zone Settings → Edit, Zone → Email Routing Rules → Edit, and Email Sending → Edit (Workers Paid required), and every deploy prepares email automatically; no GitHub variable is needed, and without these permissions email stays off with a notice in the deploy log. With email prepared, people with an account can sign in with an emailed code. Installs made by the hosted installer, which records its owner’s email, also let that owner create the first account by email, so their /setup needs no OAuth app; other deployments still configure one OAuth provider for the first sign-in. Email triggers give an automation its own address on agents.<your-domain>: a superadmin turns them on after signing in, in Admin → Integrations → Agent email, after reviewing any DNS change they would make to your main domain. Your MX records never change. See Turn on agent email for the steps and for what to do when setup refuses your SPF record.

Optional — SAM-hosted repositories (experimental): SAM can create and host Git repositories for projects directly on Cloudflare Artifacts (currently in beta), letting users start a project without connecting GitHub. If your Cloudflare account has Artifacts access, add an Account → Artifacts → Edit permission to the token. The deploy auto-detects whether the token can reach the Artifacts REST API and enables the SAM-hosted project option only when it can — so it is safe to add the permission if it is available, or omit it entirely with no effect. To force the behavior regardless of detection, set the ARTIFACTS_BINDING_ENABLED GitHub Actions variable to true or false.

Because the token includes Workers R2 Storage access, Cloudflare’s final creation screen shows both the API token and a set of R2 S3 keys (Access Key ID + Secret Access Key) together. You do not need to create a separate R2 API token. Copy all of the values before leaving the page:

  • CF_API_TOKEN — the API token itself
  • R2_ACCESS_KEY_ID — the R2 S3 Access Key ID shown alongside the token
  • R2_SECRET_ACCESS_KEY — the R2 S3 Secret Access Key shown alongside the token

Pulumi uses the R2 S3 keys for its state backend. The deploy workflow creates the Pulumi state bucket later as ${RESOURCE_PREFIX}-pulumi-state.

You can deploy SAM before creating a GitHub App. On first deploy, SAM generates a one-time SETUP_TOKEN Worker variable and the workflow prints a Cloudflare dashboard link where you can read it. The workflow log never shows the token itself: it is masked as ***, so copy it from the dashboard. Open https://app.yourdomain.com/setup and paste that token. When the deploy prepared email and the installer recorded an owner email (BOOTSTRAP_OWNER_EMAIL), setup needs only the token and emails that owner a sign-in code; if Cloudflare is still verifying the sending domain, it asks you to wait a few minutes. Otherwise setup asks for one of GitHub, Google or GitLab OAuth, because email cannot create the first account without an owner email; a provider the deployment already has (for example from GH_* secrets) is used as is. The Google login client must have https://api.yourdomain.com/api/auth/callback/google registered as an authorized redirect URI, and is a separate OAuth client from any Google/GCP infrastructure credentials (GOOGLE_CLIENT_ID). After you sign in, add the GitHub App and any other provider in Admin → Integrations. The values are stored in SAM’s encrypted platform credential store and can be rotated later by a superadmin.

If you prefer to create the GitHub App first, use the wizard below to create it with all settings pre-filled. Enter your domain, click through to GitHub, and paste the generated values into Admin → Integrations or set the optional GH_* GitHub Environment secrets before deploy.

Your Domain

Enter the domain you'll use for SAM (the same BASE_DOMAIN you'll set in Step 6).

The GitHub App needs Pull requests: Read-only for pull request and review webhooks, Issues: Read-only for issues/issue_comment, Checks: Read-only for check_run/check_suite, and Actions: Read-only for workflow_run. Subscribe it to push, pull_request, issues, issue_comment, repository, check_run, check_suite, workflow_run, pull_request_review, and pull_request_review_comment. Enable Redirect on update under the Setup URL settings so repository access changes return users to SAM.

The App that the wizard creates can read pull requests and issues but not write them. Agents can clone and push branches, but gh pr create fails, and a trigger’s run can’t comment on or label an issue. SAM doesn’t open pull requests itself (from v2026.10.17 the agent does, when asked), so to let agents open them:

  1. In the App’s settings on GitHub, under Permissions & events, set Pull requests to Read and write. Set Issues to Read and write too if runs should comment on or label issues.
  2. Save. GitHub asks the owner of each installation to accept the new permissions, and the old ones apply until they do.

Workspaces then get the new permissions on their next GitHub token, within about an hour (SAM reuses a token for up to 50 minutes). A profile can narrow them again under Platform Policy → GitHub CLI access.

Fresh deployments can keep most platform integration credentials out of GitHub Actions secrets. After the first deploy, open /setup with the one-time setup token to choose how people sign in, then configure the rest in Admin → Integrations (/admin/integrations):

  • GitHub App and GitHub OAuth for GitHub-backed projects, pull requests, and repository access.
  • Google login OAuth for Sign in with Google. This is separate from Google/GCP infrastructure OAuth.
  • GitLab OAuth when users need to create GitLab-backed projects and workspaces.
  • Google infrastructure OAuth for keyless GCP/WIF setup. It is never offered in /setup, so it cannot be confused with Google login. Runtime integration values are stored encrypted and override environment fallbacks without a redeploy.

Before users connect GCP accounts, follow Connect Google Cloud to enable the infrastructure OAuth-client project APIs and configure its callback. The guide also explains why disabled APIs can appear as permission errors.

Check where a value came from, and clear one

Section titled “Check where a value came from, and clear one”

Each integration and field on Admin → Integrations shows where its value comes from: stored in SAM (saved in /setup, on this page, or in Admin → Settings), Worker environment fallback (a GH_*, GOOGLE_* or GITLAB_* variable from your GitHub Environment), or not configured. A stored value also shows when it changed and who changed it. A value written by /setup reads first-run setup (unauthenticated), because anyone holding the setup token can write it.

To remove a stored integration, select Clear on its card and confirm. SAM deletes the stored values, including the encrypted secret, and records a reset for each field in the settings audit. The environment fallback takes over if one is set; otherwise the integration is off and its sign-in button disappears. Clear appears only on cards that have a stored value.

When the deployment can send email (see the optional email permissions above), SAM emails every active superadmin when:

  • an integration value is set or cleared, on this page or in Admin → Settings, naming who did it;
  • first-run setup completes;
  • a GitHub, Google or GitLab sign-in is linked to an admin or superadmin account.

The emails come from security@agents.yourdomain.com (on a single-box build that sends through SMTP, from SMTP_FROM; see Email on a single-box build) and link to the admin page to review. Before the first superadmin exists, the owner email the installer recorded (BOOTSTRAP_OWNER_EMAIL) gets them instead. Sending is best-effort: a failed email is logged (security_alert.send_failed) and never blocks the change. Without email, nothing is sent.

To let people sign in with GitLab and create projects from GitLab repositories:

  1. In GitLab, add an OAuth application in your user, group, or instance Applications settings (see GitLab’s OAuth provider guide):

    • Redirect URI: https://api.yourdomain.com/api/auth/callback/gitlab, using your BASE_DOMAIN.
    • Scopes: read_user, api, read_repository and write_repository. SAM asks for all four at sign-in, and GitLab-backed workspaces use them to clone and push.
  2. Enter the GitLab host (for example https://gitlab.com), the application ID, and its secret in /setup, or later in Admin → Settings under OAuth. The GITLAB_* variables in the table below are only fallbacks for an unsaved value.

    A GitLab sign-in can join an existing SAM account with the same email, and update its name and avatar, only when the host is https://gitlab.com or comes from the GITLAB_HOST environment variable. A self-managed host saved in /setup or Admin → Settings signs people in, but a person who already uses SAM through another sign-in method keeps using that method: SAM cannot check that a self-managed GitLab really verified the email it reports. To let GitLab sign-ins join existing accounts on a self-managed host, set GITLAB_HOST (plus GITLAB_CLIENT_ID and GITLAB_CLIENT_SECRET) in the GitHub Environment instead. That also applies if people already signed in with GitLab through a self-managed host saved before November 2026: SAM now stores such logins under a host-specific id, so those earlier GitLab links only match again once the host is set in GITLAB_HOST.

  3. Check it: create a test project from a GitLab repository and start a chat.

SAM’s in-app Report an Issue flow is off until you nominate a project to receive reports. Create a private project for this (SAM calls it the Operations project), then open Admin → Integrations (/admin/integrations) and select it under Operations project. PLATFORM_FEEDBACK_PROJECT_ID is still supported as a bootstrap/environment fallback, but the in-app runtime setting is preferred and overrides it. Until an effective project exists, the Report button and the crash-screen report link are hidden from every user — so if people tell you there’s no Report button, this is why. The same setting enables hourly automated triage of platform errors into that project. See Reporting Issues.

Debugger tools let agents in the Operations project read across every user’s nodes, workspaces and sessions, including raw node logs and debug packages (kept for 7 days by default). Actions that change things, each approved by a person, arrive in a later release. The tools are off by default. To turn them on, set operations.debuggerTools in Admin → Settings under Operations. Only tasks owned by an active superadmin can use them, checked on every call, and every call is audited. Leave the setting off if you do not want any agent to see other users’ infrastructure.

Agents can stop and ask the person running a chat for permission, ask them a question, or send a sign-in link to open — see When the Agent Needs You. This is off unless you turn it on, on new and updated installations alike. Until then, SAM refuses every such request the moment an agent makes it, and no card appears. Claude Code and Codex in the default Bypass Permissions mode rarely ask, so most users won’t notice, but an agent in Manual, Accept Edits, or Plan Mode — or Amp or Gemini CLI, which ask on their own, or Claude Code in a devcontainer that runs as root — is told no every time it asks to make a change. Release-specific steps are in the self-hoster notes of Recent Product Changes.

We recommend turning it on. Agents set to ask then wait for an answer — a permission request for up to 30 minutes in a task and 2 hours in a chat — and only the person who started the chat, or someone they shared it with, can answer, with no notification sent. To turn it on, add these GitHub Environment variables (not secrets) to your production environment, each set to true:

Variable What it turns on
ACP_INTERACTIONS_ENABLED Permission requests. The other two need it as well.
ACP_INTERACTION_FORMS_ENABLED Questions, in conversation-mode chats
ACP_INTERACTION_URLS_ENABLED Links to open (external service requests), in conversation-mode chats

They take effect at the next deploy: run Deploy Production, or set them before you update so the update’s deploy picks them up. Turning a switch on applies to chats started after that deploy, including after they sleep and wake. Chats started before it on v2026.10.08 or later still can’t ask; older chats pick up the current switches the first time they wake, and keep them after that. To check that it works, start a new chat with a Claude Code profile set to Manual and ask the agent to create a file: a card with a Permission needed badge should appear. Turning a switch off refuses new requests straight away, even in running chats; any already waiting can still be answered until they expire. Deadlines and size limits are in the configuration reference.

Codex needs SAM’s own build of its runtime to ask questions and send links. Every deploy publishes that build to your R2 bucket, and new sessions use it when these variables are on, so there is nothing else to set up.

If you leave requests off, this query finds the saved Claude Code modes whose requests will be refused, in user settings, profiles, skills, and projects’ Agent Overrides. Run it in the console of your SAM D1 database (the one bound as DATABASE; its name is in the deploy workflow’s Pulumi stack output) in the Cloudflare dashboard:

SQL
SELECT 'user setting' AS place, NULL AS project_id, u.email AS owner, s.permission_mode AS mode
FROM agent_settings s LEFT JOIN users u ON u.id = s.user_id
WHERE s.agent_type = 'claude-code' AND s.permission_mode NOT IN ('bypassPermissions', 'dontAsk')
UNION ALL
SELECT 'profile: ' || p.name, p.project_id, u.email, p.permission_mode
FROM agent_profiles p LEFT JOIN users u ON u.id = p.user_id
WHERE p.agent_type = 'claude-code' AND p.permission_mode NOT IN ('bypassPermissions', 'dontAsk')
UNION ALL
SELECT 'skill: ' || k.name, k.project_id, u.email, k.permission_mode
FROM skills k LEFT JOIN users u ON u.id = k.user_id
WHERE k.agent_type = 'claude-code' AND k.permission_mode NOT IN ('bypassPermissions', 'dontAsk')
UNION ALL
SELECT 'project: ' || pr.name, pr.id, u.email, pr.agent_defaults
FROM projects pr LEFT JOIN users u ON u.id = pr.user_id
WHERE pr.agent_defaults LIKE '%"permissionMode":"%';

owner is whose Settings → Agents it is, who created the profile or skill, or who owns the project. A project row lists every agent the project sets a mode for; read its JSON to see which. Set those modes to Bypass Permissions, or clear them: a user changes their own Settings → Agents, and any admin of a project can change its profiles and Agent Overrides. A skill’s mode has no field in the app; change it with SAM’s skills_write method update tool (ask an agent in the project) or the API.

Each user connects Google Cloud from Settings → Infrastructure: under Cloud accounts, click Connect account and pick Google Cloud. SAM supports two mutually exclusive authentication modes.

Section titled “Workload Identity Federation (recommended)”

WIF avoids user-managed private keys and uses short-lived credentials. Before users start the WIF wizard, a superadmin must configure the independent Google infrastructure OAuth client at /admin/integrations, or provide the environment fallback pair GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET.

Register both static redirect URIs on that infrastructure client:

  • https://api.yourdomain.com/auth/google/callback
  • https://api.yourdomain.com/api/deployment/gcp/callback

The flow requests the Google cloud-platform scope. Runtime values saved by a superadmin are encrypted in D1 and take precedence over the environment pair; removing the runtime pair reveals the environment fallback, if present. This client is never used for user login. Google sign-in uses a different client, different variable names (GOOGLE_LOGIN_*), and only https://api.yourdomain.com/api/auth/callback/google.

Several SAM installations can connect the same Google Cloud project. A workload identity provider trusts exactly one issuer URL, so each installation creates its own provider, named from its base domain (installationWifProviderId() in apps/api/src/services/gcp-wif-setup.ts; for example sam-sammy2-party-<hash> for sammy2.party). The installations share the pool (sam-pool, or sam-deploy-pool for deployments) and the service account, so every installation connected to a project can act as that project’s service account; use separate Google Cloud projects when installations must not share cloud access. GCP_WIF_PROVIDER_ID and GCP_DEPLOY_WIF_PROVIDER_ID override the derived name. SAM still refuses to update an existing provider whose issuer differs from its own (updateOidcProvider()). Existing connections keep the pool and provider recorded when they were created; reconnecting creates the installation’s own provider.

Each user-level connection is scoped to the SAM user who made it. The provider’s condition requires assertion.user_id == '<userId>', and the service account is granted to principalSet://iam.googleapis.com/projects/<number>/locations/global/workloadIdentityPools/<pool>/attribute.sam_user/<userId> (wifAttributeCondition() and wifServiceAccountMember() in apps/api/src/services/gcp-wif-setup.ts). Connections made before this scoping used an issuer-only condition and a pool/* binding, which let any user of the installation who named the pool act as its service account. Re-run Google setup on each such connection (Re-run Google setup when the connection reports an API issue, otherwise disconnect and Connect with Google again with the same project): it scopes this installation’s provider to the user and removes the pool/* member. Disconnecting deletes the connection, so plan for new Google Cloud work not starting until the user reconnects, and check compute pool settings afterwards; running VMs stay deletable. An older shared sam-oidc provider stays in the pool with its issuer-only condition, but the narrowed binding admits a token through it only when its user_id maps to that user; delete it in Google once no installation uses it. Re-running only cleans the pool and service account that GCP_WIF_POOL_ID and GCP_SERVICE_ACCOUNT_ID name now: if either changed since the connection was made, remove the principalSet://…/workloadIdentityPools/<old-pool>/* member from the previous service account by hand. If another installation shared that service account through pool/*, it loses access as soon as the first setup removes that member, so re-run that installation’s setup promptly too, so it gets its own scoped binding. A platform GCP workload identity credential needs a pool the installation configures for it; the guided setup only creates user-scoped pools.

Within one installation a pool has one owner: one user, or the installation for platform credentials. SAM refuses to save, or to exchange tokens for, a credential naming a pool that another owner claimed or that a different owner’s credential names (409 GCP_WIF_POOL_OWNED_BY_ANOTHER_OWNER; see Security). Give every user and the platform credential its own Google Cloud project or pool. The same applies to app deployments: the first SAM user to connect deployments in a Google Cloud project owns that project’s deployment pool (GCP_DEPLOY_WIF_POOL_ID), and a different user’s deployment setup in the same project is refused before it changes anything in Google. Project members re-running setup act as the original owner.

A claim stays after its credential is deleted, because the Google-side trust may stay too. Deleting a SAM account leaves its claims behind for the same reason. To hand a pool to a different owner (for example after a Google Cloud project changes hands):

  1. Remove the old owner’s trust in Google: delete the old workload identity provider, or remove its members from the service account’s roles/iam.workloadIdentityUser binding.
  2. Delete or re-point every SAM credential of the old owner that still names the pool. A live credential keeps blocking other owners even without a claim.
  3. Release the claim (<projectNumber>/<poolId>, lowercase pool ID):
Terminal window
npx wrangler d1 execute <your-d1-database> --remote \
--command "DELETE FROM gcp_wif_pool_claims WHERE pool_key = '123456789012/sam-pool'"

If STS reports an issuer mismatch, another installation’s setup replaced the shared provider this connection was recorded against (setups before per-installation providers all used sam-oidc). Reconnect the affected installation through its Connect GCP flow, which creates its own provider. Do not switch a shared provider back and forth or accept both issuers. A failed token exchange does not prove a failed node has no cloud server. After independently checking the provider account and in-flight allocation, the existing owner-confirmed removal action can remove a failed node on user-owned cloud capacity. Its audit reason stays owner_attested_manual_deletion, separate from strict provider-confirmed termination. Fresh terminal provisioning failures positively proven to precede the provider create request retain an exact incarnation and placement absence proof, allowing normal teardown without minting another token. Intermediate durable retries keep their allocation state.

Service account JSON (OAuth-free alternative)

Section titled “Service account JSON (OAuth-free alternative)”

If the installation has no infrastructure OAuth client, a user can paste or choose a dedicated Google service-account JSON key. SAM ignores endpoint fields from the upload, signs RS256 assertions, exchanges them only at Google’s fixed token endpoint, and verifies access to the selected Compute zone before replacing a working credential.

Create a dedicated least-privilege identity rather than granting Project Owner:

Terminal window
PROJECT_ID="your-gcp-project-id"
SERVICE_ACCOUNT="sam-vm-manager@${PROJECT_ID}.iam.gserviceaccount.com"
gcloud services enable compute.googleapis.com cloudbilling.googleapis.com --project="${PROJECT_ID}"
gcloud iam service-accounts create sam-vm-manager \
--project="${PROJECT_ID}" \
--display-name="SAM VM manager"
gcloud projects add-iam-policy-binding "${PROJECT_ID}" \
--member="serviceAccount:${SERVICE_ACCOUNT}" \
--role="roles/compute.instanceAdmin.v1"
gcloud projects add-iam-policy-binding "${PROJECT_ID}" \
--member="serviceAccount:${SERVICE_ACCOUNT}" \
--role="roles/compute.securityAdmin"
gcloud iam service-accounts keys create sam-service-account.json \
--iam-account="${SERVICE_ACCOUNT}" \
--project="${PROJECT_ID}"

Cloud Billing (cloudbilling.googleapis.com) lets SAM read Google’s public list prices for the machine catalog; it grants no access to your billing account. Without it, machines are still offered but show “Price unavailable”, and Settings → Infrastructure shows a warning with the exact command and an enable link. Use Check again on the Google Cloud connection after enabling it. Vertex AI access is optional and is not required for VM provisioning. If your organization policy disables service-account key creation, use WIF or ask a Google Cloud administrator to approve an appropriate key-management policy; do not weaken the policy just for SAM.

SAM encrypts the complete JSON in both credential stores with the configured credential-encryption key. Only safe metadata is returned to the browser. Derived Google access tokens are short-lived and cached only up to their returned expiry. Rotation verifies the new key before atomically replacing all SAM copies. Running VMs stay deletable after a rotation or reconnect: SAM tears them down with your current credential once each VM proves, by its SAM labels, that it belongs to the node being deleted. If the new credential points at a different Google Cloud project, those VMs are flagged as needing manual cleanup instead. Disconnect removes SAM’s encrypted copies and cached tokens, but it cannot revoke the key in Google Cloud—disable or delete the old key there after a successful rotation or disconnect.

Terminal window
openssl rand -base64 32

Add this passphrase to the GitHub Actions environment in the next step and keep a copy in your password manager for future deployments or teardown.

In your fork: Settings → Environments → New environment → name it production.

Before adding secrets, open the environment’s Deployment branches and tags setting, choose Selected branches and tags, and add only the main branch. This external GitHub Environment policy is required: it prevents a workflow dispatched from another branch or tag from reaching production secrets, even if that branch changes the workflow’s in-repository checks. Existing installations must add this policy before their next production deployment.

Environment variables:

Variable Description Example
BASE_DOMAIN Your domain example.com
PREVIEW_BASE_DOMAIN Optional full preview hostname override; defaults to preview.BASE_DOMAIN. Currently ignored: the deploy doesn’t pass it to the Worker usercontent.example.com
PREVIEW_URL_TTL_SECONDS Optional lifetime for signed interactive-preview URLs. Currently ignored: the deploy doesn’t pass it to the Worker 300
RESOURCE_PREFIX Domain-derived Cloudflare resource prefix sa379a6
CF_CONTAINER_ENABLED Optional instant-session runtime toggle. Generated deploys set true; set false to force VM runtime. false
D1_READ_REPLICATION_MODE Optional D1 read-replication mode applied on every deploy. Defaults to auto; set disabled to remove replicas. disabled
D1_SESSION_MODE Optional Worker D1 Sessions anchor. Defaults to first-primary; set disabled to send every query to the primary. disabled
D1_RESTORE_RECOVERY_WINDOW_DAYS Optional D1 restore window for accounts with narrower retention. Defaults to 30; range 1–30. 7
D1_MIGRATION_CHURNING_TABLES Optional comma-separated <binding>.<table> subset of the reviewed retention/expiry table list. May narrow the built-in list but cannot expand it. OBSERVABILITY_DATABASE.platform_errors
D1_MIGRATION_CHURNING_TABLE_MAX_DECREASE_PERCENT Maximum allowed decrease for reviewed churning tables. Defaults to 50; range 0–100. A decrease exactly at the limit is accepted. 25
ACP_INTERACTIONS_ENABLED Optional. true lets agents ask users for permission in chat; off unless set. See Let agents ask in chat for it and the two related switches. true

By default, each deploy enables D1 read replication (read_replication.mode = "auto") on the main and observability databases, and the API Worker runs each request against a single D1 session so its queries after the first can be served by a nearby replica instead of crossing to the primary region. This is safe by construction: the session is anchored first-primary, so a request never sees data older than its own start and cannot miss a write that completed before it began, and queries that do not open a session always go to the primary. (It does not promise that a write landing during a request is visible to that request’s later queries — that is the ordinary two-non-atomic-reads race, unchanged by replication and now with a shorter window.) Scheduled sweeps and Durable Objects keep the unsessioned binding. Set D1_READ_REPLICATION_MODE=disabled to remove the replicas (Cloudflare takes up to 24 hours to stop routing to them) or D1_SESSION_MODE=disabled to keep the replicas but route every Worker query at the primary. Replication needs no extra API-token permission beyond the Account → Cloudflare Workers: D1 → Edit grant the deploy token already requires.

The reviewed default churning selectors are listed in the configuration reference (DEFAULT_D1_MIGRATION_CHURNING_TABLES in scripts/deploy/d1-migration-churning-tables.ts). All other application tables retain zero row-decrease tolerance. Leave D1_MIGRATION_CHURNING_TABLES unset to use the complete reviewed default list.

The guided setup generates RESOURCE_PREFIX from BASE_DOMAIN as s plus the first six hex characters of the domain’s SHA-256 hash. Use that generated value Deploys automatically create preview.BASE_DOMAIN, its Worker route, and a persistent Pulumi-managed signing key. No manual GitHub secret is required. Keep the default hostname single-level so Cloudflare Universal SSL covers it. An override is for operators who have separately arranged DNS/TLS for that full hostname.

instead of choosing a generic prefix.

Leaving CF_CONTAINER_ENABLED at the true the deploy workflow injects lets users start work without their own cloud credential, on Instant sessions. Setting it to false means every session provisions a cloud VM. SAM chooses a project-scoped compute credential first when one is attached to the project, then falls back to the user’s personal compute credential, then to an enabled platform compute credential configured by an administrator.

GitHub Environment secrets:

Secret Description
CF_API_TOKEN Cloudflare API token
CF_ACCOUNT_ID Cloudflare account ID (32-char hex)
CF_ZONE_ID Domain zone ID (32-char hex)
R2_ACCESS_KEY_ID R2 API token access key
R2_SECRET_ACCESS_KEY R2 API token secret key
PULUMI_CONFIG_PASSPHRASE Generated passphrase
GH_CLIENT_ID Optional GitHub App client ID; can be configured in /setup instead
GH_CLIENT_SECRET Optional GitHub App client secret; can be configured in /setup instead
GH_APP_ID Optional GitHub App ID; can be configured in /setup instead
GH_APP_PRIVATE_KEY Optional GitHub App private key (PEM or base64); can be configured in /setup
GH_APP_SLUG Optional GitHub App URL slug; can be configured in /setup instead
GH_WEBHOOK_SECRET Optional GitHub App webhook secret; can be configured in /setup instead
GOOGLE_LOGIN_CLIENT_ID Optional Google login OAuth client ID (Sign in with Google); can be configured in /setup instead. Register redirect URI https://api.yourdomain.com/api/auth/callback/google
GOOGLE_LOGIN_CLIENT_SECRET Optional Google login OAuth client secret; can be configured in /setup instead
GITLAB_HOST Optional GitLab OAuth host, such as https://gitlab.com; can be configured in /setup instead. A self-managed host set here also lets GitLab sign-ins join existing accounts by email; one saved in /setup cannot. Register redirect URI https://api.yourdomain.com/api/auth/callback/gitlab and select the read_user, api, read_repository, and write_repository scopes, which SAM requests at sign-in and GitLab-backed workspaces use to clone and push
GITLAB_CLIENT_ID Optional GitLab OAuth application ID; can be configured in /setup instead
GITLAB_CLIENT_SECRET Optional GitLab OAuth secret; can be configured in /setup instead
GOOGLE_CLIENT_ID Optional environment fallback for the Google infra/GCP OAuth client ID. A superadmin can configure the independent runtime pair at /admin/integrations; not used for login.
GOOGLE_CLIENT_SECRET Optional environment fallback for the Google infra/GCP OAuth client secret. Runtime admin configuration takes precedence; not used for login.
CF_AIG_TOKEN Optional narrower Cloudflare AI Gateway Unified Billing token
DEVCONTAINER_CACHE_CLOUDFLARE_API_TOKEN Optional narrower Cloudflare token for managed devcontainer registry credentials
DEVCONTAINER_CACHE_CLOUDFLARE_ACCOUNT_ID Optional Cloudflare account override for managed devcontainer registry credentials

Go to Actions → Deploy Production → Run workflow. Choose the main branch. You may leave target_commit_sha empty to deploy the current main tip, or paste the current main tip’s exact 40-character commit SHA. Historical commits and non-main commits are rejected. No additional commit is needed after the environment is configured.

The workflow:

  1. Validates configuration
  2. Provisions infrastructure via Pulumi (D1, KV, R2, DNS), including private VM diagnostic evidence, ProjectData archived tool payloads, one-day temporary uploads, and thirty-day TTS cache objects (infra/resources/storage.ts:r2BucketLifecycle)
  3. Runs database migrations
  4. Builds the VM Agent reproducibly and publishes both architectures under immutable keys containing the deployment commit SHA
  5. On a fresh installation only, bootstraps the API Worker and its Tail Worker binding
  6. Deploys the Web UI, applies API Worker secrets in one bulk revision, and publishes the final API Worker code
  7. Runs health checks

On an established installation, the workflow skips the bootstrap Worker revisions. It publishes the immutable VM Agent artifacts before the API Worker can require them, applies secrets in one bulk revision, and then publishes code once. Re-running the same commit reuses an existing artifact only when its digest matches and fails before Worker publication if the bytes differ.

The artifact publisher also initializes missing legacy binaries for unversioned downloads, including later skip_agent deployments on a fresh installation. Existing legacy binaries are preserved unchanged so a partial deployment cannot replace bytes still needed by the live Worker.

Before publishing final API Worker code, the workflow reads its applied Durable Object migration tag. A fresh installation creates every namespace with SQLite storage; an existing installation retains its already-applied namespace history and storage backends. This is automatic—do not edit historical migration entries or create namespaces manually.

Pulumi also creates or updates the assets bucket lifecycle resource on every deploy. The defaults are sessionSnapshotTtlDays=7, diagnosticIncidentTtlDays=7, tempUploadTtlDays=1, and ttsTtlDays=30; each accepts a positive-integer Pulumi config override. The scheduled Worker owns session expiry at seven days of actual sleep, including chat terminalization and R2 deletion. Session objects deliberately have no age-only R2 lifecycle because their object age begins before sleep and must never shorten the restore window. There is likewise no age-only rule for ProjectData archived tool payloads, durable library/ data, or release-referenced compose-image-artifacts/.

If migration state cannot be read or does not match the checked-in history, deployment stops before Wrangler runs rather than risking migration replay or namespace replacement.

The workflow also records D1 row counts before migrations. It compares a database only when that database’s D1 migration ledger advances, so ordinary traffic cannot fail a deploy when no migration ran. Business tables have zero decrease tolerance. Code-reviewed tables with automatic retention or expiry use a 50% default limit so small routine churn is accepted while a destructive wipe still blocks deployment. Self-hosters can narrow (but not expand) that reviewed table list with the D1_MIGRATION_CHURNING_TABLES repository variable and tune the limit with D1_MIGRATION_CHURNING_TABLE_MAX_DECREASE_PERCENT (0–100).

If deployment stops with POST-MIGRATION DATA INTEGRITY CHECK FAILED, it has blocked Worker deployment before serving against the suspect database state. The failed step prints the pre-migration RFC3339 recovery timestamp and an exact wrangler d1 time-travel restore command for each database. Preserve that output and inspect the reported table decreases before restoring.

For guided recovery, run the D1 Time Travel Restore workflow (d1-restore.yml). The workflow keeps the existing timestamp input name for compatibility, but the value may be any Cloudflare D1 restore point:

  • Unix seconds, such as 1786083379
  • An RFC3339/JavaScript date-time with an explicit timezone, such as 2026-08-07T06:16:19Z or 2026-08-07T08:46:19.123+02:30
  • A lowercase D1 bookmark in the 8-8-8-32 hexadecimal form printed by Wrangler, such as 00000085-0000024c-00004c6d-8e61117bf38d7adb71b934ebbf891683

The validator rejects malformed values, shell metacharacters, missing timezones, future timestamps, and timestamps outside the configured recovery window before the workflow exposes Pulumi or Cloudflare credentials. The default window is 30 days. If the account has a narrower retention policy, set the repository variable D1_RESTORE_RECOVERY_WINDOW_DAYS to a whole number from 1 through 30.

Always preview first with dry_run=true; select main, observability, or both, then repeat the same command with dry_run=false only after confirming the target. The preview runs non-mutating Time Travel lookups for every selected Pulumi-resolved database and never calls the restore operation. For a bookmark, those lookups verify that it sorts between the target database’s currently retrievable recovery-window minute and current bookmark. The boundary lookup stays one D1 minute inside the moving retention cutoff so process and service clock advancement cannot invalidate the lookup itself; consequently, the earliest boundary minute is intentionally excluded. Cloudflare remains authoritative about whether a bookmark belongs to that database. For example:

Terminal window
gh workflow run d1-restore.yml --ref main \
-f environment=production \
-f timestamp=2026-08-07T06:16:19Z \
-f database=both \
-f dry_run=true

The GitHub Environment named by environment still controls the required approval and secrets. The main selection uses only the Pulumi d1DatabaseName output, observability uses only observabilityD1DatabaseName, and both preflights both before either restore step can run.

After reviewing the preview, repeat the command with -f dry_run=false. Each successful restore prints JSON containing bookmark and previousBookmark. Preserve that output: previousBookmark is the undo point. To undo, run the workflow twice with that bookmark in the timestamp field—first with dry_run=true, then with dry_run=false after confirming the exact environment and database target. Do not copy the raw bookmark into an ad hoc shell command.

If deployment stops with a Durable Object migration-state error:

  • Errors mentioning listing lag or a Worker “created moments ago” are transient. The workflow already retries the state probe a few times (tune with the DO_MIGRATION_STATE_PROBE_ATTEMPTS and DO_MIGRATION_STATE_PROBE_RETRY_DELAY_MS GitHub repository variables); re-running the deployment is safe and resumes cleanly.
  • “tag is not present in the checked-in history” means apps/api/wrangler.toml lacks migration entries that were already applied to your Worker. Usually an upgrade merge dropped fork-local [[migrations]] entries: restore them so the deployed tag appears in the history, then redeploy. If instead you deployed an older release than the one already running (a rollback), don’t edit [[migrations]]: put main back on the newer release and deploy it (see Update forward, not back).
  • Never delete the API Worker to recover. Deleting a Worker destroys every Durable Object namespace behind it — all chat sessions, messages, and task state. There is no undo.

VM diagnostic evidence, ProjectData archived tool payloads, and terminal-session archive chunks/manifests use the existing application R2 bucket; there is no separate bucket or manually generated secret to configure. Pulumi creates an independent lifecycle rule for the private diagnostic prefix and the deployment sync binds the same bucket as PROJECT_DATA_ARCHIVE_R2 for ProjectData archival. Optional stack settings are diagnosticIncidentPrefix (default diagnostic-incidents) and diagnosticIncidentTtlDays (default 7, any positive integer). Keep the diagnostic prefix private and distinct from the reserved application namespaces agents, cli, compose-image-artifacts, library, project-data, resource-history, session-snapshots, temp-uploads, and tts; Pulumi rejects overrides whose top-level segment would expire objects owned by one of those features.

After deployment completes:

Terminal window
# API health check
curl https://api.yourdomain.com/health
# Should return: {"status":"healthy","timestamp":"..."}

Open the Cloudflare dashboard link printed by the workflow, copy the plaintext SETUP_TOKEN Worker variable, then open https://app.yourdomain.com/setup. The setup page accepts the token only while first-run setup is incomplete, and setup counts as complete as soon as the instance has an active superadmin, even one created before the setup page existed. When the deploy prepared email and the installer named an owner, setup finishes with the token alone and emails that owner a sign-in code; otherwise it asks for one OAuth provider. Once setup is complete, /setup returns Gone and future changes are made by a superadmin in Admin → Integrations and Admin → Settings.

Open https://app.yourdomain.com — you should see the login page with whichever providers you configured, plus Email me a sign-in code when the deploy prepared email.

Check that setup is closed. Once you have signed in as the first superadmin, nobody else can use the setup page. Confirm it from any machine:

Terminal window
curl -i https://api.yourdomain.com/api/setup/status
# Should return: HTTP/2 410 with "error":"SETUP_CLOSED"

A 200 response with "open":true means setup is still open to anyone holding the SETUP_TOKEN: finish setup now. If it shows "forced":true, the SETUP_FORCE=true lockout-recovery override is set; remove it from the Worker’s variables once you have recovered access, because it keeps setup open even after a superadmin exists. See the security advisory on setup takeover for why this matters.

If you enabled GitLab in platform configuration, create a test project from a GitLab repository and start a lightweight chat before inviting users. That validates the OAuth app, repository metadata propagation, and workspace credential helper path together.

Pushing upstream changes to your fork’s main branch does not update the running instance by itself. Self-host forks skip the canonical repository’s full main-push CI path, so the automatic workflow_run production deploy is not the update mechanism for forks.

Before you update, read the For self-hosters & admins notes in Recent Product Changes for every cycle since your last update. They list new and changed settings, and from the 23–29 September 2026 cycle on, they also say whether updating needs any action from you.

Section titled “Option A: Update Self-Hosted Instance workflow (recommended)”

The Update Self-Hosted Instance workflow (update-self-hosted.yml) automates the entire update process. It fetches the upstream release, fast-forwards your fork’s main branch, and triggers a production deploy automatically.

  1. Open Actions → Update Self-Hosted Instance → Run workflow in your fork.
  2. Leave release as latest to use the most recent upstream release, or enter a specific CalVer tag (e.g. v2026.09.20).
  3. The workflow fast-forwards main to the release commit and triggers Deploy Production.
  4. Wait for the Deploy Production workflow to finish, then re-run the health check above.

If your fork has local commits that are not in the upstream release, the workflow will fail with a fast-forward error. In that case, merge manually and use Option B.

  1. Sync your fork’s main branch with upstream (e.g. via GitHub’s “Sync fork” button or git fetch upstream && git merge upstream/main).
  2. Open Actions → Deploy Production → Run workflow in your fork.
  3. Choose the main branch and leave target_commit_sha empty (it defaults to the current main tip). Optionally paste the current main tip’s exact 40-character SHA. Historical commits are rejected. Leave dry_run disabled.
  4. Wait for the workflow to finish, then re-run the health check above.

Use the manual workflow when you rotate deployment secrets, change GitHub Environment variables, or want to re-apply Pulumi-managed infrastructure.

Staging and production deployments wait for container application rollouts to reach 100% before reporting success. Wrangler returning successfully only means the rollout started; the workflow’s Wait for container rollout completion step compares rollout records before/after deployment and requires the exact pinned rollout to complete every step through 100% at its target. The application list can retain the previous version after completion; the gate logs this disagreement without holding a finished rollout. Application version alone never establishes completion. Multiple new rollouts fail as ambiguous; no-op or metadata-only updates require no new rollout, but await an existing pending one. Gradual rollout behavior is preserved. API errors, unreadable state and timeout fail the deployment. The wait closes the window where deployment reports success mid-rollout; it does not prove every running instance’s binary version. The authenticated /ready callback logs instant_session.agent_version_mismatch with expected and reported versions without rejecting readiness, providing evidence for remaining version discrepancies. Optional GitHub Environment variables CONTAINER_ROLLOUT_TIMEOUT_MS (default 1200000, 20 minutes) and CONTAINER_ROLLOUT_POLL_INTERVAL_MS (default 10000) accept positive integer milliseconds. These are deployment runner settings, not Worker runtime settings. Timeout errors include the rollout ID and last status.

Before the API Worker is deployed, the Resolve container images step (scripts/deploy/container-image-reuse.ts) gives each Instant container image a content key. The key covers the Dockerfile, every file it copies, and a fingerprint of every input installed from the network: the apt package indexes of each suite the image installs from, every URL the build fetches, the resolved dependency tree of each npm install -g package, and the resolved PyPI dependencies of each uv tool install (container-image-inputs.ts, container-image-fingerprints.ts). The registry tag inputs-<key> in your account’s container registry records an image built from those inputs.

  • Inputs unchanged: the deploy uses that image’s digest. Nothing is built or pushed, and when it is the running image Wrangler reports no change and starts no rollout, so the rollout gate returns at once.
  • Inputs changed (including an upstream security update or dependency release): the image is built and pushed under the new key, and the rollout gate waits for the rollout as usual.
  • Latest rollout failed or cancelled (or its state cannot be read): the image is rebuilt to a fresh digest even when its inputs are unchanged, so the deploy starts a new rollout instead of re-pointing at the one that failed.
  • Any doubt (a Dockerfile command, fetched URL or npm install script outside the reviewed lists in container-image-reviewed-inputs.ts, a failed fingerprint, a registry error): the Dockerfile is left in place and Wrangler builds the image as it would without this step. A failed image build fails the deployment.

Anyone who can push to a repository in your account’s container registry can replace the image a tag points at, so registry write access is deploy access. That was already true of the deploy token, which can publish Workers too; keep production in a Cloudflare account, or behind a token, that staging cannot use.

The step’s job summary lists each image’s outcome and reason. A clean install has no recorded images, so its first deploy builds them. To always build with Wrangler, set the GitHub Environment variable CONTAINER_IMAGE_REUSE_ENABLED to exactly false. Optional CONTAINER_IMAGE_FINGERPRINT_TIMEOUT_MS (default 180000) bounds each fingerprint request and all of an image’s lookups together, and CONTAINER_REGISTRY_CREDENTIAL_MINUTES (default 30) sets the lifetime of each short-lived registry credential.

On ordinary deployments without an installer owner binding, the first genuine human to sign in becomes the superadmin: the account that can approve other users, manage platform credentials, and reach the admin dashboard. The promotion happens once, when that person’s first session is created (establishFirstSuperadmin, apps/api/src/services/first-superadmin.ts), and only while they are the only real account on the instance.

Email sign-in codes (services/email-sign-in.ts) create an account only for the installer owner email, before that owner exists. Otherwise only addresses that already belong to an account receive a code. Deployments without an owner email never create accounts by email, because the first person to ask for a code would become the administrator. The response is the same for every address, and the code is sent after the response, so its timing reveals nothing either. The password-reset, verification and email-change code routes are closed. Codes expire after 5 minutes and allow 3 attempts. Each address gets at most 5 codes an hour, each IP address at most 20 requests, and each address at most 10 code guesses an hour from all IP addresses combined (the agentEmail.signInCodesPerEmailPerHour, agentEmail.signInCodesPerIpPerHour and agentEmail.signInCodeAttemptsPerEmailPerHour settings). GitHub is not required before the instance exists. Preserve the owner binding across routine updates.

Fresh deployments are seeded with an internal system user (system_anonymous_trials, status='system', created by a database migration). Its id dates from SAM’s retired anonymous-trial product; it now records SAM itself as the author of platform settings saved during unattended setup, and it owns the placeholder GitHub installation row that Artifacts- and GitLab-backed projects point at. Never delete either row. This system user is not a real user, cannot sign in, and never counts toward “is this the first human” checks.

Without the installer owner binding, the first-superadmin election works like this:

  • One atomic write. The promotion is a single guarded database update, so two sign-ups can never both become superadmin. It promotes the signing-in user only if they are not suspended, no other real account exists, and the election has not already happened. It then records the winner in the platform_settings row setup.firstSuperadminEstablished.
  • A later sign-up never wins. If any other real account already exists, whether active, pending or suspended, nobody is promoted. If two people sign up at the same moment on a fresh instance and both accounts exist before either election runs, neither becomes superadmin. Use the recovery steps below.
  • The election happens once. After the marker row exists, no sign-in is ever auto-promoted, even if every superadmin is later deleted. Instances that already had a superadmin got the marker from the first_superadmin_election database migration. That migration only writes the marker and never changes a user.
  • Login always succeeds. If the database fails during the election, the sign-in still completes without promotion and the error is logged as auth.first_superadmin_election.failed. The next sign-in tries again.
  • Login-time self-heal (session.create.after, apps/api/src/auth.ts) applies the same conditions and is a second attempt in the same sign-in. It is a no-op once the marker exists.

The admin API never grants the superadmin role, so an instance has at most one unless it was hit by the concurrent first-sign-up race that existed before this election, or someone edited the database by hand. SAM does not demote anyone automatically. On an instance without BOOTSTRAP_OWNER_EMAIL, each sign-in logs the warning first-superadmin.multiple_superadmins with the count, visible in the API Worker’s logs (Cloudflare dashboard → Workers → your API worker → Logs, or wrangler tail). To review the accounts, run this against your D1 database:

SQL
SELECT id, email, status, created_at FROM users
WHERE role = 'superadmin' AND status != 'system' ORDER BY created_at;

Demote any account you do not recognise with UPDATE users SET role = 'user' WHERE id = '<id>';. The admin UI can’t do this, because it refuses to modify superadmin accounts.

Recovering when no account can administer the instance

Section titled “Recovering when no account can administer the instance”

This applies when the only superadmin was deleted, or when no superadmin was ever elected (for example, after the simultaneous-sign-up case above). Pick one:

  1. Bind an owner email (recommended). Add the API Worker secret BOOTSTRAP_OWNER_EMAIL with the email address of the person who should administer the instance: wrangler secret put BOOTSTRAP_OWNER_EMAIL --name <your-api-worker-name> (the worker is named <resource-prefix>-api-<stack>), or in the Cloudflare dashboard under the API worker’s Settings → Variables and Secrets. Deploys leave a secret they don’t set in place (scripts/deploy/configure-secrets.sh skips an empty value). That person then signs in with that address as a verified email. While no superadmin exists, the owner path (bootstrapSessionAllowed, apps/api/src/services/bootstrap-owner.ts) promotes them. It does not depend on the first-superadmin marker. Until the owner has signed in, every other sign-in is refused. After that, normal sign-in resumes and the secret can stay or be removed. This option does not work on an installer-bound instance whose owner was already established (the setup.bootstrapOwnerEstablished row exists): the owner path runs only until that row is written, so use option 2 there.
  2. Edit D1 directly. Promote a specific account: UPDATE users SET role = 'superadmin', status = 'active' WHERE id = '<id>'; (wrangler d1 execute <database> --remote --command "..."). Role checks read the database on every request, so a page refresh is enough.

Deleting the setup.firstSuperadminEstablished row does not choose an account. It only lets the election run again, and the election still promotes nobody unless exactly one real account exists.

Notes:

  • Promotion is independent of REQUIRE_APPROVAL. Installer-bound deployments still require the configured verified owner identity.
  • First-login races: both the owner-bound election and the ordinary election promote at most one user, including simultaneous provider callbacks.
  • Session freshness: SAM disables BetterAuth’s session-cookie cache when reading authorization state, so role and suspension checks use current database data. Refresh the page after a promotion; if access is still missing, recheck the promotion conditions rather than waiting for a cookie-cache timeout.

Signup approval is on by default. To let new accounts in without approval, turn it off with the switch in Admin → Users, or set the REQUIRE_APPROVAL GitHub Environment variable to false; the switch overrides the variable (getSignupApprovalConfig, apps/api/src/services/signup-approval.ts). Any value other than false, including unset, keeps approval on.

Upgrading: before November 2026, approval was off unless REQUIRE_APPROVAL was true. An installation that never set the variable and never used the switch now creates new accounts as pending. Existing accounts are unchanged.

When signup approval is on, new accounts are created pending (the very first is promoted to an active superadmin when its first session starts) and stay pending until a superadmin approves them there. Accounts created while approval was off stay active. A pending account can sign in, see that it is waiting for approval, sign out, and link its own GitHub App installation. SAM’s features answer 403 APPROVAL_REQUIRED until the account is approved, including the SAM and project agent chats, API token management, every project route, and browser-session workspace access. This also applies to pending accounts that already own resources when approval is turned on. Admins and superadmins are never held for approval, and suspended accounts are refused on authenticated account surfaces. Publicly published workspace ports and valid port-access links use their own anonymous or capability access model.

Admin → Storage (/admin/storage) shows per-project ProjectData storage telemetry and the archive-sharding circuit breakers. When a project’s archive drain fails repeatedly, its breaker opens and the scheduled sweep stops archiving that project until a superadmin closes the breaker. Each opening sends every active superadmin one high-urgency Operational Failure notification that links to this page, and records one entry in Admin → Errors. Use the Close breaker button on that page (it works from a phone) once the underlying failure is fixed; it calls POST /api/admin/project-data/storage/:projectId/archive-sharding/circuit-breaker with state: "closed" and the reason you enter. Closing a breaker does not thaw migrations that were already frozen.

Below the breakers, Problem migrations lists the individual session migrations that need attention, each with its error code, attempt count, and timestamps:

Badge Meaning
Failed An attempt failed. The sweep retries it after PROJECT_DATA_ARCHIVE_FAILED_RETRY_DELAY_MS (an hour by default).
Poisoned It failed PROJECT_DATA_ARCHIVE_POISON_AFTER_ATTEMPTS times (3 by default), which is what opens the project’s breaker.
Frozen The sweep has stopped trying it. The Error code says why, and whether you need to do anything (below).

What to do, by what the card shows:

  • Frozen, error code precopy_refused: nothing. The session was still in use when the sweep tried to copy it, so nothing was copied and it reads normally; the sweep tries it again after PROJECT_DATA_ARCHIVE_PRECOPY_REFUSAL_RETRY_MS (a day). The list shows these last.
  • Frozen, error code operator_abandoned: nothing. Someone already abandoned it, and the card stays in the list as a record. These records are never removed, and the list puts older entries first, so over time they can push newer problems past its limit (PROJECT_DATA_ARCHIVE_ROLLOUT_LIST_LIMIT_DEFAULT, 25). When the page says more may exist beyond the limit, open https://api.yourdomain.com/api/admin/project-data/storage/archive-sharding/problem-migrations?limit=100&projectId=<id> in a browser tab where you’re signed in as a superadmin (100 is the default maximum; leave out projectId to list every project).
  • Failed: nothing yet. If it keeps failing it turns Poisoned.
  • Poisoned, or Frozen with any other error code: read the error and fix its cause first. Then clear the migration with Abandon (or a copy-back, if it already deleted its source — see below), and finally Close breaker for the project, because abandoning a migration does not close the breaker.

Abandon clears a migration that never got as far as deleting the session from the project’s live storage. It discards the partial archive copy, returns the session to live storage so it reads normally, and makes it eligible for a later sweep; you have to enter a reason. (The dialog calls these the partial shard copy and root, and records the result as operator_abandoned.) SAM refuses, and the page shows its reason verbatim, when the migration is still running (its lease has not expired) or has already deleted its source. That second case needs a copy-back instead, which has no button yet: POST /api/admin/project-data/storage/:projectId/archive-sharding/migrations/:migrationId/copy-back with a reason.

The Abandon migration dialog on a phone for a poisoned migration: it explains that abandoning drops the partial shard copy, returns the session to root, and freezes the journal as operator_abandoned; lists the project, migration, and session IDs; and has a filled-in Reason field above a red Abandon migration button and a Cancel button.

When a project reaches the 10 GB storage cap

Section titled “When a project reaches the 10 GB storage cap”

Cloudflare limits each project’s storage object to 10 GB. Admin → Storage shows how close each project is. At the cap every write to that project fails: new tasks and chat messages get PROJECT_DATA_STORAGE_FULL (“ProjectData storage is full; storage recovery is required before this write can complete.”), and putting sessions to sleep fails too. So do the archive drain and Abandon, because each has to write something before it can free space, and the routine search cleanup switches itself off just before the cap.

A superadmin recovery endpoint can remove the search index of older finished sessions without removing their messages, but it does not yet have a control in Admin → Storage. There is currently no supported recovery button for a project already at the cap. Monitor storage and resolve stuck archive migrations through Admin → Storage before writes stop working.

To remove all resources: Actions → Teardown → Run workflow → type DELETE to confirm.

A full teardown (with keep_data off) empties the installation’s assets bucket before it deletes the stack, because R2 refuses to delete a non-empty bucket. The emptying stops after TEARDOWN_R2_EMPTY_DEADLINE_SECONDS (GitHub Environment variable, default 600, roughly 2,000 objects); if anything is left the bucket deletion fails and the summary says so, and running the teardown again continues where it stopped. Full teardown also deletes the API Worker’s Durable Object data; keep_data leaves the Worker in place. Teardown does not delete VMs: delete workspaces and nodes in the app first.

Component Free Tier Paid Overage
Cloudflare Workers 100K req/day $0.15/million
Cloudflare D1 5M rows read/day $0.001/million
Cloudflare KV 100K reads/day $0.50/million
Cloudflare R2 10GB storage $0.015/GB/month
Cloudflare Pages Unlimited Free

The Workers Paid plan ($5/month) is required for Durable Objects and Cloudflare Containers. Beyond the base plan, usage-based costs stay within free tier allowances for small to medium usage.

VMs are billed to the cloud provider credential SAM uses for the node. In a typical self-hosted setup, that is each user’s own BYOC credential; admins may also configure a platform credential for shared zero-config provisioning. SAM supports Hetzner, Scaleway, Vultr, Infomaniak, DigitalOcean, UpCloud, and GCP. The example prices below cover the built-in Hetzner, Scaleway, Vultr, DigitalOcean, and UpCloud size mappings; Infomaniak and GCP pricing depend on the selected region and machine configuration.

Connecting a cloud credential lists its machines in the matching compute pool but adds none of them: nothing joins a pool on its own. After you add a platform credential, open Admin → Infrastructure and add the machines and regions the shared pool may use. Until a pool has machines, people who use it can run only Instant sessions. See Compute Pools.

When compute pools are enabled, the pool editor uses the provider-native catalog for the project, user, or platform credential in scope. The small/medium/large prices below remain useful as legacy provider examples, but pool editing is based on concrete provider instance types. Deprecated legacy size labels are translated into workload slices for compatibility; they do not choose a provider SKU directly, and changing one does not rewrite the native provider payload. Exact native offerings carry their own storage/image/architecture request details where the provider API supports them. After a VM is created, the provider package returns provider-reported server type and resource fields as provenance-labeled observed hardware and leaves omitted resource fields unknown (packages/providers/src/native-vm-config.ts). Persisting those observations into node-pool admission records is part of the parent section C integration.

Hetzner:

Size Specs Hourly Monthly
Small (cx23) 2 vCPU, 4GB RAM ~$0.007 ~$4.15
Medium (cx33) 4 vCPU, 8GB RAM ~$0.012 ~$7.50
Large (cx43) 8 vCPU, 16GB RAM ~$0.030 ~$18

Scaleway:

Size Type Hourly
Small (DEV1-M) 3 vCPU, 4GB RAM ~€0.024
Medium (DEV1-XL) 4 vCPU, 12GB RAM ~€0.048
Large (GP1-S) 8 vCPU, 32GB RAM ~€0.084

Vultr:

Size Specs Monthly
Small (vc2-2c-4gb) 2 vCPU, 4GB RAM, 80GB ~$20
Medium (vc2-4c-8gb) 4 vCPU, 8GB RAM, 160GB ~$40
Large (vc2-6c-16gb) 6 vCPU, 16GB RAM, 320GB ~$80

Vultr bills hourly. Machines go to the regions your compute pool allows; fra (Frankfurt) is only the provider fallback when nothing else names a region. When you create the Vultr Personal Access Token, its IP access control allowlist must be set to Allow All IPv4/IPv6 — SAM calls the Vultr API from Cloudflare Workers, which have no static egress IP, so a restricted allowlist will reject provisioning requests.

DigitalOcean:

Size Specs Monthly
Small (s-2vcpu-4gb) 2 vCPU, 4GB RAM, 80GB ~$24
Medium (s-4vcpu-8gb) 4 vCPU, 8GB RAM, 160GB ~$48
Large (s-8vcpu-16gb) 8 vCPU, 16GB RAM, 320GB ~$96

DigitalOcean bills hourly (machines go to the regions your compute pool allows; fra1, Frankfurt, is only the provider fallback) and requires a Full Access Personal Access Token (or equivalent custom scopes for droplets, block storage, tags, account, actions, images, regions, and sizes).

UpCloud:

Size Specs Approx. monthly
Small (2xCPU-4GB) 2 vCPU, 4GB RAM ~$12
Medium (4xCPU-8GB) 4 vCPU, 8GB RAM ~$24
Large (8xCPU-16GB) 8 vCPU, 16GB RAM ~$48

UpCloud billing is usage-based. SAM verifies the configured simple plan and zone through the current API before provisioning; machines go to the zones your compute pool allows, with de-fra1 (Frankfurt) as the provider fallback. Create a dedicated API subaccount with API access and storage permissions, then enter its username and password in Settings. Prices are indicative; verify current regional pricing in the UpCloud calculator.

Unresponsive machines are released automatically

Section titled “Unresponsive machines are released automatically”

A workspace VM that stops sending heartbeats is released rather than left running up a bill and holding provider quota. That covers every cloud VM SAM manages for workspaces — the ones it provisioned automatically and the ones users created from the Nodes page (Infrastructure in the main navigation):

  1. After NODE_UNHEALTHY_DRAIN_AFTER_MS (10 minutes) of silence, SAM posts a notice in each chat on the VM and asks those sessions to sleep, so idle ones can be woken on another machine later. Once every session on the VM is asleep, or if it had none, SAM deletes the VM right away.
  2. Otherwise, after NODE_UNHEALTHY_RELEASE_AFTER_MS (30 minutes), SAM deletes the VM through the provider and fails any task still running on it, with a message naming the lost node.

Machines users enrolled themselves (bring-your-own nodes), app-deployment nodes, and Instant containers are left alone. If half or more of the running workspace VMs go silent at once (NODE_UNHEALTHY_FLEET_MAX_FRACTION, applied once there are at least NODE_UNHEALTHY_FLEET_MIN_NODES, default 3), SAM assumes it has stopped receiving heartbeats rather than that every machine died. It then holds everything — no chat notices, no sleep requests, no deletions — and, once the silence outlasts the two windows combined (40 minutes by default), logs node_cleanup.fleet_heartbeat_intake_escalation_required for you to investigate. Each health decision is recorded in the node_health_events table, which keeps its rows after the node itself is deleted. The settings are in Idle & Orphan Node Reaping.

For what SAM does with a workspace VM that stops responding, see Unresponsive machines are released automatically.

If agents stop each time they need permission and no card appears in the chat, agent requests are off, so SAM refuses every request. (With requests on, a chat started on v2026.10.08 or later but before you turned them on does the same, even after it sleeps and wakes, so fork it or start a new chat.) Turn them on as described in Let agents ask in chat, or have users switch those agents to Bypass Permissions, then start a new chat — running sessions keep the setting they started with. Amp and Gemini CLI ask on their own even in Bypass Permissions, and so does Claude Code in a devcontainer that runs as root; for them, turn requests on or fix the devcontainer user.

If writes to one project fail with “ProjectData storage is full; storage recovery is required before this write can complete.”, that project has reached Cloudflare’s 10 GB limit. See When a project reaches the 10 GB storage cap.

Your PULUMI_CONFIG_PASSPHRASE doesn’t match the one used when state was created. Use the original passphrase or delete the stack in R2 and start fresh.

“OAuth callback failed” / redirect URI mismatch

Section titled ““OAuth callback failed” / redirect URI mismatch”

Check that your GitHub App’s Callback URL matches your BASE_DOMAIN exactly: https://api.yourdomain.com/api/auth/callback/github. If you changed BASE_DOMAIN after initial setup, update the Callback URL, Setup URL, and Webhook URL on the same GitHub App.

Your API token is missing the Account → SSL and Certificates → Edit permission. New nodes require this permission so the API Worker can sign the node-generated CSR via Cloudflare Origin CA for VM-agent TLS. Edit the token in the Cloudflare dashboard and add it.

Rotating legacy shared Origin CA certificates

Section titled “Rotating legacy shared Origin CA certificates”

Older deployments may have existing nodes that were provisioned before per-node CSR signing and therefore received the legacy shared ORIGIN_CA_KEY in cloud-init. To rotate safely:

  1. Drain or delete existing workspace/deployment nodes so no running VM depends on the old certificate/key pair.
  2. Re-deploy SAM with this per-node certificate model so new nodes generate their own private key locally and fetch only a signed certificate.
  3. In Cloudflare SSL/TLS → Origin Server, revoke the old wildcard Origin CA certificate after all old nodes are gone.
  4. Remove any manually configured ORIGIN_CA_CERT or ORIGIN_CA_KEY Worker secrets. They are legacy rotation inputs and are not required for new node provisioning.

Go to Workers & Pages → Analytics Engine → Enable. This is free but must be explicitly activated.

Upgrade to the Workers Paid plan ($5/month). Go to Workers & Pages → upgrade plan.

Your API token is missing the Account → Containers → Edit permission. SAM enables Cloudflare Container instant sessions by default, so edit the token and add the permission. To deploy without the container runtime, set the GitHub environment variable CF_CONTAINER_ENABLED=false and re-run the workflow.

Deploy fails at Configure R2 CORS (HTTP 400, code 10029)

Section titled “Deploy fails at Configure R2 CORS (HTTP 400, code 10029)”

Deploy Production stops at the Configure R2 CORS step because Cloudflare rejected the request: since October 2026 its API refuses the field names that releases up to v2026.10.16 send. The deploy stops before database migrations run or anything new is published, so your running instance keeps working. Update to v2026.10.17 or later with the Update Self-Hosted Instance workflow, which sends the fields Cloudflare expects, then re-run the deploy if it doesn’t start on its own.

If using a subdomain as BASE_DOMAIN (e.g., sam.example.com), the free Universal SSL certificate does not cover nested wildcards (*.sam.example.com). Use a top-level domain as BASE_DOMAIN instead.

If you changed BASE_DOMAIN, old DNS records from a previous deployment may conflict. Go to Cloudflare DNS and delete the stale api, app, and * records, then re-run the deploy.

Migrations haven’t been applied. The deploy workflow runs them automatically, but you can also run manually:

Terminal window
wrangler d1 migrations apply <deployed-d1-database-name> --remote

Use the D1 database name from the deploy workflow’s Pulumi stack output.

Check Hetzner console for VM status. If the VM is running, SSH in and check systemctl status vm-agent.

This page is the canonical troubleshooting reference for self-hosted deployments.

Compact SQLite/R2 archive writes are opt-in (PROJECT_DATA_ARCHIVE_COMPACT_ENABLED=false). Deployment supplies the existing private archive bucket; no new credentials are required. Before enabling, validate history, search and copy-back on staging and choose a migration allowance with room for normal account usage. Keep archived R2 objects for as long as their conversations exist. See the format, cost controls and recovery limits.

The user-level SAM Connector is enabled by default, including after you update to v2026.10.10 or later. People connect Claude, ChatGPT, or a command-line client from their account’s Settings → Access; superadmins manage installation policy in Admin → Integrations → Connector. To turn it off, switch off Enable Connector there or in Admin → Settings. Setting the CONNECTOR_ENABLED GitHub Environment variable to false before you deploy also works, but only while no value has been saved in the app: a saved value wins over the variable. See Use SAM from Claude and ChatGPT and the Connector settings.

Each installation has its own OAuth issuer and audience. Pulumi provisions the OAUTH_KV namespace and Worker binding. Vendor servers must reach the API host’s discovery endpoints, /oauth/*, and /connect/mcp; Cloudflare Access login walls or WAF challenges on these paths can block connection and refresh. Keep SAM’s OAuth authentication enforced when adjusting those network policies. Users also need the web host for sign-in and consent.

Deployments enable Cloudflare’s native API Worker traces at 100% sampling, alongside existing Workers logs. Traces capture dependency timings for D1, KV, outbound HTTP and Durable Object calls without an application SDK. Find new traces in the Cloudflare Workers Observability dashboard; enabling tracing cannot recover traces for older requests.

To reduce sampling or disable tracing, add the standard configuration to the top level of apps/api/wrangler.toml before deploying. The deployment generator preserves these trace settings in both staging and production:

TOML
[observability]
enabled = true
[observability.traces]
enabled = true
head_sampling_rate = 0.05 # Trace 5% of requests; use 1 for full capture.
persist = true

Set observability.traces.enabled = false to disable capture. Traces retain seven days of history. Starting December 1, 2026, stored traces count toward account-wide observability ingestion and storage allowances; 100% sampling can generate substantial volume on busy installations. Review Cloudflare tracing and observability pricing before choosing ongoing sampling. The generated configuration redacts query strings from observability URLs because callback and terminal URLs can contain credentials. Traces can still include URL paths and database statement metadata; restrict access to observability data as you would for production logs.

Instant sessions publish applications through a dedicated Cloudflare Container build executor. Cloudflare Containers are already part of SAM’s supported setup, so this adds no separate cloud account or manual secret prerequisite. Deployment targets remain VMs. VM sessions retain the node executor by default; keep deployments.buildExecutor=node in Admin → Settings until a staging VM trial verifies a served release with unchanged source build/save counters. VM publishing through Cloudflare remains unverified. DEPLOY_BUILDER_INSTANCE_TYPE and DEPLOY_BUILDER_MAX_INSTANCES are deployment-time sizing controls; see the configuration reference.

The builder runs one job per ephemeral container and can execute arbitrary Dockerfile steps as root inside DinD with host build networking and unrestricted internet access, just like VM workspaces. Context and image transfers use direct presigned URLs; no outbound proxy or HTTPS interception CA is installed. It receives no user or installation credentials, runtime secret values or workspace token. Its callback token stays in the Go supervisor’s memory and authorizes only one job and attempt until that job’s deadline or terminal state. Treat arbitrary root code as having that job’s authority. The bootstrap listener closes before build steps run, and a durable alarm attempts to destroy the microVM at the hard deadline, independent of source-session liveness. If shutdown cannot be confirmed, cron force-releases the reservation after the stored deadline plus deployments.builderReservationGraceMs (five minutes by default), marks unfinished jobs unknown and records an alert. This permits deletion and new admissions without claiming physical shutdown; Cloudflare capacity can remain occupied until reclaimed. See the build trust model for the enforcing code paths.

Connect a repository sign-in to an email account

Section titled “Connect a repository sign-in to an email account”

A person who signs in by email or Google can open Settings → GitHub to connect GitHub or GitLab, if that provider is configured. Connecting adds a sign-in method and repository authorization to the same SAM account. Google cannot be linked to an existing account.

Choose Connect, then open the confirmation email in the same browser. Choose Confirm connection to continue to the provider’s consent screen. The email is a fresh, one-time sign-in check for that account, session and provider; an existing session alone cannot add a new sign-in method. Confirmation expires after five minutes by default. An administrator can change security.accountLinkProofTtlSeconds (60–900 seconds) in Admin → Settings → Email; new confirmation emails use the updated value and existing proofs keep their original deadline. A revoked session or expired confirmation must start again. Your account email must already be confirmed and the installation must support email delivery. If your provider has not confirmed it, sign in with that provider after confirming your email there, or contact the installation administrator.

The existing OAuth application registration stays unchanged: GitHub uses https://api.<your-domain>/api/auth/callback/github and GitLab uses https://api.<your-domain>/api/auth/callback/gitlab. Flow context travels in protected OAuth state, never in per-user redirect URIs. GitLab retains its configured host and identity-trust restrictions.

The connected provider may have a different email. Linking and later provider sign-ins preserve the already-verified SAM account email; name and avatar may refresh. SAM sends a linked-provider security notification to the account owner’s stored email. Review the connected provider in Settings → GitHub and choose Disconnect if you do not recognize it. Disconnect requires a confirmed account email and available email sign-in, so removing a provider cannot remove your last sign-in method. An old session may require signing out and signing in again first.

Accounts created by a provider with an unverified email receive a provider-sign-in reminder instead of a sign-in code. Their email-code redemption is refused so BetterAuth cannot remove their provider link while proving a previously unverified email. Existing verified email users can continue using email codes after connecting or disconnecting a provider.