Agent ↔ 中枢 协议

Gateway agent 与中枢之间用 wss + JSON envelope + binary stream frame 双通道。

连接生命周期

1. agent 启动 → 读 setup.conf (host_id / install_token)
2. POST /v1/internal/agent/online
     消费 install_token → 拿 agent_token (短期 JWT)
3. wss → /v1/internal/agent/ws
     升级时带 Bearer agent_token + Sec-WebSocket-Protocol: m2gw.agent.v1
4. 进入心跳循环:
     - agent 每 30s 发 ping,连续 75s 无对端帧 → 自动重连
     - 中枢 90s 没心跳 → host.status = stale
     - 5min 没心跳 → host.status = offline
5. token 续期:用 ed25519 私钥签 challenge:
     msg = host_id + ":" + nonce + ":" + ts → sha256 → ed25519 sign
     POST /v1/internal/agent/token/refresh

JSON Envelope(控制帧)

所有控制帧统一外壳:

{
  "v": 1,
  "type": "...",
  "msg_id": "uuid-v7",
  "ts": 1718001234567,
  "in_reply_to": "<原 msg_id,回包时填>",
  /* 各 type 自己的 payload,flat */
}

中枢 → Agent

type用途
hello升级 ws 后第一帧;含 server_time / hb_interval / supported_features
ping心跳;agent 必须 30s 内回 pong
cmd远程命令;payload 含 controls / path / data / deadline_ms / stream_id?
cmd_cancel取消未完成 cmd
stream_close关掉某 stream_id
agent_reload_config通知 agent 重读配置
agent_restart通知 agent 自重启
agent_self_update通知 agent 拉取并替换自己;payload 含 exe_url / sha256 / size / version
agent_token_renewed推送新 agent_token(避免 agent 走 refresh 端点)

Agent → 中枢

type用途
hello_ack回 hello;含 agent_version / uptime / config_complete
pong回 ping
cmd_resp命令结果;payload 含 cmd_id / code / msg / data / duration_ms / bytes_in / bytes_out
cmd_progress长任务进度;含 cmd_id / phase / percent / detail
event主动事件;含 event 名 + detail(如 file_changed)
metrics5min 周期:cpu_pct / mem_pct / disk_pct / net_rx_bps / net_tx_bps / tcp_conns / uptime_s
log业务日志
error错误

Binary Stream Frame

ConPTY 终端 / FileStream 大文件分块走二进制:

[type: 1 byte] [stream_id: 16 bytes] [payload: N bytes]
type用途
0x01 stdin客户端 → host
0x02 stdouthost → 客户端
0x03 stderr同上
0x04 file_chunk_in上传文件分块
0x05 file_chunk_out下载文件分块
0x06 eof_marker流结束
0x07 data_resync重传同步点

当前版本:终端走中枢中转拉模式(每 100ms 调 SHELL_SESSION_READ 拿 base64 数据 → 转 ws binary 给浏览器)。binary frame 推流方案在路线图。

L1 兼容协议(旧 m2-gateway)

为兼容旧 SmartWay 客户端,中枢同时支持 L1:

  • HTTP POST /gateway
  • AES-256-CBC + base64 + PKCS7
  • secretKey 32 字符,IV = secretKey[:16]
  • 16 个老 controls:1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768
  • 响应 {code, data, msg},code=0 / 7

L1 走旧端口 23456 入站,新版 Rust gateway 完全兼容。

OpenAPI

外部 API(注册 / 登录 / clientapi 用户客户端 API)的完整规范见 api/openapi.yaml