以编程方式使用文档

VFS 沙箱完全在本地运行,使用内存中的虚拟文件系统。无需云服务、Docker 或外部依赖 - 非常适合开发和测试。

它使用 node-vfs-polyfill ,该模块实现了即将推出的 Node.js VFS 功能(nodejs/node#61478).

设置

    npm install @langchain/node-vfs
    
    yarn add @langchain/node-vfs
    
    pnpm add @langchain/node-vfs
    

无需身份验证。

与 deepagents 配合使用

const sandbox = await VfsSandbox.create({
  initialFiles: {
    "/src/index.js": "console.log('Hello from VFS!')",
  },
});

try {
  const agent = createDeepAgent({
    model: new ChatAnthropic({ model: "claude-sonnet-4-20250514" }),
    systemPrompt: "You are a coding assistant with VFS access.",
    backend: sandbox,
  });

  const result = await agent.invoke({
    messages: [{ role: "user", content: "Run the index.js file" }],
  });
} finally {
  await sandbox.stop();
}

独立使用

const sandbox = await VfsSandbox.create({
  initialFiles: {
    "/src/index.js": "console.log('Hello from VFS!')",
  },
});

const result = await sandbox.execute("node /src/index.js");
console.log(result.output); // "Hello from VFS!"

await sandbox.stop();

配置

选项类型默认值描述
mountPathstring"/vfs"虚拟文件系统的挂载路径
timeoutnumber30000命令执行超时时间(毫秒)
initialFiles`Record<string, string \Uint8Array>`-

工作原理

VFS 采用混合方法以获得最大兼容性:

  1. **文件存储**:文件使用虚拟文件系统存储在内存中
  2. **命令执行**:执行命令时,文件同步到临时目录,执行命令,然后将更改同步回 VFS
  3. **降级模式**:如果 node-vfs-polyfill 不可用,则回退到使用临时目录进行存储和执行

这提供了内存存储的优势(隔离性、速度),同时保持了完整的 shell 命令执行支持。

文件操作

// Upload files
const encoder = new TextEncoder();
await sandbox.uploadFiles([
  ["src/app.js", encoder.encode("console.log('Hi')")],
  ["package.json", encoder.encode('{"name": "test"}')],
]);

// Download files
const results = await sandbox.downloadFiles(["src/app.js"]);
for (const result of results) {
  if (result.content) {
    console.log(new TextDecoder().decode(result.content));
  }
}

工厂函数

// Create new sandbox per invocation
const factory = createVfsSandboxFactory({
  initialFiles: { "/README.md": "# Hello" },
});

// Or reuse an existing sandbox across invocations
const sandbox = await VfsSandbox.create();
const reuseFactory = createVfsSandboxFactoryFromSandbox(sandbox);

错误处理

try {
  await sandbox.execute("some-command");
} catch (error) {
  if (error instanceof VfsSandboxError) {
    switch (error.code) {
      case "NOT_INITIALIZED":
        // Handle uninitialized sandbox
        break;
      case "COMMAND_TIMEOUT":
        // Handle timeout
        break;
    }
  }
}

错误代码

代码描述
NOT_INITIALIZED沙箱未初始化
ALREADY_INITIALIZED沙箱已初始化
INITIALIZATION_FAILEDVFS 初始化失败
COMMAND_TIMEOUT命令执行超时
COMMAND_FAILED命令执行失败
FILE_OPERATION_FAILED文件操作失败
NOT_SUPPORTED此环境不支持 VFS

何时使用 VFS

最适合的场景: - 本地开发和测试 - CI/CD pipelines without Docker - 快速原型开发,无需云端设置 - 无法使用外部服务的环境

不适合的场景: - 需要真正容器隔离的生产工作负载 - 跨会话的持久化存储 - 繁重的计算任务(无资源限制)

未来:原生 Node.js VFS

此包使用 node-vfs-polyfill ,该模块实现了即将推出的 Node.js VFS 功能,正在以下项目中开发 nodejs/node#61478。当官方 node:vfs 模块在 Node.js 中落地后,此包将更新为使用原生实现。