执行命令与常驻后台任务
命令通过沙箱运行时进程 API 在沙箱内部执行。SDK 用户无需手动传 X-Access-Token,该 Token 来自 create/connect 响应。
执行前台命令
Section titled “执行前台命令”const result = await sandbox.commands.run("sh", { args: ["-lc", "pwd && ls -la /root/workspace"], timeoutMs: 30_000,});
console.log(result.exitCode, result.stdout, result.stderr);result = sandbox.commands.run( "sh", args=["-lc", "pwd && ls -la /root/workspace"], timeout_ms=30_000,)print(result["exit_code"], result["stdout"], result["stderr"])commands, _ := sbx.Commands()result, err := commands.Run(ctx, "sh", &sandbox.CommandRunOptions{ Args: []string{"-lc", "pwd && ls -la /root/workspace"},})启动后台服务
Section titled “启动后台服务”后台命令适合预览服务、Worker 或长运行任务。
const handle = await sandbox.commands.run("python3", { args: ["-m", "http.server", "3000", "--bind", "0.0.0.0", "--directory", "/root/workspace"], background: true,});
console.log("pid", handle.pid);console.log("open", sandbox.getHost(3000));原始 /run 契约
Section titled “原始 /run 契约”同步运行时 helper 接收命令 payload,并返回捕获的输出。
POST {envdUrl}/runX-Access-Token: <envdAccessToken>Content-Type: application/json{ "cmd": "sh", "args": ["-lc", "pwd && echo ok"], "cwd": "/root/workspace", "env": { "FOO": "bar" }, "timeoutMs": 30000, "stdin": ""}{ "stdout": "/root/workspace\nok\n", "stderr": "", "exit_code": 0, "duration_ms": 42}工作目录和环境变量
Section titled “工作目录和环境变量”await sandbox.commands.run("npm", { args: ["run", "start", "--", "--host", "0.0.0.0", "--port", "3000"], cwd: "/root/workspace/app", env: { NODE_ENV: "development" }, background: true,});| 字段 | 单位 | 说明 |
|---|---|---|
cwd | path | 命令启动目录。 |
env | map | 单个命令的环境变量覆盖。 |
timeoutMs | 毫秒 | 运行时命令预算。 |
background | boolean | 返回句柄,进程继续运行。 |
流式输出与 Process RPC
Section titled “流式输出与 Process RPC”运行时 Process API 包含 start、connect、stdin、signal、list 和 result 等流程。需要流式输出、交互式 stdin 或明确发送信号时,可使用更底层的进程接口。
POST /process.Process/StartX-Access-Token: <envdAccessToken>Connect-Protocol-Version: 1Content-Type: application/connect+json{ "process": { "cmd": "bash", "args": ["-lc", "ls -la"], "cwd": "/root/workspace" }, "tag": "inspect", "stdin": false}/process.Process/Start、/process.Process/Connect 和 /filesystem.Filesystem/WatchDir 是 Connect server-streaming 路由,应使用 Content-Type: application/connect+json。非流式 RPC 路由使用 Content-Type: application/json。
| 现象 | 原因 |
|---|---|
| 命令超时 | 运行时命令超时过短,需要增加 timeoutMs。 |
| 服务立即退出 | 启动命令失败或依赖安装未完成。 |
公网 URL 返回 502 | 服务未监听目标端口,或只绑定 127.0.0.1。 |
sh not found | 模板镜像不包含 /bin/sh,需换模板或改命令。 |