Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(sdk/go): expose download response metadata
wenmou37d71c3fc105
diff --git a/docs/sdks/go.md b/docs/sdks/go.mdindex b5f633087..d2003cc76 100644--- a/docs/sdks/go.md+++ b/docs/sdks/go.md@@ -715,6 +715,7 @@ Created with `NewExecdClient(baseURL, accessToken string, opts ...Option)`.| `UploadFile(ctx, file, opts)` | Upload a file to the sandbox || `UploadFiles(ctx, entries)` | Upload multiple files to the sandbox || `DownloadFile(ctx, remotePath, rangeHeader)` | Download a file from the sandbox |+| `DownloadFileResponse(ctx, remotePath, rangeHeader)` | Download a file with HTTP status and range metadata |**Directory Operations:**diff --git a/sdks/sandbox/go/README.md b/sdks/sandbox/go/README.mdindex 148ba5fca..bf6a44b93 100644--- a/sdks/sandbox/go/README.md+++ b/sdks/sandbox/go/README.md@@ -490,6 +490,7 @@ Created with `NewExecdClient(baseURL, accessToken string, opts ...Option)`.| `UploadFile(ctx, file, opts)` | Upload a file to the sandbox || `UploadFiles(ctx, entries)` | Upload multiple files to the sandbox || `DownloadFile(ctx, remotePath, rangeHeader, opts...)` | Download a file from the sandbox (optional `DownloadFileOptions` reads by line) |+| `DownloadFileResponse(ctx, remotePath, rangeHeader, opts...)` | Download a file with HTTP status and range metadata |**Directory Operations:**| Method | Description |diff --git a/sdks/sandbox/go/execd.go b/sdks/sandbox/go/execd.goindex f30073c9d..085360434 100644--- a/sdks/sandbox/go/execd.go+++ b/sdks/sandbox/go/execd.go@@ -25,6 +25,7 @@ import ("net/url""os""strconv"+ "strings")// ExecdClient provides access to the OpenSandbox Execd API for code execution,@@ -445,10 +446,110 @@ type DownloadFileOptions struct {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+}++// 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 {@@ -493,7 +594,24 @@ func (e *ExecdClient) DownloadFile(ctx context.Context, remotePath string, rangeif err != nil {return nil, err}- return resp.Body, nil++ 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 {+ result.TotalSize = result.ContentLength+ }+ return result, nil}// CreateDirectory creates a directory at the given path with the specified mode.diff --git a/sdks/sandbox/go/opensandbox_test.go b/sdks/sandbox/go/opensandbox_test.goindex 645d9890b..ed935243c 100644--- a/sdks/sandbox/go/opensandbox_test.go+++ b/sdks/sandbox/go/opensandbox_test.go@@ -22,6 +22,7 @@ import ("net/http""net/http/httptest""os"+ "strconv""strings""sync""testing"@@ -61,6 +62,22 @@ func jsonResponse(w http.ResponseWriter, status int, v any) {json.NewEncoder(w).Encode(v)}+type roundTripFunc func(*http.Request) (*http.Response, error)++func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {+ return f(req)+}++type closeTrackingBody struct {+ io.Reader+ closed bool+}++func (b *closeTrackingBody) Close() error {+ b.closed = true+ return nil+}+func TestCreateSandbox(t *testing.T) {now := time.Now().UTC().Truncate(time.Second)want := SandboxInfo{@@ -1823,6 +1840,137 @@ func TestDownloadFile_Range(t *testing.T) {}}+func TestDownloadFileResponse_RangeIgnored(t *testing.T) {+ fileContent := "hello from sandbox file"++ _, client := newExecdServer(t, func(w http.ResponseWriter, r *http.Request) {+ if rangeHeader := r.Header.Get("Range"); rangeHeader != "bytes=1024-" {+ assert.Fail(t, fmt.Sprintf("Range = %q, want %q", rangeHeader, "bytes=1024-"))+ }+ w.Header().Set("Content-Type", "application/octet-stream")+ w.Header().Set("Content-Disposition", `attachment; filename="output.txt"`)+ w.Header().Set("Content-Length", strconv.Itoa(len(fileContent)))+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(fileContent))+ })++ resp, err := client.DownloadFileResponse(context.Background(), "/sandbox/output.txt", "bytes=1024-")+ require.NoErrorf(t, err, "DownloadFileResponse")+ defer resp.Body.Close()++ require.Equal(t, http.StatusOK, resp.StatusCode)+ require.Equal(t, false, resp.IsPartial())+ if resp.ContentRange != nil {+ assert.Fail(t, fmt.Sprintf("ContentRange = %+v, want nil", resp.ContentRange))+ }+ require.Equal(t, int64(len(fileContent)), resp.ContentLength)+ require.Equal(t, int64(len(fileContent)), resp.TotalSize)+ require.Equal(t, "application/octet-stream", resp.ContentType)+ require.Equal(t, `attachment; filename="output.txt"`, resp.ContentDisposition)+ data, err := io.ReadAll(resp.Body)+ require.NoErrorf(t, err, "ReadAll")+ require.Equal(t, fileContent, string(data))+}++func TestDownloadFileResponse_Range(t *testing.T) {+ _, client := newExecdServer(t, func(w http.ResponseWriter, r *http.Request) {+ if rangeHeader := r.Header.Get("Range"); rangeHeader != "bytes=0-4" {+ assert.Fail(t, fmt.Sprintf("Range = %q, want %q", rangeHeader, "bytes=0-4"))+ }++ w.Header().Set("Content-Type", "application/octet-stream")+ w.Header().Set("Content-Range", "bytes 0-4/10")+ w.Header().Set("Content-Length", "5")+ w.WriteHeader(http.StatusPartialContent)+ _, _ = w.Write([]byte("hello"))+ })++ resp, err := client.DownloadFileResponse(context.Background(), "/sandbox/big.bin", "bytes=0-4")+ require.NoErrorf(t, err, "DownloadFileResponse range")+ defer resp.Body.Close()++ require.Equal(t, http.StatusPartialContent, resp.StatusCode)+ require.Equal(t, true, resp.IsPartial())+ require.Equal(t, int64(5), resp.ContentLength)+ require.Equal(t, int64(10), resp.TotalSize)+ require.NotNil(t, resp.ContentRange)+ require.Equal(t, ByteRange{Start: 0, End: 4, Total: 10, Raw: "bytes 0-4/10"}, *resp.ContentRange)+}++func TestDownloadFileResponse_InvalidContentRange(t *testing.T) {+ _, client := newExecdServer(t, func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Range", "garbage")+ w.WriteHeader(http.StatusPartialContent)+ _, _ = w.Write([]byte("hello"))+ })++ resp, err := client.DownloadFileResponse(context.Background(), "/sandbox/big.bin", "bytes=0-4")+ require.NoErrorf(t, err, "DownloadFileResponse invalid Content-Range")+ defer resp.Body.Close()++ require.NotNil(t, resp.ContentRange)+ require.Equal(t, ByteRange{Start: -1, End: -1, Total: -1, Raw: "garbage"}, *resp.ContentRange)+ require.Equal(t, int64(-1), resp.TotalSize)+}++func TestParseContentRange_UnknownTotal(t *testing.T) {+ got := parseContentRange("bytes 1024-2047/*")+ require.NotNil(t, got)+ require.Equal(t, ByteRange{Start: 1024, End: 2047, Total: -1, Raw: "bytes 1024-2047/*"}, *got)+}++func TestDownloadFileResponse_ClosesErrorBodies(t *testing.T) {+ t.Run("error", func(t *testing.T) {+ body := &closeTrackingBody{Reader: strings.NewReader(`{"code":"NOT_FOUND","message":"missing"}`)}+ client := NewExecdClient("http://execd.test", "token", WithHTTPClient(&http.Client{+ Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {+ return &http.Response{+ StatusCode: http.StatusNotFound,+ Header: make(http.Header),+ Body: body,+ }, nil+ }),+ }))++ _, err := client.DownloadFileResponse(context.Background(), "/missing", "")+ require.Error(t, err)+ require.Equal(t, true, body.closed, "error response body should be closed")+ })++ t.Run("retry", func(t *testing.T) {+ errorBody := &closeTrackingBody{Reader: strings.NewReader(`{"code":"UNAVAILABLE","message":"retry"}`)}+ successBody := &closeTrackingBody{Reader: strings.NewReader("hello")}+ attempts := 0+ client := NewExecdClient("http://execd.test", "token",+ WithHTTPClient(&http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {+ attempts+++ if attempts == 1 {+ return &http.Response{+ StatusCode: http.StatusServiceUnavailable,+ Header: make(http.Header),+ Body: errorBody,+ }, nil+ }+ return &http.Response{+ StatusCode: http.StatusOK,+ Header: make(http.Header),+ Body: successBody,+ ContentLength: 5,+ }, nil+ })}),+ WithRetry(RetryConfig{MaxRetries: 1, Multiplier: 1}),+ )++ resp, err := client.DownloadFileResponse(context.Background(), "/data", "")+ require.NoErrorf(t, err, "DownloadFileResponse retry")+ require.Equal(t, 2, attempts)+ require.Equal(t, true, errorBody.closed, "failed attempt body should be closed")+ require.Equal(t, false, successBody.closed, "successful response body should remain open")+ require.NoErrorf(t, resp.Body.Close(), "close successful response body")+ require.Equal(t, true, successBody.closed, "caller should close successful response body")+ })+}+func TestDownloadFile_WithCustomHeaders(t *testing.T) {srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.Header.Get("X-Test-Header") != "download-ok" {diff --git a/sdks/sandbox/go/sandbox_files.go b/sdks/sandbox/go/sandbox_files.goindex f865a64e1..274996c15 100644--- a/sdks/sandbox/go/sandbox_files.go+++ b/sdks/sandbox/go/sandbox_files.go@@ -103,6 +103,15 @@ func (s *Sandbox) DownloadFile(ctx context.Context, remotePath, rangeHeader strireturn s.execd.DownloadFile(ctx, remotePath, rangeHeader, opts...)}+// DownloadFileResponse downloads a file and returns its body and response+// metadata. The caller must close the response body.+func (s *Sandbox) DownloadFileResponse(ctx context.Context, remotePath, rangeHeader string, opts ...DownloadFileOptions) (*DownloadFileResponse, error) {+ if s.execd == nil {+ return nil, fmt.Errorf("opensandbox: execd client not initialized")+ }+ return s.execd.DownloadFileResponse(ctx, remotePath, rangeHeader, opts...)+}+// CreateDirectory creates a directory in the sandbox.// Mode is octal digits as int (e.g. 755 for rwxr-xr-x).func (s *Sandbox) CreateDirectory(ctx context.Context, path string, mode int) error {