CreateOS Go SDK
Launch an isolated cloud sandbox, run real commands, stream output, move files,
open a preview URL, and tear everything down from Go.
Your first sandbox
go get github.com/NodeOps-app/createos-go-sdk
package main
import (
"context"
"fmt"
"log"
"github.com/NodeOps-app/createos-go-sdk/sandbox"
"github.com/NodeOps-app/createos-go-sdk/structs"
)
func main() {
ctx := context.Background()
client, err := sandbox.NewClient(
sandbox.WithAPIKey("your-api-key"),
)
if err != nil {
log.Fatal(err)
}
instance, err := client.CreateSandbox(ctx, structs.CreateSandboxRequest{
Name: "hello-go",
Shape: "s-4vcpu-4gb",
RootFS: "devbox:1",
})
if err != nil {
log.Fatal(err)
}
defer func() {
if err := instance.Destroy(context.Background()); err != nil {
log.Printf("destroy sandbox: %v", err)
}
}()
response, err := instance.RunCommand(ctx, structs.RunCommandRequest{
Command: "sh",
Arguments: []string{"-c", `printf "Go says hello from $(uname -m)\n"`},
}, structs.ExecOptions{})
if err != nil {
log.Printf("run command: %v", err)
return
}
fmt.Print(response.Result.StandardOutput)
}
Go says hello from x86_64
WithAPIKey configures authentication explicitly. Do not commit a real API key
to source control; inject the value through your application's secret manager.
Additional client options configure the endpoint, default timeout, and retry
policy:
client, err := sandbox.NewClient(
sandbox.WithAPIKey(apiKey),
sandbox.WithBaseURL("http://localhost:8080"),
sandbox.WithTimeout(30*time.Second),
sandbox.WithRetry(3, 250*time.Millisecond, 10*time.Second),
)
NewClient() reads CREATEOS_API_KEY and the optional
CREATEOS_SANDBOX_BASE_URL. Explicit options take precedence.
Authenticated requests send the key as X-Api-Key. Health, readiness, shape,
and root-filesystem catalog requests omit it. Use HTTPS for non-loopback
endpoints. To customize proxy or TLS settings, pass an http.Client through
WithHTTPClient; the SDK rejects redirects to a different origin so the key
cannot be forwarded there.
Organize sandboxes with labels
instance, err := client.CreateSandbox(ctx, structs.CreateSandboxRequest{
Shape: "s-1vcpu-1gb",
RootFS: "alpine:3.20",
Labels: map[string]string{"team": "backend", "environment": "test"},
})
matches, err := client.ListSandboxes(ctx, structs.ListSandboxesOptions{
Labels: map[string]string{"team": "backend"},
})
err = instance.SetLabels(ctx, map[string]string{"environment": "production"})
List filters use AND semantics. SetLabels merges the supplied keys into the
existing label map.
Capture and restore snapshots
snapshot, err := instance.CreateSnapshot(ctx, structs.CreateSnapshotRequest{
Type: structs.SnapshotTypeDisk,
Name: "configured-workspace",
})
snapshot, err = client.Snapshots().Get(ctx, snapshot.ID) // poll until ready
restored, err := client.CreateSandbox(ctx, structs.CreateSandboxRequest{
SnapshotID: snapshot.ID,
})
Disk snapshots capture the filesystem. Full snapshots also retain memory and
must be restored with their captured CPU, memory, and disk sizes. Snapshot
capture requires a running source sandbox with no attached external disks.
Each account may retain up to five snapshots across both types.
Checkpoint a directory
Checkpoints keep local file history inside one running sandbox. Stop
writers before create or restore; processes are not paused automatically.
checkpoint, err := instance.Checkpoints().Create(ctx,
structs.CreateCheckpointRequest{
Path: "/workspace/project",
Name: "before-update",
})
checkpoints, err := instance.Checkpoints().List(ctx)
restored, err := instance.Checkpoints().Restore(ctx, checkpoint.ID)
err = instance.Checkpoints().Delete(ctx, checkpoint.ID)
Restore always uses the checkpoint's original path. Checkpoints remain on the
sandbox disk and are deleted with the sandbox; they are separate from reusable
VM snapshots. See the runnable example.
Delegate access to one sandbox
An owner can create one sandbox access token and pass it to another client.
The token is returned only when created or rotated; inspection provides a
redacted hint. Keep the owner's API key for token management.
created, err := instance.CreateAccessToken(ctx)
if err != nil {
return err
}
// Store created.Token securely, then give it to the sandbox worker.
workerInstance, err := instance.WithAccessToken(created.Token)
if err != nil {
return err
}
result, err := workerInstance.RunCommand(ctx, structs.RunCommandRequest{
Command: "sh", Arguments: []string{"-c", "echo hello"},
}, structs.ExecOptions{})
if err != nil {
return err
}
fmt.Print(result.Result.StandardOutput)
metadata, err := instance.GetAccessToken(ctx)
if err != nil {
return err
}
_ = metadata.TokenHint
replacement, err := instance.RotateAccessToken(ctx)
if err != nil {
return err
}
_ = replacement.Token // Replace the worker's stored token.
_, err = instance.DisableAccessToken(ctx)
if err != nil {
return err
}
Creating a second enabled token returns HTTP 409; rotation requires an existing
token. Disabling is idempotent. Revocation is immediate in the sandbox's home
region and propagates asynchronously to other regions. The delegated token can
operate its bound sandbox, including commands, files, processes, computer use,
pause, resume, and destroy. It cannot manage access tokens or account resources.
Documentation
- CreateOS Sandbox overview
explains the sandbox model, lifecycle, networking, storage, and isolation.
- CreateOS Sandbox documentation
contains the REST API reference and product guides.
- Go API reference
is generated from the SDK's public GoDoc after a tagged release.
- Runnable examples cover command execution, files, streaming,
ingress, snapshots, networking, templates, managed processes, and desktop use.
- Contributing guide documents development checks and commit
conventions.
- Security policy explains private vulnerability reporting.
- Changelog records changes by release.
SDKs
Stream output as it happens
Long-running commands do not need to disappear behind a buffered HTTP call:
stream, err := instance.StreamCommand(ctx, structs.RunCommandRequest{
Command: "sh",
Arguments: []string{"-c", `for n in 1 2 3; do echo "step $n"; sleep 1; done`},
}, structs.ExecOptions{})
if err != nil {
return err
}
defer func() {
if err := stream.Close(); err != nil {
log.Printf("close command stream: %v", err)
}
}()
for {
event, err := stream.Receive()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return err
}
switch event.Type {
case structs.ExecStreamEventStdout:
fmt.Print(event.Data)
case structs.ExecStreamEventStderr:
fmt.Fprint(os.Stderr, event.Data)
case structs.ExecStreamEventExit:
fmt.Printf("exit code: %d\n", *event.ExitCode)
}
}
Stopping early is safe: closing the stream closes the response body and
cancels the underlying request.
Move files without shell escaping
err := instance.Files().Upload(
ctx,
"/workspace/config.json",
strings.NewReader(`{"mode":"production"}`),
)
if err != nil {
return err
}
file, err := instance.Files().Download(ctx, "/workspace/config.json")
if err != nil {
return err
}
defer func() {
if err := file.Close(); err != nil {
log.Printf("close downloaded file: %v", err)
}
}()
contents, err := io.ReadAll(file)
if err != nil {
return err
}
For large transfers, override the timeout for that operation without changing
the client's default timeout:
transferOptions := structs.RequestOptions{Timeout: 30 * time.Minute}
if err := instance.Files().Upload(ctx, remotePath, source, transferOptions); err != nil {
return err
}
file, err := instance.Files().Download(ctx, remotePath, transferOptions)
if err != nil {
return err
}
defer func() {
if err := file.Close(); err != nil {
log.Printf("close downloaded file: %v", err)
}
}()
The timeout covers the complete transfer, including reading the downloaded
body. Uploads are not retried because an arbitrary io.Reader may not be safe
to replay after a partial write.
Keep a process alive after disconnecting
Managed processes are resources rather than fragile terminal sessions. Start
one, reconnect from its output sequence, send input or signals, and wait for
either the leader or its complete process tree:
process, err := instance.Processes().Create(ctx, structs.ManagedProcessCreateRequest{
Command: "python3",
Arguments: []string{"-m", "http.server", "8080"},
})
if err != nil {
return err
}
process, err = instance.Processes().Wait(ctx, process.ProcessID,
structs.ManagedProcessWaitOptions{
Scope: structs.ManagedProcessWaitScopeTree,
WaitTimeout: 30 * time.Second,
},
)
if err != nil {
return err
}
Turn a service into a URL
Create with ingress enabled, wait for the server to listen, then ask the
instance for its public URL:
instance, err := client.CreateSandbox(ctx, structs.CreateSandboxRequest{
Shape: "s-4vcpu-4gb",
RootFS: "devbox:1",
IngressEnabled: true,
})
if err != nil {
return err
}
_, err = instance.Processes().Create(ctx, structs.ManagedProcessCreateRequest{
Command: "python3",
Arguments: []string{"-m", "http.server", "8080", "--bind", "0.0.0.0"},
})
if err != nil {
return err
}
if err := instance.WaitForPort(ctx, "127.0.0.1", 8080, 15*time.Second); err != nil {
return err
}
previewURL, err := instance.PreviewURL(8080)
if err != nil {
return err
}
fmt.Println(previewURL)
Everything is already connected
Account-level services are initialized by NewClient:
templates := client.Templates()
networks := client.Networks()
disks := client.Disks()
customTemplates, err := templates.List(ctx, structs.PaginationOptions{})
if err != nil {
return err
}
fmt.Printf("%d templates ready; networks=%T disks=%T\n", len(customTemplates), networks, disks)
Instance-level services are initialized when a sandbox handle is created or
retrieved:
instance.Files()
instance.Processes()
instance.Computer().Mouse()
instance.Computer().Keyboard()
instance.Computer().Windows()
instance.Computer().Screens()
Connect sandboxes on a private network
Create an overlay network, attach a running sandbox, and inspect the resulting
membership. Cleanup runs in reverse order, so the sandbox detaches before the
network is deleted:
network, err := client.Networks().Create(ctx, structs.NetworkCreateRequest{
Name: "agent-mesh",
})
if err != nil {
return err
}
defer func() {
if err := client.Networks().Delete(context.Background(), network.ID); err != nil {
log.Printf("delete network: %v", err)
}
}()
if err := instance.AttachNetwork(ctx, network.ID); err != nil {
return err
}
defer func() {
if err := instance.DetachNetwork(context.Background(), network.ID); err != nil {
log.Printf("detach network: %v", err)
}
}()
connected, err := client.Networks().Get(ctx, network.ID)
if err != nil {
return err
}
for _, member := range connected.Members {
fmt.Printf("sandbox=%s private-ip=%s status=%s\n",
member.SandboxID,
member.IPAddress,
member.Status,
)
}
Lifecycle reads like the domain
if err := instance.Pause(ctx); err != nil {
return err
}
if err := instance.WaitUntilPaused(ctx, structs.WaitOptions{}); err != nil {
return err
}
clone, err := instance.Fork(ctx, structs.ForkSandboxRequest{})
if err != nil {
return err
}
defer func() {
if err := clone.Destroy(context.Background()); err != nil {
log.Printf("destroy clone: %v", err)
}
}()
if err := instance.Resume(ctx); err != nil {
return err
}
if err := instance.Destroy(ctx); err != nil {
return err
}
The Instance handle caches the latest server projection safely. Lifecycle
mutations and Refresh update it, while ID, Name, Status, IPAddress,
and Data provide concurrent-safe reads.
Build reusable templates
Build a sandbox root filesystem from a Dockerfile, follow its build logs, and
wait until the template is ready before creating a sandbox from its ID. See the
custom template example for the complete
workflow and cleanup.
Automate a desktop
The desktop root filesystem supports screenshots, mouse and keyboard control,
clipboard access, and temporary noVNC connections. The
desktop example exercises these operations.
Errors stay inspectable
var apiError *sandbox.APIError
if errors.As(err, &apiError) {
fmt.Printf("HTTP %d, code=%d, request=%s\n",
apiError.StatusCode,
apiError.Code,
apiError.RequestID,
)
}
if errors.Is(err, sandbox.ErrTimeout) {
// A lifecycle or readiness wait exhausted its budget.
}
Examples
Runnable examples live under examples/:
Run one with the API key in the environment:
export CREATEOS_API_KEY="your-api-key"
go run ./examples/hello-world
Development
Tool versions are pinned in .tool-versions for asdf:
asdf install
make install-hooks
make check
make test-race
Commits follow Conventional Commits and are validated locally and in pull
requests. See CONTRIBUTING.md for accepted types and examples.
The CI pipeline runs race-enabled tests, go vet, and golangci-lint. The
golangci-lint v2 configuration includes error, context, body-closing, security,
static-analysis, and formatting checks.
Package layout
sandbox/ client behavior and stateful resource handles
structs/ public request, response, option, and enum contracts
internal/ transport, JSend/NDJSON, polling, and redaction
examples/ independently compilable programs
About CreateOS
CreateOS is an execution and governance platform for AI
agents and applications. Learn more about isolated Firecracker-based workloads
on the CreateOS Sandbox product page.
License
This SDK is available under the MIT License.