Skip to content
View as Markdown

daytona

import "github.com/daytonaio/daytona/libs/sdk-go/pkg/daytona"

Package daytona provides a Go SDK for interacting with the Daytona platform.

The Daytona SDK enables developers to programmatically create, manage, and interact with sandboxes - isolated development environments that can run code, execute commands, and manage files.

Getting Started

Create a client using your API key or JWT token:

client, err := daytona.NewClient()
if err != nil {
log.Fatal(err)
}

The client reads configuration from environment variables:

  • DAYTONA_API_KEY: API key for authentication
  • DAYTONA_JWT_TOKEN: JWT token for authentication (alternative to API key)
  • DAYTONA_ORGANIZATION_ID: Organization ID (required when using JWT token)
  • DAYTONA_API_URL: API URL (defaults to https://app.daytona.io/api\)
  • DAYTONA_TARGET: Target environment

Or provide configuration explicitly:

client, err := daytona.NewClientWithConfig(&types.DaytonaConfig{
APIKey: "your-api-key",
APIUrl: "https://your-instance.daytona.io/api",
})

Creating Sandboxes

Create a sandbox from a snapshot:

sandbox, err := client.Create(ctx, types.SnapshotParams{
Snapshot: "my-snapshot",
})

Create a sandbox from a Docker image:

sandbox, err := client.Create(ctx, types.ImageParams{
Image: "python:3.11",
})

Working with Sandboxes

Execute code in a sandbox:

result, err := sandbox.Process.CodeRun(ctx, "print('Hello, World!')")

Run shell commands:

result, err := sandbox.Process.ExecuteCommand(ctx, "ls -la")

Index

Variables

Version is the semantic version of the Daytona SDK.

This value is embedded at build time from the VERSION file.

Example:

fmt.Printf("Daytona SDK version: %s\n", daytona.Version)
var Version = strings.TrimSpace(version)

type Client

Client is the main entry point for interacting with the Daytona platform.

Client provides methods to create, retrieve, list, and manage sandboxes. It handles authentication, API communication, and provides access to services like Volume and Snapshot management.

Create a Client using NewClient or NewClientWithConfig:

client, err := daytona.NewClient()
if err != nil {
log.Fatal(err)
}

The Client is safe for concurrent use by multiple goroutines.

type Client struct {
// Volume provides methods for managing persistent volumes.
Volume *VolumeService
// Snapshot provides methods for managing sandbox snapshots.
Snapshot *SnapshotService
// contains filtered or unexported fields
}

func NewClient

func NewClient() (*Client, error)

NewClient creates a new Daytona client with default configuration.

NewClient reads configuration from environment variables:

  • DAYTONA_API_KEY or DAYTONA_JWT_TOKEN for authentication (one is required)
  • DAYTONA_ORGANIZATION_ID (required when using JWT token)
  • DAYTONA_API_URL for custom API endpoint
  • DAYTONA_TARGET for target environment

For explicit configuration, use NewClientWithConfig instead.

func NewClientWithConfig

func NewClientWithConfig(config *types.DaytonaConfig) (*Client, error)

NewClientWithConfig creates a new Daytona client with a custom configuration.

Configuration values provided in config take precedence over environment variables. Any configuration field left empty will fall back to the corresponding environment variable (see NewClient for the list of supported variables).

Example:

client, err := daytona.NewClientWithConfig(&types.DaytonaConfig{
APIKey: "your-api-key",
APIUrl: "https://custom.daytona.io/api",
OrganizationID: "org-123",
})
if err != nil {
log.Fatal(err)
}

Returns an error if neither API key nor JWT token is provided, or if JWT token is provided without an organization ID.

func (*Client) Create

func (c *Client) Create(ctx context.Context, params any, opts ...func(*options.CreateSandbox)) (*Sandbox, error)

Create creates a new sandbox with the specified parameters.

The params argument accepts either [types.SnapshotParams] to create from a snapshot, or [types.ImageParams] to create from a Docker image:

// Create from a snapshot
sandbox, err := client.Create(ctx, types.SnapshotParams{
Snapshot: "my-snapshot",
SandboxBaseParams: types.SandboxBaseParams{
Name: "my-sandbox",
},
})
// Create from a Docker image
sandbox, err := client.Create(ctx, types.ImageParams{
Image: "python:3.11",
Resources: &types.Resources{
CPU: 2,
Memory: 4096,
},
})

By default, Create waits for the sandbox to reach the started state before returning. Use [options.WithWaitForStart](false) to return immediately after creation.

Optional parameters can be configured using functional options:

  • [options.WithTimeout]: Set maximum wait time for creation
  • [options.WithWaitForStart]: Control whether to wait for started state
  • [options.WithLogChannel]: Receive build logs during image builds

Returns the created Sandbox or an error if creation fails.

func (*Client) FindOne

func (c *Client) FindOne(ctx context.Context, sandboxIDOrName *string, labels map[string]string) (*Sandbox, error)

FindOne finds a single sandbox by ID/name or by matching labels.

If sandboxIDOrName is provided and non-empty, FindOne delegates to Client.Get. Otherwise, it searches for sandboxes matching the provided labels and returns the first match.

This method is useful when you need to find a sandbox but may have either its identifier or its labels:

// Find by name
name := "my-sandbox"
sandbox, err := client.FindOne(ctx, &name, nil)
// Find by labels
sandbox, err := client.FindOne(ctx, nil, map[string]string{
"environment": "production",
"team": "backend",
})

Returns errors.DaytonaNotFoundError if no matching sandbox is found.

func (*Client) Get

func (c *Client) Get(ctx context.Context, sandboxIDOrName string) (*Sandbox, error)

Get retrieves an existing sandbox by its ID or name.

The sandboxIDOrName parameter accepts either the sandbox’s unique ID or its human-readable name. If a sandbox with the given identifier is not found, a errors.DaytonaNotFoundError is returned.

Example:

sandbox, err := client.Get(ctx, "my-sandbox")
if err != nil {
var notFound *errors.DaytonaNotFoundError
if errors.As(err, &notFound) {
log.Println("Sandbox not found")
}
return err
}

func (*Client) List

func (c *Client) List(ctx context.Context, labels map[string]string, page *int, limit *int) (*PaginatedSandboxes, error)

List retrieves sandboxes with optional label filtering and pagination.

Parameters:

  • labels: Optional map of labels to filter sandboxes. Pass nil for no filtering.
  • page: Optional page number (1-indexed). Pass nil for the first page.
  • limit: Optional number of results per page. Pass nil for the default limit.

Example:

// List all sandboxes
result, err := client.List(ctx, nil, nil, nil)
// List sandboxes with pagination
page, limit := 1, 10
result, err := client.List(ctx, nil, &page, &limit)
// Filter by labels
result, err := client.List(ctx, map[string]string{"env": "dev"}, nil, nil)
// Iterate through results
for _, sandbox := range result.Items {
fmt.Printf("Sandbox: %s (state: %s)\n", sandbox.Name, sandbox.State)
}

Returns a PaginatedSandboxes containing the matching sandboxes and pagination metadata.

type CodeInterpreterService

CodeInterpreterService provides Python code execution capabilities for a sandbox.

CodeInterpreterService enables running Python code in isolated execution contexts with support for streaming output, persistent state, and environment variables. It uses WebSockets for real-time output streaming. Access through [Sandbox.CodeInterpreter].

Example:

// Simple code execution
channels, err := sandbox.CodeInterpreter.RunCode(ctx, "print('Hello, World!')")
if err != nil {
return err
}
// Wait for completion and get result
result := <-channels.Done
fmt.Println(result.Stdout)
// With persistent context
ctxInfo, _ := sandbox.CodeInterpreter.CreateContext(ctx, nil)
contextID := ctxInfo["id"].(string)
channels, _ = sandbox.CodeInterpreter.RunCode(ctx, "x = 42",
options.WithCustomContext(contextID),
)
<-channels.Done
channels, _ = sandbox.CodeInterpreter.RunCode(ctx, "print(x)",
options.WithCustomContext(contextID),
)
type CodeInterpreterService struct {
// contains filtered or unexported fields
}

func NewCodeInterpreterService

func NewCodeInterpreterService(toolboxClient *toolbox.APIClient) *CodeInterpreterService

NewCodeInterpreterService creates a new CodeInterpreterService.

This is typically called internally by the SDK when creating a Sandbox. Users should access CodeInterpreterService through [Sandbox.CodeInterpreter] rather than creating it directly.

func (*CodeInterpreterService) CreateContext

func (c *CodeInterpreterService) CreateContext(ctx context.Context, cwd *string) (map[string]any, error)

CreateContext creates an isolated execution context for persistent state.

Contexts allow you to maintain state (variables, imports, etc.) across multiple code executions. Without a context, each RunCode call starts fresh.

Parameters:

  • cwd: Optional working directory for the context

Example:

// Create a context
ctxInfo, err := sandbox.CodeInterpreter.CreateContext(ctx, nil)
if err != nil {
return err
}
contextID := ctxInfo["id"].(string)
// Use the context to maintain state
sandbox.CodeInterpreter.RunCode(ctx, "x = 42", options.WithCustomContext(contextID))
sandbox.CodeInterpreter.RunCode(ctx, "print(x)", options.WithCustomContext(contextID)) // prints 42
// Clean up when done
sandbox.CodeInterpreter.DeleteContext(ctx, contextID)

Returns context information including “id”, “cwd”, “language”, “active”, and “createdAt”.

func (*CodeInterpreterService) DeleteContext

func (c *CodeInterpreterService) DeleteContext(ctx context.Context, contextID string) error

DeleteContext removes an execution context and releases its resources.

Parameters:

  • contextID: The context identifier to delete

Example:

err := sandbox.CodeInterpreter.DeleteContext(ctx, contextID)

Returns an error if the context doesn’t exist or deletion fails.

func (*CodeInterpreterService) ListContexts

func (c *CodeInterpreterService) ListContexts(ctx context.Context) ([]map[string]any, error)

ListContexts returns all active execution contexts.

Example:

contexts, err := sandbox.CodeInterpreter.ListContexts(ctx)
if err != nil {
return err
}
for _, ctx := range contexts {
fmt.Printf("Context %s (language: %s)\n", ctx["id"], ctx["language"])
}

Returns a slice of context information maps.

func (*CodeInterpreterService) RunCode

func (c *CodeInterpreterService) RunCode(ctx context.Context, code string, opts ...func(*options.RunCode)) (*OutputChannels, error)

RunCode executes Python code and returns channels for streaming output.

This method establishes a WebSocket connection to execute code asynchronously, streaming stdout and stderr as they become available.

Optional parameters can be configured using functional options:

  • [options.WithCustomContext]: Use a persistent context for state
  • [options.WithEnv]: Set environment variables
  • [options.WithInterpreterTimeout]: Set execution timeout

Example:

// Basic execution
channels, err := sandbox.CodeInterpreter.RunCode(ctx, `
for i in range(5):
print(f"Count: {i}")
`)
if err != nil {
return err
}
// Stream output
for msg := range channels.Stdout {
fmt.Print(msg.Text)
}
// Get final result
result := <-channels.Done
if result.Error != nil {
fmt.Printf("Error: %s\n", result.Error.Value)
}
// With options
channels, err := sandbox.CodeInterpreter.RunCode(ctx, "import os; print(os.environ['API_KEY'])",
options.WithEnv(map[string]string{"API_KEY": "secret"}),
options.WithInterpreterTimeout(30*time.Second),
)

Returns OutputChannels for receiving streamed output, or an error if connection fails.

type ComputerUseService

ComputerUseService provides desktop automation operations for a sandbox.

ComputerUseService enables GUI automation including mouse control, keyboard input, screenshots, and display management. The desktop environment must be started before using these features. Access through [Sandbox.ComputerUse].

Example:

cu := sandbox.ComputerUse
// Start the desktop environment
if err := cu.Start(ctx); err != nil {
return err
}
defer cu.Stop(ctx)
// Take a screenshot
screenshot, err := cu.Screenshot().TakeFullScreen(ctx, nil)
if err != nil {
return err
}
// Click at coordinates
cu.Mouse().Click(ctx, 100, 200, nil, nil)
// Type text
cu.Keyboard().Type(ctx, "Hello, World!", nil)
type ComputerUseService struct {
// contains filtered or unexported fields
}

func NewComputerUseService

func NewComputerUseService(toolboxClient *toolbox.APIClient) *ComputerUseService

NewComputerUseService creates a new ComputerUseService.

This is typically called internally by the SDK when creating a Sandbox. Users should access ComputerUseService through [Sandbox.ComputerUse] rather than creating it directly.

func (*ComputerUseService) Display

func (c *ComputerUseService) Display() *DisplayService

Display returns the DisplayService for display information.

The service is lazily initialized on first access.

func (*ComputerUseService) GetStatus

func (c *ComputerUseService) GetStatus(ctx context.Context) (map[string]any, error)

GetStatus returns the current status of the desktop environment.

Example:

status, err := cu.GetStatus(ctx)
if err != nil {
return err
}
fmt.Printf("Desktop status: %v\n", status["status"])

Returns a map containing status information.

func (*ComputerUseService) Keyboard

func (c *ComputerUseService) Keyboard() *KeyboardService

Keyboard returns the KeyboardService for keyboard operations.

The service is lazily initialized on first access.

func (*ComputerUseService) Mouse

func (c *ComputerUseService) Mouse() *MouseService

Mouse returns the MouseService for mouse operations.

The service is lazily initialized on first access.

func (*ComputerUseService) Screenshot

func (c *ComputerUseService) Screenshot() *ScreenshotService

Screenshot returns the ScreenshotService for capturing screen images.

The service is lazily initialized on first access.

func (*ComputerUseService) Start

func (c *ComputerUseService) Start(ctx context.Context) error

Start initializes and starts the desktop environment.

The desktop environment must be started before using mouse, keyboard, or screenshot operations. Call ComputerUseService.Stop when finished.

Example:

if err := cu.Start(ctx); err != nil {
return err
}
defer cu.Stop(ctx)

Returns an error if the desktop fails to start.

func (*ComputerUseService) Stop

func (c *ComputerUseService) Stop(ctx context.Context) error

Stop shuts down the desktop environment and releases resources.

Example:

err := cu.Stop(ctx)

Returns an error if the desktop fails to stop gracefully.

type DisplayService

DisplayService provides display information and window management operations.

DisplayService enables querying display configuration and window information. Access through ComputerUseService.Display.

type DisplayService struct {
// contains filtered or unexported fields
}

func NewDisplayService

func NewDisplayService(toolboxClient *toolbox.APIClient) *DisplayService

NewDisplayService creates a new DisplayService.

func (*DisplayService) GetInfo

func (d *DisplayService) GetInfo(ctx context.Context) (map[string]any, error)

GetInfo returns information about connected displays.

Example:

info, err := display.GetInfo(ctx)
if err != nil {
return err
}
displays := info["displays"]
fmt.Printf("Connected displays: %v\n", displays)

Returns a map containing display information.

func (*DisplayService) GetWindows

func (d *DisplayService) GetWindows(ctx context.Context) (map[string]any, error)

GetWindows returns information about open windows.

Example:

result, err := display.GetWindows(ctx)
if err != nil {
return err
}
windows := result["windows"]
fmt.Printf("Open windows: %v\n", windows)

Returns a map containing window information.

type DockerImage

DockerImage provides a fluent interface for building Docker images declaratively.

DockerImage allows you to define Docker images using Go code instead of Dockerfiles. Methods can be chained to build up the image definition, which is then converted to a Dockerfile when used with SnapshotService.Create.

Example:

// Create a Python image with dependencies
image := daytona.Base("python:3.11-slim").
AptGet([]string{"git", "curl"}).
PipInstall([]string{"numpy", "pandas"}).
Workdir("/app").
Env("PYTHONUNBUFFERED", "1")
// Use with snapshot creation
snapshot, logChan, err := client.Snapshots.Create(ctx, &types.CreateSnapshotParams{
Name: "my-python-env",
DockerImage: image,
})
type DockerImage struct {
// contains filtered or unexported fields
}

func Base

func Base(baseImage string) *DockerImage

Base creates a new Image from a base Docker image.

This is typically the starting point for building an image definition. The baseImage parameter is any valid Docker image reference.

Example:

image := daytona.Base("ubuntu:22.04")
image := daytona.Base("python:3.11-slim")
image := daytona.Base("node:18-alpine")

func DebianSlim

func DebianSlim(pythonVersion *string) *DockerImage

DebianSlim creates a Python image based on Debian slim.

This is a convenience function for creating Python environments. If pythonVersion is nil, defaults to Python 3.12.

Example:

// Use default Python 3.12
image := daytona.DebianSlim(nil)
// Use specific version
version := "3.10"
image := daytona.DebianSlim(&version)

func FromDockerfile

func FromDockerfile(dockerfile string) *DockerImage

FromDockerfile creates an Image from an existing Dockerfile string.

Use this when you have an existing Dockerfile you want to use.

Example:

dockerfile := `FROM python:3.11
RUN pip install numpy
WORKDIR /app`
image := daytona.FromDockerfile(dockerfile)

func (*DockerImage) Add

func (img *DockerImage) Add(source, destination string) *DockerImage

Add adds an ADD instruction to the image.

ADD supports URLs and automatic tar extraction. For simple file copying, prefer DockerImage.Copy.

Example:

image := daytona.Base("ubuntu:22.04").
Add("https://example.com/app.tar.gz", "/app/")

func (*DockerImage) AddLocalDir

func (img *DockerImage) AddLocalDir(localPath, remotePath string) *DockerImage

AddLocalDir adds a local directory to the build context and copies it to the image.

The directory is uploaded to object storage and included in the Docker build context.

Example:

image := daytona.Base("python:3.11").
AddLocalDir("./src", "/app/src")

func (*DockerImage) AddLocalFile

func (img *DockerImage) AddLocalFile(localPath, remotePath string) *DockerImage

AddLocalFile adds a local file to the build context and copies it to the image.

The file is uploaded to object storage and included in the Docker build context.

Example:

image := daytona.Base("python:3.11").
AddLocalFile("./requirements.txt", "/app/requirements.txt").
Run("pip install -r /app/requirements.txt")

func (*DockerImage) AptGet

func (img *DockerImage) AptGet(packages []string) *DockerImage

AptGet adds an apt-get install instruction for system packages.

This automatically handles updating the package list and cleaning up afterward to minimize image size.

Example:

image := daytona.Base("ubuntu:22.04").AptGet([]string{"git", "curl", "build-essential"})

func (*DockerImage) Cmd

func (img *DockerImage) Cmd(cmd []string) *DockerImage

Cmd sets the default command for the image.

If an entrypoint is set, the cmd provides default arguments to it.

Example:

image := daytona.Base("python:3.11").
Cmd([]string{"python", "app.py"})

func (*DockerImage) Contexts

func (img *DockerImage) Contexts() []DockerImageContext

Contexts returns the build contexts for local files/directories.

This is called internally when creating snapshots to upload local files.

func (*DockerImage) Copy

func (img *DockerImage) Copy(source, destination string) *DockerImage

Copy adds a COPY instruction to copy files into the image.

For local files, use DockerImage.AddLocalFile instead, which handles uploading to the build context.

Example:

image := daytona.Base("python:3.11").
Copy("requirements.txt", "/app/requirements.txt")

func (*DockerImage) Dockerfile

func (img *DockerImage) Dockerfile() string

Dockerfile returns the generated Dockerfile content.

This is called internally when creating snapshots.

Example:

3.11
image := daytona.Base("python:3.11").PipInstall([]string{"numpy"})
fmt.Println(image.Dockerfile())
// Output:
// RUN pip install numpy

func (*DockerImage) Entrypoint

func (img *DockerImage) Entrypoint(cmd []string) *DockerImage

Entrypoint sets the entrypoint for the image.

The cmd parameter is the command and arguments as a slice.

Example:

image := daytona.Base("python:3.11").
Entrypoint([]string{"python", "-m", "myapp"})

func (*DockerImage) Env

func (img *DockerImage) Env(key, value string) *DockerImage

Env sets an environment variable in the image.

Example:

image := daytona.Base("python:3.11").
Env("PYTHONUNBUFFERED", "1").
Env("APP_ENV", "production")

func (*DockerImage) Expose

func (img *DockerImage) Expose(ports []int) *DockerImage

Expose declares ports that the container listens on.

This is documentation for users and tools; it doesn’t actually publish ports.

Example:

image := daytona.Base("python:3.11").
Expose([]int{8080, 8443})

func (*DockerImage) Label

func (img *DockerImage) Label(key, value string) *DockerImage

Label adds metadata to the image.

Example:

image := daytona.Base("python:3.11").
Label("maintainer", "team@example.com").
Label("version", "1.0.0")

func (*DockerImage) PipInstall

func (img *DockerImage) PipInstall(packages []string, opts ...func(*options.PipInstall)) *DockerImage

PipInstall adds a pip install instruction for Python packages.

Optional parameters can be configured using functional options:

  • [options.WithFindLinks]: Add find-links URLs
  • [options.WithIndexURL]: Set custom PyPI index
  • [options.WithExtraIndexURLs]: Add extra index URLs
  • [options.WithPre]: Allow pre-release versions
  • [options.WithExtraOptions]: Add additional pip options

Example:

// Basic installation
image := daytona.Base("python:3.11").PipInstall([]string{"numpy", "pandas"})
// With options
image := daytona.Base("python:3.11").PipInstall(
[]string{"torch"},
options.WithIndexURL("https://download.pytorch.org/whl/cpu"),
options.WithExtraOptions("--no-cache-dir"),
)

func (*DockerImage) Run

func (img *DockerImage) Run(command string) *DockerImage

Run adds a RUN instruction to execute a shell command.

Example:

image := daytona.Base("ubuntu:22.04").
Run("mkdir -p /app/data").
Run("chmod 755 /app")

func (*DockerImage) User

func (img *DockerImage) User(username string) *DockerImage

User sets the user for subsequent instructions and container runtime.

Example:

image := daytona.Base("python:3.11").
Run("useradd -m appuser").
User("appuser").
Workdir("/home/appuser")

func (*DockerImage) Volume

func (img *DockerImage) Volume(paths []string) *DockerImage

Volume declares mount points for the container.

Example:

image := daytona.Base("python:3.11").
Volume([]string{"/data", "/logs"})

func (*DockerImage) Workdir

func (img *DockerImage) Workdir(path string) *DockerImage

Workdir sets the working directory for subsequent instructions.

Example:

image := daytona.Base("python:3.11").
Workdir("/app").
Run("pip install -r requirements.txt")

type DockerImageContext

DockerImageContext represents a local file or directory to include in the build context.

When using DockerImage.AddLocalFile or DockerImage.AddLocalDir, the file/directory is uploaded to object storage and included in the Docker build context.

type DockerImageContext struct {
SourcePath string // Local path to the file or directory
ArchivePath string // Path within the build context archive
}

type FileSystemService

FileSystemService provides file system operations for a sandbox.

FileSystemService enables file and directory management including creating, reading, writing, moving, and deleting files. It also supports file searching and permission management. Access through [Sandbox.FileSystem].

Example:

// List files in a directory
files, err := sandbox.FileSystem.ListFiles(ctx, "/home/user")
// Create a directory
err = sandbox.FileSystem.CreateFolder(ctx, "/home/user/mydir")
// Upload a file
err = sandbox.FileSystem.UploadFile(ctx, "/local/path/file.txt", "/home/user/file.txt")
// Download a file
data, err := sandbox.FileSystem.DownloadFile(ctx, "/home/user/file.txt", nil)
type FileSystemService struct {
// contains filtered or unexported fields
}

func NewFileSystemService

func NewFileSystemService(toolboxClient *toolbox.APIClient) *FileSystemService

NewFileSystemService creates a new FileSystemService with the provided toolbox client.

This is typically called internally by the SDK when creating a Sandbox. Users should access FileSystemService through [Sandbox.FileSystem] rather than creating it directly.

func (*FileSystemService) CreateFolder

func (f *FileSystemService) CreateFolder(ctx context.Context, path string, opts ...func(*options.CreateFolder)) error

CreateFolder creates a directory at the specified path.

The path parameter specifies the absolute path for the new directory. Parent directories are created automatically if they don’t exist.

Optional parameters can be configured using functional options:

  • [options.WithMode]: Set Unix file permissions (defaults to “0755”)

Example:

// Create with default permissions
err := sandbox.FileSystem.CreateFolder(ctx, "/home/user/mydir")
// Create with custom permissions
err := sandbox.FileSystem.CreateFolder(ctx, "/home/user/private",
options.WithMode("0700"),
)

Returns an error if the directory creation fails.

func (*FileSystemService) DeleteFile

func (f *FileSystemService) DeleteFile(ctx context.Context, path string, recursive bool) error

DeleteFile deletes a file or directory.

Parameters:

  • path: The file or directory path to delete
  • recursive: If true, delete directories and their contents recursively

Example:

// Delete a file
err := sandbox.FileSystem.DeleteFile(ctx, "/home/user/file.txt", false)
// Delete a directory recursively
err := sandbox.FileSystem.DeleteFile(ctx, "/home/user/mydir", true)

Returns an error if the deletion fails (e.g., path doesn’t exist, permission denied, or attempting to delete a non-empty directory without recursive=true).

func (*FileSystemService) DownloadFile

func (f *FileSystemService) DownloadFile(ctx context.Context, remotePath string, localPath *string) ([]byte, error)

DownloadFile downloads a file from the sandbox.

Parameters:

  • remotePath: The path to the file in the sandbox
  • localPath: Optional local path to save the file. If nil, only returns the data.

Returns the file contents as a byte slice. If localPath is provided, also writes the contents to that local file.

Example:

// Download and get contents
data, err := sandbox.FileSystem.DownloadFile(ctx, "/home/user/file.txt", nil)
fmt.Println(string(data))
// Download and save to local file
localPath := "/tmp/downloaded.txt"
data, err := sandbox.FileSystem.DownloadFile(ctx, "/home/user/file.txt", &localPath)

Returns an error if the file doesn’t exist or cannot be read.

func (*FileSystemService) FindFiles

func (f *FileSystemService) FindFiles(ctx context.Context, path, pattern string) (any, error)

FindFiles searches for text content within files.

Parameters:

  • path: The directory to search in
  • pattern: The text pattern to search for (supports regex)

Returns a list of matches, each containing the file path, line number, and matching content.

Example:

result, err := sandbox.FileSystem.FindFiles(ctx, "/home/user/project", "TODO:")
if err != nil {
return err
}
matches := result.([]map[string]any)
for _, match := range matches {
fmt.Printf("%s:%d: %s\n", match["file"], match["line"], match["content"])
}

Returns an error if the search fails.

func (*FileSystemService) GetFileInfo

func (f *FileSystemService) GetFileInfo(ctx context.Context, path string) (*types.FileInfo, error)

GetFileInfo retrieves metadata for a file or directory.

The path parameter specifies the file or directory path.

Returns [types.FileInfo] containing the file’s name, size, permissions, modification time, and whether it’s a directory.

Example:

info, err := sandbox.FileSystem.GetFileInfo(ctx, "/home/user/file.txt")
if err != nil {
return err
}
fmt.Printf("Size: %d bytes, Modified: %s\n", info.Size, info.ModifiedTime)

Returns an error if the path doesn’t exist.

func (*FileSystemService) ListFiles

func (f *FileSystemService) ListFiles(ctx context.Context, path string) ([]*types.FileInfo, error)

ListFiles lists files and directories in the specified path.

The path parameter specifies the directory to list.

Returns a slice of [types.FileInfo] containing metadata for each file and directory, including name, size, permissions, modification time, and whether it’s a directory.

Example:

files, err := sandbox.FileSystem.ListFiles(ctx, "/home/user")
if err != nil {
return err
}
for _, file := range files {
if file.IsDirectory {
fmt.Printf("[DIR] %s\n", file.Name)
} else {
fmt.Printf("[FILE] %s (%d bytes)\n", file.Name, file.Size)
}
}

Returns an error if the path doesn’t exist or isn’t accessible.

func (*FileSystemService) MoveFiles

func (f *FileSystemService) MoveFiles(ctx context.Context, source, destination string) error

MoveFiles moves or renames a file or directory.

Parameters:

  • source: The current path of the file or directory
  • destination: The new path for the file or directory

This operation can be used for both moving and renaming:

  • Same directory, different name = rename
  • Different directory = move

Example:

// Rename a file
err := sandbox.FileSystem.MoveFiles(ctx, "/home/user/old.txt", "/home/user/new.txt")
// Move a file to another directory
err := sandbox.FileSystem.MoveFiles(ctx, "/home/user/file.txt", "/home/user/backup/file.txt")

Returns an error if the operation fails.

func (*FileSystemService) ReplaceInFiles

func (f *FileSystemService) ReplaceInFiles(ctx context.Context, files []string, pattern, newValue string) (any, error)

ReplaceInFiles replaces text in multiple files.

Parameters:

  • files: List of file paths to process
  • pattern: The text pattern to search for (supports regex)
  • newValue: The replacement text

Returns a list of results for each file, indicating success or failure.

Example:

files := []string{"/home/user/file1.txt", "/home/user/file2.txt"}
result, err := sandbox.FileSystem.ReplaceInFiles(ctx, files, "oldValue", "newValue")
if err != nil {
return err
}
results := result.([]map[string]any)
for _, r := range results {
if r["success"].(bool) {
fmt.Printf("Updated: %s\n", r["file"])
} else {
fmt.Printf("Failed: %s - %s\n", r["file"], r["error"])
}
}

Returns an error if the operation fails entirely.

func (*FileSystemService) SearchFiles

func (f *FileSystemService) SearchFiles(ctx context.Context, path, pattern string) (any, error)

SearchFiles searches for files matching a pattern in a directory.

Parameters:

  • path: The directory to search in
  • pattern: The glob pattern to match file names (e.g., “*.txt”, “test_*”)

Returns a map containing a “files” key with a list of matching file paths.

Example:

result, err := sandbox.FileSystem.SearchFiles(ctx, "/home/user", "*.go")
if err != nil {
return err
}
files := result.(map[string]any)["files"].([]string)
for _, file := range files {
fmt.Println(file)
}

Returns an error if the search fails.

func (*FileSystemService) SetFilePermissions

func (f *FileSystemService) SetFilePermissions(ctx context.Context, path string, opts ...func(*options.SetFilePermissions)) error

SetFilePermissions sets file permissions, owner, and group.

The path parameter specifies the file or directory to modify.

Optional parameters can be configured using functional options:

  • [options.WithPermissionMode]: Set Unix file permissions (e.g., “0644”)
  • [options.WithOwner]: Set file owner username
  • [options.WithGroup]: Set file group name

Example:

// Set permissions only
err := sandbox.FileSystem.SetFilePermissions(ctx, "/home/user/script.sh",
options.WithPermissionMode("0755"),
)
// Set owner and group
err := sandbox.FileSystem.SetFilePermissions(ctx, "/home/user/file.txt",
options.WithOwner("root"),
options.WithGroup("users"),
)
// Set all at once
err := sandbox.FileSystem.SetFilePermissions(ctx, "/home/user/file.txt",
options.WithPermissionMode("0640"),
options.WithOwner("user"),
options.WithGroup("staff"),
)

Returns an error if the operation fails.

func (*FileSystemService) UploadFile

func (f *FileSystemService) UploadFile(ctx context.Context, source any, destination string) error

UploadFile uploads a file to the sandbox.

Parameters:

  • source: Either a local file path (string) or file contents ([]byte)
  • destination: The destination path in the sandbox

Example:

// Upload from local file path
err := sandbox.FileSystem.UploadFile(ctx, "/local/path/file.txt", "/home/user/file.txt")
// Upload from byte slice
content := []byte("Hello, World!")
err := sandbox.FileSystem.UploadFile(ctx, content, "/home/user/hello.txt")

Returns an error if the upload fails.

type GitService

GitService provides Git operations for a sandbox.

GitService enables common Git workflows including cloning repositories, staging and committing changes, managing branches, and syncing with remote repositories. It is accessed through the [Sandbox.Git] field.

Example:

// Clone a repository
err := sandbox.Git.Clone(ctx, "https://github.com/user/repo.git", "/home/user/repo")
// Make changes and commit
err = sandbox.Git.Add(ctx, "/home/user/repo", []string{"."})
resp, err := sandbox.Git.Commit(ctx, "/home/user/repo", "Initial commit", "John Doe", "john@example.com")
// Push to remote
err = sandbox.Git.Push(ctx, "/home/user/repo",
options.WithPushUsername("username"),
options.WithPushPassword("token"),
)
type GitService struct {
// contains filtered or unexported fields
}

func NewGitService

func NewGitService(toolboxClient *toolbox.APIClient) *GitService

NewGitService creates a new GitService with the provided toolbox client.

This is typically called internally by the SDK when creating a Sandbox. Users should access GitService through [Sandbox.Git] rather than creating it directly.

func (*GitService) Add

func (g *GitService) Add(ctx context.Context, path string, files []string) error

Add stages files for the next commit.

The path parameter specifies the repository directory. The files parameter is a list of file paths (relative to the repository root) to stage. Use ”.” to stage all changes.

Example:

// Stage specific files
err := sandbox.Git.Add(ctx, "/home/user/repo", []string{"file1.txt", "src/main.go"})
// Stage all changes
err := sandbox.Git.Add(ctx, "/home/user/repo", []string{"."})

Returns an error if the add operation fails.

func (*GitService) Branches

func (g *GitService) Branches(ctx context.Context, path string) ([]string, error)

Branches lists all branches in a Git repository.

The path parameter specifies the repository directory.

Example:

branches, err := sandbox.Git.Branches(ctx, "/home/user/repo")
if err != nil {
return err
}
for _, branch := range branches {
fmt.Println(branch)
}

Returns a slice of branch names or an error if the operation fails.

func (*GitService) Checkout

func (g *GitService) Checkout(ctx context.Context, path, name string) error

Checkout switches to a different branch or commit.

The path parameter specifies the repository directory. The name parameter specifies the branch name or commit SHA to checkout.

Example:

// Switch to a branch
err := sandbox.Git.Checkout(ctx, "/home/user/repo", "develop")
// Checkout a specific commit
err := sandbox.Git.Checkout(ctx, "/home/user/repo", "abc123def")

Returns an error if the checkout fails (e.g., branch doesn’t exist, uncommitted changes).

func (*GitService) Clone

func (g *GitService) Clone(ctx context.Context, url, path string, opts ...func(*options.GitClone)) error

Clone clones a Git repository into the specified path.

The url parameter specifies the repository URL (HTTPS or SSH format). The path parameter specifies the destination directory for the cloned repository.

Optional parameters can be configured using functional options:

  • [options.WithBranch]: Clone a specific branch instead of the default
  • [options.WithCommitId]: Checkout a specific commit after cloning
  • [options.WithUsername]: Username for authentication (HTTPS)
  • [options.WithPassword]: Password or token for authentication (HTTPS)

Example:

// Clone the default branch
err := sandbox.Git.Clone(ctx, "https://github.com/user/repo.git", "/home/user/repo")
// Clone a specific branch with authentication
err := sandbox.Git.Clone(ctx, "https://github.com/user/private-repo.git", "/home/user/repo",
options.WithBranch("develop"),
options.WithUsername("username"),
options.WithPassword("github_token"),
)
// Clone and checkout a specific commit
err := sandbox.Git.Clone(ctx, "https://github.com/user/repo.git", "/home/user/repo",
options.WithCommitId("abc123"),
)

Returns an error if the clone operation fails.

func (*GitService) Commit

func (g *GitService) Commit(ctx context.Context, path, message, author, email string, opts ...func(*options.GitCommit)) (*types.GitCommitResponse, error)

Commit creates a new Git commit with the staged changes.

Parameters:

  • path: The repository directory
  • message: The commit message
  • author: The author name for the commit
  • email: The author email for the commit

Optional parameters can be configured using functional options:

  • [options.WithAllowEmpty]: Allow creating commits with no changes

Example:

// Create a commit
resp, err := sandbox.Git.Commit(ctx, "/home/user/repo",
"Add new feature",
"John Doe",
"john@example.com",
)
if err != nil {
return err
}
fmt.Printf("Created commit: %s\n", resp.SHA)
// Create an empty commit
resp, err := sandbox.Git.Commit(ctx, "/home/user/repo",
"Empty commit for CI trigger",
"John Doe",
"john@example.com",
options.WithAllowEmpty(true),
)

Returns the [types.GitCommitResponse] containing the commit SHA, or an error if the commit fails.

func (*GitService) CreateBranch

func (g *GitService) CreateBranch(ctx context.Context, path, name string) error

CreateBranch creates a new branch at the current HEAD.

The path parameter specifies the repository directory. The name parameter specifies the name for the new branch.

Note: This creates the branch but does not switch to it. Use GitService.Checkout to switch to the new branch after creation.

Example:

// Create a new branch
err := sandbox.Git.CreateBranch(ctx, "/home/user/repo", "feature/new-feature")
if err != nil {
return err
}
// Switch to the new branch
err = sandbox.Git.Checkout(ctx, "/home/user/repo", "feature/new-feature")

Returns an error if the branch creation fails (e.g., branch already exists).

func (*GitService) DeleteBranch

func (g *GitService) DeleteBranch(ctx context.Context, path, name string, opts ...func(*options.GitDeleteBranch)) error

DeleteBranch deletes a branch from the repository.

The path parameter specifies the repository directory. The name parameter specifies the branch to delete.

Optional parameters can be configured using functional options:

  • [options.WithForce]: Force delete the branch even if not fully merged

Note: You cannot delete the currently checked out branch.

Example:

// Delete a merged branch
err := sandbox.Git.DeleteBranch(ctx, "/home/user/repo", "feature/old-feature")
// Force delete an unmerged branch
err := sandbox.Git.DeleteBranch(ctx, "/home/user/repo", "feature/abandoned",
options.WithForce(true),
)

Returns an error if the deletion fails.

func (*GitService) Pull

func (g *GitService) Pull(ctx context.Context, path string, opts ...func(*options.GitPull)) error

Pull fetches and merges changes from the remote repository.

The path parameter specifies the repository directory.

Optional parameters can be configured using functional options:

  • [options.WithPullUsername]: Username for authentication
  • [options.WithPullPassword]: Password or token for authentication

Example:

// Pull from a public repository
err := sandbox.Git.Pull(ctx, "/home/user/repo")
// Pull with authentication
err := sandbox.Git.Pull(ctx, "/home/user/repo",
options.WithPullUsername("username"),
options.WithPullPassword("github_token"),
)

Returns an error if the pull fails (e.g., merge conflicts, authentication failure).

func (*GitService) Push

func (g *GitService) Push(ctx context.Context, path string, opts ...func(*options.GitPush)) error

Push pushes local commits to the remote repository.

The path parameter specifies the repository directory.

Optional parameters can be configured using functional options:

  • [options.WithPushUsername]: Username for authentication
  • [options.WithPushPassword]: Password or token for authentication

Example:

// Push to a public repository (no auth required)
err := sandbox.Git.Push(ctx, "/home/user/repo")
// Push with authentication
err := sandbox.Git.Push(ctx, "/home/user/repo",
options.WithPushUsername("username"),
options.WithPushPassword("github_token"),
)

Returns an error if the push fails (e.g., authentication failure, remote rejection).

func (*GitService) Status

func (g *GitService) Status(ctx context.Context, path string) (*types.GitStatus, error)

Status returns the current Git status of a repository.

The path parameter specifies the repository directory to check.

The returned [types.GitStatus] contains:

  • CurrentBranch: The name of the currently checked out branch
  • Ahead: Number of commits ahead of the remote tracking branch
  • Behind: Number of commits behind the remote tracking branch
  • BranchPublished: Whether the branch has been pushed to remote
  • FileStatus: List of files with their staging and working tree status

Example:

status, err := sandbox.Git.Status(ctx, "/home/user/repo")
if err != nil {
return err
}
fmt.Printf("On branch %s\n", status.CurrentBranch)
fmt.Printf("Ahead: %d, Behind: %d\n", status.Ahead, status.Behind)
for _, file := range status.FileStatus {
fmt.Printf("%s %s\n", file.Status, file.Path)
}

Returns an error if the status operation fails or the path is not a Git repository.

type KeyboardService

KeyboardService provides keyboard input operations.

KeyboardService enables typing text, pressing keys, and executing keyboard shortcuts. Access through ComputerUseService.Keyboard.

type KeyboardService struct {
// contains filtered or unexported fields
}

func NewKeyboardService

func NewKeyboardService(toolboxClient *toolbox.APIClient) *KeyboardService

NewKeyboardService creates a new KeyboardService.

func (*KeyboardService) Hotkey

func (k *KeyboardService) Hotkey(ctx context.Context, keys string) error

Hotkey executes a keyboard shortcut.

Parameters:

  • keys: The hotkey combination as a string (e.g., “ctrl+c”, “alt+tab”)

Example:

// Copy (Ctrl+C)
err := keyboard.Hotkey(ctx, "ctrl+c")
// Paste (Ctrl+V)
err := keyboard.Hotkey(ctx, "ctrl+v")
// Switch windows (Alt+Tab)
err := keyboard.Hotkey(ctx, "alt+tab")

Returns an error if the hotkey fails.

func (*KeyboardService) Press

func (k *KeyboardService) Press(ctx context.Context, key string, modifiers []string) error

Press simulates pressing a key with optional modifiers.

Parameters:

  • key: The key to press (e.g., “a”, “Enter”, “Tab”, “F1”)
  • modifiers: Modifier keys to hold (e.g., “ctrl”, “alt”, “shift”, “meta”)

Example:

// Press Enter
err := keyboard.Press(ctx, "Enter", nil)
// Press Ctrl+S
err := keyboard.Press(ctx, "s", []string{"ctrl"})
// Press Ctrl+Shift+N
err := keyboard.Press(ctx, "n", []string{"ctrl", "shift"})

Returns an error if the key press fails.

func (*KeyboardService) Type

func (k *KeyboardService) Type(ctx context.Context, text string, delay *int) error

Type simulates typing the specified text.

Parameters:

  • text: The text to type
  • delay: Delay in milliseconds between keystrokes, nil for default

Example:

// Type text with default speed
err := keyboard.Type(ctx, "Hello, World!", nil)
// Type with custom delay between keystrokes
delay := 50
err := keyboard.Type(ctx, "Slow typing", &delay)

Returns an error if typing fails.

type LspServerService

LspServerService provides Language Server Protocol (LSP) operations for a sandbox.

LspServerService enables IDE-like features such as code completion, symbol search, and document analysis through LSP. The service manages a language server instance for a specific language and project path. Access through [Sandbox.Lsp].

Example:

// Get LSP service for Python
lsp := sandbox.Lsp(types.LspLanguageIDPython, "/home/user/project")
// Start the language server
if err := lsp.Start(ctx); err != nil {
return err
}
defer lsp.Stop(ctx)
// Open a file for analysis
if err := lsp.DidOpen(ctx, "/home/user/project/main.py"); err != nil {
return err
}
// Get code completions
completions, err := lsp.Completions(ctx, "/home/user/project/main.py",
types.Position{Line: 10, Character: 5})
type LspServerService struct {
// contains filtered or unexported fields
}

func NewLspServerService

func NewLspServerService(toolboxClient *toolbox.APIClient, languageID types.LspLanguageID, projectPath string) *LspServerService

NewLspServerService creates a new LspServerService.

This is typically called internally by the SDK through [Sandbox.Lsp]. Users should access LspServerService through [Sandbox.Lsp] rather than creating it directly.

Parameters:

  • toolboxClient: The toolbox API client
  • languageID: The language identifier (e.g., [types.LspLanguageIDPython])
  • projectPath: The root path of the project for LSP analysis

func (*LspServerService) Completions

func (l *LspServerService) Completions(ctx context.Context, path string, position types.Position) (any, error)

Completions returns code completion suggestions at a position.

The file should be opened with LspServerService.DidOpen before requesting completions.

Parameters:

  • path: Absolute path to the file
  • position: Cursor position (line and character, 0-indexed)

Example:

lsp.DidOpen(ctx, "/home/user/project/main.py")
completions, err := lsp.Completions(ctx, "/home/user/project/main.py",
types.Position{Line: 10, Character: 5})
if err != nil {
return err
}
fmt.Printf("Completions: %v\n", completions)

Returns completion items or an error.

func (*LspServerService) DidClose

func (l *LspServerService) DidClose(ctx context.Context, path string) error

DidClose notifies the language server that a file was closed.

Call this when you’re done working with a file to allow the server to release resources associated with it.

Parameters:

  • path: Absolute path to the file

Example:

err := lsp.DidClose(ctx, "/home/user/project/main.py")

Returns an error if the notification fails.

func (*LspServerService) DidOpen

func (l *LspServerService) DidOpen(ctx context.Context, path string) error

DidOpen notifies the language server that a file was opened.

This should be called before requesting completions or symbols for a file. The path is automatically converted to a file:// URI if needed.

Parameters:

  • path: Absolute path to the file

Example:

err := lsp.DidOpen(ctx, "/home/user/project/main.py")

Returns an error if the notification fails.

func (*LspServerService) DocumentSymbols

func (l *LspServerService) DocumentSymbols(ctx context.Context, path string) ([]any, error)

DocumentSymbols returns all symbols (functions, classes, variables) in a document.

Parameters:

  • path: Absolute path to the file

Example:

symbols, err := lsp.DocumentSymbols(ctx, "/home/user/project/main.py")
if err != nil {
return err
}
for _, sym := range symbols {
fmt.Printf("Symbol: %v\n", sym)
}

Returns a slice of symbol information or an error.

func (*LspServerService) SandboxSymbols

func (l *LspServerService) SandboxSymbols(ctx context.Context, query string) ([]any, error)

SandboxSymbols searches for symbols across the entire workspace.

Use this to find symbols (functions, classes, etc.) by name across all files in the project.

Parameters:

  • query: Search query to match symbol names

Example:

symbols, err := lsp.SandboxSymbols(ctx, "MyClass")
if err != nil {
return err
}
for _, sym := range symbols {
fmt.Printf("Found: %v\n", sym)
}

Returns a slice of matching symbols or an error.

func (*LspServerService) Start

func (l *LspServerService) Start(ctx context.Context) error

Start initializes and starts the language server.

The language server must be started before using other LSP operations. Call LspServerService.Stop when finished to release resources.

Example:

if err := lsp.Start(ctx); err != nil {
return err
}
defer lsp.Stop(ctx)

Returns an error if the server fails to start.

func (*LspServerService) Stop

func (l *LspServerService) Stop(ctx context.Context) error

Stop shuts down the language server and releases resources.

Example:

err := lsp.Stop(ctx)

Returns an error if the server fails to stop gracefully.

type MouseService

MouseService provides mouse control operations.

MouseService enables cursor movement, clicking, dragging, and scrolling. Access through ComputerUseService.Mouse.

type MouseService struct {
// contains filtered or unexported fields
}

func NewMouseService

func NewMouseService(toolboxClient *toolbox.APIClient) *MouseService

NewMouseService creates a new MouseService.

func (*MouseService) Click

func (m *MouseService) Click(ctx context.Context, x, y int, button *string, double *bool) (map[string]any, error)

Click performs a mouse click at the specified coordinates.

Parameters:

  • x: X coordinate to click
  • y: Y coordinate to click
  • button: Mouse button (“left”, “right”, “middle”), nil for left click
  • double: Whether to double-click, nil for single click

Example:

// Single left click
pos, err := mouse.Click(ctx, 100, 200, nil, nil)
// Right click
button := "right"
pos, err := mouse.Click(ctx, 100, 200, &button, nil)
// Double click
doubleClick := true
pos, err := mouse.Click(ctx, 100, 200, nil, &doubleClick)

Returns a map with the click “x” and “y” coordinates.

func (*MouseService) Drag

func (m *MouseService) Drag(ctx context.Context, startX, startY, endX, endY int, button *string) (map[string]any, error)

Drag performs a mouse drag operation from start to end coordinates.

Parameters:

  • startX, startY: Starting coordinates
  • endX, endY: Ending coordinates
  • button: Mouse button to use, nil for left button

Example:

// Drag from (100, 100) to (300, 300)
pos, err := mouse.Drag(ctx, 100, 100, 300, 300, nil)

Returns a map with the final “x” and “y” coordinates.

func (*MouseService) GetPosition

func (m *MouseService) GetPosition(ctx context.Context) (map[string]any, error)

GetPosition returns the current cursor position.

Example:

pos, err := mouse.GetPosition(ctx)
if err != nil {
return err
}
fmt.Printf("Cursor at (%v, %v)\n", pos["x"], pos["y"])

Returns a map with “x” and “y” coordinates.

func (*MouseService) Move

func (m *MouseService) Move(ctx context.Context, x, y int) (map[string]any, error)

Move moves the cursor to the specified coordinates.

Parameters:

  • x: Target X coordinate
  • y: Target Y coordinate

Example:

pos, err := mouse.Move(ctx, 500, 300)

Returns a map with the new “x” and “y” coordinates.

func (*MouseService) Scroll

func (m *MouseService) Scroll(ctx context.Context, x, y int, direction string, amount *int) (bool, error)

Scroll performs a mouse scroll operation at the specified coordinates.

Parameters:

  • x, y: Coordinates where the scroll occurs
  • direction: Scroll direction (“up”, “down”, “left”, “right”)
  • amount: Scroll amount, nil for default

Example:

// Scroll down at position (500, 400)
success, err := mouse.Scroll(ctx, 500, 400, "down", nil)
// Scroll up with specific amount
amount := 5
success, err := mouse.Scroll(ctx, 500, 400, "up", &amount)

Returns true if the scroll was successful.

type OutputChannels

OutputChannels provides channels for streaming execution output.

All channels are closed when execution completes or encounters an error. The Done channel always receives exactly one message with the final result.

type OutputChannels struct {
Stdout <-chan *types.OutputMessage // Receives stdout messages as they occur
Stderr <-chan *types.OutputMessage // Receives stderr messages as they occur
Errors <-chan *types.ExecutionError // Receives execution errors
Done <-chan *types.ExecutionResult // Receives final result when execution completes
}

type PaginatedSandboxes

PaginatedSandboxes represents a paginated list of sandboxes.

type PaginatedSandboxes struct {
Items []*Sandbox // Sandboxes in this page
Total int // Total number of sandboxes
Page int // Current page number
TotalPages int // Total number of pages
}

type ProcessService

ProcessService provides process execution operations for a sandbox.

ProcessService enables command execution, session management, and PTY (pseudo-terminal) operations. It supports both synchronous command execution and interactive terminal sessions. Access through [Sandbox.Process].

Example:

// Execute a command
result, err := sandbox.Process.ExecuteCommand(ctx, "echo 'Hello, World!'")
fmt.Println(result.Result)
// Execute with options
result, err := sandbox.Process.ExecuteCommand(ctx, "ls -la",
options.WithCwd("/home/user/project"),
options.WithExecuteTimeout(30*time.Second),
)
// Create an interactive PTY session
handle, err := sandbox.Process.CreatePty(ctx, "my-terminal")
defer handle.Disconnect()
type ProcessService struct {
// contains filtered or unexported fields
}

func NewProcessService

func NewProcessService(toolboxClient *toolbox.APIClient) *ProcessService

NewProcessService creates a new ProcessService with the provided toolbox client.

This is typically called internally by the SDK when creating a Sandbox. Users should access ProcessService through [Sandbox.Process] rather than creating it directly.

func (*ProcessService) CodeRun

func (p *ProcessService) CodeRun(ctx context.Context, code string, opts ...func(*options.CodeRun)) (*types.ExecuteResponse, error)

CodeRun executes code in a language-specific way.

NOTE: This method is currently unavailable as the toolbox-api-client-go does not expose a CodeRun endpoint. For code execution, use ProcessService.ExecuteCommand or CodeInterpreterService.

Optional parameters can be configured using functional options:

  • [options.WithCodeRunParams]: Set code execution parameters
  • [options.WithCodeRunTimeout]: Set execution timeout

func (*ProcessService) ConnectPty

func (p *ProcessService) ConnectPty(ctx context.Context, sessionID string) (*PtyHandle, error)

ConnectPty establishes a WebSocket connection to an existing PTY session.

Returns a PtyHandle for interacting with the terminal. The handle provides:

  • DataChan(): Channel for receiving terminal output
  • SendInput(): Method for sending keyboard input
  • Resize(): Method for changing terminal size
  • Disconnect(): Method for closing the connection

Parameters:

  • sessionID: The PTY session to connect to

Example:

handle, err := sandbox.Process.ConnectPty(ctx, "my-terminal")
if err != nil {
return err
}
defer handle.Disconnect()
// Wait for connection
if err := handle.WaitForConnection(ctx); err != nil {
return err
}
// Read output
for data := range handle.DataChan() {
fmt.Print(string(data))
}

Returns a PtyHandle for terminal interaction, or an error.

func (*ProcessService) CreatePty

func (p *ProcessService) CreatePty(ctx context.Context, id string, opts ...func(*options.CreatePty)) (*PtyHandle, error)

CreatePty creates a new PTY session and immediately connects to it.

This is a convenience method that combines ProcessService.CreatePtySession and ProcessService.ConnectPty into a single operation.

Parameters:

  • id: Unique identifier for the PTY session

Optional parameters can be configured using functional options:

  • [options.WithCreatePtySize]: Set terminal dimensions
  • [options.WithCreatePtyEnv]: Set environment variables

Example:

handle, err := sandbox.Process.CreatePty(ctx, "interactive-shell",
options.WithCreatePtySize(types.PtySize{Rows: 24, Cols: 80}),
options.WithCreatePtyEnv(map[string]string{"TERM": "xterm-256color"}),
)
if err != nil {
return err
}
defer handle.Disconnect()
// Wait for connection
if err := handle.WaitForConnection(ctx); err != nil {
return err
}
// Send a command
handle.SendInput([]byte("ls -la\n"))
// Read output
for data := range handle.DataChan() {
fmt.Print(string(data))
}

Returns a PtyHandle for terminal interaction, or an error.

func (*ProcessService) CreatePtySession

func (p *ProcessService) CreatePtySession(ctx context.Context, id string, opts ...func(*options.PtySession)) (*types.PtySessionInfo, error)

CreatePtySession creates a PTY (pseudo-terminal) session.

A PTY session provides a terminal interface for interactive applications. Use ProcessService.ConnectPty to connect to the session after creation.

Parameters:

  • id: Unique identifier for the session

Optional parameters can be configured using functional options:

  • [options.WithPtySize]: Set terminal dimensions (rows and columns)
  • [options.WithPtyEnv]: Set environment variables

Example:

// Create with default settings
session, err := sandbox.Process.CreatePtySession(ctx, "my-terminal")
// Create with custom size
session, err := sandbox.Process.CreatePtySession(ctx, "my-terminal",
options.WithPtySize(types.PtySize{Rows: 24, Cols: 80}),
)

Returns [types.PtySessionInfo] containing session details, or an error.

func (*ProcessService) CreateSession

func (p *ProcessService) CreateSession(ctx context.Context, sessionID string) error

CreateSession creates a named session for executing multiple commands.

Sessions allow you to execute multiple commands while maintaining state (like environment variables and working directory) between commands.

Example:

// Create a session
err := sandbox.Process.CreateSession(ctx, "my-session")
if err != nil {
return err
}
defer sandbox.Process.DeleteSession(ctx, "my-session")
// Execute commands in the session
result, err := sandbox.Process.ExecuteSessionCommand(ctx, "my-session", "cd /home/user", false)
result, err = sandbox.Process.ExecuteSessionCommand(ctx, "my-session", "pwd", false)

Returns an error if session creation fails.

func (*ProcessService) DeleteSession

func (p *ProcessService) DeleteSession(ctx context.Context, sessionID string) error

DeleteSession removes a session and releases its resources.

The sessionID parameter identifies the session to delete.

Example:

err := sandbox.Process.DeleteSession(ctx, "my-session")

Returns an error if the session doesn’t exist or deletion fails.

func (*ProcessService) ExecuteCommand

func (p *ProcessService) ExecuteCommand(ctx context.Context, command string, opts ...func(*options.ExecuteCommand)) (*types.ExecuteResponse, error)

ExecuteCommand executes a shell command and returns the result.

The command is executed in a shell context. For complex commands, consider using proper shell escaping or wrapping in a script.

Optional parameters can be configured using functional options:

  • [options.WithCwd]: Set the working directory for command execution
  • [options.WithCommandEnv]: Set environment variables
  • [options.WithExecuteTimeout]: Set execution timeout

Example:

// Simple command
result, err := sandbox.Process.ExecuteCommand(ctx, "echo 'Hello'")
if err != nil {
return err
}
fmt.Println(result.Result)
// Command with options
result, err := sandbox.Process.ExecuteCommand(ctx, "npm install",
options.WithCwd("/home/user/project"),
options.WithExecuteTimeout(5*time.Minute),
)
// Check exit code
if result.ExitCode != 0 {
fmt.Printf("Command failed with exit code %d\n", result.ExitCode)
}

Returns [types.ExecuteResponse] containing the output and exit code, or an error.

func (*ProcessService) ExecuteSessionCommand

func (p *ProcessService) ExecuteSessionCommand(ctx context.Context, sessionID, command string, runAsync bool) (map[string]any, error)

ExecuteSessionCommand executes a command within a session.

Parameters:

  • sessionID: The session to execute the command in
  • command: The command to execute
  • runAsync: If true, return immediately without waiting for completion

When runAsync is true, use ProcessService.GetSessionCommand to check status and ProcessService.GetSessionCommandLogs to retrieve output.

Example:

// Synchronous execution
result, err := sandbox.Process.ExecuteSessionCommand(ctx, "my-session", "ls -la", false)
if err != nil {
return err
}
fmt.Println(result["stdout"])
// Asynchronous execution
result, err := sandbox.Process.ExecuteSessionCommand(ctx, "my-session", "long-running-cmd", true)
cmdID := result["id"].(string)
// Later: check status with GetSessionCommand(ctx, "my-session", cmdID)

Returns command result including id, exitCode (if completed), stdout, and stderr.

func (*ProcessService) GetPtySessionInfo

func (p *ProcessService) GetPtySessionInfo(ctx context.Context, sessionID string) (*types.PtySessionInfo, error)

GetPtySessionInfo retrieves information about a PTY session.

Parameters:

  • sessionID: The PTY session identifier

Example:

info, err := sandbox.Process.GetPtySessionInfo(ctx, "my-terminal")
if err != nil {
return err
}
fmt.Printf("Terminal size: %dx%d\n", info.Cols, info.Rows)

Returns [types.PtySessionInfo] with session details, or an error.

func (*ProcessService) GetSession

func (p *ProcessService) GetSession(ctx context.Context, sessionID string) (map[string]any, error)

GetSession retrieves information about a session.

The sessionID parameter identifies the session to query.

Returns a map containing:

  • sessionId: The session identifier
  • commands: List of commands executed in the session

Example:

info, err := sandbox.Process.GetSession(ctx, "my-session")
if err != nil {
return err
}
fmt.Printf("Session: %s\n", info["sessionId"])

Returns an error if the session doesn’t exist.

func (*ProcessService) GetSessionCommand

func (p *ProcessService) GetSessionCommand(ctx context.Context, sessionID, commandID string) (map[string]any, error)

GetSessionCommand retrieves the status of a command in a session.

Parameters:

  • sessionID: The session containing the command
  • commandID: The command identifier (from ExecuteSessionCommand result)

Example:

status, err := sandbox.Process.GetSessionCommand(ctx, "my-session", cmdID)
if err != nil {
return err
}
if exitCode, ok := status["exitCode"]; ok {
fmt.Printf("Command completed with exit code: %v\n", exitCode)
} else {
fmt.Println("Command still running")
}

Returns command status including id, command text, and exitCode (if completed).

func (*ProcessService) GetSessionCommandLogs

func (p *ProcessService) GetSessionCommandLogs(ctx context.Context, sessionID, commandID string) (map[string]any, error)

GetSessionCommandLogs retrieves the output logs of a command.

Parameters:

  • sessionID: The session containing the command
  • commandID: The command identifier

Example:

logs, err := sandbox.Process.GetSessionCommandLogs(ctx, "my-session", cmdID)
if err != nil {
return err
}
fmt.Println(logs["logs"])

Returns a map containing the “logs” key with command output.

func (*ProcessService) GetSessionCommandLogsStream

func (p *ProcessService) GetSessionCommandLogsStream(ctx context.Context, sessionID, commandID string, stdout, stderr chan<- string) error

GetSessionCommandLogsStream streams command logs as they become available.

This method establishes a WebSocket connection to stream logs in real-time. The stdout and stderr channels receive log chunks as strings and are closed when the stream ends or an error occurs.

Parameters:

  • sessionID: The session containing the command
  • commandID: The command identifier
  • stdout: Channel to receive stdout output
  • stderr: Channel to receive stderr output

The caller should provide buffered channels to avoid blocking.

Example:

stdout := make(chan string, 100)
stderr := make(chan string, 100)
go func() {
err := sandbox.Process.GetSessionCommandLogsStream(ctx, "session", "cmd", stdout, stderr)
if err != nil {
log.Printf("Stream error: %v", err)
}
}()
for {
select {
case chunk, ok := <-stdout:
if !ok {
stdout = nil
} else {
fmt.Print(chunk)
}
case chunk, ok := <-stderr:
if !ok {
stderr = nil
} else {
fmt.Fprint(os.Stderr, chunk)
}
}
if stdout == nil && stderr == nil {
break
}
}

Returns an error if the connection fails or stream encounters an error.

func (*ProcessService) KillPtySession

func (p *ProcessService) KillPtySession(ctx context.Context, sessionID string) error

KillPtySession terminates a PTY session.

This ends the terminal session and any processes running in it.

Parameters:

  • sessionID: The PTY session to terminate

Example:

err := sandbox.Process.KillPtySession(ctx, "my-terminal")

Returns an error if the session doesn’t exist or termination fails.

func (*ProcessService) ListPtySessions

func (p *ProcessService) ListPtySessions(ctx context.Context) ([]*types.PtySessionInfo, error)

ListPtySessions returns all active PTY sessions.

Example:

sessions, err := sandbox.Process.ListPtySessions(ctx)
if err != nil {
return err
}
for _, session := range sessions {
fmt.Printf("PTY: %s (%dx%d)\n", session.ID, session.Cols, session.Rows)
}

Returns a slice of [types.PtySessionInfo], or an error.

func (*ProcessService) ListSessions

func (p *ProcessService) ListSessions(ctx context.Context) ([]map[string]any, error)

ListSessions returns all active sessions.

Example:

sessions, err := sandbox.Process.ListSessions(ctx)
if err != nil {
return err
}
for _, session := range sessions {
fmt.Printf("Session: %s\n", session["sessionId"])
}

Returns a slice of session information maps, or an error.

func (*ProcessService) ResizePtySession

func (p *ProcessService) ResizePtySession(ctx context.Context, sessionID string, ptySize types.PtySize) (*types.PtySessionInfo, error)

ResizePtySession changes the terminal dimensions of a PTY session.

This sends a SIGWINCH signal to applications, notifying them of the size change.

Parameters:

  • sessionID: The PTY session to resize
  • ptySize: New terminal dimensions

Example:

newSize := types.PtySize{Rows: 40, Cols: 120}
info, err := sandbox.Process.ResizePtySession(ctx, "my-terminal", newSize)
if err != nil {
return err
}
fmt.Printf("New size: %dx%d\n", info.Cols, info.Rows)

Returns updated [types.PtySessionInfo], or an error.

type PtyHandle

PtyHandle manages a WebSocket connection to a PTY (pseudo-terminal) session.

PtyHandle provides methods for sending input, receiving output via channels, resizing the terminal, and managing the connection lifecycle. It implements io.Reader and io.Writer interfaces for integration with standard Go I/O.

Create a PtyHandle using ProcessService.CreatePty.

Example:

// Create a PTY session
handle, err := sandbox.Process.CreatePty(ctx, "my-pty", nil)
if err != nil {
return err
}
defer handle.Disconnect()
// Wait for connection to be established
if err := handle.WaitForConnection(ctx); err != nil {
return err
}
// Send input
handle.SendInput([]byte("ls -la\n"))
// Read output from channel
for data := range handle.DataChan() {
fmt.Print(string(data))
}
// Or use as io.Reader
io.Copy(os.Stdout, handle)
type PtyHandle struct {
// contains filtered or unexported fields
}

func (*PtyHandle) DataChan

func (h *PtyHandle) DataChan() <-chan []byte

DataChan returns a channel for receiving PTY output.

The channel receives raw bytes from the terminal. It is closed when the PTY session ends or the connection is closed.

Example:

for data := range handle.DataChan() {
fmt.Print(string(data))
}

func (*PtyHandle) Disconnect

func (h *PtyHandle) Disconnect() error

Disconnect closes the WebSocket connection and releases resources.

Call this when done with the PTY session. This does not terminate the underlying process - use PtyHandle.Kill for that.

Example:

defer handle.Disconnect()

Returns an error if the WebSocket close fails.

func (*PtyHandle) Error

func (h *PtyHandle) Error() *string

Error returns the error message if the PTY session failed, or nil otherwise.

func (*PtyHandle) ExitCode

func (h *PtyHandle) ExitCode() *int

ExitCode returns the exit code of the PTY process, or nil if still running.

func (*PtyHandle) IsConnected

func (h *PtyHandle) IsConnected() bool

IsConnected returns true if the WebSocket connection is active.

func (*PtyHandle) Kill

func (h *PtyHandle) Kill(ctx context.Context) error

Kill terminates the PTY session and its associated process.

This operation is irreversible. The process receives a SIGKILL signal and terminates immediately.

Example:

err := handle.Kill(ctx)

Returns an error if the kill operation fails.

func (*PtyHandle) Read

func (h *PtyHandle) Read(p []byte) (n int, err error)

Read implements io.Reader for reading PTY output.

This method blocks until data is available or the PTY closes (returns io.EOF). Use with io.Copy, bufio.Scanner, or any standard Go I/O utilities.

Example:

// Copy all output to stdout
io.Copy(os.Stdout, handle)
// Use with bufio.Scanner
scanner := bufio.NewScanner(handle)
for scanner.Scan() {
fmt.Println(scanner.Text())
}

func (*PtyHandle) Resize

func (h *PtyHandle) Resize(ctx context.Context, cols, rows int) (*types.PtySessionInfo, error)

Resize changes the PTY terminal dimensions.

This notifies terminal applications about the new dimensions via SIGWINCH signal. Call this when the terminal display size changes.

Parameters:

  • cols: Number of columns (width in characters)
  • rows: Number of rows (height in characters)

Example:

info, err := handle.Resize(ctx, 120, 40)

Returns updated [types.PtySessionInfo] or an error.

func (*PtyHandle) SendInput

func (h *PtyHandle) SendInput(data []byte) error

SendInput sends input data to the PTY session.

The data is sent as raw bytes and will be processed as if typed in the terminal. Use this to send commands, keystrokes, or any terminal input.

Example:

// Send a command
handle.SendInput([]byte("ls -la\n"))
// Send Ctrl+C
handle.SendInput([]byte{0x03})

Returns an error if the PTY is not connected or sending fails.

func (*PtyHandle) SessionID

func (h *PtyHandle) SessionID() string

SessionID returns the unique identifier for this PTY session.

func (*PtyHandle) Wait

func (h *PtyHandle) Wait(ctx context.Context) (*types.PtyResult, error)

Wait blocks until the PTY process exits and returns the result.

Example:

result, err := handle.Wait(ctx)
if err != nil {
return err
}
if result.ExitCode != nil {
fmt.Printf("Process exited with code: %d\n", *result.ExitCode)
}

Returns [types.PtyResult] with exit code and any error, or an error if the context is cancelled.

func (*PtyHandle) WaitForConnection

func (h *PtyHandle) WaitForConnection(ctx context.Context) error

WaitForConnection waits for the WebSocket connection to be established.

This method blocks until the PTY session is ready to receive input and send output, or until a timeout (10 seconds) expires. Always call this after creating a PTY to ensure the connection is ready.

Example:

handle, _ := sandbox.Process.CreatePty(ctx, "my-pty", nil)
if err := handle.WaitForConnection(ctx); err != nil {
return fmt.Errorf("PTY connection failed: %w", err)
}

Returns an error if the connection times out or fails.

func (*PtyHandle) Write

func (h *PtyHandle) Write(p []byte) (n int, err error)

Write implements io.Writer for sending input to the PTY.

Example:

// Write directly
handle.Write([]byte("echo hello\n"))
// Use with io.Copy
io.Copy(handle, strings.NewReader("echo hello\n"))

type PushAccessCredentials

PushAccessCredentials holds temporary credentials for uploading to object storage.

These credentials are obtained from the API and used for uploading build contexts when creating snapshots with custom DockerImage definitions.

type PushAccessCredentials struct {
StorageURL string `json:"storageUrl"`
AccessKey string `json:"accessKey"`
Secret string `json:"secret"`
SessionToken string `json:"sessionToken"`
Bucket string `json:"bucket"`
OrganizationID string `json:"organizationId"`
}

type Sandbox

Sandbox represents a Daytona sandbox environment.

A Sandbox provides an isolated development environment with file system, git, process execution, code interpretation, and desktop automation capabilities. Sandboxes can be started, stopped, archived, and deleted.

Access sandbox capabilities through the service fields:

  • FileSystem: File and directory operations
  • Git: Git repository operations
  • Process: Command execution and PTY sessions
  • CodeInterpreter: Python code execution
  • ComputerUse: Desktop automation (mouse, keyboard, screenshots)

Example:

// Create and use a sandbox
sandbox, err := client.Create(ctx)
if err != nil {
return err
}
defer sandbox.Delete(ctx)
// Execute a command
result, err := sandbox.Process.ExecuteCommand(ctx, "echo 'Hello'")
// Work with files
err = sandbox.FileSystem.UploadFile(ctx, "local.txt", "/home/user/remote.txt")
type Sandbox struct {
ID string // Unique sandbox identifier
Name string // Human-readable sandbox name
State apiclient.SandboxState // Current sandbox state
Target string // Target region/environment where the sandbox runs
ToolboxClient *toolbox.APIClient // Internal API client
// AutoArchiveInterval is the time in minutes after stopping before auto-archiving.
// Set to 0 to disable auto-archiving.
AutoArchiveInterval int
// AutoDeleteInterval is the time in minutes after stopping before auto-deletion.
// Set to -1 to disable auto-deletion.
// Set to 0 to delete immediately upon stopping.
AutoDeleteInterval int
// NetworkBlockAll blocks all network access when true.
NetworkBlockAll bool
// NetworkAllowList is a comma-separated list of allowed CIDR addresses.
NetworkAllowList *string
FileSystem *FileSystemService // File system operations
Git *GitService // Git operations
Process *ProcessService // Process and PTY operations
CodeInterpreter *CodeInterpreterService // Python code execution
ComputerUse *ComputerUseService // Desktop automation
// contains filtered or unexported fields
}

func NewSandbox

func NewSandbox(client *Client, toolboxClient *toolbox.APIClient, id string, name string, state apiclient.SandboxState, target string, autoArchiveInterval int, autoDeleteInterval int, networkBlockAll bool, networkAllowList *string) *Sandbox

NewSandbox creates a new Sandbox instance.

This is typically called internally by the SDK. Users should create sandboxes using Client.Create rather than calling this directly.

func (*Sandbox) Archive

func (s *Sandbox) Archive(ctx context.Context) error

Archive archives the sandbox, preserving its state in cost-effective storage.

When sandboxes are archived, the entire filesystem state is moved to object storage, making it possible to keep sandboxes available for extended periods at reduced cost. Use Sandbox.Start to unarchive and resume.

Example:

err := sandbox.Archive(ctx)
if err != nil {
return err
}
// Sandbox is now archived and can be restored later

func (*Sandbox) Delete

func (s *Sandbox) Delete(ctx context.Context) error

Delete deletes the sandbox with a default timeout of 60 seconds.

This operation is irreversible. All data in the sandbox will be lost. For custom timeout, use Sandbox.DeleteWithTimeout.

Example:

err := sandbox.Delete(ctx)

func (*Sandbox) DeleteWithTimeout

func (s *Sandbox) DeleteWithTimeout(ctx context.Context, timeout time.Duration) error

DeleteWithTimeout deletes the sandbox with a custom timeout.

Example:

err := sandbox.DeleteWithTimeout(ctx, 2*time.Minute)
func (s *Sandbox) GetPreviewLink(ctx context.Context, port int) (string, error)

GetPreviewLink returns a URL for accessing a port on the sandbox.

The preview URL allows external access to services running on the specified port within the sandbox.

Example:

// Start a web server on port 3000 in the sandbox
sandbox.Process.ExecuteCommand(ctx, "python -m http.server 3000 &")
// Get the preview URL
url, err := sandbox.GetPreviewLink(ctx, 3000)
if err != nil {
return err
}
fmt.Printf("Access at: %s\n", url)

func (*Sandbox) GetUserHomeDir

func (s *Sandbox) GetUserHomeDir(ctx context.Context) (string, error)

GetUserHomeDir returns the user’s home directory path in the sandbox.

Example:

homeDir, err := sandbox.GetUserHomeDir(ctx)
if err != nil {
return err
}
fmt.Printf("Home directory: %s\n", homeDir) // e.g., "/home/daytona"

func (*Sandbox) GetWorkingDir

func (s *Sandbox) GetWorkingDir(ctx context.Context) (string, error)

GetWorkingDir returns the current working directory in the sandbox.

Example:

workDir, err := sandbox.GetWorkingDir(ctx)
if err != nil {
return err
}
fmt.Printf("Working directory: %s\n", workDir)

func (*Sandbox) RefreshData

func (s *Sandbox) RefreshData(ctx context.Context) error

RefreshData refreshes the sandbox data from the API.

This updates the sandbox’s State and other properties from the server. Useful for checking if the sandbox state has changed.

Example:

err := sandbox.RefreshData(ctx)
if err != nil {
return err
}
fmt.Printf("Current state: %s\n", sandbox.State)

func (*Sandbox) SetAutoArchiveInterval

func (s *Sandbox) SetAutoArchiveInterval(ctx context.Context, intervalMinutes *int) error

SetAutoArchiveInterval sets the auto-archive interval in minutes.

The sandbox will be automatically archived after being stopped for this many minutes. Set to 0 to disable auto-archiving (sandbox will never auto-archive).

Example:

// Archive after 30 minutes of being stopped
interval := 30
err := sandbox.SetAutoArchiveInterval(ctx, &interval)
// Disable auto-archiving
interval := 0
err := sandbox.SetAutoArchiveInterval(ctx, &interval)

func (*Sandbox) SetAutoDeleteInterval

func (s *Sandbox) SetAutoDeleteInterval(ctx context.Context, intervalMinutes *int) error

SetAutoDeleteInterval sets the auto-delete interval in minutes.

The sandbox will be automatically deleted after being stopped for this many minutes.

Special values:

  • -1: Disable auto-deletion (sandbox will never auto-delete)
  • 0: Delete immediately upon stopping

Example:

// Delete after 60 minutes of being stopped
interval := 60
err := sandbox.SetAutoDeleteInterval(ctx, &interval)
// Delete immediately when stopped
interval := 0
err := sandbox.SetAutoDeleteInterval(ctx, &interval)
// Never auto-delete
interval := -1
err := sandbox.SetAutoDeleteInterval(ctx, &interval)

func (*Sandbox) SetLabels

func (s *Sandbox) SetLabels(ctx context.Context, labels map[string]string) error

SetLabels sets custom labels on the sandbox.

Labels are key-value pairs that can be used for organization and filtering. This replaces all existing labels.

Example:

err := sandbox.SetLabels(ctx, map[string]string{
"environment": "development",
"team": "backend",
"project": "api-server",
})

func (*Sandbox) Start

func (s *Sandbox) Start(ctx context.Context) error

Start starts the sandbox with a default timeout of 60 seconds.

If the sandbox is already running, this is a no-op. For custom timeout, use Sandbox.StartWithTimeout.

Example:

err := sandbox.Start(ctx)
if err != nil {
return err
}
// Sandbox is now running

func (*Sandbox) StartWithTimeout

func (s *Sandbox) StartWithTimeout(ctx context.Context, timeout time.Duration) error

StartWithTimeout starts the sandbox with a custom timeout.

The method blocks until the sandbox reaches the “started” state or the timeout is exceeded.

Example:

err := sandbox.StartWithTimeout(ctx, 2*time.Minute)
if err != nil {
return err
}

func (*Sandbox) Stop

func (s *Sandbox) Stop(ctx context.Context) error

Stop stops the sandbox with a default timeout of 60 seconds.

Stopping a sandbox preserves its state. Use Sandbox.Start to resume. For custom timeout, use Sandbox.StopWithTimeout.

Example:

err := sandbox.Stop(ctx)

func (*Sandbox) StopWithTimeout

func (s *Sandbox) StopWithTimeout(ctx context.Context, timeout time.Duration) error

StopWithTimeout stops the sandbox with a custom timeout.

The method blocks until the sandbox reaches the “stopped” state or the timeout is exceeded.

Example:

err := sandbox.StopWithTimeout(ctx, 2*time.Minute)

func (*Sandbox) WaitForStart

func (s *Sandbox) WaitForStart(ctx context.Context, timeout time.Duration) error

WaitForStart waits for the sandbox to reach the “started” state.

This method polls the sandbox state until it’s started, encounters an error state, or the timeout is exceeded.

Example:

err := sandbox.WaitForStart(ctx, 2*time.Minute)
if err != nil {
return err
}
// Sandbox is now running

func (*Sandbox) WaitForStop

func (s *Sandbox) WaitForStop(ctx context.Context, timeout time.Duration) error

WaitForStop waits for the sandbox to reach the “stopped” state.

This method polls the sandbox state until it’s stopped or the timeout is exceeded.

Example:

err := sandbox.WaitForStop(ctx, 2*time.Minute)

type ScreenshotService

ScreenshotService provides screen capture operations.

ScreenshotService enables capturing full screen or region screenshots. Access through ComputerUseService.Screenshot.

type ScreenshotService struct {
// contains filtered or unexported fields
}

func NewScreenshotService

func NewScreenshotService(toolboxClient *toolbox.APIClient) *ScreenshotService

NewScreenshotService creates a new ScreenshotService.

func (*ScreenshotService) TakeFullScreen

func (s *ScreenshotService) TakeFullScreen(ctx context.Context, showCursor *bool) (*types.ScreenshotResponse, error)

TakeFullScreen captures a screenshot of the entire screen.

Parameters:

  • showCursor: Whether to include the cursor in the screenshot, nil for default

Example:

// Capture full screen
screenshot, err := ss.TakeFullScreen(ctx, nil)
if err != nil {
return err
}
// screenshot.Image contains the base64-encoded image data
// Capture with cursor visible
showCursor := true
screenshot, err := ss.TakeFullScreen(ctx, &showCursor)

Returns [types.ScreenshotResponse] with the captured image.

func (*ScreenshotService) TakeRegion

func (s *ScreenshotService) TakeRegion(ctx context.Context, region types.ScreenshotRegion, showCursor *bool) (*types.ScreenshotResponse, error)

TakeRegion captures a screenshot of a specific screen region.

Parameters:

  • region: The region to capture (X, Y, Width, Height)
  • showCursor: Whether to include the cursor in the screenshot, nil for default

Example:

// Capture a 200x100 region starting at (50, 50)
region := types.ScreenshotRegion{X: 50, Y: 50, Width: 200, Height: 100}
screenshot, err := ss.TakeRegion(ctx, region, nil)
if err != nil {
return err
}

Returns [types.ScreenshotResponse] with the captured image.

type SnapshotService

SnapshotService provides snapshot (image template) management operations.

SnapshotService enables creating, managing, and deleting snapshots that serve as templates for sandboxes. Snapshots can be built from Docker images or custom DockerImage definitions with build contexts. Access through [Client.Snapshots].

Example:

// Create a snapshot from an existing image
snapshot, logChan, err := client.Snapshots.Create(ctx, &types.CreateSnapshotParams{
Name: "my-python-env",
Image: "python:3.11-slim",
})
if err != nil {
return err
}
// Stream build logs
for log := range logChan {
fmt.Println(log)
}
// Create a snapshot from a custom Image definition
image := daytona.Base("python:3.11-slim").
PipInstall([]string{"numpy", "pandas"}).
Workdir("/app")
snapshot, logChan, err := client.Snapshots.Create(ctx, &types.CreateSnapshotParams{
Name: "custom-python-env",
Image: image,
})
type SnapshotService struct {
// contains filtered or unexported fields
}

func NewSnapshotService

func NewSnapshotService(client *Client) *SnapshotService

NewSnapshotService creates a new SnapshotService.

This is typically called internally by the SDK when creating a Client. Users should access SnapshotService through [Client.Snapshots] rather than creating it directly.

func (*SnapshotService) Create

func (s *SnapshotService) Create(ctx context.Context, params *types.CreateSnapshotParams) (*types.Snapshot, <-chan string, error)

Create builds a new snapshot from an image and streams build logs.

The image parameter can be either a Docker image reference string (e.g., “python:3.11”) or an DockerImage builder object for custom Dockerfile definitions.

Parameters:

  • params: Snapshot creation parameters including name, image, resources, and entrypoint

Example:

// Create from Docker Hub image
snapshot, logChan, err := client.Snapshots.Create(ctx, &types.CreateSnapshotParams{
Name: "my-env",
Image: "python:3.11-slim",
})
if err != nil {
return err
}
// Stream build logs
for log := range logChan {
fmt.Println(log)
}
// Create with custom image and resources
image := daytona.Base("python:3.11").PipInstall([]string{"numpy"})
snapshot, logChan, err := client.Snapshots.Create(ctx, &types.CreateSnapshotParams{
Name: "custom-env",
Image: image,
Resources: &types.Resources{CPU: 2, Memory: 4096},
})

Returns the created [types.Snapshot], a channel for streaming build logs, or an error. The log channel is closed when the build completes or fails.

func (*SnapshotService) Delete

func (s *SnapshotService) Delete(ctx context.Context, snapshot *types.Snapshot) error

Delete permanently removes a snapshot.

Sandboxes created from this snapshot will continue to work, but no new sandboxes can be created from it after deletion.

Parameters:

  • snapshot: The snapshot to delete

Example:

err := client.Snapshots.Delete(ctx, snapshot)
if err != nil {
return err
}

Returns an error if deletion fails.

func (*SnapshotService) Get

func (s *SnapshotService) Get(ctx context.Context, nameOrID string) (*types.Snapshot, error)

Get retrieves a snapshot by name or ID.

Parameters:

  • nameOrID: The snapshot name or unique ID

Example:

snapshot, err := client.Snapshots.Get(ctx, "my-python-env")
if err != nil {
return err
}
fmt.Printf("Snapshot %s: %s\n", snapshot.Name, snapshot.State)

Returns the [types.Snapshot] or an error if not found.

func (*SnapshotService) List

func (s *SnapshotService) List(ctx context.Context, page *int, limit *int) (*types.PaginatedSnapshots, error)

List returns snapshots with optional pagination.

Parameters:

  • page: Page number (1-indexed), nil for first page
  • limit: Maximum snapshots per page, nil for default

Example:

// List first page with default limit
result, err := client.Snapshots.List(ctx, nil, nil)
if err != nil {
return err
}
// List with pagination
page, limit := 2, 10
result, err := client.Snapshots.List(ctx, &page, &limit)
fmt.Printf("Page %d of %d, total: %d\n", result.Page, result.TotalPages, result.Total)

Returns [types.PaginatedSnapshots] containing the snapshots and pagination info.

type VolumeService

VolumeService provides persistent storage volume management operations.

VolumeService enables creating, managing, and deleting persistent storage volumes that can be attached to sandboxes. Volumes persist data independently of sandbox lifecycle and can be shared between sandboxes. Access through [Client.Volumes].

Example:

// Create a new volume
volume, err := client.Volumes.Create(ctx, "my-data-volume")
if err != nil {
return err
}
// Wait for volume to be ready
volume, err = client.Volumes.WaitForReady(ctx, volume, 60*time.Second)
if err != nil {
return err
}
// List all volumes
volumes, err := client.Volumes.List(ctx)
type VolumeService struct {
// contains filtered or unexported fields
}

func NewVolumeService

func NewVolumeService(client *Client) *VolumeService

NewVolumeService creates a new VolumeService.

This is typically called internally by the SDK when creating a Client. Users should access VolumeService through [Client.Volumes] rather than creating it directly.

func (*VolumeService) Create

func (v *VolumeService) Create(ctx context.Context, name string) (*types.Volume, error)

Create creates a new persistent storage volume.

The volume starts in “pending” state and transitions to “ready” when available. Use VolumeService.WaitForReady to wait for the volume to become ready.

Parameters:

  • name: Unique name for the volume

Example:

volume, err := client.Volumes.Create(ctx, "my-data-volume")
if err != nil {
return err
}
// Wait for volume to be ready
volume, err = client.Volumes.WaitForReady(ctx, volume, 60*time.Second)

Returns the created [types.Volume] or an error.

func (*VolumeService) Delete

func (v *VolumeService) Delete(ctx context.Context, volume *types.Volume) error

Delete permanently removes a volume and all its data.

This operation is irreversible. Ensure no sandboxes are using the volume before deletion.

Parameters:

  • volume: The volume to delete

Example:

err := client.Volumes.Delete(ctx, volume)
if err != nil {
return err
}

Returns an error if deletion fails.

func (*VolumeService) Get

func (v *VolumeService) Get(ctx context.Context, name string) (*types.Volume, error)

Get retrieves a volume by its name.

Parameters:

  • name: The volume name

Example:

volume, err := client.Volumes.Get(ctx, "my-data-volume")
if err != nil {
return err
}
fmt.Printf("Volume state: %s\n", volume.State)

Returns the [types.Volume] or an error if not found.

func (*VolumeService) List

func (v *VolumeService) List(ctx context.Context) ([]*types.Volume, error)

List returns all volumes in the organization.

Example:

volumes, err := client.Volumes.List(ctx)
if err != nil {
return err
}
for _, vol := range volumes {
fmt.Printf("Volume %s: %s\n", vol.Name, vol.State)
}

Returns a slice of [types.Volume] or an error if the request fails.

func (*VolumeService) WaitForReady

func (v *VolumeService) WaitForReady(ctx context.Context, volume *types.Volume, timeout time.Duration) (*types.Volume, error)

WaitForReady waits for a volume to reach the “ready” state.

This method polls the volume status until it becomes ready, reaches an error state, or the timeout expires. The polling interval is 1 second.

Parameters:

  • volume: The volume to wait for
  • timeout: Maximum time to wait for the volume to become ready

Example:

volume, err := client.Volumes.Create(ctx, "my-volume")
if err != nil {
return err
}
// Wait up to 2 minutes for the volume to be ready
volume, err = client.Volumes.WaitForReady(ctx, volume, 2*time.Minute)
if err != nil {
return fmt.Errorf("volume failed to become ready: %w", err)
}

Returns the updated [types.Volume] when ready, or an error if the timeout expires or the volume enters an error state.