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.

RequirementPurposeTier
Cloudflare accountAPI hosting, DNS, storageWorkers Paid ($5/mo)
GitHub accountAuthentication, CI/CDFree tier
Domain on CloudflareWorkspace URLsAny 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 & PagesAnalytics EngineEnable.

You do not need a shared cloud provider account. Users provide their own Hetzner API token, Scaleway API key, 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 TypeResourceAccess
AccountCloudflare Workers: D1Edit
AccountWorkers KV StorageEdit
AccountWorkers R2 StorageEdit
AccountWorkers ScriptsEdit
AccountWorkers ObservabilityRead
AccountCloudflare PagesEdit
AccountAI GatewayEdit
AccountContainersEdit
AccountSSL and CertificatesEdit
ZoneDNSEdit
ZoneWorkers RoutesEdit
ZoneSSL and CertificatesEdit
ZoneZoneRead

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 — 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. Open https://app.yourdomain.com/setup, paste that token, and configure GitHub App, GitHub OAuth, and Google login OAuth credentials in the setup wizard. 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). 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 /setup 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 because it subscribes to the pull_request webhook event. Enable Redirect on update under the Setup URL settings so repository access changes return users to SAM.

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 and configure the integrations users need:

  • 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.

A superadmin can separately configure Google infrastructure OAuth at /admin/integrations for keyless GCP/WIF setup. It is intentionally absent from /setup so installations do not confuse it with Google login. Runtime integration values are stored encrypted and override environment fallbacks without a redeploy.

Each user connects Google Cloud from Settings → Cloud Providers → 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.

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 --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}"

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. 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.

Environment variables:

VariableDescriptionExample
BASE_DOMAINYour domainexample.com
RESOURCE_PREFIXDomain-derived Cloudflare resource prefixsa379a6
CF_CONTAINER_ENABLEDOptional instant-session runtime toggle. Defaults to true; set false to force VM runtime.false

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 instead of choosing a generic prefix.

Environment secrets:

SecretDescription
CF_API_TOKENCloudflare API token
CF_ACCOUNT_IDCloudflare account ID (32-char hex)
CF_ZONE_IDDomain zone ID (32-char hex)
R2_ACCESS_KEY_IDR2 API token access key
R2_SECRET_ACCESS_KEYR2 API token secret key
PULUMI_CONFIG_PASSPHRASEGenerated passphrase
GH_CLIENT_IDOptional GitHub App client ID; can be configured in /setup instead
GH_CLIENT_SECRETOptional GitHub App client secret; can be configured in /setup instead
GH_APP_IDOptional GitHub App ID; can be configured in /setup instead
GH_APP_PRIVATE_KEYOptional GitHub App private key (PEM or base64); can be configured in /setup
GH_APP_SLUGOptional GitHub App URL slug; can be configured in /setup instead
GH_WEBHOOK_SECRETOptional GitHub App webhook secret; can be configured in /setup instead
GOOGLE_LOGIN_CLIENT_IDOptional 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_SECRETOptional Google login OAuth client secret; can be configured in /setup instead
GITLAB_HOSTOptional GitLab OAuth host, such as https://gitlab.com; can be configured in /setup instead. Register redirect URI https://api.yourdomain.com/api/auth/callback/gitlab and grant the read_user and api scopes (api is required for repository clone/push and merge-request creation in GitLab-backed workspaces)
GITLAB_CLIENT_IDOptional GitLab OAuth application ID; can be configured in /setup instead
GITLAB_CLIENT_SECRETOptional GitLab OAuth secret; can be configured in /setup instead
GOOGLE_CLIENT_IDOptional 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_SECRETOptional environment fallback for the Google infra/GCP OAuth client secret. Runtime admin configuration takes precedence; not used for login.
CF_AIG_TOKENOptional narrower Cloudflare AI Gateway Unified Billing token
DEVCONTAINER_CACHE_CLOUDFLARE_API_TOKENOptional narrower Cloudflare token for managed devcontainer registry credentials
DEVCONTAINER_CACHE_CLOUDFLARE_ACCOUNT_IDOptional Cloudflare account override for managed devcontainer registry credentials

