Skip to content

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 Bot

Agent 缓存机制

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 GatewayOpenCode Server
目标通用消息平台Coding agent API
协议Telegram/Discord/Slack/...HTTP REST + Event Stream
Agent 缓存有(prompt cache 意识)无(durable session)
平台数量~201(HTTP)
多客户端同一 session 多个 platform 不同 session同一 session 多个 client
Cron内置

Powered by VitePress