[ PROMPT_NODE_24278 ]
Sandbox API 参考
[ SKILL_DOCUMENTATION ]
# API 参考
## 命令执行
typescript
// 基础
const result = await sandbox.exec('python3 script.py');
// 返回: { stdout, stderr, exitCode, success, duration }
// 带选项
await sandbox.exec('python3 test.py', {
cwd: '/workspace/project',
env: { API_KEY: 'secret' },
stream: true,
onOutput: (stream, data) => console.log(data)
});
## 文件操作
typescript
// 读/写
const { content } = await sandbox.readFile('/workspace/data.txt');
await sandbox.writeFile('/workspace/file.txt', 'content'); // 自动创建目录
// 列出/删除
const files = await sandbox.listFiles('/workspace');
await sandbox.deleteFile('/workspace/temp.txt');
await sandbox.deleteFile('/workspace/dir', { recursive: true });
// 工具
await sandbox.mkdir('/workspace/dir', { recursive: true });
await sandbox.pathExists('/workspace/file.txt');
## 后台进程
typescript
// 启动
const process = await sandbox.startProcess('python3 -m http.server 8080', {
processId: 'web-server',
cwd: '/workspace/public',
env: { PORT: '8080' }
});
// 返回: { id, pid, command }
// 等待就绪
await process.waitForPort(8080); // 等待端口监听
await process.waitForLog(/Server running/); // 等待日志模式
await process.waitForExit(); // 等待完成
// 管理
const processes = await sandbox.listProcesses();
const info = await sandbox.getProcess('web-server');
await sandbox.stopProcess('web-server');
const logs = await sandbox.getProcessLogs('web-server');
## 端口暴露
typescript
// 暴露端口
const { url } = await sandbox.exposePort(8080, {
name: 'web-app',
hostname: request.hostname
});
// 管理
await sandbox.isPortExposed(8080);
await sandbox.getExposedPorts(request.hostname);
await sandbox.unexposePort(8080);
## 会话 (隔离上下文)
每个会话维护自己的 shell 状态、环境变量、工作目录和进程命名空间。
typescript
// 创建带上下文的会话
const session = await sandbox.createSession({
id: 'user-123',
cwd: '/workspace/user123',
env: { USER_ID: '123' }
});
// 使用 (完整的沙箱 API)
await session.exec('echo $USER_ID');
await session.writeFile('config.txt', 'data');
// 管理
await sandbox.getSession('user-123');
await sandbox.deleteSession('user-123');
## 代码解释器
typescript
// 创建带变量的上下文
const ctx = await sandbox.createCodeContext({
language: 'python',
variables: {
data: [1, 2, 3, 4, 5],
config: { verbose: tru