> ## Documentation Index
> Fetch the complete documentation index at: https://docs.qoder.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 云端环境

> 选择 Agent 运行的容器、网络与依赖。

Environment 定义了 Session 运行的容器模板：环境类型、网络策略、预装依赖、启动脚本和 metadata。你可以为不同场景创建不同的环境：严格隔离的安全审计环境、预装数据科学库的分析环境、或者开放网络的通用开发环境。

## 环境是什么

Environment 是 Session 的基础设施层：

* **环境类型** - `cloud` 表示云端托管容器，`self_hosted` 表示自托管执行环境
* **网络策略** - 控制容器的出站网络访问
* **依赖包** - 预装系统包、Python 包、Node.js 包
* **启动脚本** - 容器准备阶段、依赖安装完成后执行的用户脚本

每个 Session 启动时会基于指定的 Environment 模板创建隔离的运行实例。

## 字段说明

| 字段                    | 类型           | 必填 | 说明                                 |
| --------------------- | ------------ | -- | ---------------------------------- |
| `id`                  | string       | -  | 系统生成，`env_` 前缀                     |
| `type`                | string       | -  | 固定为 `"environment"`                |
| `name`                | string       | 是  | 环境名称                               |
| `description`         | string       | 否  | 描述信息，默认 `""`                       |
| `config`              | object       | 是  | 环境配置                               |
| `config.type`         | string       | 是  | 环境类型：`"cloud"` 或 `"self_hosted"`   |
| `config.networking`   | object       | 否  | `cloud` 环境的网络策略                    |
| `config.packages`     | object       | 否  | `cloud` 环境的预装依赖包配置                 |
| `config.setup_script` | string       | 否  | sandbox 准备阶段执行的 shell 脚本（最大 64 KB） |
| `metadata`            | object       | 否  | 自定义 key/value metadata             |
| `archived_at`         | string\|null | -  | 归档时间（ISO 8601），未归档时为 `null`        |
| `created_at`          | string       | -  | 创建时间                               |
| `updated_at`          | string       | -  | 最后更新时间                             |

## Config 类型

`config.type` 可以是 `"cloud"` 或 `"self_hosted"`。

`self_hosted` 的 config 必须严格为：

```json theme={null}
{"type": "self_hosted"}
```

Self-hosted Environment 不会启动托管云端容器。外部 worker 通过 [Work API](/zh/cloud-agents/api/environments/work/poll) poll、ack、heartbeat 和 stop 该 Environment 下的 Session work。

`cloud` 的 config 可以包含 `networking`、`packages` 和 `setup_script`。

## 网络策略

`config.networking` 支持三种请求模式，**所有模式都必须使用对象格式**（字符串简写如 `"unrestricted"` 不被支持，会返回 400）。

| 模式   | 值                                                     | 说明                  |
| ---- | ----------------------------------------------------- | ------------------- |
| 完全开放 | `{"type": "unrestricted"}`                            | 容器可以访问任意外部地址        |
| 受限   | `{"type": "limited", "allow_package_managers": true}` | 仅允许访问已知安全的公共服务和包管理器 |
| 白名单  | `{"type": "allowed_hosts", "allowed_hosts": [...]}`   | 仅允许访问指定主机名          |

Cloud Environment 响应会包含以下 networking 字段。省略字段会按默认值返回。

| 字段                       | 类型        | 默认值       |
| ------------------------ | --------- | --------- |
| `type`                   | string    | `limited` |
| `allowed_hosts`          | string 数组 | `[]`      |
| `allow_package_managers` | boolean   | `false`   |
| `allow_mcp_servers`      | boolean   | `false`   |

### 完全开放

```json theme={null}
{
  "config": {
    "type": "cloud",
    "networking": {"type": "unrestricted"}
  }
}
```

适用于需要下载依赖、访问外部 API 的通用开发任务。

### 受限模式

```json theme={null}
{
  "config": {
    "type": "cloud",
    "networking": {
      "type": "limited",
      "allow_package_managers": true
    }
  }
}
```

适用于不需要任意外网访问、但仍需通过包管理器拉依赖的任务。

### 白名单模式

```json theme={null}
{
  "config": {
    "type": "cloud",
    "networking": {
      "type": "allowed_hosts",
      "allowed_hosts": [
        "api.github.com",
        "registry.npmjs.org",
        "pypi.org"
      ]
    }
  }
}
```

适用于安全合规要求高的场景，精确控制可访问的外部服务。

## 预装依赖

通过 `config.packages` 指定容器启动时预装的依赖：

```json theme={null}
{
  "config": {
    "type": "cloud",
    "networking": {"type": "unrestricted"},
    "packages": {
      "apt": ["git", "build-essential", "libssl-dev"],
      "pip": ["pandas", "numpy", "scikit-learn"],
      "npm": ["typescript", "eslint", "prettier"]
    }
  }
}
```

| 包管理器 | 字段             | 说明                |
| ---- | -------------- | ----------------- |
| apt  | `packages.apt` | Debian/Ubuntu 系统包 |
| pip  | `packages.pip` | Python 包          |
| npm  | `packages.npm` | Node.js 包         |

<Note>
  预装依赖会增加环境初始化时间。只添加确实需要的包，其余可在 Session 运行时按需安装。
</Note>

## 启动脚本

`config.setup_script` 是一段在 sandbox 准备阶段、`packages` 安装完成之后执行的 shell 脚本，使用 `/bin/bash -lc` 解释器运行。常用于克隆代码、写配置文件、warmup 缓存等无法用 `packages` 表达的初始化步骤。

