網關核心
源码版本v2026.7.20
職責
網關是 agent 與外部世界的橋梁:接收各平台(Telegram/Discord/Slack/Signal/微信…)訊息,轉成統一的 MessageEvent 餵給 agent;把 agent 的串流輸出轉成各平台的發送動作。gateway/run.py 是這層的主程式(GatewayRunner),協調轉接器、會話、串流消費、投遞帳本、hooks、cron 心跳等多條子系統。
關鍵檔案
class GatewayRunner:3029— 網關主類別,混入授權/Kanban/Slash 能力_handle_message:9947— 入站訊息分發入口_handle_message_with_agent:11956— 把訊息交給 agent 跑一輪_start_one_profile_adapter / _start_secondary:9389-9947— 啟動各 profile 的平台轉接器_start_stream_consumer:21218— 啟動串流消費器_start_gateway_housekeeping:22246— 週期性巡檢(60s)_start_cron_ticker:22335— cron 心跳(60s)def main:22965— 網關程式入口例外與脫敏:276-340—_gateway_loop_exception_handler/_redact_gateway_user_facing_secretsPlatformEntry:39-162— 平台註冊項資料類別class PlatformRegistry:162-260— 註冊表(register / register_deferred / unregister)
資料流
main()(gateway/run.py:22965)啟動GatewayRunner。_start_one_profile_adapter:9389逐個拉起平台轉接器(見平台轉接器)。- 轉接器收到平台原始事件,轉成統一
MessageEvent(見gateway/platforms/base.py:1759)。 _handle_message(gateway/run.py:9947)分發:授權檢查、會話解析、slash 命令路由,或交給_handle_message_with_agent(gateway/run.py:11956)。- 後者呼叫 agent 的
run_conversation:588,並把串流回調接到GatewayStreamConsumer:83。 - 串流輸出經消費器漸進式編輯平台訊息;最終態由
delivery_ledger記帳,防止崩潰丟失最終回覆。 - 巡檢與 cron 心跳在背景 60s 週期跑(
gateway/run.py:22246/gateway/run.py:22335)。
小結
網關核心是「事件匯流排 + 串流橋接」:統一 MessageEvent 抽象屏蔽平台差異,GatewayStreamConsumer 把同步 agent 回調橋到非同步平台投遞,delivery_ledger 保證最終態不丟。它和 agent 解耦——agent 只管跑迴圈,投遞細節全在網關。