Skip to content

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

fix(execd): report zero exit code for foreground command completion

leo pein69207856e93c
diff --git a/components/execd/pkg/web/controller/command.go b/components/execd/pkg/web/controller/command.go
index dfb65b50d..30c2d5a31 100644
--- a/components/execd/pkg/web/controller/command.go
+++ b/components/execd/pkg/web/controller/command.go
@@ -77,9 +77,14 @@ func (c *CodeInterpretingController) RunCommand() {
close(completeCh)
})
}
- origComplete := eventsHandler.OnExecuteComplete
eventsHandler.OnExecuteComplete = func(executionTime time.Duration) {
- origComplete(executionTime)
+ var exitCode *int
+ if !request.Background {
+ // The foreground runtime invokes this hook only after a successful wait.
+ code := 0
+ exitCode = &code
+ }
+ c.writeExecutionComplete(executionTime, exitCode)
recordExecution("success")
signalComplete()
}
diff --git a/components/execd/pkg/web/controller/command_exit_code_test.go b/components/execd/pkg/web/controller/command_exit_code_test.go
new file mode 100644
index 000000000..acd821cc4
--- /dev/null
+++ b/components/execd/pkg/web/controller/command_exit_code_test.go
@@ -0,0 +1,128 @@
+// 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.
+
+//go:build !windows
+
+package controller
+
+import (
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/alibaba/opensandbox/execd/pkg/flag"
+ "github.com/alibaba/opensandbox/execd/pkg/runtime"
+ "github.com/stretchr/testify/require"
+)
+
+func commandWireEvents(t *testing.T, body string) []map[string]json.RawMessage {
+ t.Helper()
+ var events []map[string]json.RawMessage
+ for _, line := range strings.Split(body, "\n") {
+ if strings.TrimSpace(line) == "" {
+ continue
+ }
+ var event map[string]json.RawMessage
+ require.NoError(t, json.Unmarshal([]byte(line), &event))
+ events = append(events, event)
+ }
+ return events
+}
+
+func TestRunCommandSuccessfulExitCode(t *testing.T) {
+ previousRunner, previousTimeout := codeRunner, flag.ApiGracefulShutdownTimeout
+ flag.ApiGracefulShutdownTimeout = 0
+ t.Cleanup(func() { codeRunner = previousRunner; flag.ApiGracefulShutdownTimeout = previousTimeout })
+
+ for _, tc := range []struct {
+ name, body, terminal string
+ hasExitCode bool
+ }{
+ {name: "zero", body: `{"argv":["/bin/sh","-c","exit 0"]}`, terminal: "execution_complete", hasExitCode: true},
+ {name: "nonzero", body: `{"argv":["/bin/sh","-c","exit 7"]}`, terminal: "error"},
+ {name: "start_failure", body: `{"argv":["/nonexistent-execd-exit-code-test"]}`, terminal: "error"},
+ {name: "background", body: `{"argv":["/bin/sh","-c","exit 0"],"background":true}`, terminal: "execution_complete"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ codeRunner = runtime.NewController("", "")
+ ctx, w := newTestContext(http.MethodPost, "/command", []byte(tc.body))
+ NewCodeInterpretingController(ctx).RunCommand()
+ require.Equal(t, http.StatusOK, w.Code, w.Body.String())
+ found := false
+ for _, event := range commandWireEvents(t, w.Body.String()) {
+ if string(event["type"]) == `"`+tc.terminal+`"` {
+ found = true
+ if tc.hasExitCode {
+ require.Contains(t, event, "exit_code")
+ require.JSONEq(t, "0", string(event["exit_code"]))
+ } else {
+ require.NotContains(t, event, "exit_code")
+ }
+ if tc.name == "nonzero" {
+ var payload map[string]json.RawMessage
+ require.NoError(t, json.Unmarshal(event["error"], &payload))
+ require.JSONEq(t, "7", string(payload["exit_code"]))
+ }
+ if tc.name == "start_failure" {
+ var payload map[string]json.RawMessage
+ require.NoError(t, json.Unmarshal(event["error"], &payload))
+ require.NotContains(t, payload, "exit_code")
+ }
+ } else {
+ require.NotContains(t, event, "exit_code")
+ }
+ }
+ require.True(t, found, w.Body.String())
+ })
+ }
+}
+
+func TestRunCommandTimeoutDoesNotReportSuccess(t *testing.T) {
+ previousRunner, previousTimeout := codeRunner, flag.ApiGracefulShutdownTimeout
+ codeRunner = runtime.NewController("", "")
+ flag.ApiGracefulShutdownTimeout = 0
+ t.Cleanup(func() { codeRunner = previousRunner; flag.ApiGracefulShutdownTimeout = previousTimeout })
+ ctx, w := newTestContext(http.MethodPost, "/command", []byte(`{"argv":["/bin/sh","-c","sleep 30"],"timeout":100}`))
+ NewCodeInterpretingController(ctx).RunCommand()
+ found := false
+ for _, event := range commandWireEvents(t, w.Body.String()) {
+ require.NotEqual(t, `"execution_complete"`, string(event["type"]))
+ require.NotContains(t, event, "exit_code")
+ if string(event["type"]) == `"error"` {
+ found = true
+ var payload map[string]json.RawMessage
+ require.NoError(t, json.Unmarshal(event["error"], &payload))
+ require.JSONEq(t, "-1", string(payload["exit_code"]))
+ }
+ }
+ require.True(t, found, w.Body.String())
+}
+
+func TestRunCodeCompletionOmitsProcessExitCode(t *testing.T) {
+ previousRunner := codeRunner
+ codeRunner = &fakeCodeRunner{execute: func(request *runtime.ExecuteCodeRequest) error {
+ request.Hooks.OnExecuteComplete(time.Millisecond)
+ return nil
+ }}
+ t.Cleanup(func() { codeRunner = previousRunner })
+ ctx, w := newTestContext(http.MethodPost, "/code", []byte(`{"code":"print(1)","language":"python"}`))
+ NewCodeInterpretingController(ctx).RunCode()
+ require.Equal(t, http.StatusOK, w.Code, w.Body.String())
+ events := commandWireEvents(t, w.Body.String())
+ require.Len(t, events, 1)
+ require.JSONEq(t, `"execution_complete"`, string(events[0]["type"]))
+ require.NotContains(t, events[0], "exit_code")
+}
diff --git a/components/execd/pkg/web/controller/sse.go b/components/execd/pkg/web/controller/sse.go
index 1255df88a..1162f185b 100644
--- a/components/execd/pkg/web/controller/sse.go
+++ b/components/execd/pkg/web/controller/sse.go
@@ -119,13 +119,7 @@ func (c *CodeInterpretingController) setServerEventsHandler(ctx context.Context)
}
},
OnExecuteComplete: func(executionTime time.Duration) {
- event := model.ServerStreamEvent{
- Type: model.StreamEventTypeComplete,
- ExecutionTime: executionTime.Milliseconds(),
- Timestamp: time.Now().UnixMilli(),
- }
- payload := event.ToJSON()
- c.writeSingleEvent("OnExecuteComplete", payload, true, event.Summary())
+ c.writeExecutionComplete(executionTime, nil)
},
OnExecuteError: func(err *execute.ErrorOutput) {
if err == nil {
@@ -184,6 +178,16 @@ func (c *CodeInterpretingController) setServerEventsHandler(ctx context.Context)
return hooks, stopSSE
}
+func (c *CodeInterpretingController) writeExecutionComplete(executionTime time.Duration, exitCode *int) {
+ event := model.ServerStreamEvent{
+ Type: model.StreamEventTypeComplete,
+ ExecutionTime: executionTime.Milliseconds(),
+ ExitCode: exitCode,
+ Timestamp: time.Now().UnixMilli(),
+ }
+ c.writeSingleEvent("OnExecuteComplete", event.ToJSON(), true, event.Summary())
+}
+
func (c *basicController) writeSingleEvent(handler string, data []byte, verbose bool, summary string) {
if c == nil || c.ctx == nil || c.ctx.Writer == nil {
return
diff --git a/components/execd/pkg/web/model/codeinterpreting.go b/components/execd/pkg/web/model/codeinterpreting.go
index 845eaa92b..c8138d276 100644
--- a/components/execd/pkg/web/model/codeinterpreting.go
+++ b/components/execd/pkg/web/model/codeinterpreting.go
@@ -134,6 +134,7 @@ type ServerStreamEvent struct {
Type ServerStreamEventType `json:"type,omitempty"`
Text string `json:"text,omitempty"`
ExecutionCount int `json:"execution_count,omitempty"`
+ ExitCode *int `json:"exit_code,omitempty"`
ExecutionTime int64 `json:"execution_time,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"`
Results map[string]any `json:"results,omitempty"`
diff --git a/docs/architecture/data-plane/execd.md b/docs/architecture/data-plane/execd.md
index 7ae988c1a..f402e47be 100644
--- a/docs/architecture/data-plane/execd.md
+++ b/docs/architecture/data-plane/execd.md
@@ -58,6 +58,8 @@ Execution modes:
Foreground `stdout` and `stderr` event text preserves the command's line endings (`\n`, `\r`, or `\r\n`). Concatenate event text for each stream to reconstruct its output; the last event may be an unterminated fragment.
+A successful foreground `POST /command` ends with `execution_complete` carrying `exit_code: 0`. This optional field is omitted from background startup acknowledgements and code execution events; absence is not an exit status. Non-zero command exits retain `error.exit_code` on the `error` event. Older execd versions omit the successful exit code, so clients may retain their existing foreground-only completion inference. A stream that ends before a terminal event does not establish success.
+
Sessions use Bash when the image provides it and fall back to POSIX `sh` on minimal images — commands sent to a fallback session must be `sh`-compatible. Windows sandboxes are supported (environment names are case-insensitive; batch files require shell syntax).
## Code execution
diff --git a/sdks/sandbox/javascript/src/api/execd.ts b/sdks/sandbox/javascript/src/api/execd.ts
index 91624b768..f62c8fddf 100644
--- a/sdks/sandbox/javascript/src/api/execd.ts
+++ b/sdks/sandbox/javascript/src/api/execd.ts
@@ -1420,6 +1420,11 @@ export interface components {
* @example 1
*/
execution_count?: number;
+ /**
+ * @description Successful foreground POST /command process exit status (0), present only on its execution_complete event after the process has exited. Omitted for background startup acknowledgements, code execution, and other events. Absence does not imply success; older servers omit this field. Non-zero command exits use error.exit_code instead.
+ * @example 0
+ */
+ exit_code?: number;
/**
* Format: int64
* @description Execution duration in milliseconds
diff --git a/sdks/sandbox/javascript/tests/commands.run.test.mjs b/sdks/sandbox/javascript/tests/commands.run.test.mjs
index e3b217b3b..b89bafde0 100644
--- a/sdks/sandbox/javascript/tests/commands.run.test.mjs
+++ b/sdks/sandbox/javascript/tests/commands.run.test.mjs
@@ -35,23 +35,25 @@ function createAdapter(responseBody, opts = {}) {
);
}
-test("CommandsAdapter.run populates complete and exitCode for successful foreground commands", async () => {
- const adapter = createAdapter(
- [
- 'data: {"type":"init","text":"cmd-1","timestamp":1}',
- 'data: {"type":"stdout","text":"hi","timestamp":2}',
- 'data: {"type":"execution_complete","timestamp":3,"execution_time":4}',
- "",
- ].join("\n"),
- );
+for (const explicitExitCode of [false, true]) {
+ test(`CommandsAdapter.run populates complete and exitCode for successful foreground commands (explicit exit code: ${explicitExitCode})`, async () => {
+ const adapter = createAdapter(
+ [
+ 'data: {"type":"init","text":"cmd-1","timestamp":1}',
+ 'data: {"type":"stdout","text":"hi","timestamp":2}',
+ `data: ${JSON.stringify({ type: "execution_complete", timestamp: 3, execution_time: 4, ...(explicitExitCode ? { exit_code: 0 } : {}) })}`,
+ "",
+ ].join("\n"),
+ );
- const execution = await adapter.run("echo hi");
+ const execution = await adapter.run("echo hi");
- assert.equal(execution.id, "cmd-1");
- assert.equal(execution.logs.stdout[0].text, "hi");
- assert.equal(execution.complete?.executionTimeMs, 4);
- assert.equal(execution.exitCode, 0);
-});
+ assert.equal(execution.id, "cmd-1");
+ assert.equal(execution.logs.stdout[0].text, "hi");
+ assert.equal(execution.complete?.executionTimeMs, 4);
+ assert.equal(execution.exitCode, 0);
+ });
+}
test("CommandsAdapter.run infers non-zero exitCode from final error state", async () => {
const adapter = createAdapter(
diff --git a/sdks/sandbox/python/src/opensandbox/api/execd/models/server_stream_event.py b/sdks/sandbox/python/src/opensandbox/api/execd/models/server_stream_event.py
index a67547b94..c2cf20596 100644
--- a/sdks/sandbox/python/src/opensandbox/api/execd/models/server_stream_event.py
+++ b/sdks/sandbox/python/src/opensandbox/api/execd/models/server_stream_event.py
@@ -42,6 +42,10 @@ class ServerStreamEvent:
text (str | Unset): Textual data for status, init, and stream events Example: Hello, World!
.
execution_count (int | Unset): Cell execution number in the session Example: 1.
+ exit_code (int | Unset): Successful foreground POST /command process exit status (0), present only on its
+ execution_complete event after the process has exited. Omitted for background startup acknowledgements, code
+ execution, and other events. Absence does not imply success; older servers omit this field. Non-zero command
+ exits use error.exit_code instead.
execution_time (int | Unset): Execution duration in milliseconds Example: 150.
timestamp (int | Unset): When the event was generated (Unix milliseconds) Example: 1700000000000.
results (ServerStreamEventResults | Unset): Execution output in various MIME types (e.g., "text/plain",
@@ -52,6 +56,7 @@ class ServerStreamEvent:
type_: ServerStreamEventType | Unset = UNSET
text: str | Unset = UNSET
execution_count: int | Unset = UNSET
+ exit_code: int | Unset = UNSET
execution_time: int | Unset = UNSET
timestamp: int | Unset = UNSET
results: ServerStreamEventResults | Unset = UNSET
@@ -67,6 +72,8 @@ class ServerStreamEvent:
execution_count = self.execution_count
+ exit_code = self.exit_code
+
execution_time = self.execution_time
timestamp = self.timestamp
@@ -88,6 +95,8 @@ class ServerStreamEvent:
field_dict["text"] = text
if execution_count is not UNSET:
field_dict["execution_count"] = execution_count
+ if exit_code is not UNSET:
+ field_dict["exit_code"] = exit_code
if execution_time is not UNSET:
field_dict["execution_time"] = execution_time
if timestamp is not UNSET:
@@ -116,6 +125,8 @@ class ServerStreamEvent:
execution_count = d.pop("execution_count", UNSET)
+ exit_code = d.pop("exit_code", UNSET)
+
execution_time = d.pop("execution_time", UNSET)
timestamp = d.pop("timestamp", UNSET)
@@ -138,6 +149,7 @@ class ServerStreamEvent:
type_=type_,
text=text,
execution_count=execution_count,
+ exit_code=exit_code,
execution_time=execution_time,
timestamp=timestamp,
results=results,
diff --git a/sdks/sandbox/python/tests/test_command_service_adapter_streaming.py b/sdks/sandbox/python/tests/test_command_service_adapter_streaming.py
index 8d63b2505..9dfc96c9e 100644
--- a/sdks/sandbox/python/tests/test_command_service_adapter_streaming.py
+++ b/sdks/sandbox/python/tests/test_command_service_adapter_streaming.py
@@ -48,7 +48,8 @@ LITERAL_ARGV = [
class _SseTransport(httpx.AsyncBaseTransport):
- def __init__(self) -> None:
+ def __init__(self, explicit_exit_code: bool = False) -> None:
+ self.explicit_exit_code = explicit_exit_code
self.last_request: httpx.Request | None = None
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
@@ -65,6 +66,8 @@ class _SseTransport(httpx.AsyncBaseTransport):
b'data: {"type":"result","results":{"text":"ok"},"timestamp":3}\n\n'
b'data: {"type":"execution_complete","timestamp":4,"execution_time":5}\n\n'
)
+ if self.explicit_exit_code:
+ sse = sse.replace(b'"execution_time":5}', b'"execution_time":5,"exit_code":0}')
return httpx.Response(
200,
headers={"Content-Type": "text/event-stream"},
@@ -164,8 +167,9 @@ class _SseTransport(httpx.AsyncBaseTransport):
@pytest.mark.asyncio
-async def test_run_command_streaming_happy_path_updates_execution() -> None:
- transport = _SseTransport()
[email protected]("explicit_exit_code", [False, True])
+async def test_run_command_streaming_happy_path_updates_execution(explicit_exit_code: bool) -> None:
+ transport = _SseTransport(explicit_exit_code)
cfg = ConnectionConfig(protocol="http", transport=transport)
endpoint = SandboxEndpoint(endpoint="localhost:44772", port=44772)
adapter = CommandsAdapter(cfg, endpoint)
@@ -543,3 +547,13 @@ async def test_error_exit_code_propagates_to_execution(
assert execution.error.exit_code == expected_error_exit_code
assert execution.exit_code == expected_exit_code
assert execution.complete is None
+
+
+def test_server_stream_event_preserves_optional_zero_exit_code() -> None:
+ from opensandbox.api.execd.models.server_stream_event import ServerStreamEvent
+
+ explicit = ServerStreamEvent.from_dict({"type": "execution_complete", "exit_code": 0})
+ assert explicit.exit_code == 0
+ assert explicit.to_dict()["exit_code"] == 0
+ legacy = ServerStreamEvent.from_dict({"type": "execution_complete"})
+ assert "exit_code" not in legacy.to_dict()
diff --git a/sdks/sandbox/python/tests/test_sync_command_service_adapter_streaming.py b/sdks/sandbox/python/tests/test_sync_command_service_adapter_streaming.py
index af25195df..863acbf18 100644
--- a/sdks/sandbox/python/tests/test_sync_command_service_adapter_streaming.py
+++ b/sdks/sandbox/python/tests/test_sync_command_service_adapter_streaming.py
@@ -44,7 +44,8 @@ LITERAL_ARGV = [
class _SseTransport(httpx.BaseTransport):
- def __init__(self) -> None:
+ def __init__(self, explicit_exit_code: bool = False) -> None:
+ self.explicit_exit_code = explicit_exit_code
self.last_request: httpx.Request | None = None
def handle_request(self, request: httpx.Request) -> httpx.Response:
@@ -58,6 +59,8 @@ class _SseTransport(httpx.BaseTransport):
b'data: {"type":"stdout","text":"hi","timestamp":2}\n\n'
b'data: {"type":"execution_complete","timestamp":4,"execution_time":5}\n\n'
)
+ if self.explicit_exit_code:
+ sse = sse.replace(b'"execution_time":5}', b'"execution_time":5,"exit_code":0}')
return httpx.Response(
200,
headers={"Content-Type": "text/event-stream"},
@@ -178,8 +181,9 @@ def test_sync_run_command_rejects_negative_timeout(timeout: timedelta) -> None:
adapter.run("pwd", opts=RunCommandOpts(timeout=timeout))
-def test_sync_run_command_streaming_happy_path_updates_execution() -> None:
- cfg = ConnectionConfigSync(protocol="http", transport=_SseTransport())
[email protected]("explicit_exit_code", [False, True])
+def test_sync_run_command_streaming_happy_path_updates_execution(explicit_exit_code: bool) -> None:
+ cfg = ConnectionConfigSync(protocol="http", transport=_SseTransport(explicit_exit_code))
endpoint = SandboxEndpoint(endpoint="localhost:44772", port=44772)
adapter = CommandsAdapterSync(cfg, endpoint)
diff --git a/specs/execd-api.yaml b/specs/execd-api.yaml
index 493710fa3..b84e9acea 100644
--- a/specs/execd-api.yaml
+++ b/specs/execd-api.yaml
@@ -2733,6 +2733,10 @@ components:
type: integer
description: Cell execution number in the session
example: 1
+ exit_code:
+ type: integer
+ description: "Successful foreground POST /command process exit status (0), present only on its execution_complete event after the process has exited. Omitted for background startup acknowledgements, code execution, and other events. Absence does not imply success; older servers omit this field. Non-zero command exits use error.exit_code instead."
+ example: 0
execution_time:
type: integer
format: int64