Skip to content

Secure, Fast, and Extensible Sandbox runtime for AI agents.

22.6 KB
Raw Blame
// Copyright 2026 The OpenSandbox Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package opensandbox

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"net/textproto"
	"net/url"
	"os"
	"strconv"
	"strings"
)

// ExecdClient provides access to the OpenSandbox Execd API for code execution,
// command execution, file operations, and system metrics.
type ExecdClient struct {
	client *Client
}

// execdAuthHeader is the authentication header used by the Execd API.
const execdAuthHeader = "X-EXECD-ACCESS-TOKEN"

// NewExecdClient creates a new ExecdClient for the given base URL and access token.
func NewExecdClient(baseURL, accessToken string, opts ...Option) *ExecdClient {
	return &ExecdClient{
		client: NewClient(baseURL, accessToken, execdAuthHeader, opts...),
	}
}

// Ping verifies that the Execd server is running and responsive.
func (e *ExecdClient) Ping(ctx context.Context) error {
	return e.client.doRequest(ctx, http.MethodGet, "/ping", nil, nil)
}

// ListContexts returns all active code execution contexts for the given language.
func (e *ExecdClient) ListContexts(ctx context.Context, language string) ([]CodeContext, error) {
	var result []CodeContext
	params := url.Values{}
	params.Set("language", language)
	path := "/code/contexts?" + params.Encode()
	err := e.client.doRequest(ctx, http.MethodGet, path, nil, &result)
	return result, err
}

// CreateContext creates a new code execution context and returns its context ID.
func (e *ExecdClient) CreateContext(ctx context.Context, req CreateContextRequest) (*CodeContext, error) {
	var result CodeContext
	err := e.client.doRequest(ctx, http.MethodPost, "/code/context", req, &result)
	if err != nil {
		return nil, err
	}
	return &result, nil
}

// GetContext retrieves the details of an existing code execution context by ID.
func (e *ExecdClient) GetContext(ctx context.Context, contextID string) (*CodeContext, error) {
	var result CodeContext
	path := "/code/contexts/" + url.PathEscape(contextID)
	err := e.client.doRequest(ctx, http.MethodGet, path, nil, &result)
	if err != nil {
		return nil, err
	}
	return &result, nil
}

// DeleteContext deletes a code execution context by ID.
func (e *ExecdClient) DeleteContext(ctx context.Context, contextID string) error {
	path := "/code/contexts/" + url.PathEscape(contextID)
	return e.client.doRequest(ctx, http.MethodDelete, path, nil, nil)
}

// DeleteContextsByLanguage deletes all code execution contexts for the given language.
func (e *ExecdClient) DeleteContextsByLanguage(ctx context.Context, language string) error {
	params := url.Values{}
	params.Set("language", language)
	path := "/code/contexts?" + params.Encode()
	return e.client.doRequest(ctx, http.MethodDelete, path, nil, nil)
}

// ExecuteCode executes code in the specified context and streams output events
// via SSE. The handler is called for each event received from the server.
func (e *ExecdClient) ExecuteCode(ctx context.Context, req RunCodeRequest, handler EventHandler) error {
	return e.client.doStreamRequest(ctx, http.MethodPost, "/code", req, handler)
}

// InterruptCode interrupts the currently running code execution.
func (e *ExecdClient) InterruptCode(ctx context.Context, sessionID string) error {
	params := url.Values{}
	params.Set("id", sessionID)
	path := "/code?" + params.Encode()
	return e.client.doRequest(ctx, http.MethodDelete, path, nil, nil)
}

// CreateSession creates a new bash session and returns it with a session ID.
// An optional CreateSessionRequest sets the session's working directory.
// At most one option is honored (first wins, matching DownloadFile).
func (e *ExecdClient) CreateSession(ctx context.Context, opts ...CreateSessionRequest) (*Session, error) {
	req := CreateSessionRequest{}
	if len(opts) > 0 {
		req = opts[0]
	}
	var result Session
	err := e.client.doRequest(ctx, http.MethodPost, "/session", req, &result)
	if err != nil {
		return nil, err
	}
	return &result, nil
}

