npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@vectorx/ai-sandbox

v1.1.0

Published

AI sandbox for VectorX

Readme

@vectorx/ai-sandbox

阿里云 Code 沙箱 SDK,提供类似 @vercel/sandbox 的 API 接口,支持在安全的沙箱环境中执行代码、管理文件系统、执行命令等功能。

功能特性

  • 🚀 沙箱管理: 创建、获取、停止和删除沙箱实例
  • 💻 代码执行: 支持 Python 和 JavaScript 代码的安全执行
  • 📁 文件操作: 上传、下载、读取、写入、移动、删除文件和目录
  • 🔧 命令执行: 在沙箱中执行 shell 命令
  • 📦 上下文管理: 独立的代码执行环境,支持多个上下文
  • ⏱️ 超时控制: 灵活的沙箱生命周期和超时管理

安装

npm install @vectorx/ai-sandbox
# 或
pnpm add @vectorx/ai-sandbox

快速开始

基本使用

import { Sandbox } from '@vectorx/ai-sandbox';
import ms from 'ms';

async function main() {
  // 创建沙箱
  const sandbox = await Sandbox.create({
    // 阿里云配置
    accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID!,
    accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET!,
    accountId: process.env.ALIYUN_ACCOUNT_ID!,
    region: 'cn-hangzhou',
    
    // 沙箱配置
    templateName: 'python-sandbox', // 模板名称
    timeout: ms('5m'), // 超时时间
  });

  try {
    // 执行命令
    const echo = await sandbox.runCommand('echo', ['Hello sandbox!']);
    console.log(`Message: ${await echo.stdout()}`);
    console.log(`Exit code: ${echo.exitCode}`);

    // 执行 Python 代码
    const result = await sandbox.executeCode(`
      import math
      print(f"π = {math.pi}")
      result = 2 + 2
      print(f"2 + 2 = {result}")
    `, 'python');
    
    console.log('Code execution results:');
    result.results.forEach((r) => {
      if (r.type === 'stdout' && r.text) {
        console.log(r.text);
      }
    });

    // 写入文件
    await sandbox.writeFiles([
      {
        path: '/tmp/test.txt',
        content: Buffer.from('Hello, World!'),
      },
    ]);

    // 读取文件
    const buffer = await sandbox.readFileToBuffer({ path: '/tmp/test.txt' });
    if (buffer) {
      console.log('File content:', buffer.toString());
    }

    // 列出目录
    const files = await sandbox.listFiles({ path: '/tmp' });
    console.log('Files:', files.entries.map((e) => e.name));
  } finally {
    // 停止沙箱
    await sandbox.stop();
  }
}

main().catch(console.error);

获取已有沙箱

import { Sandbox } from '@vectorx/ai-sandbox';

const sandbox = await Sandbox.get({
  sandboxId: 'your-sandbox-id',
  accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID!,
  accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET!,
  accountId: process.env.ALIYUN_ACCOUNT_ID!,
  region: 'cn-hangzhou',
});

执行命令

// 简单形式
const result = await sandbox.runCommand('ls', ['-la', '/tmp']);

// 对象形式
const result = await sandbox.runCommand({
  cmd: 'python',
  args: ['script.py'],
  cwd: '/workspace',
  env: { PYTHONPATH: '/workspace' },
});

console.log(await result.stdout());
console.log(await result.stderr());
console.log(result.exitCode);

执行代码

// Python 代码
const pythonResult = await sandbox.executeCode(`
  import pandas as pd
  df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
  print(df)
`, 'python');

// JavaScript 代码
const jsResult = await sandbox.executeCode(`
  const arr = [1, 2, 3, 4, 5];
  const sum = arr.reduce((a, b) => a + b, 0);
  console.log('Sum:', sum);
`, 'javascript');

文件操作

// 写入文件
await sandbox.writeFiles([
  { path: '/tmp/file1.txt', content: Buffer.from('Content 1') },
  { path: '/tmp/file2.txt', content: Buffer.from('Content 2') },
]);

