> ## 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.

# 创建 Session

> 创建绑定 Agent 和 Environment 的新 Session。

`POST /api/v1/cloud/sessions`

创建 Session。新 Session 初始状态为 `idle`，发送事件后开始执行。

## 请求头

| 头部              | 必选 | 说明                  |
| --------------- | -- | ------------------- |
| `Authorization` | 是  | `Bearer $QODER_PAT` |
| `Content-Type`  | 是  | `application/json`  |

## 请求体

| 字段                              | 类型              | 必填 | 说明                                                                                                                                                           |
| ------------------------------- | --------------- | -- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `agent`                         | string 或 object | 是  | Agent ID，或包含 `id`、必填 `type: "agent"`、可选 `version` 的对象。详见 [Agent 引用](/zh/cloud-agents/api/sessions/schemas#agent-引用)                                          |
| `environment_id`                | string          | 是  | `env_` 前缀的已有 Environment ID                                                                                                                                  |
| `title`                         | string \| null  | 否  | Session 标题                                                                                                                                                   |
| `metadata`                      | object          | 否  | Session 元数据                                                                                                                                                  |
| `environment_variables`         | string          | 否  | 注入到 agent 运行时的 Session 级环境变量。请求侧使用单字符串，`KEY=VALUE` 之间用 `;`（也接受换行或全角 `；`）分隔；响应侧返回 JSON 对象，详见 [校验规则](#environment-variables-校验)。Self-hosted Environment 不支持    |
| `incremental_streaming_enabled` | boolean         | 否  | 是否为当前 Session 开启增量流式事件。默认 `false`。设为 `true` 后，list 和 stream 事件 API 会在最终完整事件之外暴露 `agent.message_start`、`agent.content_block_delta`、`agent.message_stop` 等增量事件 |
| `resources`                     | array           | 否  | 创建时挂载的 file、GitHub repository 或 Memory Store 资源                                                                                                              |
| `vault_ids`                     | array           | 否  | Session 可使用的 Vault ID                                                                                                                                        |

旧请求字段 `environment`、`delta_flush_interval_ms`、`vaults` 和 `memory_store_ids` 不支持。挂载 Memory Store 请使用 `resources[]` 中的 `type: "memory_store"`。

### environment\_variables 校验

变量名必须匹配 `[A-Za-z_][A-Za-z0-9_]*`；保留名 `SERVER_ENDPOINT`、`USER_ID`、`WORK_DIR`，以及任何带 `CAW_`、`QODER_` 前缀的名称都会被拒绝。单个 value 不超过 8 KiB；总条目不超过 64 条且总字节不超过 64 KiB。重复键、格式错误或在 self-hosted Environment 上使用会返回 400 `invalid_request_error`。

## 资源参数

| 资源类型                | 必填字段                                 | 可选字段                     |
| ------------------- | ------------------------------------ | ------------------------ |
| `file`              | `type`, `file_id`                    | `mount_path`             |
| `github_repository` | `type`, `url`, `authorization_token` | `mount_path`, `checkout` |
| `memory_store`      | `type`, `memory_store_id`            | `access`, `instructions` |

Self-hosted Environment 当前不支持 Session resources。

## 示例请求

```bash theme={null}
curl -X POST https://api.qoder.com/api/v1/cloud/sessions \
  -H "Authorization: Bearer $QODER_PAT" \
  -H "Content-Type: application/json" \
  -d '{
    "agent": {"id": "agent_019e390add9f7bac9b6cc806db46fcbd", "type": "agent", "version": 2},
    "environment_id": "env_019e2590d33f711fabf42f2857cecd8a",
    "title": "Code review session",
    "metadata": {"purpose": "review"},
    "environment_variables": "FEATURE_FLAG=on;LOG_LEVEL=debug",
    "incremental_streaming_enabled": true,
    "resources": [
      {
        "type": "github_repository",
        "url": "https://github.com/your-org/your-repo",
        "mount_path": "/data/workspace/your-repo",
        "authorization_token": "ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
      },
      {
        "type": "memory_store",
        "memory_store_id": "memstore_019eed05b61e78cea61bfd366e072878",
        "access": "read_write",
        "instructions": "Use this memory for long-lived project context."
      }
    ],
    "vault_ids": ["vault_019eed0519807975983d0ffc4b4b4c79"]
  }'
```

## 示例响应

**HTTP 200 OK**

返回 [Session 对象](/zh/cloud-agents/api/sessions/schemas#session-对象)。

```json theme={null}
{
  "id": "sess_019e3bb1e8c171fd9abbb1477ffb84cc",
  "type": "session",
  "agent": {
    "id": "agent_019e390add9f7bac9b6cc806db46fcbd",
    "type": "agent",
    "name": "doc-test-agent",
    "description": "Documentation example Agent",
    "model": {
      "id": "ultimate",
      "effective_context_window": 200000
    },
    "system": "You are a test assistant.",
    "tools": [],
    "skills": [],
    "mcp_servers": [],
    "version": 2
  },
  "environment_id": "env_019e2590d33f711fabf42f2857cecd8a",
  "title": "Code review session",
  "status": "idle",
  "metadata": {"purpose": "review"},
  "environment_variables": {"FEATURE_FLAG": "on", "LOG_LEVEL": "debug"},
  "incremental_streaming_enabled": true,
  "resources": [],
  "vault_ids": ["vault_019eed0519807975983d0ffc4b4b4c79"],
  "deployment_id": null,
  "outcome_evaluations": [],
  "stats": {"active_seconds": 0, "duration_seconds": 0},
  "archived_at": null,
  "created_at": "2026-05-18T15:26:15.747298Z",
  "updated_at": "2026-05-18T15:26:15.747298Z"
}
```

## 错误码

| HTTP | 类型                      | 触发条件                                            |
| ---- | ----------------------- | ----------------------------------------------- |
| 400  | `invalid_request_error` | 请求体错误、缺少必填字段、使用不支持的旧字段或资源非法                     |
| 401  | `authentication_error`  | PAT 无效或过期                                       |
| 404  | `not_found_error`       | Agent、Environment、File、Memory Store 或 Vault 不存在 |
| 409  | `invalid_request_error` | 引用的文件未 ready，或资源路径/ID 冲突                        |

**HTTP 400 Bad Request**

```json theme={null}
{
  "type": "error",
  "request_id": "cb80235f-76a2-4ff3-9e28-5aa2da12dc14",
  "error": {
    "type": "invalid_request_error",
    "message": "Field 'agent' is required."
  }
}
```

**HTTP 404 Not Found**

```json theme={null}
{
  "type": "error",
  "request_id": "cb80235f-76a2-4ff3-9e28-5aa2da12dc14",
  "error": {
    "type": "not_found_error",
    "message": "Agent 'agent_does_not_exist_0000000000000000000000000000' was not found."
  }
}
```

注意：`agent` 缺少 `agent_` 前缀（或 `environment_id` 缺少 `env_` 前缀）时同样会被解析为 404 `not_found_error`，而不是 400。

详见 [Errors](/zh/cloud-agents/api/conventions/errors)。

## 相关

<CardGroup cols={2}>
  <Card title="启动 Session" icon="play" href="/zh/cloud-agents/sessions">
    让 Agent 在环境中以有状态对话的方式运行。
  </Card>
</CardGroup>
