Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(sdk-js): parse CR-delimited execution event streams
redyyang316ddd53c513
diff --git a/docs/sdks/javascript.md b/docs/sdks/javascript.mdindex 58b8d196a..e6cd515ed 100644--- a/docs/sdks/javascript.md+++ b/docs/sdks/javascript.md@@ -230,6 +230,8 @@ const sandbox = await Sandbox.create({Execute commands and handle output streams in real-time.+Command and code-interpreter event streams accept LF, CRLF, and CR line endings, including when a line ending is split across network chunks.+```tsimport type { ExecutionHandlers } from "@alibaba-group/opensandbox";diff --git a/sdks/code-interpreter/javascript/src/adapters/sse.ts b/sdks/code-interpreter/javascript/src/adapters/sse.tsindex 0471c15f4..c0ed00ce6 100644--- a/sdks/code-interpreter/javascript/src/adapters/sse.ts+++ b/sdks/code-interpreter/javascript/src/adapters/sse.ts@@ -60,7 +60,8 @@ export async function* parseJsonEventStream<T>(buf += decoder.decode(value, { stream: true });let idx: number;- while ((idx = buf.indexOf("\n")) >= 0) {+ // SSE permits CRLF, LF, and CR. Empty lines from a split CRLF are skipped below.+ while ((idx = buf.search(/[\r\n]/)) >= 0) {const rawLine = buf.slice(0, idx);buf = buf.slice(idx + 1);@@ -87,4 +88,4 @@ export async function* parseJsonEventStream<T>(const parsed = tryParseJson(jsonLine);if (parsed) yield parsed as T;}-}\ No newline at end of file+}diff --git a/sdks/code-interpreter/javascript/tests/sse.line-endings.test.mjs b/sdks/code-interpreter/javascript/tests/sse.line-endings.test.mjsnew file mode 100644index 000000000..8cbdfe9f7--- /dev/null+++ b/sdks/code-interpreter/javascript/tests/sse.line-endings.test.mjs@@ -0,0 +1,62 @@+// 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.++import assert from "node:assert/strict";+import test from "node:test";++import { DefaultAdapterFactory } from "../dist/index.js";++function eventResponse(ending, framed, fragmented) {+ const events = [+ { type: "init", text: "exec-line-endings", timestamp: 1 },+ { type: "stdout", text: "你好\r\n", timestamp: 2 },+ { type: "execution_complete", timestamp: 3, execution_time: 4, exit_code: 0 },+ ];+ const wire = events.map((event) => `${framed ? "data: " : ""}${JSON.stringify(event)}`)+ .join(ending + (framed ? ending : ""));+ const bytes = new TextEncoder().encode(wire);+ return new Response(new ReadableStream({+ start(controller) {+ if (fragmented) {+ // Split CRLF pairs, JSON tokens and UTF-8 characters across reads.+ for (let index = 0; index < bytes.length; index += 1) {+ controller.enqueue(bytes.subarray(index, index + 1));+ }+ } else {+ controller.enqueue(bytes);+ }+ controller.close();+ },+ }), { headers: { "content-type": framed ? "text/event-stream" : "application/x-ndjson" } });+}++for (const [name, ending] of [["LF", "\n"], ["CRLF", "\r\n"], ["CR", "\r"]]) {+ for (const framed of [true, false]) {+ for (const fragmented of [true, false]) {+ test(`CodesAdapter.run parses ${framed ? "SSE" : "NDJSON"} ${name} lines (${fragmented ? "byte chunks" : "one chunk"})`, async () => {+ const fetchImpl = async () => eventResponse(ending, framed, fragmented);+ const adapter = new DefaultAdapterFactory().createCodes({+ sandbox: { connectionConfig: { headers: {}, fetch: fetchImpl, sseFetch: fetchImpl } },+ execdBaseUrl: "http://sandbox.invalid",+ endpointHeaders: {},+ });+ const execution = await adapter.run("print(1)");++ assert.equal(execution.id, "exec-line-endings");+ assert.deepEqual(execution.logs.stdout.map((entry) => entry.text), ["你好\r\n"]);+ assert.equal(execution.complete?.executionTimeMs, 4);+ });+ }+ }+}diff --git a/sdks/sandbox/javascript/src/adapters/sse.ts b/sdks/sandbox/javascript/src/adapters/sse.tsindex ee9fea12a..d44105291 100644--- a/sdks/sandbox/javascript/src/adapters/sse.ts+++ b/sdks/sandbox/javascript/src/adapters/sse.ts@@ -63,7 +63,8 @@ export async function* parseJsonEventStream<T>(buf += decoder.decode(value, { stream: true });let idx: number;- while ((idx = buf.indexOf("\n")) >= 0) {+ // SSE permits CRLF, LF, and CR. Empty lines from a split CRLF are skipped below.+ while ((idx = buf.search(/[\r\n]/)) >= 0) {const rawLine = buf.slice(0, idx);buf = buf.slice(idx + 1);@@ -103,4 +104,4 @@ export async function* parseJsonEventStream<T>(await reader.cancel().catch(() => undefined);reader.releaseLock();}-}\ No newline at end of file+}diff --git a/sdks/sandbox/javascript/tests/sse.line-endings.test.mjs b/sdks/sandbox/javascript/tests/sse.line-endings.test.mjsnew file mode 100644index 000000000..b255119b4--- /dev/null+++ b/sdks/sandbox/javascript/tests/sse.line-endings.test.mjs@@ -0,0 +1,58 @@+// 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.++import assert from "node:assert/strict";+import test from "node:test";++import { CommandsAdapter } from "../dist/internal.js";++function eventResponse(ending, framed, fragmented) {+ const events = [+ { type: "init", text: "exec-line-endings", timestamp: 1 },+ { type: "stdout", text: "你好\r\n", timestamp: 2 },+ { type: "execution_complete", timestamp: 3, execution_time: 4, exit_code: 0 },+ ];+ const wire = events.map((event) => `${framed ? "data: " : ""}${JSON.stringify(event)}`)+ .join(ending + (framed ? ending : ""));+ const bytes = new TextEncoder().encode(wire);+ return new Response(new ReadableStream({+ start(controller) {+ if (fragmented) {+ // Split CRLF pairs, JSON tokens and UTF-8 characters across reads.+ for (let index = 0; index < bytes.length; index += 1) {+ controller.enqueue(bytes.subarray(index, index + 1));+ }+ } else {+ controller.enqueue(bytes);+ }+ controller.close();+ },+ }), { headers: { "content-type": framed ? "text/event-stream" : "application/x-ndjson" } });+}++for (const [name, ending] of [["LF", "\n"], ["CRLF", "\r\n"], ["CR", "\r"]]) {+ for (const framed of [true, false]) {+ for (const fragmented of [true, false]) {+ test(`CommandsAdapter.run parses ${framed ? "SSE" : "NDJSON"} ${name} lines (${fragmented ? "byte chunks" : "one chunk"})`, async () => {+ const fetchImpl = async () => eventResponse(ending, framed, fragmented);+ const adapter = new CommandsAdapter({}, { baseUrl: "http://sandbox.invalid", fetch: fetchImpl });+ const execution = await adapter.run("printf test");++ assert.equal(execution.id, "exec-line-endings");+ assert.deepEqual(execution.logs.stdout.map((entry) => entry.text), ["你好\r\n"]);+ assert.equal(execution.complete?.executionTimeMs, 4);+ });+ }+ }+}