> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Deno

> 将 Deno 沙盒后端与 deepagents 配合使用，在 Linux 微虚拟机中进行隔离代码执行

[Deno Deploy](https://deno.com) 提供用于隔离代码执行的 Linux 微虚拟机。最适合 Deno 和 JavaScript 工作负载。

## 设置

<CodeGroup>
  ```bash npm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  npm install @langchain/deno
  ```

  ```bash yarn theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  yarn add @langchain/deno
  ```

  ```bash pnpm theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
  pnpm add @langchain/deno
  ```
</CodeGroup>

### 认证

从 [app.deno.com](https://app.deno.com) → 设置 → 组织令牌 获取您的令牌。

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
export DENO_DEPLOY_TOKEN=your_token
```

或直接传递凭证：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const sandbox = await DenoSandbox.create({
  auth: { token: "your-token-here" },
});
```

## 与 deepagents 配合使用

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { createDeepAgent } from "deepagents";
import { ChatAnthropic } from "@langchain/anthropic";
import { DenoSandbox } from "@langchain/deno";

const sandbox = await DenoSandbox.create({
  memoryMb: 1024,
  lifetime: "10m",
});

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

  const result = await agent.invoke({
    messages: [{ role: "user", content: "Create a hello world Deno app and run it" }],
  });
} finally {
  await sandbox.close();
}
```

## 独立使用

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { DenoSandbox } from "@langchain/deno";

const sandbox = await DenoSandbox.create({
  memoryMb: 1024,
  lifetime: "10m",
});

const result = await sandbox.execute("deno --version");
console.log(result.output);

await sandbox.close();
```

## 配置

| 选项         | 类型                    | 默认值         | 描述                                  |
| ---------- | --------------------- | ----------- | ----------------------------------- |
| `memoryMb` | `number`              | `768`       | 内存，单位为 MB (768-4096)                |
| `lifetime` | `"session" \| string` | `"session"` | 生命周期 (`"session"`, `"5m"`, `"30s"`) |
| `region`   | `string`              | -           | 区域。选项：`"ams" \| "ord"`              |

### 可用区域

| 区域代码  | 位置    |
| ----- | ----- |
| `ams` | 阿姆斯特丹 |
| `ord` | 芝加哥   |

### 生命周期选项

* `"session"` (默认)：当您关闭/释放客户端时，沙盒关闭
* 时长字符串：让沙盒保持运行特定时间 (例如，`"5m"`, `"30s"`)

## 访问 Deno SDK

要使用高级功能，请访问底层的 Deno SDK：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
const denoSandbox = await DenoSandbox.create();
const sdk = denoSandbox.sandbox;

// 暴露 HTTP 端口
const url = await sdk.exposeHttp({ port: 3000 });

// 暴露 SSH
const ssh = await sdk.exposeSsh();

// 执行 JavaScript
const result = await sdk.eval("1 + 2");

// 设置环境变量
await sdk.env.set("API_KEY", "secret");

// Shell 模板字符串
const output = await sdk.sh`echo "Hello from Deno!"`.text();

// 启动 JavaScript 运行时
const runtime = await sdk.createJsRuntime({ entrypoint: "server.ts" });
```

## 重新连接到现有沙盒

重新连接需要基于时长的生命周期 (不是 `"session"`)：

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
// 使用时长生命周期创建
const sandbox = await DenoSandbox.create({
  memoryMb: 1024,
  lifetime: "30m",
});
const sandboxId = sandbox.id;
await sandbox.close(); // 关闭连接，沙盒继续运行

// 稍后：重新连接
const reconnected = await DenoSandbox.connect(sandboxId);
const result = await reconnected.execute("ls -la");
```

## 工厂函数

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { createDenoSandboxFactory, createDenoSandboxFactoryFromSandbox } from "@langchain/deno";

// 每次调用创建新沙盒
const factory = createDenoSandboxFactory({ memoryMb: 1024 });

// 或在多次调用间复用现有沙盒
const sandbox = await DenoSandbox.create();
const reuseFactory = createDenoSandboxFactoryFromSandbox(sandbox);
```

## 错误处理

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { DenoSandboxError } from "@langchain/deno";

try {
  await sandbox.execute("some command");
} catch (error) {
  if (error instanceof DenoSandboxError) {
    switch (error.code) {
      case "NOT_INITIALIZED":
        await sandbox.initialize();
        break;
      case "COMMAND_TIMEOUT":
        console.error("Command took too long");
        break;
      case "AUTHENTICATION_FAILED":
        console.error("Check your Deno Deploy token");
        break;
    }
  }
}
```

### 错误代码

| 代码                        | 描述                         |
| ------------------------- | -------------------------- |
| `NOT_INITIALIZED`         | 沙盒未初始化 - 调用 `initialize()` |
| `ALREADY_INITIALIZED`     | 不能初始化两次                    |
| `AUTHENTICATION_FAILED`   | 无效或缺失的 Deno Deploy 令牌      |
| `SANDBOX_CREATION_FAILED` | 创建沙盒失败                     |
| `SANDBOX_NOT_FOUND`       | 沙盒 ID 未找到或已过期              |
| `COMMAND_TIMEOUT`         | 命令执行超时                     |
| `COMMAND_FAILED`          | 命令执行失败                     |
| `FILE_OPERATION_FAILED`   | 文件读写失败                     |
| `RESOURCE_LIMIT_EXCEEDED` | 超出 CPU、内存或存储限制             |

## 限制和约束

| 约束   | 值              |
| ---- | -------------- |
| 最小内存 | 768 MB         |
| 最大内存 | 4096 MB (4 GB) |
| 磁盘空间 | 10 GB          |
| vCPU | 2              |
| 工作目录 | `/home/app`    |
| 网络访问 | 完全访问 (默认)      |

## 环境变量

| 变量                  | 描述                 |
| ------------------- | ------------------ |
| `DENO_DEPLOY_TOKEN` | Deno Deploy 组织访问令牌 |

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs) 通过 MCP 连接到 Claude、VSCode 等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/javascript/integrations/providers/deno.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
