Templates
Define a typed template from a Git context, build it into a private digest-addressed image, and create sessions from it.
A template is a reusable definition of a prepared environment. Instead of fetching a repo and installing the same tools at the start of every session, you define the environment once as a typed recipe, build it, and create sessions from the resulting image, so every session starts in the same known state. See Concepts for how templates relate to snapshots and images.
Working with a template is three steps:
- Define the spec: a base image, a Git context, ordered build steps, runtime behavior, and default resources.
- Build it. Sandbox fetches the context, runs the steps, and captures the result. A successful build automatically registers a private image, versioned and addressed by a real content digest.
- Create sessions from that image.
Publishing is a separate, optional step: it changes an image's visibility or sharing. Builds never make an image public on their own.
Primitives
A template is defined by a TemplateSpec, the recipe you build. It is one of a few related things worth keeping straight:
Deleting a template removes its recipe and build history but leaves images it already produced launchable until you delete them from the registry.
Build and use a template
The SDKs give you a typed builder that compiles to the canonical spec document (see The template spec); createTemplate and buildTemplate send it to the server.
import { LuxorSandbox, TemplateSpec } from "@luxorai/sandbox";
const sandbox = new LuxorSandbox();
// 1. Define the spec (compiles to the canonical JSON document)
const spec = new TemplateSpec()
.fromImage("sandbox")
.withGitContext({ repo: "https://github.com/acme/node-api", ref: "main" })
.workdir("/home/tenki/app")
.buildEnv({ NODE_ENV: "production" })
.run("npm ci", { timeoutSeconds: 1800 })
.start("npm run dev", {
runAt: "build",
snapshotMode: "filesystem",
readyWhen: [{ http: { url: "http://127.0.0.1:3000/health", successStatusCodes: [200, 204] } }],
})
.resources({ cpuCores: 2, memoryMb: 4096, diskSizeGb: 10 });
// 2. Build it. Streams events; resolves to a private, digest-addressed image
const build = await sandbox.buildTemplate(await sandbox.createTemplate({ name: "node-api", spec }), {
buildSecrets: { GITHUB_TOKEN: token },
waitForCompletion: true,
});
// 3. Create a session from the built image
const session = await sandbox.create({ image: build.image, waitForRuntime: true });The session comes up in the prepared state with no install step. --no-wait detaches the build; Ctrl-C stops local streaming only and never cancels the remote build.
Manage templates
Templates and their images are scoped to the workspace bound to your API key, so template calls don't take a workspace ID. Updating a template's typed spec is an atomic full replacement. Deleting a template leaves images it already produced launchable — remove those from the registry separately.
const templates = await sandbox.listTemplates();
const tpl = await sandbox.getTemplate("node-api");
await sandbox.updateTemplate(tpl, { spec }); // atomic replacement of the typed recipe
await sandbox.deleteTemplate("node-api");
await sandbox.cancelTemplateBuild(buildId); // stops a remote buildThe template spec
A template is a single typed document. You rarely write it by hand — the SDK builder in Build and use and the CLI's template init both compile to it, and it is the canonical form the server validates, fills in with defaults, and hashes. The builder is immutable — each method returns a new spec — and every SDK can import, export, and validate a spec locally (fromJSON, toJSON, validate); the server rejects unknown fields and unsupported spec versions. Here is the complete spec the quickstart above produces:
{
"specVersion": "tenki.template.v1",
"base": { "image": "sandbox" },
"workdir": "/home/tenki/app",
"context": {
"source": { "git": { "repo": "https://github.com/acme/node-api", "ref": "main" } },
"checkout": { "dest": "/home/tenki/app", "mode": "contents" }
},
"build": {
"env": { "NODE_ENV": "production" }
},
"steps": [{ "run": { "command": "npm ci", "timeoutSeconds": 1800 } }],
"runtime": {
"runAt": "build",
"start": { "command": "npm run dev", "workdir": "/home/tenki/app" },
"snapshotMode": "filesystem",
"readyWhen": {
"timeoutSeconds": 60,
"pollIntervalSeconds": 1,
"checks": [{ "http": { "url": "http://127.0.0.1:3000/health", "successStatusCodes": [200, 204] } }]
}
},
"resources": { "cpuCores": 2, "memoryMb": 4096, "diskSizeGb": 10 }
}Each block maps to one part of the recipe:
Steps run in order and support run, copy (from the Git context to an absolute guest path), writeFile, mkdir, remove, rename, symlink, and the package helpers apt, pip, npm, and bun. A run step takes a shell command or an argv list; shell commands run under sh -lc, with a default timeout of 1800 seconds.
Snapshot modes
runtime.snapshotMode decides what a build captures.
A snapshot is captured only for a runtime started during the build (runAt: "build"). If a memory image cannot be restored on a given host, Sandbox cold-boots the snapshot's own disk instead of a clean base image, starts the declared runtime, and waits for the same readiness before the session is ready.
Runtime and readiness
Runtime is optional and declares exactly one of a single start command or a processCompose configuration. For multi-process apps, processCompose points at a config path with an optional workdir and explicitly listed env files; Sandbox owns supervision, logging, restart, and shutdown.
- When it starts —
runAtisboot(the default when a runtime exists),build(started during the build so it can be snapshotted), ormanual. - When it is ready —
readyWhenlists port, localhost HTTP, and exec checks. They run together and all must pass once. The samereadyWhencontract applies at build time, at boot, for manual starts, and for cold-boot recovery. A build snapshot is captured only after readiness. - Session readiness is separate — a session reaching
RUNNINGmeans the platform is ready: VM, guest agent, and networking. Application readiness has its own states —STARTING,READY,FAILED,STOPPED— and does not gateRUNNINGor affect provisioning latency and its metrics. Opt into waiting for it withwaitForRuntime.
Environment and secrets
Environment variables are plaintext configuration and appear in read APIs. Set build-scoped variables under build.env and runtime-scoped variables under runtime.env.
Build secrets are different: request-time values you pass to a build for private Git checkout or secret-dependent steps. They are encrypted, carried only as an opaque reference, and never reach the runtime or appear in logs, provenance, or snapshots. The CLI reads build secrets from explicit flags and can detect GIT_TOKEN, GH_TOKEN, or GITHUB_TOKEN. Redaction is best-effort — a command that deliberately prints a secret can still leak it, so keep secrets out of build output. Pass these credentials per build. For saved workspace secrets delivered when the app starts, see Using secrets.
Using secrets
A template can use the .env.example already in your repository. Sandbox captures that file during the build and fills in its secret placeholders each time you create a sandbox.
Use SDK version 1.4.0 or later. First save a workspace secret named GITHUB_TOKEN. Your repository's .env.example should contain:
GITHUB_TOKEN=secrets://GITHUB_TOKENReplace the repository URL below with your public Node.js app. It should have a package-lock.json and an npm run dev script that loads .env from the app's directory.
import { LuxorSandbox, TemplateSpec } from "@luxorai/sandbox";
const client = new LuxorSandbox();
const spec = new TemplateSpec()
.fromImage("sandbox")
.withGitContext({ repo: "https://github.com/your-org/your-app.git", ref: "main" })
.workdir("/home/tenki/web")
.run("npm ci")
.start("npm run dev", {
runAt: "boot",
secretFiles: [{ source: "/home/tenki/web/.env.example", path: "/home/tenki/web/.env" }],
});
const template = await client.createTemplate({ name: "web-with-secrets", spec });
const build = await client.buildTemplate(template, { waitForCompletion: true });
const session = await client.createAndWait({ image: build.image });
console.log(session.id);source is the file to read during the build. path is where Sandbox writes the completed file in each new sandbox, before starting npm run dev. The app receives the real token through .env; no request policy is needed.
With runAt: "boot", the build installs dependencies and saves the placeholder file without starting the app or resolving its runtime secrets. New sandboxes use the current secret value. Rotating a secret does not change files in sandboxes that are already running.
Keep the sandbox running while you use the app. When finished, terminate it using the session ID:
luxor sandbox terminate --session SESSION_IDFor a sandbox created without a template, see Secret files from an SDK.
Image references
A build produces a private image in your workspace registry, referenced three ways:
acme/node-api— the untagged reference, which tracks the newest successful build.acme/node-api:prod— an optional tag you manage, a moving reference.acme/node-api@sha256:…— an immutable digest that pins the exact built output.
The digest is computed over the image's launch artifacts and behavior, so identical inputs always produce the same digest. A failed or older build never moves the untagged reference. Older name@<snapshot-id> references still resolve but are deprecated; new workspace builds emit digest references only.
Our pre-built images are not workspace builds and carry no digest, so a snapshot reference is how you pin one to an exact build.
Build lifecycle
A build moves through PENDING, BUILDING, READY, and FAILED. Waiting for a build streams one ordered stream of log and progress events; a waited failure raises a typed error carrying the final, redacted build. Reconnect to an in-flight build to resume streaming. Editing a template does not affect a build already in flight — each build freezes its own spec on submission.
Build from CI
Because the spec is a single file, templates fit a GitOps flow: commit it to your repository as .tenki/template.json and let CI rebuild the image whenever the spec changes. Our GitHub Actions wrap the CLI for this — setup-cli installs luxor, and template-build creates or updates the template from the committed spec, builds it, and outputs the immutable digest ref.
name: Build sandbox template
on:
push:
branches: [main]
paths: [".tenki/template.json"]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: LuxorLabs/tenki-actions/setup-cli@v1
- uses: LuxorLabs/tenki-actions/template-build@v1
id: template
env:
TENKI_API_KEY: ${{ secrets.LUXORAI_API_KEY }}
GITHUB_TOKEN: ${{ github.token }}
with:
template: node-api
- run: luxor sandbox create --image "${{ steps.template.outputs.image }}"Scaffold the spec once with luxor template init, then commit it. On each run, template-build creates the template if the name is new or replaces its spec if it already exists, waits for the build, and sets steps.<id>.outputs.image to the digest ref for later jobs. The LUXORAI_API_KEY repository secret (use secrets.TENKI_API_KEY instead if your repository already stores the key under that name), passed to the action as TENKI_API_KEY, determines the workspace the template and image belong to.
Pass build secrets — such as a token for a private Git checkout — with the build-secret-env input, naming job env vars to forward for that build only. The well-known GITHUB_TOKEN, GH_TOKEN, and GIT_TOKEN are detected automatically. See Environment and secrets.
Publish and share
The registry is a per-workspace namespace of images. Each image has a visibility: private (the default), public, or shared with specific workspaces. Publishing changes visibility or grants sharing; it is always explicit. Share an image across workspaces with luxor sandbox registry share --target-workspace <workspace-id>.
Browse and resolve images:
const images = await sandbox.listRegistryImages({ workspace: "myworkspace" });
const image = await sandbox.getRegistryImage("myworkspace/node-api");
const resolved = await sandbox.resolveRegistryRef("myworkspace/node-api:prod");Not supported
A few things are out of scope today:
- Local filesystem or archive build contexts — the build context is Git only.
- Launching a session from an inline recipe file — the template must exist as a resource first. Once it does, you can either build it into an image or launch a session directly from its stored spec with
luxor sandbox create --from-template-spec <name-or-id>. - Dockerfile ingestion and full devcontainer features.
- Per-build overrides for Git ref, environment, or resources.
- Automatic public or shared publishing, and turning build numbers into tags — visibility and tags are always explicit.
Errors
Template and registry calls fail when a reference is unknown, a build fails, or a name collides. Every SDK surfaces these as typed errors or exceptions; see the SDK reference for the names in each language.