实战 07:简易 OpenClaw——Gateway、Session、Channel 与身份模型
1、本篇任务:从单渠道扩展为多客户端 Gateway
单渠道版已解决 webhook 可靠性。本篇将 Gateway 定义成中心控制平面:多个 Channel Adapter、Control UI/CLI、Agent Runtime 和设备节点都通过版本化协议连接,共享身份、Session 与事件模型。
2、Gateway 拓扑
Telegram / Slack / Discord adapters ─┐
Control UI / CLI / Mobile clients ───┼→ Gateway Protocol
Paired device / execution nodes ─────┘
├─ Identity & Roles
├─ Session Registry & Ownership
├─ Agent/Tool/Skill Catalog
├─ Scheduler & Event Bus
└─ Persistence / Audit
Channel Adapter 只负责渠道协议;Gateway 负责统一路由;Agent 不直接持有渠道 token。新增渠道不能复制一套 Session 或权限实现。
3、版本化协议
连接建立时 client 声明 protocol version、client type、capabilities 与认证;Gateway 返回 accepted version、server capabilities 和 session scope。请求采用 id/method/params,响应关联 id,事件无请求 id 但带全局或 scope sequence。
type RpcRequest = { id: string; method: string; params: unknown };
type RpcResponse = { id: string; ok: boolean; result?: unknown; error?: { code: string; message: string } };
type GatewayEvent = { seq: number; topic: string; scope: string; payload: unknown };
未知 method 返回稳定错误;未知事件由旧客户端安全忽略。能力协商避免客户端调用 Server 未实现功能。
4、身份、设备和角色
Channel peer、Control UI 用户和 paired device 是不同 principal。认证后映射到内部 identity/role/scopes;device token 不应自动等于用户管理员权限。
principal → role → scopes → resource policy
operator.read:查看自己的 Session
operator.write:发消息、批准动作
admin:配置、Channel、角色与审计
node.execute:仅接受匹配 node policy 的任务
角色变化立即使旧连接重新认证。互不信任的租户不共享一个 Gateway 作为强安全边界,应拆独立实例/主机。
5、Session Scope 与 Identity Links
DM scope 可选 main、per-peer、per-channel-peer、per-account-channel-peer。个人助理可 main;多用户必须至少 per-channel-peer。群、频道、thread/topic 始终使用独立 key。
同一真人跨渠道需要显式、已验证 identity link,不能按 display name 或邮箱猜测合并。合并前审计已有 Session/Memory,避免把两个不同用户数据拼在一起。
6、Thread Binding 和 Session Ownership
Discord thread、Telegram topic 等可绑定某 Session,并设置 idle/max age。Router 收到新消息先查绑定,再按 scope 建 key。Session 同时只能有一个 owner worker;ownership 使用租约,崩溃后可回收。
unowned → claimed(runId, leaseUntil) → active
→ waiting_input(可释放/保留策略)
→ completed / expired
所有 enqueue、steer、cancel、move 操作检查当前 revision,防止两个客户端同时改变运行状态。
7、多渠道能力差异
Adapter 暴露 capability:最大文本长度、线程、按钮、编辑消息、typing、文件、语音、reaction。Renderer 根据 capability 降级:无按钮的渠道用一次性确认码;不能编辑消息则节流发送状态;长 Markdown 按渠道语法安全切分。
不要在核心 Agent prompt 中写大量渠道分支。Gateway runtime 提供标准 reply surface,Adapter 处理表现。
8、事件订阅和重连
Control Client 订阅允许 scope 的 Session/Channel/Job 事件,带 last seq 重连。Gateway 对不同角色过滤 payload;“private state”不会因为事件协议自动保密,必须字段 allowlist。
客户端先 snapshot 后订阅,处理 snapshot 与事件之间的 revision;窗口过期重新 snapshot。不可通过列举 Session ID 读取他人历史。
9、跨 Session 工具与子 Agent
sessions_list/history/send/spawn 等能力要受可见范围和 tool profile 限制。子 Agent 默认新隔离 Session,父只获得状态、结果和 artifacts;跨 Session send 记录 source/target/actor,限制循环消息和 fan-out。
10、测试
同一用户跨两个已绑定渠道按策略共享/隔离;同 display name 不自动合并;群 thread binding 过期后新建 Session;两个 worker 争抢 ownership 只有一个成功;旧客户端忽略新事件;角色撤销后连接不能继续写;低权限用户看不到他人 Session;Channel 降级仍能完成审批。
官方参考:Gateway Architecture、Gateway Protocol、Session Management。
如果您觉得这篇文章有帮助,请点个赞吧~
评论
请登录后发表评论
去登录