Secure, Fast, and Extensible Sandbox runtime for AI agents.
refactor(sdks/js): share exit-code inference and tighten exit_code tests
BootstrapperSBL1c99f1bf6e1a
diff --git a/sdks/sandbox/javascript/src/adapters/commandsAdapter.ts b/sdks/sandbox/javascript/src/adapters/commandsAdapter.tsindex 477c19252..41f668c13 100644--- a/sdks/sandbox/javascript/src/adapters/commandsAdapter.ts+++ b/sdks/sandbox/javascript/src/adapters/commandsAdapter.ts@@ -25,6 +25,7 @@ import type {} from "../models/execd.js";import type { ExecdCommands } from "../services/execdCommands.js";import type { ExecutionHandlers } from "../models/execution.js";+import { inferExecutionExitCode } from "../models/execution.js";import { ExecutionEventDispatcher } from "../models/executionEventDispatcher.js";function joinUrl(baseUrl: string, pathname: string): string {@@ -92,21 +93,6 @@ function toRunInSessionRequest(return body;}-function inferForegroundExitCode(execution: CommandExecution): number | null {- // Prefer the authoritative `error.exit_code`; fall back to parsing `evalue` for older servers.- if (typeof execution.error?.exitCode === "number") {- return execution.error.exitCode;- }- const errorValue = execution.error?.value?.trim();- const parsedExitCode =- errorValue && /^-?\d+$/.test(errorValue) ? Number(errorValue) : Number.NaN;- return execution.error != null- ? (Number.isFinite(parsedExitCode) ? parsedExitCode : null)- : execution.complete- ? 0- : null;-}-function assertNonBlank(value: string, field: string): void {if (!value.trim()) {throw new Error(`${field} cannot be empty`);@@ -272,7 +258,7 @@ export class CommandsAdapter implements ExecdCommands {}if (inferExitCode) {- execution.exitCode = inferForegroundExitCode(execution);+ execution.exitCode = inferExecutionExitCode(execution);}return execution;diff --git a/sdks/sandbox/javascript/src/adapters/isolatedSessionsAdapter.ts b/sdks/sandbox/javascript/src/adapters/isolatedSessionsAdapter.tsindex 9c7a5b0c4..8d4b4fd3a 100644--- a/sdks/sandbox/javascript/src/adapters/isolatedSessionsAdapter.ts+++ b/sdks/sandbox/javascript/src/adapters/isolatedSessionsAdapter.ts@@ -18,6 +18,7 @@ import { parseJsonEventStream } from "./sse.js";import type { components as ExecdComponents } from "../api/execd.js";import type { CommandExecution, ServerStreamEvent } from "../models/execd.js";import type { ExecutionHandlers } from "../models/execution.js";+import { inferExecutionExitCode } from "../models/execution.js";import { ExecutionEventDispatcher } from "../models/executionEventDispatcher.js";import type { SandboxFiles } from "../services/filesystem.js";import type {@@ -58,21 +59,6 @@ function utf8ByteLength(text: string): number {return new TextEncoder().encode(text).byteLength;}-function inferExitCode(execution: CommandExecution): number | null {- // Prefer the authoritative `error.exit_code`; fall back to parsing `evalue` for older servers.- if (typeof execution.error?.exitCode === "number") {- return execution.error.exitCode;- }- const errorValue = execution.error?.value?.trim();- const parsedExitCode =- errorValue && /^-?\d+$/.test(errorValue) ? Number(errorValue) : Number.NaN;- return execution.error != null- ? (Number.isFinite(parsedExitCode) ? parsedExitCode : null)- : execution.complete- ? 0- : null;-}-export interface IsolatedSessionsAdapterOptions {baseUrl: string;fetch?: typeof fetch;@@ -257,7 +243,7 @@ export class IsolatedSessionsAdapter implements IsolationService {await dispatcher.dispatch(ev as any);}- execution.exitCode = inferExitCode(execution);+ execution.exitCode = inferExecutionExitCode(execution);return execution;}diff --git a/sdks/sandbox/javascript/src/models/execution.ts b/sdks/sandbox/javascript/src/models/execution.tsindex 2a2d2455b..983a08253 100644--- a/sdks/sandbox/javascript/src/models/execution.ts+++ b/sdks/sandbox/javascript/src/models/execution.ts@@ -63,6 +63,40 @@ export interface Execution {exitCode?: number | null;}+/**+ * Normalizes a wire `error.exit_code` value. Only integers are accepted; anything else+ * (missing, non-numeric, fractional) yields `undefined` so callers fall back to `evalue`.+ *+ * @internal+ */+export function normalizeExitCode(value: unknown): number | undefined {+ return typeof value === "number" && Number.isInteger(value) ? value : undefined;+}++/**+ * Infers the final exit code of a foreground command execution.+ *+ * Prefers the authoritative `error.exitCode` (from `error.exit_code`) and falls back to+ * parsing `error.value` (`evalue`) for servers that predate `exit_code`. A completed+ * execution without an error is `0`; anything else is `null`.+ *+ * @internal+ */+export function inferExecutionExitCode(execution: Pick<Execution, "error" | "complete">): number | null {+ const error = execution.error;+ if (error != null) {+ const exitCode = normalizeExitCode(error.exitCode);+ if (exitCode !== undefined) {+ return exitCode;+ }+ const errorValue = error.value?.trim();+ const parsedExitCode =+ errorValue && /^-?\d+$/.test(errorValue) ? Number(errorValue) : Number.NaN;+ return Number.isFinite(parsedExitCode) ? parsedExitCode : null;+ }+ return execution.complete ? 0 : null;+}+export interface ExecutionHandlers {/*** Optional low-level hook for every server-sent event (SSE) received.diff --git a/sdks/sandbox/javascript/src/models/executionEventDispatcher.ts b/sdks/sandbox/javascript/src/models/executionEventDispatcher.tsindex 3686a1d5a..a7d925ec9 100644--- a/sdks/sandbox/javascript/src/models/executionEventDispatcher.ts+++ b/sdks/sandbox/javascript/src/models/executionEventDispatcher.ts@@ -13,6 +13,7 @@// limitations under the License.import type { Execution, ExecutionComplete, ExecutionError, ExecutionHandlers, ExecutionInit, ExecutionResult, OutputMessage } from "./execution.js";+import { normalizeExitCode } from "./execution.js";import type { ServerStreamEvent } from "./execd.js";function extractText(results: ServerStreamEvent["results"] | undefined): string | undefined {@@ -89,8 +90,9 @@ export class ExecutionEventDispatcher {timestamp: ts,traceback: Array.isArray(e.traceback) ? e.traceback.map(String) : [],};- if (typeof e.exit_code === "number" && Number.isInteger(e.exit_code)) {- err.exitCode = e.exit_code;+ const exitCode = normalizeExitCode(e.exit_code);+ if (exitCode !== undefined) {+ err.exitCode = exitCode;}this.execution.error = err;await this.handlers?.onError?.(err);diff --git a/sdks/sandbox/javascript/tests/commands.run.test.mjs b/sdks/sandbox/javascript/tests/commands.run.test.mjsindex 447e79295..e3b217b3b 100644--- a/sdks/sandbox/javascript/tests/commands.run.test.mjs+++ b/sdks/sandbox/javascript/tests/commands.run.test.mjs@@ -246,10 +246,11 @@ test("CommandsAdapter.runInSession infers non-zero exitCode from final error sta});test("CommandsAdapter.run propagates error.exit_code and prefers it over evalue", async () => {+ // evalue and exit_code deliberately disagree so the evalue fallback cannot satisfy the test.const adapter = createAdapter(['data: {"type":"init","text":"cmd-exit","timestamp":1}',- 'data: {"type":"error","error":{"ename":"CommandExecError","evalue":"3","traceback":["exit status 3"],"exit_code":3},"timestamp":2}',+ 'data: {"type":"error","error":{"ename":"CommandExecError","evalue":"9","traceback":["exit status 3"],"exit_code":3},"timestamp":2}',"",].join("\n"),);@@ -264,7 +265,7 @@ test("CommandsAdapter.run reports a signal kill (exit_code -1) as a failure", asconst adapter = createAdapter(['data: {"type":"init","text":"cmd-sig","timestamp":1}',- 'data: {"type":"error","error":{"ename":"CommandExecError","evalue":"-1","traceback":["signal: terminated"],"exit_code":-1},"timestamp":2}',+ 'data: {"type":"error","error":{"ename":"CommandExecError","evalue":"signal: terminated","traceback":["signal: terminated"],"exit_code":-1},"timestamp":2}',"",].join("\n"),);@@ -295,7 +296,7 @@ test("CommandsAdapter.runInSession propagates error.exit_code", async () => {const adapter = createAdapter(['data: {"type":"init","text":"sess-exit","timestamp":1}',- 'data: {"type":"error","error":{"ename":"CommandExecError","evalue":"-1","traceback":["signal: killed"],"exit_code":-1},"timestamp":2}',+ 'data: {"type":"error","error":{"ename":"CommandExecError","evalue":"signal: killed","traceback":["signal: killed"],"exit_code":-1},"timestamp":2}',"",].join("\n"),);@@ -306,6 +307,36 @@ test("CommandsAdapter.runInSession propagates error.exit_code", async () => {assert.equal(execution.exitCode, -1);});+test("CommandsAdapter.run ignores a non-integer exit_code and falls back to evalue", async () => {+ const adapter = createAdapter(+ [+ 'data: {"type":"init","text":"cmd-frac","timestamp":1}',+ 'data: {"type":"error","error":{"ename":"CommandExecError","evalue":"7","traceback":["exit status 7"],"exit_code":3.5},"timestamp":2}',+ "",+ ].join("\n"),+ );++ const execution = await adapter.run("exit 7");++ assert.equal(execution.error?.exitCode, undefined);+ assert.equal(execution.exitCode, 7);+});++test("CommandsAdapter.run ignores a string exit_code and leaves exitCode null without a numeric evalue", async () => {+ const adapter = createAdapter(+ [+ 'data: {"type":"init","text":"cmd-str","timestamp":1}',+ 'data: {"type":"error","error":{"ename":"CommandExecError","evalue":"signal: killed","traceback":["signal: killed"],"exit_code":"3"},"timestamp":2}',+ "",+ ].join("\n"),+ );++ const execution = await adapter.run("kill -KILL $$");++ assert.equal(execution.error?.exitCode, undefined);+ assert.equal(execution.exitCode, null);+});+test("execd client error message carries unstructured JSON error body", async () => {const adapter = new CommandsAdapter(createExecdClient({diff --git a/sdks/sandbox/javascript/tests/isolationRunOnce.test.mjs b/sdks/sandbox/javascript/tests/isolationRunOnce.test.mjsindex 7cd2893b7..433fdb1fc 100644--- a/sdks/sandbox/javascript/tests/isolationRunOnce.test.mjs+++ b/sdks/sandbox/javascript/tests/isolationRunOnce.test.mjs@@ -96,6 +96,122 @@ describe("runOnce", () => {});});+function mockFetchStreamingRun(sessionId, events) {+ return async (url, init) => {+ const urlStr = typeof url === "string" ? url : url.toString();+ const method = init?.method ?? "GET";+ if (method === "POST" && urlStr.includes("/run")) {+ const body = events.map((ev) => `data: ${JSON.stringify(ev)}\n\n`).join("");+ return new Response(body, {+ status: 200,+ headers: { "content-type": "text/event-stream" },+ });+ }+ if (method === "POST" && urlStr.includes("/v1/isolated/session")) {+ return new Response(+ JSON.stringify({ session_id: sessionId, created_at: "2026-01-01T00:00:00Z" }),+ { status: 201, headers: { "content-type": "application/json" } },+ );+ }+ if (method === "DELETE") {+ return new Response(null, { status: 204 });+ }+ return new Response("not found", { status: 404 });+ };+}++describe("isolated session run exit codes", () => {+ it("prefers error.exit_code over evalue", async () => {+ const adapter = createAdapter(+ mockFetchStreamingRun("sess-exit", [+ { type: "init", text: "run-1", timestamp: 1 },+ {+ type: "error",+ error: { ename: "CommandExecError", evalue: "9", traceback: ["exit status 3"], exit_code: 3 },+ timestamp: 2,+ },+ ]),+ );++ const execution = await adapter.runOnce("exit 3", "/workspace");++ assert.equal(execution.error?.exitCode, 3);+ assert.equal(execution.exitCode, 3);+ });++ it("reports a signal kill (exit_code -1) with a non-numeric evalue", async () => {+ const adapter = createAdapter(+ mockFetchStreamingRun("sess-sig", [+ {+ type: "error",+ error: { ename: "CommandExecError", evalue: "signal: killed", traceback: [], exit_code: -1 },+ timestamp: 1,+ },+ ]),+ );++ const execution = await adapter.runOnce("kill -KILL $$", "/workspace");++ assert.equal(execution.error?.exitCode, -1);+ assert.equal(execution.exitCode, -1);+ });++ it("leaves exitCode null for start failures without exit_code", async () => {+ const adapter = createAdapter(+ mockFetchStreamingRun("sess-start", [+ {+ type: "error",+ error: {+ ename: "CommandExecError",+ evalue: "fork/exec /bin/sh: argument list too long",+ traceback: ["fork/exec /bin/sh: argument list too long"],+ },+ timestamp: 1,+ },+ ]),+ );++ const execution = await adapter.runOnce("huge", "/workspace");++ assert.equal(execution.error?.exitCode, undefined);+ assert.equal(execution.exitCode, null);+ });++ it("falls back to evalue for legacy servers without exit_code", async () => {+ const adapter = createAdapter(+ mockFetchStreamingRun("sess-legacy", [+ {+ type: "error",+ error: { ename: "CommandExecError", evalue: "7", traceback: ["exit status 7"] },+ timestamp: 1,+ },+ ]),+ );++ const execution = await adapter.runOnce("exit 7", "/workspace");++ assert.equal(execution.error?.exitCode, undefined);+ assert.equal(execution.exitCode, 7);+ });++ it("ignores a non-integer exit_code", async () => {+ const adapter = createAdapter(+ mockFetchStreamingRun("sess-frac", [+ {+ type: "error",+ error: { ename: "CommandExecError", evalue: "signal: killed", traceback: [], exit_code: 3.5 },+ timestamp: 1,+ },+ ]),+ );++ const execution = await adapter.runOnce("exit", "/workspace");++ assert.equal(execution.error?.exitCode, undefined);+ assert.equal(execution.exitCode, null);+ });+});+describe("list", () => {it("returns the sessions array from the response", async () => {const calls = [];