
OpenSandbox Code Interpreter JavaScript/TypeScript SDK 实战在安全沙箱中运行 Python、Java、Go 代码【免费下载链接】OpenSandboxSecure, Fast, and Extensible Sandbox runtime for AI agents.项目地址: https://gitcode.com/GitHub_Trending/ope/OpenSandbox本指南以 OpenSandbox 官方alibaba-group/opensandbox-code-interpreterJavaScript/TypeScript 版为核心讲解如何在安全的隔离沙箱中编写、运行和管理多语言代码。读完本文你将掌握 SDK 的安装方式、Sandbox与CodeInterpreter的组合使用、语言版本选择、执行上下文管理以及流式输出处理并能结合仓库源码理解其健康检查与 SSE 通信的底层原理。SDK 是什么面向 AI Agent 的多语言代码执行层OpenSandbox 是一个面向 AI Agent 的安全、快速、可扩展沙箱运行时。Code Interpreter SDK 在其之上提供了一层开箱即用的多语言代码执行 API你不再需要手动处理容器编排、端口转发或运行时进程管理只需传入一段代码即可在隔离环境中以 Python、Java、Go、TypeScript 等语言安全执行。JavaScript/TypeScript 版 SDK 是官方多语言 SDK 家族的一员与 Python、Kotlin、C#/.NET、Go 版本能力对齐README 明确说明上下文管理 API 与 Python/Kotlin SDK 保持一致。从源码结构看它整体构建在通用 alibaba-group/opensandbox 基础 SDK 之上复用其Sandbox、ConnectionConfig、流式事件与传输能力从而获得一致的连接与生命周期语义。前置条件理解镜像与运行时依赖SDK 本身并不内置语言运行时它需要一个包含 Code Interpreter 运行时环境的 Docker 镜像。必须使用opensandbox/code-interpreter镜像或其衍生镜像该镜像预装了 Python、Java、Go、Node.js 等语言的运行时。以下几点是实际使用的前提镜像可用性确保你的沙箱提供方如 OpenSandbox 服务端已具备opensandbox/code-interpreter镜像。基础 SDK 依赖package.json中声明了对alibaba-group/opensandboxworkspace 依赖的引用安装时会被一并拉取。Node.js 版本package.json的engines字段要求node 20仓库使用 pnpm 管理packageManager: pnpm9.15.0。关于镜像的更多信息历史版本中镜像构建产物位于 OpenSandbox monorepo 内现已迁移至独立的 sandbox-images 仓库管理但镜像名称、v1.1.0等已有标签、启动路径与语言版本环境变量完全兼容参见 code-interpreter-image-migration。重要运行示例前请确保 OpenSandbox 服务已启动详见仓库根目录 README.md 的启动说明。安装 SDK使用你习惯的包管理器安装即可# npm npm install alibaba-group/opensandbox-code-interpreter # pnpm pnpm add alibaba-group/opensandbox-code-interpreter # yarn yarn add alibaba-group/opensandbox-code-interpreter包名为alibaba-group/opensandbox-code-interpreter当前版本0.1.4遵循 Apache-2.0 协议ESM 格式同时提供import与require两种入口见 package.json。快速开始创建沙箱并运行 Python 代码核心思路分三步配置连接 → 创建带运行时镜像的 Sandbox → 用 CodeInterpreter 包装并执行代码。完整示例import { ConnectionConfig, Sandbox } from alibaba-group/opensandbox; import { CodeInterpreter, SupportedLanguages } from alibaba-group/opensandbox-code-interpreter; // 1. Configure connection const config new ConnectionConfig({ domain: api.opensandbox.io, apiKey: your-api-key, }); // 2. Create a Sandbox with the code-interpreter image runtime versions const sandbox await Sandbox.create({ connectionConfig: config, image: opensandbox/code-interpreter:v1.1.0, entrypoint: [/opt/code-interpreter/code-interpreter.sh], env: { PYTHON_VERSION: 3.11, JAVA_VERSION: 17, NODE_VERSION: 20, GO_VERSION: 1.24, }, timeoutSeconds: 15 * 60, }); // 3. Create CodeInterpreter wrapper const ci await CodeInterpreter.create(sandbox); // 4. Create an execution context (Python) const ctx await ci.codes.createContext(SupportedLanguages.PYTHON); // 5. Run code const result await ci.codes.run(import sys\nprint(sys.version)\nresult 2 2\nresult, { context: ctx, }); // 6. Print output console.log(result.result[0]?.text); // 7. Cleanup remote instance (optional but recommended) await sandbox.kill(); await sandbox.close();各步骤要点ConnectionConfig声明服务端地址domain与鉴权凭证apiKeyCodeInterpreter 会复用该配置建立 execd 客户端。Sandbox.create指定镜像opensandbox/code-interpreter:v1.1.0、入口脚本/opt/code-interpreter/code-interpreter.sh以及各语言版本环境变量timeoutSeconds控制沙箱的总体超时。CodeInterpreter.create(sandbox)包装已有Sandbox实例内部通过sandbox.getEndpoint(DEFAULT_EXECD_PORT)获取 execd 端点默认执行严格健康检查就绪后才返回详见下文健康检查原理。ci.codes.run返回的Execution中result[0]?.text即最后一条结果输出。清理sandbox.kill()销毁远端实例sandbox.close()释放本地连接资源推荐在结束前调用。运行时配置镜像与语言版本选择Docker 镜像SDK 依赖专用环境镜像请确认沙箱提供方拥有opensandbox/code-interpreter镜像。镜像的启动入口固定为/opt/code-interpreter/code-interpreter.sh该路径在镜像迁移后保持不变。语言版本选择通过Sandbox.create时的env环境变量指定各语言版本未设置时使用镜像默认版本。语言环境变量示例值未设置时默认值PythonPYTHON_VERSION3.11镜像默认JavaJAVA_VERSION17镜像默认Node.jsNODE_VERSION20镜像默认GoGO_VERSION1.24镜像默认只指定需要固定版本的语言即可const sandbox await Sandbox.create({ connectionConfig: config, image: opensandbox/code-interpreter:v1.1.0, entrypoint: [/opt/code-interpreter/code-interpreter.sh], env: { JAVA_VERSION: 17, GO_VERSION: 1.24, }, });使用示例详解0. 使用language参数默认语言上下文如果不需要管理显式的上下文 ID可以直接传language运行代码。当context.id省略时execd 会为该语言创建/复用默认会话因此状态可以跨多次运行持久保留import { SupportedLanguages } from alibaba-group/opensandbox-code-interpreter; await ci.codes.run(x 42, { language: SupportedLanguages.PYTHON }); const execution await ci.codes.run(result x\nresult, { language: SupportedLanguages.PYTHON }); console.log(execution.result[0]?.text); // 42从实现看codes.run允许context与language二者择一同时传入会抛出InvalidArgumentException两者都省略时默认使用python见 codesAdapter.ts 的缺省逻辑。0.1 上下文管理list/get/delete显式管理上下文与 Python/Kotlin SDK 行为对齐const ctx await ci.codes.createContext(SupportedLanguages.PYTHON); const same await ci.codes.getContext(ctx.id!); console.log(same.id, same.language); const all await ci.codes.listContexts(); const pyOnly await ci.codes.listContexts(SupportedLanguages.PYTHON); await ci.codes.deleteContext(ctx.id!); await ci.codes.deleteContexts(SupportedLanguages.PYTHON); // bulk cleanupCodes接口见 services/codes.ts完整提供以下能力底层均映射为 execd 的 REST 接口方法说明底层 HTTP 接口createContext(language)创建执行上下文POST /code/contextgetContext(contextId)按 ID 查询上下文GET /code/contexts/{context_id}listContexts(language?)列出上下文可按语言过滤GET /code/contextsdeleteContext(contextId)删除单个上下文DELETE /code/contexts/{context_id}deleteContexts(language)按语言批量删除DELETE /code/contexts?language...interrupt(contextId)中断进行中的代码执行DELETE /code?id...run(...)/runStream(...)执行代码一次性/流式POST /codeSSEping(signal?)可选execd 存活探测GET /ping上述映射关系已由 contexts.test.mjs 测试用例逐条验证测试断言了每个方法对应的 method URL 组合。SupportedLanguages常量定义于 models.tsPYTHON、JAVA、GO、TYPESCRIPT、JAVASCRIPT、BASH对应小写字符串值python、java、go、typescript、javascript、bash。1. Java 代码执行与 Python 类似创建 Java 上下文后执行一段多行 Java 代码import { SupportedLanguages } from alibaba-group/opensandbox-code-interpreter; const javaCtx await ci.codes.createContext(SupportedLanguages.JAVA); const execution await ci.codes.run( [ System.out.println(Calculating sum...);, int a 10;, int b 20;, int sum a b;, System.out.println(Sum: sum);, sum, ].join(\n), { context: javaCtx }, ); console.log(execution.logs.stdout.map((m) m.text));这里execution.logs.stdout保存了标准输出消息数组m.text为每条输出的文本内容与 Python SDK 中的语义一致。2. 流式输出处理通过ExecutionHandlers实时接收 stdout/stderr 与结果事件适合需要边执行边展示进度的场景如 Agent 逐步推理import type { ExecutionHandlers } from alibaba-group/opensandbox; import { SupportedLanguages } from alibaba-group/opensandbox-code-interpreter; const handlers: ExecutionHandlers { onStdout: (m) console.log(STDOUT:, m.text), onStderr: (m) console.error(STDERR:, m.text), onResult: (r) console.log(RESULT:, r.text), }; const pyCtx await ci.codes.createContext(SupportedLanguages.PYTHON); await ci.codes.run(import time\nfor i in range(5):\n print(i)\n time.sleep(0.2), { context: pyCtx, handlers, });源码级原理SDK 的分层与执行链路要真正用好这个 SDK理解其内部架构大有裨益。从源码结构看SDK 分为四层门面层CodeInterpreterinterpreter.ts包装Sandbox对外暴露codes、files、commands、metrics四个访问器后三者与底层Sandbox是同一实例便于在同一沙箱内组合文件操作与命令执行。服务层Codesservices/codes.ts定义上下文管理与代码执行的接口契约。适配层CodesAdapteradapters/codesAdapter.ts把接口翻译为对 execd 的 HTTP/SSE 调用并把流式事件汇聚成结构化的Execution对象。工厂层DefaultAdapterFactoryfactory/defaultAdapterFactory.ts负责创建 execd 客户端将connectionConfig.headers与端点级endpointHeaders合并后注入每次请求。执行链路可概括为ci.codes.run(code, opts)→ 构造RunCodeRequestcode context→ 通过fetch向POST {execdBaseUrl}/code发起请求携带accept: text/event-stream→ 由parseJsonEventStream逐帧解析 SSE 事件 →ExecutionEventDispatcher一边写入execution.logs/result一边触发handlers回调见 codesAdapter.ts。SSE 解析器adapters/sse.ts同时兼容两种帧格式标准 SSE 的data: {...}前缀以及每行一个 JSON 对象的换行分隔格式对于非 2xx 响应会从响应体尝试提取错误信息并包装为SandboxApiException附带x-request-id便于排查。流式请求使用connectionConfig.sseFetch与 Python/Kotlin SDK 对齐普通请求使用connectionConfig.fetch。健康检查为什么CodeInterpreter.create有时会等待CodeInterpreter.create默认执行严格双重健康检查可通过skipHealthCheck: true跳过execd 守护进程探测GET /ping优先走codes.ping能力若自定义适配器未实现则回退为基于连接配置直接探测 execd/ping。解释器运行时就绪探测通过沙箱命令 API 执行bash -c exec 3/dev/tcp/127.0.0.1/${JUPYTER_PORT:-44771}确认 Jupyter kernel gateway 真的在监听端口。注释中解释了为何要如此严格execd 在入口脚本启动 Jupyter 之前就会先服务/ping而 setup 阶段还会运行短暂的jupyter kernelspec辅助进程因此仅靠守护进程 ping 或进程名 grep 都无法证明运行时已就绪只有探测 Jupyter 监听端口默认127.0.0.1:44771与入口脚本默认一致通过才算真正可用。轮询参数可在CodeInterpreter.create的选项中配置见 interpreter.ts选项类型默认值说明skipHealthCheckbooleanfalse跳过严格就绪检查execd 尚未就绪时首次使用可能失败readyTimeoutSecondsnumber基础 SDK 的DEFAULT_READY_TIMEOUT_SECONDS等待就绪的最长秒数超时抛出SandboxReadyTimeoutExceptionhealthCheckPollingIntervalnumber基础 SDK 的DEFAULT_HEALTH_CHECK_POLLING_INTERVAL_MILLIS健康检查轮询间隔毫秒signalAbortSignal无用于取消健康检查等待轮询实现会按剩余预算收敛休眠时间避免最后一次失败检查超出总超时过多整个机制的正确性由 interpreter.healthcheck.test.mjs 覆盖包括运行时端口未监听时抛超时ping 失败不触发运行时探测设置 skipHealthCheck 后完全跳过检查等场景。健康检查依赖的 execd 端口常量DEFAULT_EXECD_PORT来自基础 SDK端点级请求头会通过getEndpoint透传见 interpreter.headers.test.mjs。连接与请求头的合并策略DefaultAdapterFactory.createCodes会把两层请求头合并后发给 execdconst headers: Recordstring, string { ...(opts.sandbox.connectionConfig.headers ?? {}), ...(opts.endpointHeaders ?? {}), };即连接级全局请求头 端点级动态请求头端点级优先。测试 contexts.test.mjs 断言了每次请求都同时携带x-global与x-endpoint两个头说明端点鉴权头不会因复用连接而被丢弃——这是多租户/多沙箱场景下保证请求命中正确目标的关键细节。注意事项与最佳实践生命周期CodeInterpreter包装已有Sandbox实例并复用其连接配置。每个沙箱实例会通过ConnectionConfig.withTransportIfMissing()克隆传输层因此使用完毕后务必调用sandbox.close()释放 Node.js 的 keep-alive agent避免连接泄漏。默认上下文codes.run(..., { language })使用语言默认上下文状态可跨多次运行持久保留需要隔离状态时请显式createContext。参数校验run要求代码非空context与language不能同时提供均会抛出InvalidArgumentException。超时配置推荐像快速开始示例那样为沙箱设置合理的timeoutSeconds防止长时间运行的任务占用远端资源。测试与版本本包通过node --test运行测试构建产物在dist/测试文件为 contexts.test.mjs、interpreter.headers.test.mjs、interpreter.healthcheck.test.mjs可作为自定义适配器与请求头行为的参考实现。参考资源SDK 源码与结构sdks/code-interpreter/javascript核心门面实现interpreter.ts代码执行服务契约services/codes.ts语言常量与上下文模型models.ts基础 SDKSandbox/ConnectionConfigsdks/sandbox/javascript/README.md代码解释器镜像迁移说明镜像路径、环境变量兼容性docs/reference/code-interpreter-image-migration.md仓库根 READMEOpenSandbox 服务启动方式README.md【免费下载链接】OpenSandboxSecure, Fast, and Extensible Sandbox runtime for AI agents.项目地址: https://gitcode.com/GitHub_Trending/ope/OpenSandbox创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考