跳转到内容
返回主页

创建首个沙箱

本快速开始会从 base 创建一个沙箱,写入文件,执行 shell 命令,打印结果,并删除沙箱。

你需要:

  • 一个具备创建沙箱权限的 SeaCloud API Key。
  • 目标环境中可访问 base 官方模板。
  • 本地已安装 Node.js、Python 或 Go。
  • 运行环境可以访问 https://sandbox-gateway.cloud.seaart.ai

创建 SeaCloud API Key 后,在 shell 或运行时密钥管理中配置 Gateway 地址和 Token。

Terminal window
export SEACLOUD_BASE_URL="https://sandbox-gateway.cloud.seaart.ai"
export SEACLOUD_API_KEY="YOUR_API_KEY"
Terminal window
npm install @seacloudai/sandbox
import { Sandbox } from "@seacloudai/sandbox";
const sandbox = await Sandbox.create("base", {
waitReady: true,
timeout: 1800,
});
try {
await sandbox.files.write("/root/workspace/hello.txt", "hello from node\n");
const run = await sandbox.commands.run("sh", {
args: ["-lc", "pwd && cat /root/workspace/hello.txt"],
});
console.log(run.exitCode, run.stdout);
} finally {
await sandbox.delete();
}

命令应打印退出码 0,并输出类似内容:

/root/workspace
hello from node

不同语言的 stdout 包装可能不同,但成功运行应满足三个条件:

  1. 沙箱进入 running
  2. /root/workspace/hello.txt 文件可读取。
  3. delete() 清理时没有生命周期错误。
步骤API 表面
创建沙箱SDK 内部调用 POST /api/v1/sandboxes
等待就绪waitReady: true 等待运行时 API 可用
写入文件sandbox.files 背后的运行时文件系统 API
执行命令sandbox.commands 背后的运行时进程 API
删除沙箱sandbox.delete() 内部调用 DELETE /api/v1/sandboxes/:sandboxID
现象检查项
401403SEACLOUD_API_KEY 是否存在、有效,并属于目标项目。
template not found在目标环境列出官方模板,确认 base 可见。
沙箱等待过久增加生命周期 timeout;查询沙箱详情中的 timelinediagnostic
缺少运行时凭据查询沙箱详情,确认存在 envdUrlenvdAccessToken
命令超时增加运行时命令 timeoutMs;单位是毫秒,不是秒。
清理失败使用 Sandbox ID 重试 delete(),再检查生命周期状态。

SDK 设置失败时,可先用该命令验证 Gateway 和 API Key:

Terminal window
curl -sS "${SEACLOUD_BASE_URL}/api/v1/sandboxes" \
-H "X-API-Key: ${SEACLOUD_API_KEY}" \
-H "Content-Type: application/json" \
--data '{
"templateID": "base",
"timeout": 1800,
"waitReady": true
}' | jq .

保存返回的 sandboxID,测试后删除:

Terminal window
curl -sS -X DELETE "${SEACLOUD_BASE_URL}/api/v1/sandboxes/${SANDBOX_ID}" \
-H "X-API-Key: ${SEACLOUD_API_KEY}" -i