// RunInSession executes a command in an existing bash session and streams
// output events via SSE.
func (e *ExecdClient) RunInSession(ctx context.Context, sessionID string, req RunInSessionRequest, handler EventHandler) error {
	path := "/session/" + url.PathEscape(sessionID) + "/run"
	return e.client.doStreamRequest(ctx, http.MethodPost, path, req, handler)
}

// DeleteSession deletes a bash session by ID.
func (e *ExecdClient) DeleteSession(ctx context.Context, sessionID string) error {
	path := "/session/" + url.PathEscape(sessionID)
	return e.client.doRequest(ctx, http.MethodDelete, path, nil, nil)
}

// RunCommand executes a shell command and streams output events via SSE.
func (e *ExecdClient) RunCommand(ctx context.Context, req RunCommandRequest, handler EventHandler) error {
	if !req.Background {
		return e.client.doStreamRequest(ctx, http.MethodPost, "/command", req, handler)
	}
	// Returning a private sentinel closes the response without masking callback errors.
	complete := fmt.Errorf("background command started")
	err := e.client.doStreamRequest(ctx, http.MethodPost, "/command", req, func(event StreamEvent) error {
		if err := handler(event); err != nil {
			return err
		}
		var payload struct{ Type string }
		if json.Unmarshal([]byte(event.Data), &payload) == nil && payload.Type == "execution_complete" {
			return complete
		}
		return nil
	})
	if err == complete {
		return nil
	}
	return err
}

// InterruptCommand interrupts the currently running command execution.
func (e *ExecdClient) InterruptCommand(ctx context.Context, sessionID string) error {
	params := url.Values{}
	params.Set("id", sessionID)
	path := "/command?" + params.Encode()
	return e.client.doRequest(ctx, http.MethodDelete, path, nil, nil)
}

// GetCommandStatus returns the current status of a command by ID.
func (e *ExecdClient) GetCommandStatus(ctx context.Context, commandID string) (*CommandStatusResponse, error) {
	var result CommandStatusResponse
	path := "/command/status/" + url.PathEscape(commandID)
	err := e.client.doRequest(ctx, http.MethodGet, path, nil, &result)
	if err != nil {
		return nil, err
	}
	return &result, nil
}

// GetCommandLogs returns stdout/stderr for a background command. Pass a nil
// cursor or cursor=0 for the full log. The returned CommandLogsResponse includes
// the tail cursor for incremental polling.
func (e *ExecdClient) GetCommandLogs(ctx context.Context, commandID string, cursor *int64) (*CommandLogsResponse, error) {
	if cursor != nil && *cursor < 0 {
		return nil, &InvalidArgumentError{Field: "cursor", Message: "must not be negative"}
	}

	path := "/command/" + url.PathEscape(commandID) + "/logs"
	if cursor != nil {
		path += "?cursor=" + strconv.FormatInt(*cursor, 10)
	}

	var result *CommandLogsResponse
	err := e.client.withRetry(ctx, func() error {
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, e.client.baseURL+path, nil)
		if err != nil {
			return fmt.Errorf("opensandbox: create request: %w", err)
		}
		req.Header.Set("User-Agent", "OpenSandbox-Go-SDK/"+Version)
		for k, v := range e.client.headers {
			req.Header.Set(k, v)
		}
		if e.client.apiKey != "" {
			req.Header.Set(e.client.authHeader, e.client.apiKey)
		}
		req.Header.Set("Accept", "text/plain")

		resp, err := e.client.httpClient.Do(req)
		if err != nil {
			return fmt.Errorf("opensandbox: do request: %w", err)
		}
		defer resp.Body.Close()

		if resp.StatusCode >= 400 {
			return handleError(resp)
		}

		body, err := io.ReadAll(resp.Body)
		if err != nil {
			return fmt.Errorf("opensandbox: read response: %w", err)
		}

		logResp := &CommandLogsResponse{
			Output: string(body),
		}
		if cursorStr := resp.Header.Get("EXECD-COMMANDS-TAIL-CURSOR"); cursorStr != "" {
			parsed, parseErr := strconv.ParseInt(cursorStr, 10, 64)
			if parseErr != nil {
				return fmt.Errorf("opensandbox: invalid EXECD-COMMANDS-TAIL-CURSOR header %q: %w", cursorStr, parseErr)
			}
			logResp.Cursor = parsed
		}
		result = logResp
		return nil
	})
	if err != nil {
		return nil, err
	}
	return result, nil
}

