Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ reqwest = { version = "0.12", default-features = false, features = ["json", "rus
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tempfile = "3.27"
tokio = { version = "1.53", features = ["macros", "rt-multi-thread", "time", "signal", "io-util", "io-std", "net"] }
tokio = { version = "1.53", features = ["macros", "rt-multi-thread", "time", "signal", "io-util", "io-std", "net", "sync"] }
tokio-tungstenite = { version = "0.29", features = ["rustls-tls-native-roots"] }
url = "2.5"
uuid = { version = "1.27", features = ["v4"] }
uuid = { version = "1.27", features = ["v4", "serde"] }

[target.'cfg(unix)'.dev-dependencies]
[target.'cfg(unix)'.dependencies]
libc = "0.2"

[profile.release]
Expand Down
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,28 @@ Sandboxes expire after one hour by default.
Use `--ttl SECONDS` to change this time.
Use `--no-expiry` to disable automatic expiry.

### Run sandboxes locally

On Apple Silicon macOS or x86_64 Linux with KVM, point Adapt at a compatible
Goblin bundle containing `goblind` and an embedded-firmware `goblin-worker`:

```sh
export ADAPT_LOCAL_RUNTIME=/path/to/goblin-release/bin
adapt sandbox sh --local --image ubuntu:24.04 -- uname -m
adapt sandbox sh --local
adapt --local sandbox create --image ubuntu:24.04 --wait
adapt --local sandbox list
adapt --local exec SANDBOX_ID -- uname -m
adapt --local sandbox delete SANDBOX_ID
```

Adapt starts and reuses a private local manager without Platform login. The shell
or command from `sandbox sh` runs in a VM that is deleted when the session ends.
`sandbox create` keeps the VM for later commands until you stop or delete it. Existing
commands keep their cloud default; `sandbox sh --cloud` selects it explicitly.
This initial local workflow requires a manually supplied runtime bundle. See
[local sandbox options and limitations](docs/cli-reference.md#local-sandboxes).

## Create a sandbox

Create a sandbox that stays available after each command:
Expand Down
92 changes: 90 additions & 2 deletions docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ adapt sandbox sh --image ubuntu:24.04 --cpu 2 --memory 2048 --env EDITOR=vim
adapt sandbox sh --image-id IMAGE_ID --variable-set VARIABLE_SET_ID
```

`sandbox sh` accepts every `sandbox create` option, including `--data`.
Cloud `sandbox sh` accepts every `sandbox create` option, including `--data`.
It always waits for the sandbox to run, even without `--wait`.
Without a command, it requires a terminal and opens an interactive login shell.
It selects the shell from the guest's `$SHELL` or passwd entry.
Expand Down Expand Up @@ -223,6 +223,91 @@ The `--ttl` option sets expiry in seconds.
The `--no-expiry` option disables automatic expiry.
Shells have a maximum execution timeout of 24 hours.

### Local sandboxes

```sh
export ADAPT_LOCAL_RUNTIME=/path/to/goblin-release/bin
adapt sandbox sh --local --image ubuntu:24.04 -- uname -m
adapt --local sandbox create --image ubuntu:24.04 --env EDITOR=vim --wait
adapt --local sandbox list
adapt --local sandbox get SANDBOX_ID
adapt --local exec SANDBOX_ID -- /bin/sh -c 'echo "$EDITOR"'
adapt --local exec SANDBOX_ID -it -- /bin/sh
adapt --local sandbox stop SANDBOX_ID --wait
adapt --local sandbox delete SANDBOX_ID
```

`--local` selects the local backend on Apple Silicon macOS or x86_64 Linux with
KVM. `--cloud` explicitly selects Platform, which remains the default. These are
global flags: they work before or after a subcommand and cannot be combined.
Runtime environment variables configure the local runtime without selecting it.
Local resource commands do not read cloud profiles or send Platform tokens.
Unsupported operations return an error before launching a runtime; they never
fall back to the cloud. `auth logout --local` retains its credential-removal
meaning, and `skill` commands remain offline.

| Operation | Local support |
| --- | --- |
| `sandbox create`, `get`, `list`, `stop`, `delete`, `wait`, `sh` | Supported |
| `exec`, including stdin and PTY | Supported; sandbox remains after execution |
| `sandbox start`, `usage` | Not supported yet |
| `exec --detach`, `execs`, `files` | Not supported yet |
| `images`, `volumes`, `endpoints`, other Platform services | Not supported yet |

Local resource IDs must be full UUIDs. `sandbox list` returns all UUID-addressed
VMs in the selected manager; `--query` filters UUID prefixes, and `--all` is
accepted. Named VMs created outside Adapt are omitted. `--limit` and `--cursor`
are not supported locally. Local responses expose common `id`, `status`, `cpu`,
and `memoryMiB` fields where available, alongside Goblin's diagnostics. Goblin's
`ready` and `busy` states both map to `running`. Local waits accept `running`,
`stopped`, `deleted`, `failed`, or `completed`, and respect `--wait-timeout`.
Stopping a VM ends its processes; restarting it is not implemented yet.

Supply a compatible Goblin runtime with `--runtime-dir` or `ADAPT_LOCAL_RUNTIME`.
The directory must contain `goblind` with `--ready-file` and `--unix-socket`
support and a native `goblin-worker` with matching embedded firmware. The macOS
worker must be signed with its hypervisor entitlement. Automatic bundle
installation is not included yet. Adapt discovers a running manager before
requiring the bundle path again.

State, image cache, the local token, discovery metadata, sandbox environment
files, and `goblind.log` live in `ADAPT_CONFIG_DIR/local` (using the usual config
directory default). Override this with `--local-state-dir` or
`ADAPT_LOCAL_STATE_DIR`; use the same directory on subsequent commands. It must
be private and owned by the current user. The manager runs independently of the
terminal, listens on a private `goblind.sock` Unix socket, and uses a separate
token. Adapt validates socket ownership and permissions before sending
credentials; HTTP and WebSocket requests bypass proxies. Stale TCP discovery
records are rejected. Concurrent commands reuse one manager.

Local creation accepts `--image`, `--cpu`, `--memory`, `--disk`, and repeated
`--env`. Defaults are `ubuntu:24.04`, one CPU, 1024 MiB memory, and a 2048 MiB
writable disk. Environment values are stored in private files and applied by
later `adapt exec` commands; execution `--env` flags override them. Names must
match `[A-Za-z_][A-Za-z0-9_]*` and be at most 128 bytes. Goblin allows 128 variables
and 32 KiB of names and values combined; values cannot contain NUL. Adapt checks
these limits before creation and again after merging execution overrides. They
are not image startup configuration. The guest can reach public internet destinations,
with private/loopback egress blocked by Goblin's public policy. Host mounts and
local/cloud moves are not implemented.

`--wait` on create or stop waits for the requested state. `sandbox sh` always
waits, streams stdin/output, and deletes its VM on exit, Ctrl-], stream failure,
or handled interruption. Persistent `sandbox create` leaves the VM running until
explicitly stopped or deleted. Local sandboxes have no daemon-enforced expiry;
`--no-expiry` is accepted. `--data`, cloud image IDs, labels, variable sets, image
startup commands, TTL, and idempotency keys are rejected before runtime startup.

Ctrl-] remains available when the guest stops reading input. Interactive input
queues up to 32 KiB locally; further input is discarded with a warning until the
guest resumes reading. Piped input is backpressured without discarding bytes.
Temporary shells have a 24-hour execution limit. An uncatchable CLI kill or failed
cleanup can leave a VM behind; use `adapt --local sandbox list` and `delete` to
inspect and remove it. Adapt releases completed execution sessions after the
stream closes, retrying while Goblin processes the detach. A disconnect from a running command does not
cancel it; its retained session remains until sandbox deletion. Local logs and
session output do not have Platform's retained, redacted log service.

### Sandbox options

Memory and disk values use MiB.
Expand Down Expand Up @@ -423,7 +508,7 @@ adapt models discover PROVIDER_ID

## Resource IDs

These resources accept full UUIDs or unique ID prefixes:
On the cloud backend, these resources accept full UUIDs or unique ID prefixes:

- Sandboxes and executions.
- Images and registry credentials.
Expand Down Expand Up @@ -630,6 +715,9 @@ It does not retry this request automatically.

| Setting | Option | Environment variable |
| --- | --- | --- |
| Backend; default: cloud | `--local` / `--cloud` | None |
| Local runtime bundle | `--runtime-dir` | `ADAPT_LOCAL_RUNTIME` |
| Local state directory | `--local-state-dir` | `ADAPT_LOCAL_STATE_DIR` |
| API origin | `--api-url` | `ADAPT_API_URL` |
| Profile; default: `default` | `--profile` | `ADAPT_PROFILE` |
| Organization for this request | `--org` | `ADAPT_ORG_ID` |
Expand Down
20 changes: 20 additions & 0 deletions skills/adapt/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,26 @@ Use `exec --detach` to return execution metadata immediately, or `exec -it`
for an interactive terminal. Normal command execution streams output and returns
the remote exit code.

Use the global `--local` flag for local sandboxes on Apple Silicon macOS or
x86_64 Linux with KVM. Set `ADAPT_LOCAL_RUNTIME` to a compatible Goblin bundle's
`bin` directory, or pass `--runtime-dir`. Local commands work without Platform
login. Cloud remains the default; `--cloud` selects it explicitly. Never retry an
unsupported local operation against the cloud unless the user chooses that target.

Local `sandbox create`, `list`, `get`, `stop`, `delete`, `wait`, `sh`, and attached
`exec` are supported. Use full sandbox UUIDs. `sandbox create --wait` leaves the
VM running for later commands; `sandbox sh` deletes it on exit. Creation accepts
image, CPU, memory, disk, and environment flags. Local `--env` values persist for
later `exec` commands, whose environment flags override them. Use the same
`--local-state-dir` / `ADAPT_LOCAL_STATE_DIR` across commands when overriding it.

Local start/restart, usage, `exec --detach`, `execs`, files, other resource
families, mounts, moves, TTL, cloud image IDs, variable sets, labels, `--data`,
image startup, and idempotency keys return unsupported errors. Local lists are
unpaginated; `--query` matches UUID prefixes, while `--limit` and `--cursor` are
unsupported. Local VMs do not expire automatically; use `adapt --local sandbox
list` and `adapt --local sandbox delete ID` to clean up a VM left after a killed CLI.

```sh
adapt execs get EXEC_ID
adapt execs logs EXEC_ID
Expand Down
150 changes: 150 additions & 0 deletions src/backend/cloud.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
use super::Backend;
use crate::{
api::{Api, ApiError},
cli::*,
commands,
input::ResourceRef,
output, stream,
};
use anyhow::Result;
use reqwest::{Method, StatusCode};
use serde_json::{Value, json};
use uuid::Uuid;

pub struct CloudBackend<'a>(pub &'a Api);

impl Backend for CloudBackend<'_> {
fn name(&self) -> &'static str {
"cloud"
}

async fn sandbox_list(&self, args: SandboxList) -> Result<Value> {
let filters = args
.query
.iter()
.map(|text| ("query".into(), text.clone()))
.collect::<Vec<_>>();
self.0
.list("/v1/sandboxes", "sandboxes", &args.page, true, &filters)
.await
}
async fn sandbox_get(&self, id: ResourceRef) -> Result<Value> {
self.0.get(&format!("/v1/sandboxes/{id}")).await
}
async fn sandbox_create(&self, args: SandboxCreate) -> Result<Value> {
commands::create_sandbox(self.0, args).await
}
async fn sandbox_start(&self, id: ResourceRef) -> Result<Value> {
self.0
.post(&format!("/v1/sandboxes/{id}/start"), &json!({}))
.await
}
async fn sandbox_stop(&self, id: ResourceRef) -> Result<Value> {
self.0
.post(&format!("/v1/sandboxes/{id}/stop"), &json!({}))
.await
}
async fn sandbox_delete(&self, id: ResourceRef) -> Result<Value> {
self.0
.json(
Method::DELETE,
&format!("/v1/sandboxes/{id}"),
None,
&[],
None,
)
.await
}
async fn sandbox_wait(&self, id: ResourceRef, status: &str, seconds: u64) -> Result<Value> {
commands::wait_for(self.0, "sandboxes", id, status, seconds).await
}
async fn sandbox_usage(&self, id: ResourceRef, hours: &str) -> Result<Value> {
self.0
.json(
Method::GET,
&format!("/v1/sandboxes/{id}/usage"),
None,
&[("hours".into(), hours.into())],
None,
)
.await
}
async fn execute(&self, args: ExecArgs, json: bool) -> Result<u8> {
commands::execute(self.0, args, json).await
}
async fn executions(&self, command: ExecCommand, json: bool) -> Result<u8> {
let result = match command {
ExecCommand::Get { id } => self.0.get(&format!("/v1/execs/{id}")).await?,
ExecCommand::Cancel { id } => {
self.0
.post(&format!("/v1/execs/{id}/cancel"), &json!({}))
.await?
}
ExecCommand::Logs { id, cursor } => {
return stream::logs(self.0, id, cursor, json).await;
}
ExecCommand::Attach {
id,
after,
stdin,
tty,
} => return stream::attach(self.0, id, after, stdin || tty, tty, json).await,
};
output::print(&result, json)?;
Ok(0)
}
async fn files(&self, command: FileCommand) -> Result<Value> {
commands::files(self.0, command).await
}
async fn volumes(&self, command: VolumeCommand) -> Result<Value> {
commands::volumes(self.0, command).await
}
async fn images(&self, command: ImageCommand, json: bool) -> Result<u8> {
if let ImageCommand::List(args) = command {
return commands::list_images(self.0, args, json).await;
}
output::print(&commands::images(self.0, command).await?, json)?;
Ok(0)
}
async fn endpoints(&self, command: EndpointCommand, json: bool) -> Result<u8> {
if let EndpointCommand::Request(args) = command {
return commands::request_endpoint(self.0, args).await;
}
output::print(&commands::endpoints(self.0, command).await?, json)?;
Ok(0)
}
async fn cleanup(&self, id: Uuid) -> Result<()> {
cleanup(self.0, id).await
}
}

async fn cleanup(api: &Api, id: Uuid) -> Result<()> {
eprintln!("Deleting temporary sandbox {id}…");
let result: Result<()> = async {
let response = api
.json(
Method::DELETE,
&format!("/v1/sandboxes/{id}"),
None,
&[],
None,
)
.await?;
if response["status"] != 204 {
commands::wait_for(api, "sandboxes", id, "deleted", 600).await?;
}
Ok(())
}
.await;
// Expiry or another client may already have removed the sandbox.
match result {
Err(error)
if error
.downcast_ref::<ApiError>()
.is_some_and(|e| e.status == StatusCode::NOT_FOUND) =>
{
Ok(())
}
result => result,
}
}
Loading
Loading