runlease
CLAUDE.md1 starsChanged 16 days agoApache-2.0View on GitHub
Runlease provisions ephemeral cloud spot instances and routes terminal/port traffic to them through a credential-less WebSocket relay. Use case: a developer (or AI agent) needs a short-lived VM to run a build, deploy, test against — without opening inbound firewall rules and without persistent infra. The relay never sees plaintext. Even if it's compromised it can't authenticate to the instance, impersonate it, or decrypt traffic. Single Go module: github.com/marshal-org/runlease (Go 1.26+). Relay (cmd/runlease-relay): - --addr :7777 and --agent-binary <path> are…
In this repository6 other files it gives its agents.
- rules/AGENTS.mdAGENTS.md
- fanoutSkill
- machineSkill
- sandboxSkill
- setupSkill
- troubleshootSkill
The file
We split this CLAUDE.md into the rules it gives an agent
3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 132
Every registry write goes through Registry.mutate: file lock, re-read, one change, atomic rename.
- Very specific: line 157
Sudo is locked by default: Only /usr/local/bin/runlease-terminate and /usr/local/bin/runlease-snooze are NOPASSWD (the latter re-arms the …
- Very specific: line 169
Cobra args: prefer cobra.MinimumNArgs(N) / RangeArgs.
≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Runlease — Project CLAUDE.md
Runlease provisions ephemeral cloud spot instances and routes terminal/port traffic to them through a credential-less WebSocket relay. Use case: a developer (or AI agent) needs a short-lived VM to run a build, deploy, test against — without opening inbound firewall rules and without persistent infra.
The relay never sees plaintext. Even if it's compromised it can't authenticate to the instance, impersonate it, or decrypt traffic.
Repo Layout
cmd/runlease/ CLI (cobra subcommands; one file per command)
cmd/runlease-agent/ Tiny binary that runs on each launched instance — registers with relay, runs yamux server
cmd/runlease-relay/ Public WebSocket relay server (deployed to a fixed VM)
pkg/manifest/ Manifest YAML schema + validation + setup-file inlining
pkg/userdata/ Templated boot script — sshd hardening, agent install, optional sudo + setup steps
pkg/agent/ Agent core loop (importable; cmd/runlease-agent/main.go is a thin wrapper)
pkg/relay/ Relay HTTP+WS server, yamux session coordinator, wsConn net.Conn wrapper
pkg/credential/ Per-instance keypair gen + envelope-encrypted at-rest storage
pkg/registry/ ~/.runlease/registry.json — instance handles, relay tokens, manifest forwards
pkg/config/ ~/.runlease/config.yaml — user defaults
pkg/provider/ Cloud provider interface + aws/, gcp/, azure/ implementations
pkg/instanceclass/ compute.small → e2-standard-2 etc. catalog resolver
pkg/lifecycle/ Reclaim daemon (TTL expiry sweeper)
pkg/signin/ `runlease login`: Google device sign-in flow + saved session (~/.runlease/auth.json)
deploy/relay/ Terraform module for a relay VM (gcp/) + tiers.example.yaml
site/ Project website, published by .github/workflows/pages.yml
plugin/ Claude Code plugin: the source of truth for skills and commands
skills/ commands/ antigravity/ rules/ .antigravity-plugin/ gemini-extension.json mcp_config.json
Antigravity plugin + Gemini CLI extension. skills/, commands/ and antigravity/
are generated from plugin/ by scripts/gen-agent-plugins.py (--check fails on
drift). See docs/google-agents.md
docs/ Reference + integration docs (Mermaid only — no ASCII diagrams)
- manifest.md full schema reference (CLI: `runlease manifest schema`)
examples/manifests/ Sample manifest YAMLsSingle Go module: github.com/marshal-org/runlease (Go 1.26+).
Tech Stack
- Go 1.26, modules at repo root
- CLI:
spf13/cobrav1.10 - WebSocket:
gorilla/websocket - Multiplexing:
hashicorp/yamux(agent↔relay link; one yamux session per agent, one stream per CLI client) - SSH client:
golang.org/x/crypto/ssh(CLI side and bridged through forwards) - SFTP:
pkg/sftp(push/pull) - Logging:
log/slogto stderr (JSON or text depending on the binary) - Cloud SDKs: AWS SDK v2, GCP compute via
google.golang.org/api, Azure SDK - Auth: Google ID token (relay-side allow-list); local KMS via per-user
master.key
Required Env Vars
Relay (cmd/runlease-relay):
--addr :7777and--agent-binary <path>are flags, not env vars.--audienceplus--allowed-emails/--allowed-domainsgateregisterhandshakes. The relay refuses to start without auth unless--insecure-no-authis passed.--max-slotscaps live slots (default 5000).
Agent (cmd/runlease-agent):
RUNLEASE_RELAY_ADDR—ws://host:portorwss://hostor barehost:port.RUNLEASE_RELAY_TOKEN— 32-byte hex, pre-registered by the CLI atrunlease uptime.RUNLEASE_LOCAL_TARGET(optional) — TCP dial target per yamux stream. Defaultlocalhost:22. Used in tests; could also bridge to non-standard sshd.
CLI (cmd/runlease):
RUNLEASE_HOME(optional) — base directory forconfig.yaml,registry.json,master.key,credentials/. Default~/.runlease.
Build & Test
go build ./... # all three binaries
go build -o ./runlease ./cmd/runlease # CLI only (host arch)
go test ./... # full test sweep (~10s)
go vet ./... # static analysis
# cross-compile relay+agent for the deployed Linux VM:
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags="-s -w" -o /tmp/runlease-relay-linux ./cmd/runlease-relay
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags="-s -w" -o /tmp/runlease-agent-linux ./cmd/runlease-agentTests are pure Go — no docker, no env setup. pkg/relay/server_test.go brings up the real HTTP+WS server in-process and exercises the full yamux path (incl. TestRelay_concurrentClients proving multi-stream).
Architecture
Yamux relay-mux (since 0.0.6)
flowchart LR
subgraph Dev["Developer machine"]
C1["runlease forward<br/>(holds a tunnel)"]
C2["runlease exec / push / pull<br/>(other shells, concurrent)"]
end
subgraph VM["Spot instance"]
SSHD["sshd :22"]
A["runlease-agent<br/>(yamux server)"]
end
R[("Relay<br/>WebSocket")]
C1 -- "WS /relay (raw bytes,<br/>SSH client traffic)" --> R
C2 -- "WS /relay (raw bytes)" --> R
R -. "single WS to agent<br/>(yamux frames)" .- A
A -- "one yamux stream per<br/>CLI client → dial 127.0.0.1:22" --> SSHD- The agent runs
yamux.Serveron its outbound WebSocket. - The relay runs
yamux.Clientagainst the agent and callsOpenStream()for every incoming CLI client. The CLI side stays a raw byte stream — yamux is terminated by the relay against the agent's socket. - Any number of concurrent CLI processes work against one VM through one agent socket.
forwardholding a tunnel + another shell runningexec/push/pullis the canonical demo. - yamux keepalives stay enabled — gorilla WebSocket doesn't ping on its own, so NAT timeouts would otherwise drop idle agent sessions.
Token/slot lifecycle
runlease upregisters a random 32-byte token with the relay (role: register, gated by Google ID token allow-list).- The new VM boots; its startup script runs
runlease-agentwith that token in env. - The agent connects to the relay with
role: instance, token: …and getsstatus: registered. - The relay wraps the agent WS in
yamux.Clientand the slot is ready (/readyreturns 200). - Each CLI subcommand opens a fresh WebSocket with
role: client, token: …— relay doessession.OpenStream()and bridges the stream to the CLI WebSocket. - A slot lives for its tier's
slotTTL(24h when no tiers file sets one) and is dropped earlier afteridleTTLwith no agent or client. Past that, reconnects are rejected until the CLI registers the token again (runlease connectdoes).down,sync, the daemon and a faileduprelease the slot at once.
Instance lifecycle
The registry is the only local record of a machine, so these rules keep it from losing one:
uprefuses a name that is in the registry and whose machine still exists (freeName). If the machine is gone, the stale entry is cleared first.- The entry is written (
State: pending) as soon as the create request is accepted, before the wait for running. A create error that comes with a handle still gets recorded. A machine that cannot be recorded is deleted (abandonLaunch). - Every registry write goes through
Registry.mutate: file lock, re-read, one change, atomic rename. Never write back a map loaded earlier. Remove by instance ID (RemoveID), not by name. - Gone means the cloud says not found (or AWS
terminated). Powered off (StatusStopped, including GCPTERMINATED) still exists and is billed:syncand the daemon delete it before dropping the entry. - The lease is a deadline on the VM's disk (
/var/lib/runlease/lease-deadline), re-armed at each boot byrunlease-lease.service. The boot script runs once (/var/lib/runlease/booted).selfTerminationdefaults to true. - Waiting for the agent is bounded and explains itself (
waitForAgent): the slot is gone (relay 404), the boot script failed (it writesRUNLEASE_BOOT_FAILED stage=… exit=…to the serial console, read throughprovider.ConsoleReader), or the time is up. A setup step that fails ends the log with__RUNLEASE_SETUP_FAILED__. - Commands reach a machine through
openRelay, which registers the slot again when the relay answers "unauthorized". Don't calldialRelaydirectly from a command. upfinds where the VM will download its agent and checks the digest (checkRelayAgent) before it reserves a slot or creates anything.- The registry is not the last word on what exists.
listalso asks the cloud for instances labelledrunlease-managed(provider.ManagedLister) and reports the ones the registry does not hold.down --leakeddeletes only those that are stopped AND past the lease on their label. It must never delete a running machine:snoozeextends a lease on the VM without updating the label, so the label cannot prove a running machine is overdue. - The daemon rescans the registry every poll, retries a failed terminate, and reads the registry again before acting on a deadline.
What lives where
- Manifest schema —
pkg/manifest/manifest.go. New fields go here. The wizard (cmd/runlease/manifest.go) emits commented hints — keep it in sync when adding fields. - Userdata template —
pkg/userdata/userdata.go. The template is a Go raw string literal, so no backticks inside it (use single-quotes). - CLI subcommands — one file per command in
cmd/runlease/. Convention:var fooCmd = &cobra.Command{…}; func runFoo(cmd, args).runlease forwardand friends sharenewSSHClientfromforward.go. - Registry —
~/.runlease/registry.json(or$RUNLEASE_HOME/registry.json). One entry per launched instance; includesForwardssnapshot forforward --all.
Security Invariants
These must hold regardless of feature work:
- The relay holds nothing that can open a session. It never sees SSH keys or plaintext bytes from the SSH session. It does see two things: the Google ID token a CLI presents to register a slot or call
/me, which it verifies and does not store, and the OAuth client ID and secret of the sign-in client, which it publishes to CLIs (an installed-application client; Google does not treat that secret as confidential). Don't give the relay any secret that grants access to a VM or a cloud account. Even on the agent side, the relay holds yamux frames — the SSH protocol on top is end-to-end between CLI and sshd. Don't add anything that requires the relay to inspect application bytes. - Host keys are pre-issued, not TOFU.
runlease upgenerates the instance's ed25519 host keypair locally; the public key is embedded in the userdata for sshd and the private key is base64'd into the userdata. The CLI side usescryptossh.FixedHostKeyagainst the known public key. Don't introduceInsecureIgnoreHostKeyor trust-on-first-use anywhere. - sshd is hardened by the bootstrap.
PasswordAuthentication no,AllowUsers runlease-agent,PermitRootLogin no, only ed25519 host key offered. Don't relax this without explicit user request. - Sudo is locked by default. Only
/usr/local/bin/runlease-terminateand/usr/local/bin/runlease-snoozeare NOPASSWD (the latter re-arms the namedrunlease-selfterminatetimer forrunlease snooze).manifest.sudo: passwordlessis the opt-in. Don't add fields that quietly grant elevated privileges, and gate any new NOPASSWD entry to a single specific script. - The agent is verified and unprivileged. The boot script checks the relay-served agent against a SHA-256 before running it, and the agent's systemd unit runs as
runlease-agentwith no capabilities. Don't add a path that executes an unverified download or runs the agent as root. - The relay fails closed. It validates slot tokens (32 to 128 chars of
[A-Za-z0-9_-]), caps slots, and won't start open by accident. Never slice or log a token without going throughshortTok. - Connection ownership.
newSSHClientandexecOverConncloseconnon every error path; callers don't double-close. SFTP/forward clients are bound to one SSH client they own end-to-end.
Go Conventions
- Errors wrap with context:
fmt.Errorf("operation: %w", err). - Logging is
log/slogto stderr. Use structured key/value pairs, neverfmt.Sprintfinto a single string. - Cobra commands: each subcommand has its own
init()that callsrootCmd.AddCommand. Flags are package-level vars (var manifestPath string). Don't introduce a global flag-config struct. - Cobra args: prefer
cobra.MinimumNArgs(N)/RangeArgs. For "first arg might be instance name, might not", useresolveInstance(cmd, reg, args, verb)incmd/runlease/root.go. - Provider abstraction: anything cloud-specific lives behind
pkg/provider/interface.go. Don'timport "github.com/aws/…"outsidepkg/provider/aws/. - Tests: pure Go, no fixtures dir. Use
t.TempDir()andhttptest.NewServer. ThefakeAgenthelper inpkg/relay/server_test.gois the canonical way to test relay flows.
Deployment Story
Release builds of the CLI carry the SHA-256 of the agent from the same release, and a VM runs only that agent. The boot script downloads it from the relay by digest (GET /agent/sha256/<hex>?version=<tag>). The relay serves it from --agent-binary or its cache, or fetches it once from the GitHub release and keeps it if the digest matches (pkg/relay/agents.go). So a CLI release never needs a relay release, and a relay release never breaks older CLIs. A relay older than this route serves only its own agent at /agent; the CLI falls back to it when its digest matches.
The wire protocol is versioned (relay.Protocol, MinProtocol, MaxProtocol). A handshake carries "proto" as a string (old agents decode replies as map[string]string); no field means 1. Keep changes additive and raise MaxProtocol; raise MinProtocol only to drop old clients on purpose. CI runs the latest released agent against the relay of every commit (TestRelay_releasedAgent).
How to deploy, authenticate and upgrade a relay: docs/self-hosting-relay.md.
Existing VMs that booted with the previous agent are not auto-upgraded. They keep running their old agent until the spot instance dies.
Commit & PR Conventions
- Conventional commits:
type(scope): subject. Types:feat,fix,docs,refactor,chore,test. Scopes are component-local:exec,forward,relay,agent,manifest,userdata,discover,attach,transfer,json,sudo,setup,forwards. One commit per logical change, not one big mega-commit. - No
Co-Authored-By: Claudeor any "Generated by Claude" bylines in commit messages or PR bodies. Ever. - Releases are managed by release-please (
googleapis/release-please-action@v4). runlease is a single Go module → one release-please package at the repo root (.release-please-config.json/.release-please-manifest.json), so it produces barevX.Y.Ztags (no component prefix) and the three binaries (runlease,runlease-agent,runlease-relay) are released together. Flow: every push tomainupdates a "release PR" from conventional-commit history (feat→ minor,fix→ patch;chore/docs/refactor/ci/testdon't bump). Merging that release PR bumps the version, regenerates theCHANGELOG.mdentry, and creates the tag + GitHub Release; the same workflow's gated build job then attaches binaries for darwin/linux × amd64/arm64 + windows/amd64. So don't hand-editCHANGELOG.mdor pushv*tags manually — let release-please do both. Conventional commit types now drive the version bump, so type them accurately. Commits that change onlysite/are left out of releases (exclude-paths), whatever their type: the site publishes throughpages.yml, and a release forces a relay redeploy. - PR test plan: include a
## Test planchecklist when the change spans more than a refactor. For yamux/protocol changes, include an explicit "deployed relay + spun up fresh VM + ran N concurrent clients" item; the unit tests aren't sufficient on their own.
Common Pitfalls
- Backticks in
pkg/userdata/userdata.go: the template is a Go raw string literal, so any backtick inside it is a Go syntax error. Use single-quotes in inline comments. runlease sshrequires a TTY: that's intentional. For non-interactive use,runlease exec.- Concurrent CLI calls work only against the deployed yamux relay. If the relay binary on
runlease-relayis older than0.0.6, a second CLI process getsi/o timeouton the relay handshake while the first is active. Verify the deployed version before assuming a relay bug.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

