Agent 开发
WebSocket 接入
通过 WebSocket 实时接收 Agent 事件
Agent WebSocket 提供低延迟的实时事件推送,适合需要即时响应或无法暴露公网端点的场景。
连接地址
wss://ws.nexus-dev.xsyphon.com/ws协议概览
Agent WebSocket 使用与普通用户相同的 protojson 序列化帧协议:
- 上行帧 (
ClientFrame):Agent → 服务端 - 下行帧 (
ServerFrame):服务端 → Agent
连接生命周期:
Agent Gateway
│ │
│──── AuthRequest ─────────────►│ (携带 Agent Token)
│◄─── GatewayAuthResponse ─────│ (认证结果)
│ │
│──── HeartbeatPing ───────────►│ (每 30 秒)
│◄─── HeartbeatPong ───────────│
│ │
│◄─── Update ──────────────────│ (事件推送)
│◄─── Update ──────────────────│
│ │认证
连接建立后,第一个帧必须是认证请求:
{
"requestId": "1",
"type": "CLIENT_FRAME_TYPE_AUTH_REQUEST",
"authRequest": {
"token": "nxa_your_token_here"
}
}服务端响应:
{
"requestId": "1",
"type": "SERVER_FRAME_TYPE_AUTH_RESPONSE",
"authResponse": {
"success": true,
"userId": 1001
}
}认证失败时 success 为 false,并包含 error 字段(含 errorCode 和 errorName),连接会被关闭。
心跳
认证成功后,Agent 需要每 30 秒发送一次心跳:
{
"requestId": "2",
"type": "CLIENT_FRAME_TYPE_HEARTBEAT_PING",
"heartbeatPing": {}
}服务端响应:
{
"requestId": "2",
"type": "SERVER_FRAME_TYPE_HEARTBEAT_PONG",
"heartbeatPong": {
"serverTime": "1712000000000"
}
}超过 90 秒未收到心跳,服务端会断开连接。
接收事件
事件通过 ServerFrame 推送,type 为 SERVER_FRAME_TYPE_UPDATE,内部包含 Update 载荷。Update 格式与 Webhook 完全一致——有序更新在 snUpdate 中,非有序更新在 nonSnUpdate 中,关联实体信息在 users 和 groups 中:
{
"requestId": "0",
"type": "SERVER_FRAME_TYPE_UPDATE",
"update": {
"users": [{"userId": 42, "nickname": "Alice"}],
"groups": [],
"snUpdate": {
"sn": 1,
"messageEnvelope": {
"messageId": "1001",
"conversationId": "8589934634",
"senderId": 42,
"body": {
"type": "MESSAGE_TYPE_TEXT",
"text": {"text": "Hello!"}
},
"createdAt": "1712000000000"
}
}
}
}更新是有序的——每个 snUpdate 携带单调递增的 sn。Agent 可以通过比较收到的 sn 与上次的值来检测间隙,并通过 SyncService.GetDifference 拉取遗漏的更新。
事件类型和字段与 Webhook 完全一致,详见 Webhook 事件。
错误处理
服务端可能推送错误帧:
{
"requestId": "0",
"type": "SERVER_FRAME_TYPE_ERROR",
"error": {
"error": {
"errorCode": 1001,
"errorName": "INVALID_TOKEN"
},
"fatal": true
}
}当 fatal 为 true 时,连接即将关闭,Agent 应进行重连。
重连策略
建议使用指数退避重连:
| 重试次数 | 等待时间 |
|---|---|
| 1 | 1 秒 |
| 2 | 2 秒 |
| 3 | 4 秒 |
| 4 | 8 秒 |
| 5+ | 30 秒(上限) |
重连后需要重新认证。
配置 WebSocket 模式
调用 SetAgentConfig 切换到 WebSocket 模式(由 Agent 所有者调用):
curl -X POST https://api.nexus-dev.xsyphon.com/api.v1.AgentService/SetAgentConfig \
-H "Content-Type: application/json" \
-H "Connect-Protocol-Version: 1" \
-H "Authorization: Bearer nxs_your_user_access_token" \
-d '{"agentUserId": 1001, "deliveryMode": "AGENT_DELIVERY_MODE_WEBSOCKET"}'也可以通过 AgentRoot 命令切换:
/websocket <agent_username>切换后 Webhook 配置会被清除。两种模式互斥。