Go to Actions → Deploy Production → Run workflow. Choose the main branch. No commit is needed after the environment is configured.

The workflow:

  1. Validates configuration
  2. Provisions infrastructure via Pulumi (D1, KV, R2, DNS)
  3. Deploys API Worker and Web UI
  4. Runs database migrations
  5. Builds and uploads VM Agent binaries
  6. Runs health check

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. After you save a valid login provider and complete setup, /setup returns Gone and future changes move to the superadmin platform config UI.

Open https://app.yourdomain.com — you should see the login page with whichever providers you configured.

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.

Sync or merge upstream SAM changes into your fork’s main branch when you want to update. Pushing those changes to the fork 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.

To deploy an update:

  1. Sync your fork’s main branch with upstream.
  2. Open Actions → Deploy Production → Run workflow in your fork.
  3. Choose the main branch and leave dry_run disabled.
  4. Wait for the workflow to finish, then re-run the health check above.

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

The first genuine human to sign in to a fresh deployment becomes the superadmin — the account that can approve other users, manage platform credentials, and reach the admin dashboard.

Fresh deployments are seeded with an internal sentinel user (system_anonymous_trials, status='system', created by a database migration) used for anonymous trials. This sentinel is not a real user and never counts toward “is this the first human” checks. Two mechanisms guarantee the first real human is promoted regardless of the sentinel:

  • Deploy-time backfill (migration): when a deployment has exactly one non-system human and no superadmin yet, that human is promoted to superadmin/active when migrations run. This also covers accounts created via token-login or device-flow.
  • Login-time self-heal (all sign-in paths): on every session creation — GitHub OAuth, token-login, and device-flow — if the signing-in user is the only non-system human and no superadmin exists, they are promoted in a single atomic, idempotent write. A failure here never blocks login.

Both mechanisms apply the same promotion conditions and are strictly no-ops in any other state — they never promote a second user, never touch an existing superadmin, and never auto-promote a suspended or system account. They differ only in how they exclude the sentinel: the login-time hook excludes it by both status='system' and id, while the deploy-time migration excludes it by status='system' alone. On managed/multi-user deployments nothing changes.

Notes:

  • Promotion happens regardless of REQUIRE_APPROVAL. Even with open registration, the first human owns the deployment.
  • First-login race: if two brand-new users sign in at the exact same moment, the atomic guard ensures at most one becomes superadmin; the other remains a normal user.
  • Cookie-cache staleness: the session role is cached for up to 5 minutes. If you were promoted while already holding a session (e.g. the deploy-time backfill ran during a deploy while you were logged in), the cached session still shows your old user role. Log out and log back in to pick up superadmin access immediately; otherwise you must wait for the cache to expire (up to 5 minutes). If the admin dashboard is still not visible after re-logging in, the promotion did not occur — recheck the guard conditions above.

The sentinel user id defaults to system_anonymous_trials. If your deployment uses a different sentinel id, set TRIAL_ANONYMOUS_USER_ID to that value so the first-user checks exclude it correctly. This variable scopes the login-time self-heal hook and the first-user creation check; the deploy-time migration excludes the sentinel by its status='system' flag (not by id), so it stays correct regardless of this setting because the sentinel is always seeded with status='system'. Most deployments never need to set this.

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

ComponentFree TierPaid Overage
Cloudflare Workers100K req/day$0.15/million
Cloudflare D15M rows read/day$0.001/million
Cloudflare KV100K reads/day$0.50/million
Cloudflare R210GB storage$0.015/GB/month
Cloudflare PagesUnlimitedFree

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, and GCP. The example prices below cover the built-in Hetzner and Scaleway size mappings; GCP pricing depends on the selected project, zone, and machine family.

Hetzner:

SizeSpecsHourlyMonthly
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:

SizeTypeHourly
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

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 & PagesAnalytics EngineEnable. 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.

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.