このコンテンツはまだ日本語訳がありません。
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
- type Client
- func NewClient() (*Client, error)
- func NewClientWithConfig(config *types.DaytonaConfig) (*Client, error)
- func (c *Client) Create(ctx context.Context, params any, opts …func(*options.CreateSandbox)) (*Sandbox, error)
- func (c *Client) FindOne(ctx context.Context, sandboxIDOrName *string, labels map[string]string) (*Sandbox, error)
- func (c *Client) Get(ctx context.Context, sandboxIDOrName string) (*Sandbox, error)
- func (c *Client) List(ctx context.Context, labels map[string]string, page *int, limit *int) (*PaginatedSandboxes, error)
- type CodeInterpreterService
- func NewCodeInterpreterService(toolboxClient *toolbox.APIClient) *CodeInterpreterService
- func (c *CodeInterpreterService) CreateContext(ctx context.Context, cwd *string) (map[string]any, error)
- func (c *CodeInterpreterService) DeleteContext(ctx context.Context, contextID string) error
- func (c *CodeInterpreterService) ListContexts(ctx context.Context) ([]map[string]any, error)
- func (c *CodeInterpreterService) RunCode(ctx context.Context, code string, opts …func(*options.RunCode)) (*OutputChannels, error)
- type ComputerUseService
- func NewComputerUseService(toolboxClient *toolbox.APIClient) *ComputerUseService
- func (c *ComputerUseService) Display() *DisplayService
- func (c *ComputerUseService) GetStatus(ctx context.Context) (map[string]any, error)
- func (c *ComputerUseService) Keyboard() *KeyboardService
- func (c *ComputerUseService) Mouse() *MouseService
- func (c *ComputerUseService) Screenshot() *ScreenshotService
- func (c *ComputerUseService) Start(ctx context.Context) error
- func (c *ComputerUseService) Stop(ctx context.Context) error
- type DisplayService
- type DockerImage
- func Base(baseImage string) *DockerImage
- func DebianSlim(pythonVersion *string) *DockerImage
- func FromDockerfile(dockerfile string) *DockerImage
- func (img *DockerImage) Add(source, destination string) *DockerImage
- func (img *DockerImage) AddLocalDir(localPath, remotePath string) *DockerImage
- func (img *DockerImage) AddLocalFile(localPath, remotePath string) *DockerImage
- func (img *DockerImage) AptGet(packages []string) *DockerImage
- func (img *DockerImage) Cmd(cmd []string) *DockerImage
- func (img *DockerImage) Contexts() []DockerImageContext
- func (img *DockerImage) Copy(source, destination string) *DockerImage
- func (img *DockerImage) Dockerfile() string
- func (img *DockerImage) Entrypoint(cmd []string) *DockerImage
- func (img *DockerImage) Env(key, value string) *DockerImage
- func (img *DockerImage) Expose(ports []int) *DockerImage
- func (img *DockerImage) Label(key, value string) *DockerImage
- func (img *DockerImage) PipInstall(packages []string, opts …func(*options.PipInstall)) *DockerImage
- func (img *DockerImage) Run(command string) *DockerImage
- func (img *DockerImage) User(username string) *DockerImage
- func (img *DockerImage) Volume(paths []string) *DockerImage
- func (img *DockerImage) Workdir(path string) *DockerImage
- type DockerImageContext
- type FileSystemService
- func NewFileSystemService(toolboxClient *toolbox.APIClient) *FileSystemService
- func (f *FileSystemService) CreateFolder(ctx context.Context, path string, opts …func(*options.CreateFolder)) error
- func (f *FileSystemService) DeleteFile(ctx context.Context, path string, recursive bool) error
- func (f *FileSystemService) DownloadFile(ctx context.Context, remotePath string, localPath *string) ([]byte, error)
- func (f *FileSystemService) FindFiles(ctx context.Context, path, pattern string) (any, error)
- func (f *FileSystemService) GetFileInfo(ctx context.Context, path string) (*types.FileInfo, error)
- func (f *FileSystemService) ListFiles(ctx context.Context, path string) ([]*types.FileInfo, error)
- func (f *FileSystemService) MoveFiles(ctx context.Context, source, destination string) error
- func (f *FileSystemService) ReplaceInFiles(ctx context.Context, files []string, pattern, newValue string) (any, error)
- func (f *FileSystemService) SearchFiles(ctx context.Context, path, pattern string) (any, error)
- func (f *FileSystemService) SetFilePermissions(ctx context.Context, path string, opts …func(*options.SetFilePermissions)) error
- func (f *FileSystemService) UploadFile(ctx context.Context, source any, destination string) error
- type GitService
- func NewGitService(toolboxClient *toolbox.APIClient) *GitService
- func (g *GitService) Add(ctx context.Context, path string, files []string) error
- func (g *GitService) Branches(ctx context.Context, path string) ([]string, error)
- func (g *GitService) Checkout(ctx context.Context, path, name string) error
- func (g *GitService) Clone(ctx context.Context, url, path string, opts …func(*options.GitClone)) error
- func (g *GitService) Commit(ctx context.Context, path, message, author, email string, opts …func(*options.GitCommit)) (*types.GitCommitResponse, error)
- func (g *GitService) CreateBranch(ctx context.Context, path, name string) error
- func (g *GitService) DeleteBranch(ctx context.Context, path, name string, opts …func(*options.GitDeleteBranch)) error
- func (g *GitService) Pull(ctx context.Context, path string, opts …func(*options.GitPull)) error
- func (g *GitService) Push(ctx context.Context, path string, opts …func(*options.GitPush)) error
- func (g *GitService) Status(ctx context.Context, path string) (*types.GitStatus, error)
- type KeyboardService
- func NewKeyboardService(toolboxClient *toolbox.APIClient) *KeyboardService
- func (k *KeyboardService) Hotkey(ctx context.Context, keys string) error
- func (k *KeyboardService) Press(ctx context.Context, key string, modifiers []string) error
- func (k *KeyboardService) Type(ctx context.Context, text string, delay *int) error
- type LspServerService
- func NewLspServerService(toolboxClient *toolbox.APIClient, languageID types.LspLanguageID, projectPath string) *LspServerService
- func (l *LspServerService) Completions(ctx context.Context, path string, position types.Position) (any, error)
- func (l *LspServerService) DidClose(ctx context.Context, path string) error
- func (l *LspServerService) DidOpen(ctx context.Context, path string) error
- func (l *LspServerService) DocumentSymbols(ctx context.Context, path string) ([]any, error)
- func (l *LspServerService) SandboxSymbols(ctx context.Context, query string) ([]any, error)
- func (l *LspServerService) Start(ctx context.Context) error
- func (l *LspServerService) Stop(ctx context.Context) error
- type MouseService
- func NewMouseService(toolboxClient *toolbox.APIClient) *MouseService
- func (m *MouseService) Click(ctx context.Context, x, y int, button *string, double *bool) (map[string]any, error)
- func (m *MouseService) Drag(ctx context.Context, startX, startY, endX, endY int, button *string) (map[string]any, error)
- func (m *MouseService) GetPosition(ctx context.Context) (map[string]any, error)
- func (m *MouseService) Move(ctx context.Context, x, y int) (map[string]any, error)
- func (m *MouseService) Scroll(ctx context.Context, x, y int, direction string, amount *int) (bool, error)
- type OutputChannels
- type PaginatedSandboxes
- type ProcessService
- func NewProcessService(toolboxClient *toolbox.APIClient) *ProcessService
- func (p *ProcessService) CodeRun(ctx context.Context, code string, opts …func(*options.CodeRun)) (*types.ExecuteResponse, error)
- func (p *ProcessService) ConnectPty(ctx context.Context, sessionID string) (*PtyHandle, error)
- func (p *ProcessService) CreatePty(ctx context.Context, id string, opts …func(*options.CreatePty)) (*PtyHandle, error)
- func (p *ProcessService) CreatePtySession(ctx context.Context, id string, opts …func(*options.PtySession)) (*types.PtySessionInfo, error)
- func (p *ProcessService) CreateSession(ctx context.Context, sessionID string) error
- func (p *ProcessService) DeleteSession(ctx context.Context, sessionID string) error
- func (p *ProcessService) ExecuteCommand(ctx context.Context, command string, opts …func(*options.ExecuteCommand)) (*types.ExecuteResponse, error)
- func (p *ProcessService) ExecuteSessionCommand(ctx context.Context, sessionID, command string, runAsync bool) (map[string]any, error)
- func (p *ProcessService) GetPtySessionInfo(ctx context.Context, sessionID string) (*types.PtySessionInfo, error)
- func (p *ProcessService) GetSession(ctx context.Context, sessionID string) (map[string]any, error)
- func (p *ProcessService) GetSessionCommand(ctx context.Context, sessionID, commandID string) (map[string]any, error)
- func (p *ProcessService) GetSessionCommandLogs(ctx context.Context, sessionID, commandID string) (map[string]any, error)
- func (p *ProcessService) GetSessionCommandLogsStream(ctx context.Context, sessionID, commandID string, stdout, stderr chan<- string) error
- func (p *ProcessService) KillPtySession(ctx context.Context, sessionID string) error
- func (p *ProcessService) ListPtySessions(ctx context.Context) ([]*types.PtySessionInfo, error)
- func (p *ProcessService) ListSessions(ctx context.Context) ([]map[string]any, error)
- func (p *ProcessService) ResizePtySession(ctx context.Context, sessionID string, ptySize types.PtySize) (*types.PtySessionInfo, error)
- type PtyHandle
- func (h *PtyHandle) DataChan() <-chan []byte
- func (h *PtyHandle) Disconnect() error
- func (h *PtyHandle) Error() *string
- func (h *PtyHandle) ExitCode() *int
- func (h *PtyHandle) IsConnected() bool
- func (h *PtyHandle) Kill(ctx context.Context) error
- func (h *PtyHandle) Read(p []byte) (n int, err error)
- func (h *PtyHandle) Resize(ctx context.Context, cols, rows int) (*types.PtySessionInfo, error)
- func (h *PtyHandle) SendInput(data []byte) error
- func (h *PtyHandle) SessionID() string
- func (h *PtyHandle) Wait(ctx context.Context) (*types.PtyResult, error)
- func (h *PtyHandle) WaitForConnection(ctx context.Context) error
- func (h *PtyHandle) Write(p []byte) (n int, err error)
- type PushAccessCredentials
- type Sandbox
- 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
- func (s *Sandbox) Archive(ctx context.Context) error
- func (s *Sandbox) Delete(ctx context.Context) error
- func (s *Sandbox) DeleteWithTimeout(ctx context.Context, timeout time.Duration) error
- func (s *Sandbox) GetPreviewLink(ctx context.Context, port int) (string, error)
- func (s *Sandbox) GetUserHomeDir(ctx context.Context) (string, error)
- func (s *Sandbox) GetWorkingDir(ctx context.Context) (string, error)
- func (s *Sandbox) RefreshData(ctx context.Context) error
- func (s *Sandbox) SetAutoArchiveInterval(ctx context.Context, intervalMinutes *int) error
- func (s *Sandbox) SetAutoDeleteInterval(ctx context.Context, intervalMinutes *int) error
- func (s *Sandbox) SetLabels(ctx context.Context, labels map[string]string) error
- func (s *Sandbox) Start(ctx context.Context) error
- func (s *Sandbox) StartWithTimeout(ctx context.Context, timeout time.Duration) error
- func (s *Sandbox) Stop(ctx context.Context) error
- func (s *Sandbox) StopWithTimeout(ctx context.Context, timeout time.Duration) error
- func (s *Sandbox) WaitForStart(ctx context.Context, timeout time.Duration) error
- func (s *Sandbox) WaitForStop(ctx context.Context, timeout time.Duration) error
- type ScreenshotService
- func NewScreenshotService(toolboxClient *toolbox.APIClient) *ScreenshotService
- func (s *ScreenshotService) TakeFullScreen(ctx context.Context, showCursor *bool) (*types.ScreenshotResponse, error)
- func (s *ScreenshotService) TakeRegion(ctx context.Context, region types.ScreenshotRegion, showCursor *bool) (*types.ScreenshotResponse, error)
- type SnapshotService
- func NewSnapshotService(client *Client) *SnapshotService
- func (s *SnapshotService) Create(ctx context.Context, params *types.CreateSnapshotParams) (*types.Snapshot, <-chan string, error)
- func (s *SnapshotService) Delete(ctx context.Context, snapshot *types.Snapshot) error
- func (s *SnapshotService) Get(ctx context.Context, nameOrID string) (*types.Snapshot, error)
- func (s *SnapshotService) List(ctx context.Context, page *int, limit *int) (*types.PaginatedSnapshots, error)
- type VolumeService
- func NewVolumeService(client *Client) *VolumeService
- func (v *VolumeService) Create(ctx context.Context, name string) (*types.Volume, error)
- func (v *VolumeService) Delete(ctx context.Context, volume *types.Volume) error
- func (v *VolumeService) Get(ctx context.Context, name string) (*types.Volume, error)
- func (v *VolumeService) List(ctx context.Context) ([]*types.Volume, error)
- func (v *VolumeService) WaitForReady(ctx context.Context, volume *types.Volume, timeout time.Duration) (*types.Volume, error)
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 snapshotsandbox, err := client.Create(ctx, types.SnapshotParams{ Snapshot: "my-snapshot", SandboxBaseParams: types.SandboxBaseParams{ Name: "my-sandbox", },})
// Create from a Docker imagesandbox, 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 namename := "my-sandbox"sandbox, err := client.FindOne(ctx, &name, nil)
// Find by labelssandbox, 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, ¬Found) { 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 sandboxesresult, err := client.List(ctx, nil, nil, nil)
// List sandboxes with paginationpage, limit := 1, 10result, err := client.List(ctx, nil, &page, &limit)
// Filter by labelsresult, err := client.List(ctx, map[string]string{"env": "dev"}, nil, nil)
// Iterate through resultsfor _, 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 executionchannels, err := sandbox.CodeInterpreter.RunCode(ctx, "print('Hello, World!')")if err != nil { return err}
// Wait for completion and get resultresult := <-channels.Donefmt.Println(result.Stdout)
// With persistent contextctxInfo, _ := sandbox.CodeInterpreter.CreateContext(ctx, nil)contextID := ctxInfo["id"].(string)channels, _ = sandbox.CodeInterpreter.RunCode(ctx, "x = 42", options.WithCustomContext(contextID),)<-channels.Donechannels, _ = sandbox.CodeInterpreter.RunCode(ctx, "print(x)", options.WithCustomContext(contextID),)type CodeInterpreterService struct { // contains filtered or unexported fields}func NewCodeInterpreterService
func NewCodeInterpreterService(toolboxClient *toolbox.APIClient) *CodeInterpreterServiceNewCodeInterpreterService 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 contextctxInfo, err := sandbox.CodeInterpreter.CreateContext(ctx, nil)if err != nil { return err}contextID := ctxInfo["id"].(string)
// Use the context to maintain statesandbox.CodeInterpreter.RunCode(ctx, "x = 42", options.WithCustomContext(contextID))sandbox.CodeInterpreter.RunCode(ctx, "print(x)", options.WithCustomContext(contextID)) // prints 42
// Clean up when donesandbox.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) errorDeleteContext 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 executionchannels, err := sandbox.CodeInterpreter.RunCode(ctx, ` for i in range(5): print(f"Count: {i}")`)if err != nil { return err}
// Stream outputfor msg := range channels.Stdout { fmt.Print(msg.Text)}
// Get final resultresult := <-channels.Doneif result.Error != nil { fmt.Printf("Error: %s\n", result.Error.Value)}
// With optionschannels, 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 environmentif err := cu.Start(ctx); err != nil { return err}defer cu.Stop(ctx)
// Take a screenshotscreenshot, err := cu.Screenshot().TakeFullScreen(ctx, nil)if err != nil { return err}
// Click at coordinatescu.Mouse().Click(ctx, 100, 200, nil, nil)
// Type textcu.Keyboard().Type(ctx, "Hello, World!", nil)type ComputerUseService struct { // contains filtered or unexported fields}func NewComputerUseService
func NewComputerUseService(toolboxClient *toolbox.APIClient) *ComputerUseServiceNewComputerUseService 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() *DisplayServiceDisplay 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() *KeyboardServiceKeyboard returns the KeyboardService for keyboard operations.
The service is lazily initialized on first access.
func (*ComputerUseService) Mouse
func (c *ComputerUseService) Mouse() *MouseServiceMouse returns the MouseService for mouse operations.
The service is lazily initialized on first access.
func (*ComputerUseService) Screenshot
func (c *ComputerUseService) Screenshot() *ScreenshotServiceScreenshot 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) errorStart 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) errorStop 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) *DisplayServiceNewDisplayService 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 dependenciesimage := daytona.Base("python:3.11-slim"). AptGet([]string{"git", "curl"}). PipInstall([]string{"numpy", "pandas"}). Workdir("/app"). Env("PYTHONUNBUFFERED", "1")
// Use with snapshot creationsnapshot, 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) *DockerImageBase 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) *DockerImageDebianSlim 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.12image := daytona.DebianSlim(nil)
// Use specific versionversion := "3.10"image := daytona.DebianSlim(&version)func FromDockerfile
func FromDockerfile(dockerfile string) *DockerImageFromDockerfile 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.11RUN pip install numpyWORKDIR /app`image := daytona.FromDockerfile(dockerfile)func (*DockerImage) Add
func (img *DockerImage) Add(source, destination string) *DockerImageAdd 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) *DockerImageAddLocalDir 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) *DockerImageAddLocalFile 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) *DockerImageAptGet 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) *DockerImageCmd 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() []DockerImageContextContexts 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) *DockerImageCopy 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() stringDockerfile returns the generated Dockerfile content.
This is called internally when creating snapshots.
Example:
image := daytona.Base("python:3.11").PipInstall([]string{"numpy"})fmt.Println(image.Dockerfile())// Output:// RUN pip install numpyfunc (*DockerImage) Entrypoint
func (img *DockerImage) Entrypoint(cmd []string) *DockerImageEntrypoint 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) *DockerImageEnv 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) *DockerImageExpose 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) *DockerImageLabel 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)) *DockerImagePipInstall 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 installationimage := daytona.Base("python:3.11").PipInstall([]string{"numpy", "pandas"})
// With optionsimage := 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) *DockerImageRun 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) *DockerImageUser 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) *DockerImageVolume 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) *DockerImageWorkdir 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 directoryfiles, err := sandbox.FileSystem.ListFiles(ctx, "/home/user")
// Create a directoryerr = sandbox.FileSystem.CreateFolder(ctx, "/home/user/mydir")
// Upload a fileerr = sandbox.FileSystem.UploadFile(ctx, "/local/path/file.txt", "/home/user/file.txt")
// Download a filedata, 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) *FileSystemServiceNewFileSystemService 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)) errorCreateFolder 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 permissionserr := sandbox.FileSystem.CreateFolder(ctx, "/home/user/mydir")
// Create with custom permissionserr := 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) errorDeleteFile 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 fileerr := sandbox.FileSystem.DeleteFile(ctx, "/home/user/file.txt", false)
// Delete a directory recursivelyerr := 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 contentsdata, err := sandbox.FileSystem.DownloadFile(ctx, "/home/user/file.txt", nil)fmt.Println(string(data))
// Download and save to local filelocalPath := "/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) errorMoveFiles 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 fileerr := sandbox.FileSystem.MoveFiles(ctx, "/home/user/old.txt", "/home/user/new.txt")
// Move a file to another directoryerr := 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)) errorSetFilePermissions 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 onlyerr := sandbox.FileSystem.SetFilePermissions(ctx, "/home/user/script.sh", options.WithPermissionMode("0755"),)
// Set owner and grouperr := sandbox.FileSystem.SetFilePermissions(ctx, "/home/user/file.txt", options.WithOwner("root"), options.WithGroup("users"),)
// Set all at onceerr := 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) errorUploadFile 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 patherr := sandbox.FileSystem.UploadFile(ctx, "/local/path/file.txt", "/home/user/file.txt")
// Upload from byte slicecontent := []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 repositoryerr := sandbox.Git.Clone(ctx, "https://github.com/user/repo.git", "/home/user/repo")
// Make changes and commiterr = 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 remoteerr = 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) *GitServiceNewGitService 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) errorAdd 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 fileserr := sandbox.Git.Add(ctx, "/home/user/repo", []string{"file1.txt", "src/main.go"})
// Stage all changeserr := 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) errorCheckout 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 brancherr := sandbox.Git.Checkout(ctx, "/home/user/repo", "develop")
// Checkout a specific commiterr := 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)) errorClone 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 brancherr := sandbox.Git.Clone(ctx, "https://github.com/user/repo.git", "/home/user/repo")
// Clone a specific branch with authenticationerr := 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 commiterr := 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 commitresp, 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 commitresp, 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) errorCreateBranch 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 brancherr := sandbox.Git.CreateBranch(ctx, "/home/user/repo", "feature/new-feature")if err != nil { return err}
// Switch to the new brancherr = 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)) errorDeleteBranch 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 brancherr := sandbox.Git.DeleteBranch(ctx, "/home/user/repo", "feature/old-feature")
// Force delete an unmerged brancherr := 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)) errorPull 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 repositoryerr := sandbox.Git.Pull(ctx, "/home/user/repo")
// Pull with authenticationerr := 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)) errorPush 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 authenticationerr := 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) *KeyboardServiceNewKeyboardService creates a new KeyboardService.
func (*KeyboardService) Hotkey
func (k *KeyboardService) Hotkey(ctx context.Context, keys string) errorHotkey 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) errorPress 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 Entererr := keyboard.Press(ctx, "Enter", nil)
// Press Ctrl+Serr := keyboard.Press(ctx, "s", []string{"ctrl"})
// Press Ctrl+Shift+Nerr := 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) errorType 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 speederr := keyboard.Type(ctx, "Hello, World!", nil)
// Type with custom delay between keystrokesdelay := 50err := 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 Pythonlsp := sandbox.Lsp(types.LspLanguageIDPython, "/home/user/project")
// Start the language serverif err := lsp.Start(ctx); err != nil { return err}defer lsp.Stop(ctx)
// Open a file for analysisif err := lsp.DidOpen(ctx, "/home/user/project/main.py"); err != nil { return err}
// Get code completionscompletions, 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) *LspServerServiceNewLspServerService 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) errorDidClose 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) errorDidOpen 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) errorStart 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) errorStop 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) *MouseServiceNewMouseService 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 clickpos, err := mouse.Click(ctx, 100, 200, nil, nil)
// Right clickbutton := "right"pos, err := mouse.Click(ctx, 100, 200, &button, nil)
// Double clickdoubleClick := truepos, 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 amountamount := 5success, 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 commandresult, err := sandbox.Process.ExecuteCommand(ctx, "echo 'Hello, World!'")fmt.Println(result.Result)
// Execute with optionsresult, err := sandbox.Process.ExecuteCommand(ctx, "ls -la", options.WithCwd("/home/user/project"), options.WithExecuteTimeout(30*time.Second),)
// Create an interactive PTY sessionhandle, 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) *ProcessServiceNewProcessService 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 connectionif err := handle.WaitForConnection(ctx); err != nil { return err}
// Read outputfor 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 connectionif err := handle.WaitForConnection(ctx); err != nil { return err}
// Send a commandhandle.SendInput([]byte("ls -la\n"))
// Read outputfor 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 settingssession, err := sandbox.Process.CreatePtySession(ctx, "my-terminal")
// Create with custom sizesession, 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) errorCreateSession 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 sessionerr := sandbox.Process.CreateSession(ctx, "my-session")if err != nil { return err}defer sandbox.Process.DeleteSession(ctx, "my-session")
// Execute commands in the sessionresult, 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) errorDeleteSession 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 commandresult, err := sandbox.Process.ExecuteCommand(ctx, "echo 'Hello'")if err != nil { return err}fmt.Println(result.Result)
// Command with optionsresult, err := sandbox.Process.ExecuteCommand(ctx, "npm install", options.WithCwd("/home/user/project"), options.WithExecuteTimeout(5*time.Minute),)
// Check exit codeif 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 executionresult, err := sandbox.Process.ExecuteSessionCommand(ctx, "my-session", "ls -la", false)if err != nil { return err}fmt.Println(result["stdout"])
// Asynchronous executionresult, 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) errorGetSessionCommandLogsStream 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) errorKillPtySession 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 sessionhandle, err := sandbox.Process.CreatePty(ctx, "my-pty", nil)if err != nil { return err}defer handle.Disconnect()
// Wait for connection to be establishedif err := handle.WaitForConnection(ctx); err != nil { return err}
// Send inputhandle.SendInput([]byte("ls -la\n"))
// Read output from channelfor data := range handle.DataChan() { fmt.Print(string(data))}
// Or use as io.Readerio.Copy(os.Stdout, handle)type PtyHandle struct { // contains filtered or unexported fields}func (*PtyHandle) DataChan
func (h *PtyHandle) DataChan() <-chan []byteDataChan 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() errorDisconnect 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() *stringError returns the error message if the PTY session failed, or nil otherwise.
func (*PtyHandle) ExitCode
func (h *PtyHandle) ExitCode() *intExitCode returns the exit code of the PTY process, or nil if still running.
func (*PtyHandle) IsConnected
func (h *PtyHandle) IsConnected() boolIsConnected returns true if the WebSocket connection is active.
func (*PtyHandle) Kill
func (h *PtyHandle) Kill(ctx context.Context) errorKill 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 stdoutio.Copy(os.Stdout, handle)
// Use with bufio.Scannerscanner := 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) errorSendInput 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 commandhandle.SendInput([]byte("ls -la\n"))
// Send Ctrl+Chandle.SendInput([]byte{0x03})Returns an error if the PTY is not connected or sending fails.
func (*PtyHandle) SessionID
func (h *PtyHandle) SessionID() stringSessionID 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) errorWaitForConnection 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 directlyhandle.Write([]byte("echo hello\n"))
// Use with io.Copyio.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 sandboxsandbox, err := client.Create(ctx)if err != nil { return err}defer sandbox.Delete(ctx)
// Execute a commandresult, err := sandbox.Process.ExecuteCommand(ctx, "echo 'Hello'")
// Work with fileserr = 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) *SandboxNewSandbox 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) errorArchive 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 laterfunc (*Sandbox) Delete
func (s *Sandbox) Delete(ctx context.Context) errorDelete 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) errorDeleteWithTimeout deletes the sandbox with a custom timeout.
Example:
err := sandbox.DeleteWithTimeout(ctx, 2*time.Minute)func (*Sandbox) GetPreviewLink
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 sandboxsandbox.Process.ExecuteCommand(ctx, "python -m http.server 3000 &")
// Get the preview URLurl, 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) errorRefreshData 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) errorSetAutoArchiveInterval 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 stoppedinterval := 30err := sandbox.SetAutoArchiveInterval(ctx, &interval)
// Disable auto-archivinginterval := 0err := sandbox.SetAutoArchiveInterval(ctx, &interval)func (*Sandbox) SetAutoDeleteInterval
func (s *Sandbox) SetAutoDeleteInterval(ctx context.Context, intervalMinutes *int) errorSetAutoDeleteInterval 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 stoppedinterval := 60err := sandbox.SetAutoDeleteInterval(ctx, &interval)
// Delete immediately when stoppedinterval := 0err := sandbox.SetAutoDeleteInterval(ctx, &interval)
// Never auto-deleteinterval := -1err := sandbox.SetAutoDeleteInterval(ctx, &interval)func (*Sandbox) SetLabels
func (s *Sandbox) SetLabels(ctx context.Context, labels map[string]string) errorSetLabels 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) errorStart 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 runningfunc (*Sandbox) StartWithTimeout
func (s *Sandbox) StartWithTimeout(ctx context.Context, timeout time.Duration) errorStartWithTimeout 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) errorStop 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) errorStopWithTimeout 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) errorWaitForStart 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 runningfunc (*Sandbox) WaitForStop
func (s *Sandbox) WaitForStop(ctx context.Context, timeout time.Duration) errorWaitForStop 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) *ScreenshotServiceNewScreenshotService 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 screenscreenshot, err := ss.TakeFullScreen(ctx, nil)if err != nil { return err}// screenshot.Image contains the base64-encoded image data
// Capture with cursor visibleshowCursor := truescreenshot, 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 imagesnapshot, logChan, err := client.Snapshots.Create(ctx, &types.CreateSnapshotParams{ Name: "my-python-env", Image: "python:3.11-slim",})if err != nil { return err}
// Stream build logsfor log := range logChan { fmt.Println(log)}
// Create a snapshot from a custom Image definitionimage := 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) *SnapshotServiceNewSnapshotService 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 imagesnapshot, logChan, err := client.Snapshots.Create(ctx, &types.CreateSnapshotParams{ Name: "my-env", Image: "python:3.11-slim",})if err != nil { return err}
// Stream build logsfor log := range logChan { fmt.Println(log)}
// Create with custom image and resourcesimage := 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) errorDelete 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 limitresult, err := client.Snapshots.List(ctx, nil, nil)if err != nil { return err}
// List with paginationpage, limit := 2, 10result, 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 volumevolume, err := client.Volumes.Create(ctx, "my-data-volume")if err != nil { return err}
// Wait for volume to be readyvolume, err = client.Volumes.WaitForReady(ctx, volume, 60*time.Second)if err != nil { return err}
// List all volumesvolumes, err := client.Volumes.List(ctx)type VolumeService struct { // contains filtered or unexported fields}func NewVolumeService
func NewVolumeService(client *Client) *VolumeServiceNewVolumeService 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 readyvolume, 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) errorDelete 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 readyvolume, 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.