深入解析 OpenClaw Agent Loop:運作機制與架構指南
開發 Agent 最頭痛的往往不是模型本身,而是如何穩定地處理從接收訊息到執行工具的完整循環。如果狀態管理沒做好,或是並行處理出了差錯,整個 Session 就會變得一團糟。
Agentic loop 是 Agent 真正運行的完整過程:從接收輸入、組裝 Context、模型推理、執行 Tool、串流回覆到最後的持久化儲存。這是將一則訊息轉化為行動與最終回覆的權威路徑,同時能確保 Session 狀態的一致性。在 OpenClaw 中,Loop 是每個 Session 獨立且序列化的運行過程,當模型思考、呼叫工具或串流輸出時,它會發送生命週期與串流事件。這份文件將解釋這個真實的 Loop 是如何端到端串連起來的。
進入點 (Entry points)
Section titled “進入點 (Entry points)”- Gateway RPC:
agent與agent.wait。 - CLI:
agent命令。
運作原理(高階概覽) (How it works (high-level))
Section titled “運作原理(高階概覽) (How it works (high-level))”agentRPC 驗證參數,解析 Session(sessionKey/sessionId),持久化 Session 元數據,並立即回傳{ runId, acceptedAt }。agentCommand執行 Agent:- 解析模型以及 thinking/verbose 的預設值
- 載入 Skills 快照
- 呼叫
runEmbeddedPiAgent(pi-agent-core 運行時) - 如果內嵌的 Loop 沒有發出結束或錯誤事件,則由它發出 lifecycle end/error
runEmbeddedPiAgent:- 透過每個 Session 獨立的隊列與全域隊列來序列化運行過程
- 解析模型與 Auth Profile 並建立 pi session
- 訂閱 pi 事件並串流 Assistant/Tool 的增量內容 (deltas)
- 執行超時機制 -> 如果超過時間則中止運行
- 回傳 Payload 與使用量元數據
subscribeEmbeddedPiSession將 pi-agent-core 事件橋接到 OpenClaw 的agent串流:- Tool 事件 =>
stream: "tool" - Assistant deltas =>
stream: "assistant" - Lifecycle 事件 =>
stream: "lifecycle"(phase: "start" | "end" | "error")
- Tool 事件 =>
agent.wait使用waitForAgentJob:- 等待特定
runId的 lifecycle end/error - 回傳
{ status: ok|error|timeout, startedAt, endedAt, error? }
- 等待特定
隊列與並行處理 (Queueing + concurrency)
Section titled “隊列與並行處理 (Queueing + concurrency)”- 運行過程會根據 Session Key(Session 通道)進行序列化,也可以選擇通過全域通道。
- 這樣可以防止 Tool 或 Session 產生競態條件 (race conditions),並保持 Session 歷史紀錄的一致性。
- 訊息頻道可以選擇不同的隊列模式(collect/steer/followup)來餵給這個通道系統。詳見 Command Queue。
Session 與 Workspace 準備 (Session + workspace preparation)
Section titled “Session 與 Workspace 準備 (Session + workspace preparation)”- 解析並建立 Workspace;沙盒運行可能會重定向到沙盒 Workspace 根目錄。
- 載入 Skills(或從快照中重複使用),並注入到環境變數與 Prompt 中。
- 解析 Bootstrap/Context 檔案並注入到 System Prompt 報告中。
- 獲取 Session 寫入鎖;在開始串流前開啟並準備好
SessionManager。
Prompt 組裝與 System Prompt (Prompt assembly + system prompt)
Section titled “Prompt 組裝與 System Prompt (Prompt assembly + system prompt)”- System Prompt 是由 OpenClaw 的基礎 Prompt、Skills Prompt、Bootstrap Context 以及每次運行的覆寫參數組合成的。
- 執行模型特定的限制與 Compaction 預留 Token 規則。
- 關於模型看到的具體內容,請參考 System prompt。
Hook 點(攔截位置) (Hook points (where you can intercept))
Section titled “Hook 點(攔截位置) (Hook points (where you can intercept))”OpenClaw 有兩套 Hook 系統:
- 內部 Hook (Gateway hooks):針對命令與生命週期事件的事件驅動腳本。
- Plugin Hook:位於 Agent/Tool 生命週期與 Gateway 管道中的擴充點。
內部 Hook (Gateway hooks)
Section titled “內部 Hook (Gateway hooks)”agent:bootstrap:在最終確定 System Prompt 之前,建立 Bootstrap 檔案時運行。你可以用它來增加或移除 Bootstrap Context 檔案。- Command hooks:
/new,/reset,/stop以及其他命令事件(參考 Hooks 文件)。
設定與範例請參考 Hooks。
Plugin Hook (Agent + Gateway 生命週期)
Section titled “Plugin Hook (Agent + Gateway 生命週期)”這些 Hook 運行在 Agent Loop 或 Gateway 管道內部:
before_model_resolve:在 Session 建立前運行(此時沒有messages),用於在模型解析前強制覆寫 Provider 或模型。before_prompt_build:在 Session 載入後運行(帶有messages),用於在提交 Prompt 前注入prependContext、systemPrompt、prependSystemContext或appendSystemContext。建議將prependContext用於每輪對話的動態文字,將 System-context 欄位用於應放在 System Prompt 空間的穩定引導。before_agent_start:舊版相容 Hook,可能在任一階段運行;建議優先使用上述明確的 Hook。before_agent_reply:在行內動作之後、LLM 呼叫之前運行,允許 Plugin 接管該輪對話並回傳合成回覆,或完全靜音該輪對話。agent_end:在完成後檢查最終訊息列表與運行元數據。before_compaction/after_compaction:觀察或註解 Compaction 週期。before_tool_call/after_tool_call:攔截 Tool 參數或結果。before_install:檢查內建的掃描結果,並可選擇攔截 Skill 或 Plugin 的安裝。tool_result_persist:在 Tool 結果寫入 Session 紀錄之前,同步轉換這些結果。message_received/message_sending/message_sent:輸入與輸出的訊息 Hook。session_start/session_end:Session 生命週期的邊界。gateway_start/gateway_stop:Gateway 生命週期事件。
針對輸出或 Tool 防護的 Hook 決策規則:
before_tool_call:{ block: true }是終端狀態,會停止低優先級的處理程序。before_tool_call:{ block: false }無操作,不會清除先前的 block 狀態。before_install:{ block: true }是終端狀態,會停止低優先級的處理程序。before_install:{ block: false }無操作,不會清除先前的 block 狀態。message_sending:{ cancel: true }是終端狀態,會停止低優先級的處理程序。message_sending:{ cancel: false }無操作,不會清除先前的 cancel 狀態。
關於 Hook API 與註冊細節,請參考 Plugin hooks。
串流與部分回覆 (Streaming + partial replies)
Section titled “串流與部分回覆 (Streaming + partial replies)”- Assistant deltas 會從 pi-agent-core 串流出來,並以
assistant事件發送。 - 區塊串流 (Block streaming) 可以在
text_end或message_end時發送部分回覆。 - 推理串流 (Reasoning streaming) 可以作為獨立串流或區塊回覆發送。
- 關於分塊與區塊回覆行為,請參考 Streaming。
Tool 執行與訊息傳遞 Tool (Tool execution + messaging tools)
Section titled “Tool 執行與訊息傳遞 Tool (Tool execution + messaging tools)”- Tool 的開始、更新與結束事件會在
tool串流中發送。 - Tool 結果在記錄或發送前,會針對大小與圖片 Payload 進行清理。
- 訊息傳遞 Tool 的發送會被追蹤,以抑制重複的 Assistant 確認訊息。
回覆成型與抑制 (Reply shaping + suppression)
Section titled “回覆成型與抑制 (Reply shaping + suppression)”- 最終的 Payload 由以下內容組裝:
- Assistant 文字(以及選用的推理內容)
- 行內 Tool 摘要(當 verbose 開啟且允許時)
- 當模型出錯時的 Assistant 錯誤文字
NO_REPLY被視為靜音 Token,會從輸出的 Payload 中過濾掉。- 訊息傳遞 Tool 的重複內容會從最終 Payload 列表中移除。
- 如果沒有剩餘可渲染的 Payload 且 Tool 出錯,則會發送備用的 Tool 錯誤回覆(除非訊息傳遞 Tool 已經發送了使用者可見的回覆)。
Compaction 與重試 (Compaction + retries)
Section titled “Compaction 與重試 (Compaction + retries)”- 自動 Compaction 會發送
compaction串流事件,並可能觸發重試。 - 重試時,記憶體緩衝區與 Tool 摘要會重置,以避免重複輸出。
- 關於 Compaction 管道,請參考 Compaction。
事件串流(現狀) (Event streams (today))
Section titled “事件串流(現狀) (Event streams (today))”lifecycle:由subscribeEmbeddedPiSession發出(或作為agentCommand的備案)。assistant:來自 pi-agent-core 的串流增量內容。tool:來自 pi-agent-core 的串流 Tool 事件。
聊天頻道處理 (Chat channel handling)
Section titled “聊天頻道處理 (Chat channel handling)”- Assistant deltas 會被緩衝到聊天
delta訊息中。 - 當 lifecycle end/error 發生時,會發送聊天
final訊息。
超時設定 (Timeouts)
Section titled “超時設定 (Timeouts)”agent.wait預設:30 秒(僅針對等待過程)。可用timeoutMs參數覆寫。- Agent 運行時:
agents.defaults.timeoutSeconds預設為 172800 秒(48 小時);由runEmbeddedPiAgent中的中止計時器強制執行。
哪些情況會提前結束 (Where things can end early)
Section titled “哪些情況會提前結束 (Where things can end early)”- Agent 超時(中止)
- AbortSignal(取消)
- Gateway 連線斷開或 RPC 超時
agent.wait超時(僅停止等待,不會停止 Agent)
相關資源 (Related)
Section titled “相關資源 (Related)”- Tools — 可用的 Agent 工具
- Hooks — 由 Agent 生命週期事件觸發的事件驅動腳本
- Compaction — 長對話如何被摘要處理
- Exec Approvals — Shell 命令的審批閘門
- Thinking — 思考與推理層級的配置
想要更深入了解如何配置你的 Agent?可以詢問我們的 AI Setup Assistant。
- 閱讀 Command Queue 了解訊息如何排隊。
- 探索 Plugin hooks 建立你自己的攔截邏輯。
OpenClaw Expert
還是卡住了?
如果這篇文件沒有解決你的情境,直接問 OpenClaw Expert,拿到可執行步驟。