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

# Devin ACP WebSocket API

> 使用智能体客户端协议和个人访问令牌，通过 /acp/live WebSocket 直接连接 Devin，即可创建会话、发送提示，并以流式传输方式获取会话内容。

> [!WARNING]
>
> 此端点不保证与智能体客户端协议 (ACP) 规范完全一致，且该 API 目前尚不稳定，可能随时变更。如需稳定性保证，请联系我们。

通过 Devin ACP WebSocket 端点，你可以使用[智能体客户端协议 (ACP) ](https://agentclientprotocol.com/)直接连接 Devin Cloud。只需一个持久的 WebSocket 连接，你就能创建会话、发送提示、列出或恢复现有会话，并以流式传输方式实时获取响应、工具调用和任务更新，无需轮询 REST API。

## 端点

```text theme={null}
wss://api.devin.ai/acp/live
```

## 身份验证

在 WebSocket 升级请求的 `Authorization` 标头中携带[个人访问令牌 (PAT) ](https://docs.devin.ai/zh/api-reference/personal-access-tokens.md) (`cog_...`) 进行身份验证：

```http theme={null}
Authorization: Bearer cog_your_token_here
```

PAT 以您的人工用户身份进行身份验证，可访问您有权访问的所有组织，并具备您的常规权限和完整的 ACP 方法集。如果您的账户禁用了 PAT，或该令牌违反了账户的 PAT 策略，连接将被拒绝。

> [!NOTE]
>
> **企业账户：** 如需使用**服务用户 API 密钥**或 **OAuth app** 连接到 `/acp/live`，请联系您的 Cognition 账户团队申请访问权限。

## 传输与协议

`/acp/live` 通过 WebSocket 文本帧 (JSON-RPC 2.0) 使用 [智能体客户端协议 (ACP) v2](https://agentclientprotocol.com/) 进行通信。有关帧格式、[初始化](https://agentclientprotocol.com/protocol/v2/initialization)、[会话配置](https://agentclientprotocol.com/protocol/v2/session-setup) 和 [提示生命周期](https://agentclientprotocol.com/protocol/v2/prompt-lifecycle) 的详细信息，请参阅 ACP v2 规范。

Devin 特有说明：

* **协议版本：** 在 `initialize` 中传入 `"protocolVersion": 2`。
* **组织与会话选项：** `session/new` 会立即分配一个 `devin-...` 形式的 `sessionId`，并在收到第一个 `session/prompt` 时启动会话。如需指定某个组织，请在 `session/new` 中传入 `_meta["cognition.ai/orgId"]` (省略则使用您的默认组织) ；并在发送第一个提示之前，通过 `session/set_config_option` 设置相关选项 (例如 `org_id` 或 `repos`) 。
* **列出会话：** `session/list` 支持可选的 `_meta` 筛选条件：`cognition.ai/orgIds`、`cognition.ai/archivedStatus` (`ACTIVE`、`ARCHIVED` 或 `ALL`) 、`cognition.ai/createdAfter`、`cognition.ai/updatedAfter` 和 `cognition.ai/content`。
* **服务器发起的请求：** 回复任何服务器请求 (例如 [elicitation](https://agentclientprotocol.com/protocol/v2/elicitation)) 时需使用匹配的 `id`；对于您的客户端不处理的方法，返回 JSON-RPC 错误 `-32601`。
* **重新连接：** 定期发送 WebSocket ping。当服务器因部署排空或连接时长轮换而主动关闭连接时，应重新连接、运行 `initialize`，并通过 `session/resume` 重新附加到会话。

## 最小示例

此 Rust 示例基于 `tokio-tungstenite` 使用 [`agent-client-protocol`](https://crates.io/crates/agent-client-protocol) crate，通过个人访问令牌建立连接、启动 ACP v2 会话、发送提示，并以流式方式接收 Devin 的响应，直到当前对话轮次结束。

```toml Cargo.toml theme={null}
[dependencies]
agent-client-protocol = { version = "5", features = ["unstable_protocol_v2"] }
futures-util = { version = "0.3", features = ["sink"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "tls12"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync"] }
tokio-tungstenite = { version = "0.28", features = ["rustls-tls-native-roots"] }
```

```rust src/main.rs theme={null}
use std::io::{self, Write};

use agent_client_protocol::schema::ProtocolVersion;
use agent_client_protocol::v2::{ConnectionTo, schema};
use agent_client_protocol::{Agent, Client, Error, Lines};
use futures_util::{SinkExt, StreamExt};
use tokio::sync::mpsc::unbounded_channel;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;

const ACP_URL: &str = "wss://api.devin.ai/acp/live";

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let token = std::env::var("DEVIN_PAT")?; // cog_...
    let org_id = std::env::var("DEVIN_ORG_ID").ok();

    let mut request = ACP_URL.into_client_request()?;
    request
        .headers_mut()
        .insert("Authorization", format!("Bearer {token}").parse()?);

    let (ws, _) = tokio_tungstenite::connect_async(request).await?;
    let (ws_tx, ws_rx) = ws.split();

    let outgoing = ws_tx
        .sink_map_err(io::Error::other)
        .with(|line: String| async move {
            Ok::<_, io::Error>(Message::Text(line.trim_end().into()))
        });
    let incoming = ws_rx.filter_map(|frame| async move {
        match frame {
            Ok(Message::Text(text)) => Some(Ok(text.to_string())),
            Err(err) => Some(Err(io::Error::other(err))),
            _ => None,
        }
    });

    let (update_tx, mut update_rx) = unbounded_channel();

    Client
        .v2()
        .on_receive_notification(
            async move |notification: schema::UpdateSessionNotification,
                        _cx: ConnectionTo<Agent>| {
                update_tx
                    .send(notification)
                    .map_err(Error::into_internal_error)
            },
            agent_client_protocol::on_receive_notification!(),
        )
        .connect_with(Lines::new(outgoing, incoming), async move |cx| {
            // 1. 初始化（ACP v2）
            cx.send_request(schema::InitializeRequest::new(
                ProtocolVersion::V2,
                schema::Implementation::new("acp-quickstart", "0.1.0"),
            ))
            .block_task()
            .await?;

            // 2. 分配新会话
            let mut new_session = schema::NewSessionRequest::new("/");
            if let Some(org_id) = org_id {
                let mut meta = serde_json::Map::new();
                meta.insert("cognition.ai/orgId".into(), org_id.into());
                new_session = new_session.meta(meta);
            }
            let opened = cx
                .build_session_from(new_session)
                .start_session()
                .block_task()
                .await?;
            let session = opened.session;

            // 3. 发送首条提示，并流式接收更新，直到本轮对话结束
            session
                .send_prompt("Reply with hello world.")
                .block_task()
                .await?;

            let mut observed_active = false;
            while let Some(notification) = update_rx.recv().await {
                if &notification.session_id != session.session_id() {
                    continue;
                }
                match notification.update {
                    schema::SessionUpdate::AgentMessageChunk(chunk) => {
                        if let schema::ContentBlock::Text(text) = chunk.content {
                            print!("{}", text.text);
                            let _ = io::stdout().flush();
                        }
                    }
                    schema::SessionUpdate::StateUpdate(schema::StateUpdate::Idle(idle))
                        if observed_active =>
                    {
                        println!("\nDone: {:?}", idle.stop_reason);
                        break;
                    }
                    schema::SessionUpdate::StateUpdate(_) => observed_active = true,
                    _ => {}
                }
            }

            session.close().block_task().await?;
            Ok(())
        })
        .await?;

    Ok(())
}
```

## 后续步骤

* [个人访问令牌](https://docs.devin.ai/zh/api-reference/personal-access-tokens.md) — 创建和管理 PAT，以及配置企业 PAT 策略
* [身份验证](https://docs.devin.ai/zh/api-reference/authentication.md) — 对比 PAT 与服务用户 API 密钥
* [API 概述](https://docs.devin.ai/zh/api-reference/overview.md) — 了解 Devin REST API


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.