| 约束   | 值                              |
| ---- | ------------------------------ |
| 类型   | string                         |
| 最大长度 | 64 KB                          |
| 解释器  | `/bin/bash -lc`                |
| 超时   | 10 分钟                          |
| 执行时机 | sandbox 准备阶段，`packages` 安装完成之后 |

```bash theme={null}
# 创建一个会自动 clone 项目并预装依赖的环境
curl -s -X POST https://api.qoder.com/api/v1/cloud/environments \
  -H "Authorization: Bearer $QODER_PAT" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "node-with-init",
    "config": {
      "type": "cloud",
      "networking": {"type": "unrestricted"},
      "packages": {
        "npm": ["pnpm@9"]
      },
      "setup_script": "set -euo pipefail\n[ -d /workspace/.git ] || git clone https://github.com/me/repo /workspace\ncd /workspace && pnpm install --frozen-lockfile"
    }
  }' | jq .
```

执行成功后会在沙箱内写入完成标记，本次 sandbox 内不会重复执行；沙箱被回收重建后会再次执行。脚本以非零状态退出会导致 Session 启动失败，错误响应中会带上 exit code 和 stderr 摘要。

## 创建环境

```bash theme={null}
# 创建一个数据科学专用环境
curl -s -X POST https://api.qoder.com/api/v1/cloud/environments \
  -H "Authorization: Bearer $QODER_PAT" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "data-science",
    "config": {
      "type": "cloud",
      "networking": {"type": "unrestricted"},
      "packages": {
        "apt": ["build-essential"],
        "pip": ["pandas", "numpy", "matplotlib", "scikit-learn", "jupyter"]
      }
    }
  }' | jq .
```

成功返回 **200 OK**：

```json theme={null}
{
  "id": "env_019e44eb66bb748cabcd1489f6fa4428",
  "type": "environment",
  "name": "data-science",
  "description": "",
  "config": {
    "type": "cloud",
    "networking": {
      "type": "unrestricted",
      "allowed_hosts": [],
      "allow_package_managers": false,
      "allow_mcp_servers": false
    },
    "packages": {
      "type": "packages",
      "apt": ["build-essential"],
      "npm": [],
      "pip": ["pandas", "numpy", "matplotlib", "scikit-learn", "jupyter"]
    }
  },
  "metadata": {},
  "archived_at": null,
  "created_at": "2026-05-18T10:00:00Z",
  "updated_at": "2026-05-18T10:00:00Z"
}
```

## 创建安全受限环境

```bash theme={null}
# 创建一个仅允许访问内部 API 的安全环境
curl -s -X POST https://api.qoder.com/api/v1/cloud/environments \
  -H "Authorization: Bearer $QODER_PAT" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "secure-internal",
    "config": {
      "type": "cloud",
      "networking": {
        "type": "allowed_hosts",
        "allowed_hosts": ["internal-api.mycompany.com", "git.mycompany.com"]
      },
      "packages": {
        "apt": ["git", "curl"]
      }
    }
  }' | jq .
```

## 查询环境

```bash theme={null}
# 列出所有环境
curl -s https://api.qoder.com/api/v1/cloud/environments \
  -H "Authorization: Bearer $QODER_PAT"
```

```bash theme={null}
# 获取单个环境详情
curl -s https://api.qoder.com/api/v1/cloud/environments/env_ds456 \
  -H "Authorization: Bearer $QODER_PAT"
```

## 更新环境

```bash theme={null}
# 为已有环境添加新的依赖包
curl -s -X POST https://api.qoder.com/api/v1/cloud/environments/env_ds456 \
  -H "Authorization: Bearer $QODER_PAT" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "data-science",
    "config": {
      "type": "cloud",
      "networking": {"type": "unrestricted"},
      "packages": {
        "apt": ["build-essential", "libpq-dev"],
        "pip": ["pandas", "numpy", "matplotlib", "scikit-learn", "jupyter", "sqlalchemy"]
      }
    }
  }' | jq .
```

<Note>
  更新环境不会影响已运行的 Session。新配置仅对后续创建的 Session 生效。
</Note>

## 环境选型建议

| 场景       | 推荐配置                            |
| -------- | ------------------------------- |
| 通用开发     | `default` 环境，无需额外配置             |
| 数据分析     | 预装 pandas/numpy，开放网络            |
| 安全审计     | 白名单网络，最小依赖                      |
| 前端开发     | 预装 Node.js 生态工具，开放 npm registry |
| CI/CD 集成 | 预装 git/docker CLI，白名单模式         |

## 常见问题

**Q: 环境创建后需要等待多久才能使用？**

A: 环境创建后可立即用于创建 Session。实际的容器初始化（包括安装依赖）发生在 Session 启动时。

**Q: 预装包的版本可以指定吗？**

A: pip 和 npm 包支持版本指定，如 `"pandas==2.1.0"` 或 `"typescript@5.0.0"`。apt 包使用系统源的默认版本。

**Q: networking 设置错误导致 Agent 运行失败怎么办？**

A: 创建一个新的环境（或更新现有环境），修改网络策略后重新启动 Session。

**Q: 一个账号最多能创建多少个环境？**

A: 无硬性限制，但建议按实际需求创建，避免管理混乱。建议通过命名规范分类。

## 下一步

<CardGroup cols={2}>
  <Card title="启动 Session" icon="play" href="/zh/cloud-agents/sessions">
    将 Agent 和 Environment 组合，开始执行任务。
  </Card>

  <Card title="定义 Agent" icon="user-gear" href="/zh/cloud-agents/define-agent">
    回顾 Agent 配置。
  </Card>
</CardGroup>
