Hermes Gateway 架构
GatewayRunner
text
gateway/run.py (17,851 行!)GatewayRunner 是 Hermes 的消息平台中枢。
python
class GatewayRunner:
"""Multi-platform messaging gateway for Hermes Agent."""
async def start(self):
# 1. 加载所有 platform adapters
# 2. 启动 event loop
# 3. 处理消息路由
# 4. 管理 session → AIAgent 映射核心职责
| 职责 | 实现 |
|---|---|
| 平台管理 | 加载 Telegram/Discord/Slack/... adapter |
| 消息路由 | MessageEvent → session_key → AIAgent |
| Agent 缓存 | 按 session_key 缓存 AIAgent(保留 prompt cache) |
| 并发控制 | running agents map + queue + busy debounce |
| 权限 | 授权检查、slash command 权限 |
| Session 恢复 | 启动时恢复 pending sessions |
| Cron 集成 | 内置 scheduler |
| Profile | 支持多 profile multiplexing |
Platform Adapters
text
gateway/platforms/
├── telegram.py # Telegram Bot API
├── discord.py # Discord Bot
├── slack.py # Slack App
├── whatsapp_cloud.py # WhatsApp Cloud API
├── signal.py # Signal Messenger
├── api_server.py # REST API server
├── bluebubbles.py # iMessage
├── weixin.py # 微信
├── yuanbao.py # 元宝
└── qqbot/ # QQ BotAgent 缓存机制
python
# GatewayRunner 内部
_agent_cache: dict[str, AIAgent] # session_key → agent
# LRU: 最多保留 128 个 agent
# Idle TTL: 1 小时无活动则回收
async def get_agent(session_key):
if session_key in _agent_cache:
if not expired(_agent_cache[session_key]):
return _agent_cache[_agent_key]
agent = await create_agent(session_key)
_agent_cache[session_key] = agent
return agent为什么不每次创建? GPT-5 级别模型,system prompt 有几 KB tokens。每次新建 agent 都要重新构建 system prompt → 破坏 prompt cache → 成本暴增 ~10 倍。
消息流
Telegram message
↓
platform adapter (gateway/platforms/telegram.py)
↓
MessageEvent {
platform, user_id, chat_id, thread_id,
text, attachments, is_command, ...
}
↓
GatewayRunner.route(event)
↓
session_key = f"{platform}:{chat_id}:{thread_id}"
↓
get_agent(session_key) # from cache or create
↓
agent.run_conversation(user_text)
↓
response → platform.send(chat_id, response)与 OpenCode Server 对比
| 维度 | Hermes Gateway | OpenCode Server |
|---|---|---|
| 目标 | 通用消息平台 | Coding agent API |
| 协议 | Telegram/Discord/Slack/... | HTTP REST + Event Stream |
| Agent 缓存 | 有(prompt cache 意识) | 无(durable session) |
| 平台数量 | ~20 | 1(HTTP) |
| 多客户端 | 同一 session 多个 platform 不同 session | 同一 session 多个 client |
| Cron | 内置 | 无 |