// GetFileInfo retrieves metadata for the file at the given path.
func (e *ExecdClient) GetFileInfo(ctx context.Context, path string) (map[string]FileInfo, error) {
	var result map[string]FileInfo
	params := url.Values{}
	params.Set("path", path)
	reqPath := "/files/info?" + params.Encode()
	err := e.client.doRequest(ctx, http.MethodGet, reqPath, nil, &result)
	return result, err
}

// DeleteFiles deletes one or more files from the sandbox.
func (e *ExecdClient) DeleteFiles(ctx context.Context, paths []string) error {
	params := url.Values{}
	for _, p := range paths {
		params.Add("path", p)
	}
	reqPath := "/files?" + params.Encode()
	return e.client.doRequest(ctx, http.MethodDelete, reqPath, nil, nil)
}

// SetPermissions changes permissions, owner, and group for the specified files.
func (e *ExecdClient) SetPermissions(ctx context.Context, req PermissionsRequest) error {
	return e.client.doRequest(ctx, http.MethodPost, "/files/permissions", req, nil)
}

// MoveFiles renames or moves files to new paths.
func (e *ExecdClient) MoveFiles(ctx context.Context, req MoveRequest) error {
	return e.client.doRequest(ctx, http.MethodPost, "/files/mv", req, nil)
}

// SearchFiles searches for files matching a glob pattern within a directory.
func (e *ExecdClient) SearchFiles(ctx context.Context, dir string, pattern string) ([]FileInfo, error) {
	var result []FileInfo
	params := url.Values{}
	params.Set("path", dir)
	if pattern != "" {
		params.Set("pattern", pattern)
	}
	reqPath := "/files/search?" + params.Encode()
	err := e.client.doRequest(ctx, http.MethodGet, reqPath, nil, &result)
	return result, err
}

// ListDirectory lists the immediate children of the given directory using the
// server-side default depth (1). Use ListDirectoryWithDepth to override.
func (e *ExecdClient) ListDirectory(ctx context.Context, path string) ([]FileInfo, error) {
	return e.listDirectory(ctx, path, nil)
}

// ListDirectoryWithDepth lists directory contents up to the given depth.
// depth=0 returns an empty slice (the directory itself is not listed).
// depth=1 returns the immediate children. Larger values include descendants
// up to that many levels below path. Negative values are rejected by the
// server.
func (e *ExecdClient) ListDirectoryWithDepth(ctx context.Context, path string, depth int) ([]FileInfo, error) {
	d := depth
	return e.listDirectory(ctx, path, &d)
}

func (e *ExecdClient) listDirectory(ctx context.Context, path string, depth *int) ([]FileInfo, error) {
	var result []FileInfo
	params := url.Values{}
	params.Set("path", path)
	if depth != nil {
		params.Set("depth", strconv.Itoa(*depth))
	}
	reqPath := "/directories/list?" + params.Encode()
	err := e.client.doRequest(ctx, http.MethodGet, reqPath, nil, &result)
	return result, err
}

// ReplaceInFiles performs text replacement in the specified files.
func (e *ExecdClient) ReplaceInFiles(ctx context.Context, req ReplaceRequest) error {
	return e.client.doRequest(ctx, http.MethodPost, "/files/replace", req, nil)
}

