Skip to content

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

fix(sdk-go): keep code-interpreter output fragments together in Execution.Text

Jackmeson1a5f9c1611712
diff --git a/docs/sdks/go.md b/docs/sdks/go.md
index b5f633087..5cca0dbf1 100644
--- a/docs/sdks/go.md
+++ b/docs/sdks/go.md
@@ -79,6 +79,8 @@ The following snippets go inside a function returning `error`, with the live `sa
`Execution.Text()` combines stdout events while preserving their line-ending bytes and any unterminated final fragment. It inserts a newline between events only when the preceding event ends in neither `\n` nor `\r`, preserving ordinary legacy stripped-line output without appending a final terminator. A trailing `\r` is always treated as a line ending, including when an older producer retained it as content while stripping another terminator.
+For a language-backed code execution returned by `Sandbox.ExecuteCode`, `CodeInterpreter.Execute` or `CodeInterpreter.ExecuteInContext`, `Text()` concatenates stdout events without inserting any newline: `"Loading"` followed by `"...done\n"` produces `"Loading...done\n"`. CR, LF and trailing terminators are preserved, and the fragments stay unchanged in `Execution.Stdout`. Requests with no context, an empty language, or the `command` or `background-command` language use the command-output rule above. The SDK records the formatting mode in an unexported field; a plain struct copy keeps it, while an `Execution` constructed by hand or reconstructed into a fresh value from JSON uses the command-output rule.
+
Use structured callbacks for normal command output:
```go
diff --git a/sdks/sandbox/go/code_interpreter_test.go b/sdks/sandbox/go/code_interpreter_test.go
index ce4d70ba0..47ef89fde 100644
--- a/sdks/sandbox/go/code_interpreter_test.go
+++ b/sdks/sandbox/go/code_interpreter_test.go
@@ -20,6 +20,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
+ "strings"
"sync/atomic"
"testing"
"time"
@@ -146,3 +147,200 @@ func TestCreateCodeInterpreter_NegativeHealthCheckIntervalUsesDefault(t *testing
calls := atomic.LoadInt32(&commandCalls)
require.True(t, calls <= 5, fmt.Sprintf("runtime check ran %d times in 500ms, want the default 200ms spacing", calls))
}
+
+// newFragmentServer replays one execd stream on path: an init event, one event
+// per fragment on the given stream ("stdout" or "stderr"), and a completion.
+func newFragmentServer(t *testing.T, path, stream string, fragments []string) *httptest.Server {
+ t.Helper()
+ events := []map[string]any{{"type": "init", "text": "exec-fragments", "timestamp": 0}}
+ for i, text := range fragments {
+ events = append(events, map[string]any{"type": stream, "text": text, "timestamp": i + 1})
+ }
+ events = append(events, map[string]any{"type": "execution_complete", "timestamp": len(fragments) + 1})
+
+ var body strings.Builder
+ for _, event := range events {
+ data, err := json.Marshal(event)
+ require.NoError(t, err, "marshal event")
+ fmt.Fprintf(&body, "data: %s\n\n", data)
+ }
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != path {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ w.Header().Set("Content-Type", "text/event-stream")
+ fmt.Fprint(w, body.String())
+ }))
+ t.Cleanup(srv.Close)
+ return srv
+}
+
+func outputTexts(messages []OutputMessage) []string {
+ var texts []string
+ for _, m := range messages {
+ texts = append(texts, m.Text)
+ }
+ return texts
+}
+
+func TestCodeInterpreter_Execute_TextJoinsStreamFragments(t *testing.T) {
+ tests := []struct {
+ name string
+ fragments []string
+ want string
+ }{
+ {name: "partial line", fragments: []string{"Loading", "...done\n"}, want: "Loading...done\n"},
+ {name: "progress dots", fragments: []string{".", ".", "."}, want: "..."},
+ {name: "terminated lines", fragments: []string{"first\n", "second\n"}, want: "first\nsecond\n"},
+ {name: "blank line", fragments: []string{"first\n", "\n", "last\n"}, want: "first\n\nlast\n"},
+ {name: "only blank line", fragments: []string{"\n"}, want: "\n"},
+ {name: "carriage returns", fragments: []string{"first\r", "last\r"}, want: "first\rlast\r"},
+ {name: "CRLF lines", fragments: []string{"first\r\n", "last\r\n"}, want: "first\r\nlast\r\n"},
+ {name: "split CRLF", fragments: []string{"first\r", "\n", "last\r", "\n"}, want: "first\r\nlast\r\n"},
+ {name: "unterminated final fragment", fragments: []string{"first\n", "last"}, want: "first\nlast"},
+ {name: "empty fragments", fragments: []string{"", "Loading", "", "...done\n", ""}, want: "Loading...done\n"},
+ {name: "no output", want: ""},
+ }
+ for _, stream := range []string{"stdout", "stderr"} {
+ for _, tc := range tests {
+ t.Run(stream+"/"+tc.name, func(t *testing.T) {
+ srv := newFragmentServer(t, "/code", stream, tc.fragments)
+ ci := newTestCodeInterpreter(t, srv.URL)
+
+ exec, err := ci.Execute(context.Background(), "python", "print('synthetic stream')", nil)
+ require.NoError(t, err, "Execute")
+ require.Equal(t, "exec-fragments", exec.ID)
+ require.NotNil(t, exec.Complete, "execution_complete")
+
+ // The fragments stay intact; Text() reports stdout only.
+ if stream == "stdout" {
+ require.Equal(t, tc.fragments, outputTexts(exec.Stdout), "stdout fragments")
+ if got := exec.Text(); got != tc.want {
+ t.Errorf("Text() = %q, want %q", got, tc.want)
+ }
+ return
+ }
+ require.Equal(t, tc.fragments, outputTexts(exec.Stderr), "stderr fragments")
+ if got := exec.Text(); got != "" {
+ t.Errorf("Text() = %q, want no stderr text", got)
+ }
+ })
+ }
+ }
+}
+
+func TestCodeInterpreter_ExecuteEntryPoints_TextJoinsStreamFragments(t *testing.T) {
+ ctx := context.Background()
+ tests := []struct {
+ name string
+ run func(ci *CodeInterpreter) (*Execution, error)
+ }{
+ {name: "Execute", run: func(ci *CodeInterpreter) (*Execution, error) {
+ return ci.Execute(ctx, "python", "print('synthetic stream')", nil)
+ }},
+ {name: "ExecuteInContext", run: func(ci *CodeInterpreter) (*Execution, error) {
+ return ci.ExecuteInContext(ctx, "ctx-1", "python", "print('synthetic stream')", nil)
+ }},
+ {name: "Sandbox.ExecuteCode", run: func(ci *CodeInterpreter) (*Execution, error) {
+ return ci.Sandbox.ExecuteCode(ctx, RunCodeRequest{
+ Context: &CodeContext{Language: "python"},
+ Code: "print('synthetic stream')",
+ }, nil)
+ }},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ srv := newFragmentServer(t, "/code", "stdout", []string{"Loading", "...done\n"})
+ exec, err := tc.run(newTestCodeInterpreter(t, srv.URL))
+ require.NoError(t, err, tc.name)
+ if got, want := exec.Text(), "Loading...done\n"; got != want {
+ t.Errorf("Text() = %q, want %q", got, want)
+ }
+ })
+ }
+}
+
+func TestCodeInterpreter_ShellModesKeepLineSeparators(t *testing.T) {
+ ctx := context.Background()
+ tests := []struct {
+ name string
+ run func(ci *CodeInterpreter) (*Execution, error)
+ }{
+ {name: "Execute empty language", run: func(ci *CodeInterpreter) (*Execution, error) {
+ return ci.Execute(ctx, "", "echo a; echo b", nil)
+ }},
+ {name: "ExecuteInContext empty language", run: func(ci *CodeInterpreter) (*Execution, error) {
+ return ci.ExecuteInContext(ctx, "ctx-1", "", "echo a; echo b", nil)
+ }},
+ {name: "ExecuteCode no context", run: func(ci *CodeInterpreter) (*Execution, error) {
+ return ci.Sandbox.ExecuteCode(ctx, RunCodeRequest{Code: "echo a; echo b"}, nil)
+ }},
+ {name: "ExecuteCode empty context", run: func(ci *CodeInterpreter) (*Execution, error) {
+ return ci.Sandbox.ExecuteCode(ctx, RunCodeRequest{
+ Context: &CodeContext{},
+ Code: "echo a; echo b",
+ }, nil)
+ }},
+ {name: "Execute command language", run: func(ci *CodeInterpreter) (*Execution, error) {
+ return ci.Execute(ctx, "command", "echo a; echo b", nil)
+ }},
+ {name: "Execute background-command language", run: func(ci *CodeInterpreter) (*Execution, error) {
+ return ci.Execute(ctx, "background-command", "echo a; echo b", nil)
+ }},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ srv := newFragmentServer(t, "/code", "stdout", []string{"a", "b"})
+ exec, err := tc.run(newTestCodeInterpreter(t, srv.URL))
+ require.NoError(t, err, tc.name)
+ if got, want := exec.Text(), "a\nb"; got != want {
+ t.Errorf("Text() = %q, want %q", got, want)
+ }
+ })
+ }
+}
+
+// Command output keeps joining events as lines: only a code execution is
+// treated as a stream of fragments.
+func TestExecution_Text_CommandPathsKeepLineSeparators(t *testing.T) {
+ ctx := context.Background()
+ paths := []struct {
+ name string
+ path string
+ run func(sb *Sandbox) (*Execution, error)
+ }{
+ {name: "RunCommand", path: "/command", run: func(sb *Sandbox) (*Execution, error) {
+ return sb.RunCommand(ctx, "echo", nil)
+ }},
+ {name: "RunInSession", path: "/session/sess-1/run", run: func(sb *Sandbox) (*Execution, error) {
+ return sb.RunInSession(ctx, "sess-1", RunInSessionRequest{Command: "echo"}, nil)
+ }},
+ {name: "IsolationSession.Run", path: "/v1/isolated/session/iso-1/run", run: func(sb *Sandbox) (*Execution, error) {
+ session := &IsolationSession{sandbox: sb, info: &IsolatedSessionInfo{SessionID: "iso-1"}}
+ return session.Run(ctx, IsolatedRunRequest{Code: "echo"}, nil)
+ }},
+ }
+ tests := []struct {
+ name string
+ fragments []string
+ want string
+ }{
+ {name: "stripped lines", fragments: []string{"a", "b"}, want: "a\nb"},
+ {name: "partial line", fragments: []string{"Loading", "...done\n"}, want: "Loading\n...done\n"},
+ {name: "terminated lines", fragments: []string{"a\n", "b\n"}, want: "a\nb\n"},
+ }
+ for _, p := range paths {
+ for _, tc := range tests {
+ t.Run(p.name+"/"+tc.name, func(t *testing.T) {
+ srv := newFragmentServer(t, p.path, "stdout", tc.fragments)
+ sb := &Sandbox{id: "command-test-sandbox", execd: NewExecdClient(srv.URL, "tok")}
+ exec, err := p.run(sb)
+ require.NoError(t, err, p.name)
+ if got := exec.Text(); got != tc.want {
+ t.Errorf("Text() = %q, want %q", got, tc.want)
+ }
+ })
+ }
+ }
+}
diff --git a/sdks/sandbox/go/execution.go b/sdks/sandbox/go/execution.go
index b3873be7c..bc7842757 100644
--- a/sdks/sandbox/go/execution.go
+++ b/sdks/sandbox/go/execution.go
@@ -92,13 +92,19 @@ type Execution struct {
// ExitCode is the process exit code. Nil if not available.
ExitCode *int
+
+ // codeExecution marks a language-backed code execution. Shell command
+ // modes keep line-based joining; code output is streamed as fragments.
+ codeExecution bool
}
-// Text returns the combined stdout text.
+// Text returns the combined stdout text. For command output, a newline is
+// inserted between two events only when the first ends in neither LF nor CR.
+// For a code execution, the stdout fragments are concatenated unchanged.
func (e *Execution) Text() string {
var b strings.Builder
for i, m := range e.Stdout {
- if i > 0 {
+ if i > 0 && !e.codeExecution {
previous := e.Stdout[i-1].Text
if !strings.HasSuffix(previous, "\n") && !strings.HasSuffix(previous, "\r") {
b.WriteByte('\n')
diff --git a/sdks/sandbox/go/sandbox_exec.go b/sdks/sandbox/go/sandbox_exec.go
index a6a7c6d9f..f0e90ac06 100644
--- a/sdks/sandbox/go/sandbox_exec.go
+++ b/sdks/sandbox/go/sandbox_exec.go
@@ -47,6 +47,15 @@ func (s *Sandbox) ExecuteCode(ctx context.Context, req RunCodeRequest, handlers
return nil, fmt.Errorf("opensandbox: execd client not initialized")
}
exec := &Execution{}
+ if req.Context != nil {
+ // An omitted language selects shell execution in execd, as do the
+ // explicit command modes. Keep their legacy line separators.
+ switch req.Context.Language {
+ case "", "command", "background-command":
+ default:
+ exec.codeExecution = true
+ }
+ }
err := s.execd.ExecuteCode(ctx, req, func(event StreamEvent) error {
return processStreamEvent(exec, event, handlers)
})