// 读取文件
const buffer = await sandbox.readFileToBuffer({ path: '/tmp/file1.txt' });
if (buffer) {
  console.log(buffer.toString());
}

// 创建目录
await sandbox.mkDir('/tmp/my-dir');

// 列出目录
const dir = await sandbox.listFiles({ path: '/tmp', depth: 2 });
dir.entries.forEach((entry) => {
  console.log(`${entry.type}: ${entry.path}`);
});

API 参考

Sandbox

Sandbox.create(params)

创建新沙箱实例。

参数:

  • accessKeyId: 阿里云 AccessKey ID
  • accessKeySecret: 阿里云 AccessKey Secret
  • accountId: 阿里云主账号 ID
  • region: 区域,如 cn-hangzhou
  • templateName: 模板名称(必需)
  • sandboxId: 自定义沙箱 ID(可选)
  • timeout: 超时时间(毫秒)
  • baseUrl: 自定义数据面 API 基础 URL(可选)
  • fetch: 自定义 fetch 函数(可选)

返回: Promise<Sandbox>

Sandbox.get(params)

获取已有沙箱实例。

参数:

  • sandboxId: 沙箱 ID
  • accessKeyId: 阿里云 AccessKey ID
  • accessKeySecret: 阿里云 AccessKey Secret
  • accountId: 阿里云主账号 ID
  • region: 区域

返回: Promise<Sandbox>

sandbox.runCommand(cmd, args?, opts?)

执行命令。

返回: Promise<CommandFinished>

sandbox.executeCode(code, language?, opts?)

执行代码(Python 或 JavaScript)。

返回: Promise<CodeExecutionResult>

sandbox.writeFiles(files, opts?)

写入文件。

sandbox.readFile(file, opts?)

读取文件为流。

sandbox.readFileToBuffer(file, opts?)

读取文件为 Buffer。

sandbox.mkDir(path, opts?)

创建目录。

sandbox.listFiles(opts?)

列出目录内容。

sandbox.stop(opts?)

停止沙箱。

sandbox.delete(opts?)

删除沙箱。

返回: Promise<SandboxMetadata> - 删除后的沙箱元数据,包含沙箱 ID、状态、创建时间等信息。

CommandFinished

command.stdout()

获取标准输出。

返回: Promise<string>

command.stderr()

获取标准错误输出。

返回: Promise<string>

command.output()

获取所有输出。

返回: Promise<string>

配置说明

环境变量

建议使用环境变量存储敏感信息:

ALIYUN_ACCESS_KEY_ID=your_access_key_id
ALIYUN_ACCESS_KEY_SECRET=your_access_key_secret
ALIYUN_ACCOUNT_ID=your_account_id

模板创建

在使用 SDK 之前,需要先在阿里云控制台创建代码解释器模板,或通过控制面 API 创建。

注意事项

  1. 认证方式: 使用阿里云 AccessKey/SecretKey + 签名认证
  2. API 端点: 数据面和控制面使用不同的 baseUrl
  3. 超时处理: 沙箱最长生命周期为 6 小时
  4. 上下文管理: 代码执行需要先创建 context,命令执行不需要
  5. 文件限制: 上传文件最大 100MB,只支持文本文件扩展名

错误处理

import { APIError } from '@vectorx/ai-sandbox';

try {
  const sandbox = await Sandbox.create({ ... });
} catch (error) {
  if (error instanceof APIError) {
    console.error('API Error:', error.message);
    console.error('Status:', error.response.status);
    console.error('Response:', error.json);
  } else {
    console.error('Unknown error:', error);
  }
}

示例代码

更多使用示例请参考 example/ 目录:

  • example/basic-usage.ts - 基本使用示例
  • example/advanced-usage.ts - 高级功能示例

运行示例:

# 设置环境变量
export ALIYUN_ACCESS_KEY_ID="your_key"
export ALIYUN_ACCESS_KEY_SECRET="your_secret"
export ALIYUN_ACCOUNT_ID="your_account_id"

# 运行示例
cd example
pnpm install
pnpm example

许可证

ISC