The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
TL;DR
mdeploy selects the stage's cloud engine, validates its inputs, and applies one shared BoxLite resource model.
mdeploy reference
Infrastructure index · Deployment walkthrough · Architecture
mdeploy derives API runtime IAM from explicit capabilities. Read API runtime IAM capabilities before adding an API permission, diagnosing Filestore lookup permissions, or deciding whether deployment grants a role automatically.
Execution path
mstage: stage declaration + identity + encrypted environment
→ mdeploy: intent and protection checks
→ GCP: Pulumi → GCP providers → GCS state
→ AWS: SST → AWS providers → SST state
The current command is npm run mdeploy -- --stage <stage> from apps/infra.
The retained npm run deploy command uses deployment/sst.ts and the legacy stack/ tree;
its flags, state assumptions and post-deploy checks are not interchangeable with mdeploy's.
AWS bootstrap and mdeploy currently use different app names; read the
AWS compatibility boundary before a transition.
Inputs
| Input | Owner |
|---|---|
| App identity, build artifacts, environment groups | Committed mstage.env.json |
| Cloud, region/project, registry and resource sizing | Ignored .mstage.config.json |
| Domains, fleet count, secrets and feature settings | Encrypted stage environment |
| Container identity | Invocation's BOXLITE_IMAGE_TAG |
| Runner release | Workspace Cargo.toml, or invocation's VERSION |
| Runner commit build | RUNNER_ARTIFACT_SOURCE=build and RUNNER_ARTIFACT_REF=<full-sha> |
See configuration for writing and verifying each input.
BOXLITE_IMAGE_TAG accepts a full lowercase SHA or vX.Y.Z-<sha> for release images.
The environment describes the desired deployment; setting a tag does not build an artifact.
Use mbuild and the runner runbook to prepare it first.
Hosted GitHub CI Listener
Personal and Organization Apps use separate credentials and webhook URLs. Add
CI_GITHUB_ORG_APP_CLIENT_ID and CI_GITHUB_ORG_APP_SLUG as ordinary settings
for the Organization App. Its CI_GITHUB_ORG_APP_PRIVATE_KEY,
CI_GITHUB_ORG_WEBHOOK_SECRET and optional CI_GITHUB_ORG_APP_CLIENT_SECRET
use secret refs in both the api and secret groups, as the Personal App does.
An Organization App requires the Personal App storage anchor and a distinct
client ID. The deployment validates this configuration before infrastructure
changes; configuring both Apps still creates one hosted Listener and one account quota.
The API imports the shared TypeScript Listener. Configure its App identity and slug
as ordinary mstage API settings. Configure CI_GITHUB_APP_PRIVATE_KEY,
CI_GITHUB_WEBHOOK_SECRET and CI_SECRET_ENCRYPTION_KEY as secret references.
The committed catalog already places the credentials in both the optional api
consumer group and the optional secret marker group; no additional enable flag is needed.
A partial CI configuration or plaintext credential channel stops deployment.
Dashboard browser connect additionally uses optional CI_GITHUB_OAUTH_CLIENT_ID
and a separate CI_GITHUB_OAUTH_CLIENT_SECRET reference. The identity OAuth App
requests only profile and organization-membership reads; the CI Apps keep their
runner permissions. Device Flow and the scheduler do not require identity OAuth.
For a GCP stage, store reference documents rather than secret values:
npm run mstage env set -- --stage dev CI_GITHUB_APP_CLIENT_ID=YOUR_CLIENT_ID CI_GITHUB_APP_SLUG=YOUR_APP_SLUG CI_GITHUB_OAUTH_CLIENT_ID=YOUR_IDENTITY_OAUTH_CLIENT_ID
npm run mstage env set -- --stage dev --json \
'CI_GITHUB_APP_PRIVATE_KEY={"address":"projects/PROJECT/secrets/ci-app-private-key/versions/1"}' \
'CI_GITHUB_WEBHOOK_SECRET={"address":"projects/PROJECT/secrets/ci-webhook/versions/1"}' \
'CI_SECRET_ENCRYPTION_KEY={"address":"projects/PROJECT/secrets/ci-connect-encryption/versions/1"}' \
'CI_GITHUB_OAUTH_CLIENT_SECRET={"address":"projects/PROJECT/secrets/ci-identity-oauth-client-secret/versions/1"}'
npm run mstage env list -- --stage dev --select-group api
Run these commands from apps/infra, replacing the placeholders with existing
secrets. The final command prints configured names. mdeploy grants the API identity
read access to the referenced secrets and emits Cloud Run secretKeyRef entries;
the PEM/HMAC/encryption values are not copied into revision configuration or passed
to runner hosts and JIT Boxes. The encryption secret holds base64 for exactly 32
bytes. Keep it stable across replicas while connect attempts are pending.
For browser connect, add the exact ${DASHBOARD_URL}/settings/ci/callback URL
to the GitHub App; leave wildcard matching and OAuth-during-installation disabled.
Apply the additive CI web-connect migration. For GCP, the API image bundles both
API and Dashboard artifacts; one Cloud Run revision updates both surfaces.
The Dashboard's CI tab starts authorization; merely installing the App does not
establish BoxLite account ownership. Keep the current standalone Listener and its
webhook active until a coordinated hosted cutover can avoid duplicate providers.
Pin secret versions and deploy a new revision when rotating them. The API receives
the resolved values at instance startup; it does not fetch Secret Manager itself.
The GCP API retains cpuIdle: false for custom-domain background work.
Set deploy.api.minInstances in the mstage declaration to configure the Cloud Run service minimum, including zero.
When omitted, hosted CI sets a minimum of one; otherwise the service minimum is omitted.
Continuous CPU applies only while an instance exists and incurs idle instance costs.
Multiple replicas use the PostgreSQL lease to select one CI scheduler.
See the API configuration contract and Cloud Run secret delivery. Provider-input tests do not replace a deployed App/CI acceptance run.
Scheduler deployment generation
mdeploy passes the invocation's CI_SCHEDULER_GENERATION, or GITHUB_RUN_ID
when no override is supplied, into the API environment on both clouds.
The value must be a positive safe integer in canonical decimal form.
This is per-deployment metadata, like BOXLITE_IMAGE_TAG; do not store it in
mstage groups. Invocations without either value retain local lease behavior.
A newer generation takes over scheduling after its API listens and the current database transaction finishes. Older deployments cannot renew or reacquire ownership. Retrying the same workflow run preserves its generation. To roll back an image, dispatch a new workflow run so the rollback receives a higher generation. Manual invocations must supply a generation greater than the last active deployment.
To test this PR's deployment program, dispatch the workflow with
--ref fix/ci-label-capacity; the deploy program comes from the dispatch ref.
Runner convergence
Runner hosts retain local box state and are protected against replacement. Boot-image, startup and attached-disk changes are ignored for existing hosts; binary and unit-environment updates have a separate path.
For a staged Runner, first boot and upgrades match the literal archive name in its sidecar and verify the SHA-256 before extraction. Updates also verify readiness. Already-converged hosts need no restart; release downgrade requires the explicit operator command. Follow GCP runner convergence or AWS runner convergence for the update mechanism and its completion boundary.
Runner process environment
BOXLITE_RUNNER_ENV is an optional JSON object in mstage's runner environment
group. From apps/infra, for example:
npm run mstage env set -- --stage dev --json 'BOXLITE_RUNNER_ENV={"BOXLITE_EXPERIMENTAL":"nested-virtualization"}'
Apply the stage with mdeploy after changing the value. New hosts receive the map at boot; existing GCP hosts converge through OS Config and AWS hosts through the existing update payload. Changes restart the Runner process, without rebooting or replacing the instance. Running boxes are affected by that process restart. An unchanged map, including reordered keys, causes no environment-driven restart.
Values must be single-line strings; JSON trailing commas are invalid. The map
adds process settings, not guest environment or secret references. Deployment-owned
identity, API, storage, kernel and telemetry keys, direct runner-group settings,
secret names/address keys, and PATH cannot be overridden here. The cloud secret
wrappers need the deployment's tool search path. Use the existing
configuration channels. Map values appear in deployment state and host configuration;
use the secret channel for credentials.
Removing a map entry removes its previously managed value; {} or removing the
wrapper clears all managed entries. Unrelated settings and file permissions are
preserved. A previously injected duplicate of a newly managed key is replaced
when adopted and does not return after removal. The map grants no capabilities
itself; a setting's effect depends on the deployed Runner's configuration support.
Cloud implementations
Each stage declares home; that field selects credentials, store backend, engine and provider bundle.
There is no repository-wide cloud default. Read the separate GCP or
AWS architecture and operations guides for resource mappings and network paths.
For the GCP stage environment, the API, Collector, Registry Proxy and both Secret Server services declare the service-level label stage=stage.
Backoffice uses this label to scope discovery within the shared dev project; labels do not provide IAM isolation.
Service discovery requires deployment and Cloud Asset indexing.
GCP workload service accounts keep the <appShort>-<stage>-<artifact>-run identity format and the 30-character limit.
For stage, two artifact segments use shorter names:
| Workload | Service account ID | Characters |
|---|---|---|
| Collector | bl-app-stage-otel-run |
21 |
| Registry Proxy | bl-app-stage-registry-run |
25 |
Other roles and environments retain their existing IDs. Logical resource names, workload roles and IAM references remain attached to the same account resources. Do not rename existing dev/prod accounts: changing an account ID replaces the identity.
For the pinned GCP provider, Cloud Run container ports is a single { name, containerPort } object;
the Proxy and ClickStack backend healthChecks fields take the health-check resource's ID directly.
These fields are not arrays, despite their plural names. Kubernetes, firewall and forwarding-rule port lists retain their separate array contracts.
The provider-shape regressions inspect actual constructor inputs; a successful preview must also be checked for type warnings before apply.
Private registry upstreams
On GCP stages with a registry proxy, an organization's matching credential allows private pulls from a custom HTTPS registry with a same-host Bearer token endpoint. Deploy the registry proxy before the API when enabling custom private registries.
The optional REGISTRY_PROXY_UPSTREAM_HOSTS setting in the stage's deploy
group controls anonymous pulls through the proxy. A nonempty value replaces the
default hosts. Anonymous pulls that go directly through a Runner use the API's
separate BOXLITE_IMAGE_REGISTRY_ALLOWLIST.
CI orchestration
mdeploy-all.yml resolves the requested ref, ensures
its artifacts exist, checks the stage digest, then previews or applies. Release images must already
exist in GHCR; the workflow imports their digests into the target stage's AR/ECR repository and
enforces that stage's scan policy before deployment. Missing GHCR images stop the run and print
a manual mbuild-release dispatch command. Deployment never starts a release build.
GCP imports and scans use GCP_IMAGE_PUBLISHER; the job restores GCP_DEPLOYER before image verification and apply.
It is the public rollout entrypoint; the internal CLI receives the same components selection for preview and apply.
| Selection | GCP deployment scope |
|---|---|
api |
Existing Cloud Run Api and CloudAppWorker services and API Secret Manager read grants; image/env changes create new revisions |
runner |
Existing Runner OS Policy assignments and artifact-read grant; retains canary-before-fleet rollout and waits |
api+runner (default) |
Full infrastructure graph, including shared resources and topology changes |
AWS/SST supports only api+runner; individual API/Runner selection fails before artifact preparation.
GCP scoped updates require an existing workload and do not bootstrap a new stack.
The first Cloud Apps deployment requires api+runner to create its worker and source-storage grants.
Runner selection refuses changed host counts, labels or policy membership; reconcile those through a full deployment.
Component routing handles each selection explicitly and checks exhaustiveness at compile time.
Adding a scoped component requires its own target mapping; unknown runtime selections are rejected.
VMs, disks, proxy, database and other shared resources are outside the individual component targets.
The API and Runner keep their existing environment groups and assembly; changing a store value alone does not update a running workload.
For a configuration-only change, select its component and reuse the deployed artifact ref.
Pulumi still evaluates the full inline program and validates its inputs, using recorded outputs for untargeted dependencies.
New API secret references and a Runner release-to-build transition include their required read grants, even when absent from old state.
Shared infrastructure changes require a full deployment; scoped updates skip the unrelated DNS/certificate preflight.
On GCP, a Runner-only release plan validates the Runner manifest and archive digests and targets the Runner OS policies and artifact access grant.
It can use a release that predates the Secret Server image. API and full GCP release plans require a digest for each image deployed in the selected stage.
For example, dev2 uses four images. GCP dev, stage and prod also require the Secret Server digest.
On the dev/prod release path, API-only runs require a published release and can proceed without Runner attachments.
For a commit or stage tag, API-only runs verify and, when necessary, build the single API image shared by the API and CloudAppWorker.
For an intentional host downgrade, use runner:update --allow-downgrade from a checkout that understands the deployed policy.
Local provider/target tests do not prove live Cloud Run health or OS Config host compliance.
A commit or open PR merge commit is accepted for dev and stage; both may use candidate workflow branches.
prod requires a published release; release dispatches run from main.
Stage resolves stable tags to their commits and uses SHA-tagged images and a commit Runner build.
The Runner archive version comes from the same commit as the build, including when the deployment workflow runs from another branch.
Dev/prod release deployments import the existing version-qualified images from GHCR.
Commit images and Runner artifacts each have a parallel plan/build matrix leg with isolated checkout and cloud credentials.
Review both pending preparation jobs as one target Environment batch; commit deployment requires a separate approval.
Published releases verify, import and deploy within one protected job, requiring one approval.
The shared image and deployment actions preserve the same artifact and apply checks. Check actual environment reviewers and branch protections separately: source
configuration is not evidence of the live GitHub settings.
Use the deployment walkthrough for commands and the workflow reference for the wider CI graph.
Commands and protection
npm run mdeploy -- --help
npm run mdeploy -- --stage dev --diff
npm run mdeploy -- --stage dev
npm run mdeploy -- --stage prod --confirm
npm run mdeploy -- --stage dev --refresh
| Intent | Effect |
|---|---|
| Default | Apply the resource graph; protected stages require --confirm |
--diff |
Preview resource changes |
--refresh |
Reconcile deployment state with the cloud; protected stages require --confirm |
--remove --confirm |
Remove an unprotected stage; always refused for a protected stage |
--local-env |
Read ambient environment instead of the encrypted stage store |
--components |
Internal workflow selection: api+runner by default; GCP api/runner accept preview/apply only |
--diff, --refresh, and --remove are mutually exclusive. All intents check the selected
stage's login requirements. --local-env is an explicit diagnostic override, not the ordinary
configuration path; the caller must supply the required inputs.
Checkpoint archive bucket
GCP creates a dedicated Checkpoints resource named <app>-<stage>-checkpoints.
Archives use gs://<bucket>/checkpoints/; the stack passes this location to the
API as CHECKPOINT_ARCHIVE_PREFIX and the same bucket to runner object grants.
The API and runners receive roles/storage.objectUser on this bucket alone.
Uniform access and public access prevention are enabled; versioning and soft
delete retention are disabled for this archive bucket.
This bucket is separate from application storage, per-volume buckets and the infrastructure engine's state/checkpoint bucket. AWS does not enable this archive capability. Deploy the checkpoint database migration and compatible API/runners with this storage configuration before enabling capture. The REST API and capture/import orchestration use this archive path; see the API checkpoint contract.
Implementation and validation
src/run.ts: input parsing, login and protected-stage guards.src/deploy.ts: the cloud-specific engine/backend bundle.src/config.ts: deployment sizing schema.src/stack-env.ts: values supplied to both cloud engines.stack/index.ts: resource composition.sst.config.ts/pulumi/program.ts: engine entrypoints.
stack/clickhouse-retention.ts owns the shared retention default
and hour validation for both clouds. The legacy deployment path imports it through
mdeploy/clickhouse-retention; mdeploy's own modules use relative imports within the package.
This keeps one retention rule without a dependency from mdeploy back into its enclosing infra project.
The lint configuration permits eager imports of this entrypoint, which has no dependencies,
while keeping mdeploy's CLI entrypoints lazy.
The legacy key-policy contract scans this exported configuration reader alongside the legacy source roots,
so moving the helper preserves its check against the shared store's allowlist.
Run make test:apps:infra from the repository root for tooling checks. A passing local test or
preview is not live rollout proof; follow the deployment verification.
GCP Secret Server
A full GCP dev, stage or prod deploy creates boxlite_secrets on the existing Cloud SQL instance and connects through
the mounted Unix socket as boxlite. The database and generated 32-byte master key have Pulumi replacement protection.
Write and fetch revisions receive pinned Secret Manager versions for DATABASE_URL and SECRET_MASTER_KEY_BASE64.
The shared PostgreSQL account retains access to both databases. Each stage generates its own key. Both production
roles run with ENVIRONMENT=production and Google authentication. They use the same SECRET_MASTER_KEY_ID and
numbered SECRET_MASTER_KEY_BASE64 version across revisions. Restore the database with the matching key ID and material.
| Cloud Run role | Ingress and invoker | Application checks |
|---|---|---|
write |
Internal, API service account | Google token audience and API email allowlist |
fetch |
Internal, Runner service account | Full instance identity, project, service account and registered machine ID |
In dev, stage and prod, Cloud Run keeps one instance of each service warm even when idle. Write and fetch scale independently with CPU usage and concurrent requests. Each revision can scale up to two instances.
Both Secret Server roles attach to the stage's primary private subnet using its regional resource ID
(projects/<project>/regions/<region>/subnetworks/<name>). Both callers use the private run.app DNS zone.
Deployment selects the Cloud Run serving URL that matches
the role's configured Google token audience. If Cloud Run omits that address, deployment stops before distributing it.
The API receives the write URL. On full apply, once the VMs exist and any extra Runner registrations finish,
the deployment host waits up to five minutes for /api/health on the public API. For each slot it reads
the live GCE instance ID as a decimal string by project, zone and VM name using gcloud compute instances describe.
It then uses the slot's token to read the UUID from GET /api/runners/me on the same origin, retrying briefly
if the default Runner is still registering.
It verifies the registered name and v2 API version and passes the complete gcp_iit map to the fetch revision.
A missing identity, repeated UUID or failed lookup stops publication. A later full apply reads the current fleet
again, including replacement VMs and re-registered Runners. The GCE OS Config policy distributes the verified
fetch URL and the VM IDs from the ready Fetch revision serving all traffic. If an apply stops after discovery,
a Runner-only retry uses the registry from the last completed Fetch rollout. A replacement VM needs a full apply to enroll.
OS Config installs the URL and the host's own ID in /etc/boxlite/secret-fetch.env through a systemd drop-in.
This can run before first boot finishes and survives the boot script rewriting runner.env on restart.
The startup wrapper checks the ID against GCE metadata before launching the Runner. API registration
can complete while the host waits. OS Config applies the environment before checking the binary. Release updates
wait for the restarted Runner to report its current version before deciding whether to replace it.
Existing VMs keep their original boot scripts and receive the settings during the full rollout.
When only the enrollment ID needs installing, OS Config leaves a running Runner and its Boxes in place after
verifying the process already uses the correct fetch URL. A waiting startup wrapper or changed runtime settings
still require service activation.
Use a full deploy to provision or change this registry; component previews and Runner-only updates do not run identity discovery.
Set SECRET_SERVER_ENABLED=true in the API group to exercise forwarding and wait for Runner OS Config convergence before the E2E test.
Cloud Run sends the write and fetch service logs to Cloud Logging in dev, stage and prod.
To enable Secret Server alerts in an environment, set SECRET_SERVER_INCIDENT_CHANNEL in its deploy group to
projects/<stage-project-id>/notificationChannels/<id> for its incident.io webhook channel.
Leaving it unset or empty skips the three log-based metrics and their alert policies. Removing a previously configured
channel removes those managed resources on the next full apply. Alerts cover decryption failures, API-confirmed replays
and high successful fetch counts.
The default volume threshold is 100 successful requests for one Runner in five minutes, summed across revisions.
SECRET_SERVER_FETCH_LIMIT overrides that count. Fetch-side metrics start receiving events when the fetch handler is deployed.
Verify a rollout
- For dev infrastructure changes, dispatch from an upstream task branch at the exact deployment PR head, targeting a PR based on
main. For stage, dispatch frommainand select a stable tag. A full deployment uses that tag's infrastructure. A scoped rollback uses the dispatch commit's deployment tool and the tag's application or Runner code. Every stage API-only candidate (tag, SHA or PR merge commit) must support the worker role and register CloudAppWorker. The workflow checks the selected commit before building images. For example,v0.16.1passes andv0.16.0is refused. For prod in Backoffice, selectprodand a published stable GitHub Release containing the production-capable Secret Server image. Use the same release for preview and apply, with protected-stage confirmation on apply. Full rollbacks also need a compatible image. - Preview
components=api+runner. Check the plan for the dedicated database on the existing instance, the two internal services, the per-service invokers and the secret references. Where alerts are enabled, check the incident channel on each policy. Apply the reviewed revision using the same inputs. - Keep
SECRET_SERVER_ENABLEDabsent orfalseon the deployed API revision. From the corresponding authorized workload in the VPC, request each service's/readywith a Google ID token for that service URL. Record only the status and revision. Cross-call using the other workload's identity and a fresh token for the destination to verify IAM denial. - Inspect the schema from an authorized SQL session with the query below. Both revisions complete startup only after running migrations and reading back the encrypted canary. A second successful startup with the pinned key checks persistence.
gh workflow run mdeploy-all.yml --repo boxlite-ai/boxlite --ref "$DEPLOY_BRANCH" \
-f stage=dev -f ref="#$PR_NUMBER" -f components=api+runner -f apply=false
gh workflow run mdeploy-all.yml --repo boxlite-ai/boxlite --ref main \
-f stage=stage -f ref="$RELEASE_TAG" -f components=api+runner -f apply=false
SELECT current_database(), current_user,
(SELECT max(version_id) FROM goose_db_version WHERE is_applied) AS migration_version,
EXISTS (SELECT FROM key_verification_canary WHERE id = 1) AS canary_present;
Expect boxlite_secrets, boxlite, the image's migration version and true. Both authorized readiness requests return HTTP 200.
Keep the Actions run, resolved SHA, revision names and status codes with the acceptance result.
Run Box E2E after the write handler, fetch handler and v2 Runner are deployed to dev.