// ReplaceInFilesDetailed performs text replacement and returns per-file replacement counts.
func (e *ExecdClient) ReplaceInFilesDetailed(ctx context.Context, req ReplaceRequest) (ReplaceResponse, error) {
	var resp ReplaceResponse
	err := e.client.doRequest(ctx, http.MethodPost, "/files/replace?verbose=true", req, &resp)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

// UploadFileOptions configures the destination path and multipart filename for an upload.
type UploadFileOptions struct {
	FileName string
	Metadata FileMetadata
}

// UploadFileEntry describes one file part in a multi-file upload request.
type UploadFileEntry struct {
	File    io.Reader
	Options UploadFileOptions
}

// UploadFile uploads a single file to the sandbox.
func (e *ExecdClient) UploadFile(ctx context.Context, file io.Reader, opts UploadFileOptions) error {
	return e.UploadFiles(ctx, []UploadFileEntry{{File: file, Options: opts}})
}

// UploadFiles uploads one or more files to the sandbox in a single multipart request.
func (e *ExecdClient) UploadFiles(ctx context.Context, entries []UploadFileEntry) error {
	req, bodyCloser, err := e.newUploadFilesRequest(ctx, entries)
	if err != nil {
		return err
	}
	defer bodyCloser.Close()

	req.Header.Set("User-Agent", "OpenSandbox-Go-SDK/"+Version)
	for k, v := range e.client.headers {
		req.Header.Set(k, v)
	}
	if e.client.apiKey != "" {
		req.Header.Set(e.client.authHeader, e.client.apiKey)
	}

	resp, err := e.client.transferHTTPClient().Do(req)
	if err != nil {
		return fmt.Errorf("opensandbox: do request: %w", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode >= 400 {
		return handleError(resp)
	}
	return nil
}

func (e *ExecdClient) newUploadFilesRequest(ctx context.Context, entries []UploadFileEntry) (*http.Request, io.Closer, error) {
	if len(entries) == 0 {
		return nil, nil, &InvalidArgumentError{Field: "entries", Message: "at least one file entry is required"}
	}
	for i, entry := range entries {
		if entry.File == nil {
			return nil, nil, &InvalidArgumentError{Field: fmt.Sprintf("entries[%d].file", i), Message: "file reader is required"}
		}
		if entry.Options.Metadata.Path == "" {
			return nil, nil, &InvalidArgumentError{Field: fmt.Sprintf("entries[%d].metadata.path", i), Message: "path is required"}
		}
	}

	pr, pw := io.Pipe()
	writer := multipart.NewWriter(pw)
	contentType := writer.FormDataContentType()

	go func() {
		for i, entry := range entries {
			metaJSON, err := json.Marshal(entry.Options.Metadata)
			if err != nil {
				_ = pw.CloseWithError(fmt.Errorf("opensandbox: marshal metadata for entry %d: %w", i, err))
				return
			}
			metaHeader := make(textproto.MIMEHeader)
			metaHeader.Set("Content-Disposition", `form-data; name="metadata"; filename="metadata"`)
			metaHeader.Set("Content-Type", "application/json")
			metaPart, err := writer.CreatePart(metaHeader)
			if err != nil {
				_ = pw.CloseWithError(fmt.Errorf("opensandbox: create metadata part for entry %d: %w", i, err))
				return
			}
			if _, err := metaPart.Write(metaJSON); err != nil {
				_ = pw.CloseWithError(fmt.Errorf("opensandbox: write metadata for entry %d: %w", i, err))
				return
			}

			fileName := entry.Options.FileName
			if fileName == "" {
				fileName = "file"
			}
			filePart, err := writer.CreateFormFile("file", fileName)
			if err != nil {
				_ = pw.CloseWithError(fmt.Errorf("opensandbox: create file part for entry %d: %w", i, err))
				return
			}
			if _, err := io.Copy(filePart, entry.File); err != nil {
				_ = pw.CloseWithError(fmt.Errorf("opensandbox: write file for entry %d: %w", i, err))
				return
			}
		}
		if err := writer.Close(); err != nil {
			_ = pw.CloseWithError(fmt.Errorf("opensandbox: close multipart: %w", err))
			return
		}
		_ = pw.Close()
	}()

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, e.client.baseURL+"/files/upload", pr)
	if err != nil {
		_ = pr.Close()
		return nil, nil, fmt.Errorf("opensandbox: create request: %w", err)
	}
	req.Header.Set("Content-Type", contentType)
	return req, pr, nil
}

// DownloadFileOptions configures line-based reading for DownloadFile.
type DownloadFileOptions struct {
	// Offset is the starting line number (1-based). Mutually exclusive with Range header.
	Offset int
	// Limit is the number of lines to return. Mutually exclusive with Range header.
	Limit int
}

// ByteRange is a parsed Content-Range response header. Start and End are
// inclusive byte offsets. Total is -1 when the complete file size is unknown.
type ByteRange struct {
	// Start is the inclusive first byte offset, or -1 if parsing failed.
	Start int64
	// End is the inclusive last byte offset, or -1 if parsing failed.
	End int64
	// Total is the complete file size, or -1 if unknown or parsing failed.
	Total int64
	// Raw is the original Content-Range header value.
	Raw string
}

// DownloadFilesystem is the optional capability for HTTP download metadata.
// ExecdClient implements it, including clients returned by FilesWithIdentity.
// Callers must close the returned response body.
type DownloadFilesystem interface {
	DownloadFileResponse(context.Context, string, string, ...DownloadFileOptions) (*DownloadFileResponse, error)
}

// DownloadFileResponse contains a download body and its HTTP response
// metadata. The caller must close Body.
type DownloadFileResponse struct {
	// Body contains the downloaded bytes and must be closed by the caller.
	Body io.ReadCloser
	// StatusCode is the complete HTTP response status code.
	StatusCode int
	// ContentType is the Content-Type response header.
	ContentType string
	// ContentDisposition is the Content-Disposition response header.
	ContentDisposition string

	// ContentLength is the size of the response body, or -1 when unknown.
	// For partial responses it is the size of the returned byte range, not the
	// complete file.
	ContentLength int64

	// TotalSize is the complete file size, or -1 when unknown.
	TotalSize int64

	// ContentRange is populated for a 206 response with a non-empty
	// Content-Range header. If the header is malformed, Raw is preserved and
	// the numeric fields are -1.
	ContentRange *ByteRange
}

// IsPartial reports whether the server honored the Range request and returned
// 206 Partial Content.
func (r *DownloadFileResponse) IsPartial() bool {
	return r != nil && r.StatusCode == http.StatusPartialContent
}

func parseContentRange(raw string) *ByteRange {
	if raw == "" {
		return nil
	}

	result := &ByteRange{Start: -1, End: -1, Total: -1, Raw: raw}
	parts := strings.Fields(raw)
	if len(parts) != 2 || !strings.EqualFold(parts[0], "bytes") {
		return result
	}

	interval, totalText, ok := strings.Cut(parts[1], "/")
	if !ok {
		return result
	}
	startText, endText, ok := strings.Cut(interval, "-")
	if !ok {
		return result
	}

	start, err := strconv.ParseInt(startText, 10, 64)
	if err != nil || start < 0 {
		return result
	}
	end, err := strconv.ParseInt(endText, 10, 64)
	if err != nil || end < start {
		return result
	}

	total := int64(-1)
	if totalText != "*" {
		total, err = strconv.ParseInt(totalText, 10, 64)
		if err != nil || total <= end {
			return result
		}
	}

	result.Start = start
	result.End = end
	result.Total = total
	return result
}

// DownloadFile downloads a file from the sandbox. The caller must close the
// returned io.ReadCloser. Pass rangeHeader (e.g. "bytes=0-1023") for partial
// content, or empty string for the full file. Use opts for line-based reading.
// Use DownloadFileResponse when response status or range metadata is needed.
func (e *ExecdClient) DownloadFile(ctx context.Context, remotePath string, rangeHeader string, opts ...DownloadFileOptions) (io.ReadCloser, error) {
	resp, err := e.DownloadFileResponse(ctx, remotePath, rangeHeader, opts...)
	if err != nil {
		return nil, err
	}
	return resp.Body, nil
}

// DownloadFileResponse downloads a file and returns both its body and response
// metadata. Callers resuming a download should check IsPartial before appending
// the body to an existing file.
func (e *ExecdClient) DownloadFileResponse(ctx context.Context, remotePath string, rangeHeader string, opts ...DownloadFileOptions) (*DownloadFileResponse, error) {
	params := url.Values{}
	params.Set("path", remotePath)
	if len(opts) > 0 {
		o := opts[0]
		if o.Offset > 0 {
			params.Set("offset", strconv.Itoa(o.Offset))
		}
		if o.Limit > 0 {
			params.Set("limit", strconv.Itoa(o.Limit))
		}
	}
	reqPath := "/files/download?" + params.Encode()

	var resp *http.Response
	err := e.client.withRetry(ctx, func() error {
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, e.client.baseURL+reqPath, nil)
		if err != nil {
			return fmt.Errorf("opensandbox: create request: %w", err)
		}
		req.Header.Set("User-Agent", "OpenSandbox-Go-SDK/"+Version)
		for k, v := range e.client.headers {
			req.Header.Set(k, v)
		}
		if e.client.apiKey != "" {
			req.Header.Set(e.client.authHeader, e.client.apiKey)
		}
		if rangeHeader != "" {
			req.Header.Set("Range", rangeHeader)
		}

		r, err := e.client.transferHTTPClient().Do(req)
		if err != nil {
			return fmt.Errorf("opensandbox: do request: %w", err)
		}
		if r.StatusCode >= 400 {
			defer r.Body.Close()
			return handleError(r)
		}
		resp = r
		return nil
	})
	if err != nil {
		return nil, err
	}

	result := &DownloadFileResponse{
		Body:               resp.Body,
		StatusCode:         resp.StatusCode,
		ContentType:        resp.Header.Get("Content-Type"),
		ContentDisposition: resp.Header.Get("Content-Disposition"),
		ContentLength:      resp.ContentLength,
		TotalSize:          -1,
	}
	if resp.StatusCode == http.StatusPartialContent {
		result.ContentRange = parseContentRange(resp.Header.Get("Content-Range"))
		if result.ContentRange != nil {
			result.TotalSize = result.ContentRange.Total
		}
	} else if !params.Has("offset") && !params.Has("limit") {
		result.TotalSize = result.ContentLength
	}
	return result, nil
}

// CreateDirectory creates a directory at the given path with the specified mode.
// Parent directories are created as needed (like mkdir -p).
// Mode is specified as octal digits in decimal form (e.g. 755 for rwxr-xr-x).
// Use OctalMode() to convert Go os.FileMode to the expected format.
func (e *ExecdClient) CreateDirectory(ctx context.Context, path string, mode int) error {
	body := map[string]map[string]int{
		path: {"mode": mode},
	}
	return e.client.doRequest(ctx, http.MethodPost, "/directories", body, nil)
}

// OctalMode converts a Go os.FileMode to the octal-digits-as-int format
// expected by the OpenSandbox server (e.g. os.FileMode(0755) -> 755).
func OctalMode(m os.FileMode) int {
	v, _ := strconv.Atoi(fmt.Sprintf("%o", m))
	return v
}

// DeleteDirectory deletes a directory and all its contents recursively.
func (e *ExecdClient) DeleteDirectory(ctx context.Context, path string) error {
	params := url.Values{}
	params.Set("path", path)
	reqPath := "/directories?" + params.Encode()
	return e.client.doRequest(ctx, http.MethodDelete, reqPath, nil, nil)
}

// GetMetrics retrieves current system resource metrics.
func (e *ExecdClient) GetMetrics(ctx context.Context) (*Metrics, error) {
	var result Metrics
	err := e.client.doRequest(ctx, http.MethodGet, "/metrics", nil, &result)
	if err != nil {
		return nil, err
	}
	return &result, nil
}

// WatchMetrics streams system metrics in real-time via SSE. The handler
// receives a new event approximately every second until the context is
// cancelled or an error occurs.
func (e *ExecdClient) WatchMetrics(ctx context.Context, handler EventHandler) error {
	return e.client.doStreamRequest(ctx, http.MethodGet, "/metrics/watch", nil, handler)
}