研究日期
2026-04-06
簡介
2026 年的 AI 工程圈有一個共識正在快速成形:模型能力只是上限,真正決定 agent 是否可用、可控、可部署的是 harness。
什麼是 Harness?簡單說,它不是 Agent 本身(推理、決策、規劃),也不是 Tool(被呼叫的能力單元),而是把 LLM/Agent「變成可用系統」的執行外殼與控制平面。如果 Agent 是「大腦」,Tool 是「手腳」,那 Harness 就是「神經系統+操作系統+安全邊界」。
這個概念源自傳統軟體工程中的 test harness——建立可控環境去驗證被測系統。如今它已演進為涵蓋工具接入、狀態管理、sandbox、workflow orchestration、feedback loop、policy guardrails、evaluation 與 observability 的完整工程學科。
OpenAI 在 2026 年初發布了 Harness Engineering 一文,描述其團隊以 Codex 產出近百萬行程式碼、約 1,500 PRs,且人類幾乎不手寫 code。Martin Fowler 也在 2026 年 4 月發表 Harness Engineering for Coding Agent Users,正式把這門學問工程化。LangChain 則在 The Anatomy of an Agent Harness 中提出了一個公式:Agent = Model + Harness。
本文將從原理到實作,系統性地拆解 Harness Engineering。
核心概念
Harness vs Agent vs Tool
flowchart TB
subgraph Harness["🔧 Harness(控制平面)"]
SM[Session Manager]
MR[Message Router]
TE[Tool Executor]
PE[Permission Layer]
CL[Context & Memory]
ORC[Orchestrator]
end
subgraph Agent["🧠 Agent(推理平面)"]
LLM[LLM Core]
PLAN[Planning]
DEC[Decision Making]
end
subgraph Tools["🛠️ Tools(能力平面)"]
T1[Shell]
T2[File I/O]
T3[Web/API]
T4[Browser]
T5[MCP Servers]
end
Harness --> Agent
Agent --> Harness
Harness --> Tools
Tools --> Harness
| 層級 | 職責 | 類比 |
|---|---|---|
| Agent | 推理、決策、規劃、工具選擇 | 大腦 |
| Tool | 執行具體操作(shell、讀寫檔案、網路請求) | 手腳 |
| Harness | 包住 agent,協調上下文、協議、權限、安全、I/O | 神經系統+OS |
Feedforward + Feedback 框架
Martin Fowler 提出了一個控制論框架來理解 harness:
-
Guides(Feedforward):在 agent 執行前就注入正確的上下文與約束,提高首次做對的機率
- System prompts、CLAUDE.md/AGENTS.md、rules、skills
- Task decomposition、plan templates
- Policy pre-configuration
-
Sensors(Feedback):在 agent 執行後收集結果並建立修正迴路
- Computational:tests、linters、type checkers、CI
- Inferential:LLM judge、semantic review、code review agent
失敗時不是叫模型「try harder」,而是補齊 missing capability 或建立 legible/enforceable scaffold。
架構與原理
核心模組架構
一個生產級的 AI Agent Harness 通常包含以下七個核心模組:
flowchart TD
UI[User / IDE / CLI / Channel] --> H[Harness Frontend]
H --> SM[Session Manager]
SM --> MR[Message Router / Event Bus]
MR --> ARA[Agent Runtime Adapter]
ARA --> LLM[LLM / Agent Core]
MR --> TE[Tool Executor]
TE --> MC[MCP Client Layer]
MC --> MS1[MCP Server: Git]
MC --> MS2[MCP Server: Browser]
MC --> MS3[MCP Server: DB/API]
H --> PE[Permission / Policy Engine]
PE --> TE
SM --> CL[Context & Memory Layer]
SM --> ORC[Orchestrator]
ORC --> ARA
1. Session Manager
職責:管理 agent 的整個生命週期。
- 建立
session_id/run_id - 維護狀態機:
created → running → awaiting → completed | failed | cancelled - 保存對話歷史、工具執行歷史、artifact 索引
- 支援
resume/retry/cancel - 支援 context compaction / summarization
狀態轉換:
stateDiagram-v2
[*] --> created
created --> running: submit prompt
running --> awaiting: need human input
running --> completed: task done
running --> failed: error
running --> cancelled: cancel
awaiting --> running: human resume
awaiting --> cancelled: cancel
completed --> [*]
failed --> running: retry
cancelled --> [*]
常見實作模式:
- In-memory + WAL/log append:本地 CLI 最快
- DB-backed:Postgres / SQLite / Redis,適合 distributed / HA
- Event-sourced:所有訊息/工具事件先 append,再 materialize view
關鍵原則:Session state 跟 message history 要分離。用 event log + projection 而非單一 blob 更新,才能支援 partial replay。
偽代碼:
|
|
2. Message Router
職責:處理所有來源的事件流,決定路由去向。
|
|
最佳實踐:
- UI stream 與 durable event stream 分開
- Tool stdout/stderr 不要直接全灌回 prompt,先聚合或截斷
- Router 需支援 backpressure,否則 streaming tool output 會拖垮 UI
3. Tool Executor
職責:統一管理工具呼叫的生命週期。
- Schema validation(JSON Schema)
- Timeout / retry / concurrency limit
- Stdout/stderr capture 與串流
- Side-effect 標記(read / write / destructive / network)
- Result normalization
實作模式:
| 模式 | 說明 | 代表 |
|---|---|---|
| Function-call style | JSON schema tool calling | Claude Code, OpenAI Assistants |
| Code execution style | 模型產生 code,sandbox 內跑 | smolagents |
| External protocol style | 工具本身是 MCP server / HTTP service | MCP 生態 |
| CLI wrapping | 用 subprocess 包 shell / git / codex | Codex CLI, Aider |
|
|
4. Permission Layer / Policy Engine
核心原則:權限判斷不能只是 prompt 裡的一句話,必須是硬邏輯層。
Policy 維度:
flowchart LR
A[File Scope] --> D{Policy Decision}
B[Side Effect Level] --> D
C[Trust Level] --> D
E[Tool Annotation] --> D
F[Environment] --> D
D -->|allow| G[執行]
D -->|ask| H[人類審批]
D -->|deny| I[拒絕]
|
|
典型分層(從低到高風險):
- Read — 讀取檔案、搜尋、查詢
- Edit — 修改現有檔案
- Exec — 執行命令
- Network — 網路請求
- Credential — 存取金鑰、憑證
- External Side Effects — git push、deploy、發布、發郵件
5. Context & Memory Layer
- 短期上下文(對話歷史 + system prompt)
- 長期記憶(跨 session 的知識持久化)
- 摘要 / 壓縮機制(避免 context window 超限)
- 支援多種 storage backend:vector DB、KV store、file-based
6. Transport / Protocol Adapters
Harness 需要支援多種通訊協議:
- MCP(Model Context Protocol):tool/resource 接入
- ACP(Agent Communication Protocol):agent session 控制
- CLI/TUI:終端機互動
- WebSocket / SSE:即時串流
- HTTP/REST:API endpoint
7. Orchestrator
管理單 agent loop 或多 agent 協作:
flowchart TD
ORC[Orchestrator] --> A[Worker A: Research]
ORC --> B[Worker B: Coding]
ORC --> C[Worker C: Review]
ORC --> D[Synthesizer: Merge]
A --> ORC
B --> ORC
C --> ORC
D --> ORC
Orchestrator 要提供:sub-session identity、ownership、result propagation、cancellation tree、concurrency limits、message isolation。
ACP 與 MCP:Harness 的兩大協議
MCP(Model Context Protocol)— 能力平面
MCP 是目前最成熟的 agent 工具接入標準,基於 JSON-RPC 2.0。
核心概念:
- 三個角色:Host / Client / Server
- Server 提供:Resources、Tools、Prompts
- Client 可提供:Sampling
- 支援 capability negotiation、stateful connection
在 Harness 中的正確整合方式:
flowchart LR
U[User/UI] --> H[Harness Host]
H --> PE[Permission Engine]
H --> TE[Tool Executor]
TE --> MC1[MCP Client A]
TE --> MC2[MCP Client B]
MC1 --> S1[MCP Server: Git/Jira]
MC2 --> S2[MCP Server: Browser/DB]
關鍵原則:
- Harness 是 Host,不應該把 MCP server 直接暴露給模型
- 每個 MCP server connection 最好是獨立 client instance
- Host 決定哪些 resources/tools 可見、哪些要 ask、哪些給哪些 subagent 用
- MCP tool descriptions 可能是 untrusted,不要盲目信任
- 遠端 MCP server 不應看到完整對話
2026 Roadmap 重點:
- Transport scalability
- Agent communication(Tasks primitive, SEP-1686)
- Governance maturation
- Enterprise readiness
ACP(Agent Communication Protocol)— 控制平面
ACP 目前有多個同名但不同定位的協議:
| 協議 | 定位 | 適用場景 |
|---|---|---|
| Agent Client Protocol (agentclientprotocol.com) | IDE/Client ↔ Coding Agent 通訊標準化 | 把 harness 暴露成可被編輯器使用的 endpoint |
| BeeAI ACP (i-am-bee) | Agent runtime API | 多 agent / app / human 互通、遠端 agent session 控制 |
| Agntcy ACP (Agent Connect Protocol) | REST/OpenAPI 風格的遠端 agent invoke | 跨組織 agent discovery / invocation |
BeeAI ACP 的核心概念(最完整的 ACP 實作):
- Run lifecycle:
created → in-progress → awaiting → cancelling → cancelled → completed → failed - 三種 run mode:sync / async / stream
- Await 機制:agent 可請求 client 補資料再 resume
- Session continuity:跨 run 的狀態延續
- 多模態 message parts:text、image、citation、trajectory metadata
|
|
實務建議:
- 本地 coding harness:MCP 用於 tool/plugin,ACP 用於 agent-to-client
- Session manager 保持本地 truth,ACP adapter 只是 transport façade
- 不要把核心 state 綁死在協定
MCP 解決能力接入;ACP 解決 agent session 控制。兩者互補,不互斥。
真實案例分析
OpenAI Codex CLI
OpenAI Codex 是「agent-first CLI harness」的代表。從其開源 repo(codex-rs/core/src)可觀察到清晰的模組分離:
|
|
設計亮點:
- Policy / event / tool / context 模組分得清楚
- Human-readable 與 JSONL output processor 分離,自動化與互動共存
- Sandbox 與 approval 不是附屬功能,是核心能力
- macOS 用 Seatbelt,Linux 用 bubblewrap + seccomp / Landlock
Claude Code
Claude Code 是「terminal-native + repo-native harness」的代表:
- 內建 Read / Write / Edit / Bash / Glob / Grep / WebSearch / WebFetch
- Hooks 系統:PreToolUse / PostToolUse / Stop / SessionStart / SessionEnd…
- Subagents 有獨立 context、權限、memory
- 記憶設計:instruction memory(CLAUDE.md)+ auto-notes(agent 自動學習)
- 支援多 surface:Terminal / IDE / Desktop / Web
設計亮點:
- Hooks 是最乾淨的 governance extension point
- Subagent 不是平行 thread,而是有 scope / tools / permission / memory 的 specialized runtime
Cursor / Windsurf
Cursor — IDE-native harness:
- Editor state / selection / repo context 作為自然上下文
- Tool surface 偏編輯器能力、終端、檔案、搜尋
- 特別重視「編輯-預覽-接受」的 UX flow
Windsurf(Cascade) — IDE + agent workflow:
- 除了基本工具,加入了 Memories、Rules、AGENTS.md、Workflows、Skills
- 把 harness 做成 agent operating environment
開源框架
| 框架 | Harness 模式 | 適合場景 |
|---|---|---|
| LangGraph | Graph-based workflow + state checkpoint | 明確工作流、可視化 pipeline |
| AutoGen | Conversation-first multi-agent | 多代理對話、協商、角色分工 |
| CrewAI | Role-based crew coordination | Business workflow / team orchestration |
| OpenHands | SDK + CLI + GUI + Cloud 分層 | Runtime library + 多 surface 部署 |
實作範例:最小可用 Harness
以下展示一個最小化的 Harness 核心架構,用於理解各組件如何協作:
|
|
這個最小示例展示了 Harness 的核心邏輯:session 管理 + 事件驅動 + 權限控制 + 工具執行 + agent loop。生產級的 Harness 會在此基础上加入 MCP 整合、subagent orchestration、sandboxing、observability 等能力。
最佳實踐
設計可靠 Harness 的 10 個原則
- Session-first,不是 completion-first — 把 agent 當成長期互動的 session,不是單次 API call
- Side-effect aware — 每個工具呼叫都要標記副作用等級
- Fail-closed permissions — 預設拒絕,明確允許才開放
- Tool calls 必須結構化 — JSON Schema validation,不要裸字串
- 所有重要事件可追蹤 — Event-sourced logs,支援 replay / debug
- 支持 cancel / retry / resume — 長任務不能卡死
- Agent 與 UI 分離 — 協議中介清晰,UI 換了 runtime 不用改
- MCP/外部工具整合要經 policy proxy — 不要直接暴露給模型
- 同一 session 的並發要可控 — Queue owner / single-writer model
- 對 prompt injection 視為系統級威脅 — Untrusted content 要隔離上下文
常見陷阱與解法
| 陷阱 | 後果 | 解法 |
|---|---|---|
| 把 agent 當同步函數呼叫 | 無法 cancel、resume、debug | 引入 session + event sourcing |
| Tool result 與 agent state 沒持久化 | Crash 後全部丟失 | WAL log + checkpoint |
| 無 cancellation 機制 | 長任務卡死 | Cancellation token tree |
| 多 prompt 對同 session 並發 | Race condition、狀態混亂 | Queue owner / single-writer |
| 權限粗粒度 | 過度授權、安全漏洞 | Multi-dimensional policy engine |
| 外部內容直接注入主上下文 | Prompt injection | Separate context window for untrusted fetches |
| Session resume 後 state 漂移 | Mode/model/tool 配置錯亂 | Desired state replay on fresh session |
| MCP server 看到完整對話 | 資料外洩 | Host isolation、最小暴露 |
測試策略
應測的層次:
- Protocol tests — initialize、session create/load、prompt、cancel、config mutation、error mapping
- Tool integration tests — schema validation、timeout、malformed output、partial failure
- Security tests — path escape、command injection、prompt injection、approval bypass
- Lifecycle tests — agent crash mid-turn、restart & resume、pending cancel
- Concurrency tests — multiple prompt submissions、session lock contention、queue depth bounds
好的 debug 能力:raw event log、normalized + original error、lifecycle snapshot、tool call trace、permission decision trace。
安全與治理
企業級考量
企業級 Harness 不只是「讓 agent 會做事」,而是要讓 agent:
- 做對事(policy enforcement)
- 在對的權限下做(least privilege)
- 留下可審計紀錄(audit trail)
- 出錯時可收斂與回滾(rollback / replay)
安全模型
flowchart TD
IN[Agent Tool Call] --> PE{Policy Engine}
PE -->|allow| SANDBOX[Sandbox Execution]
PE -->|ask| HUMAN[Human Approval]
PE -->|deny| REJECT[Rejected]
HUMAN -->|approve| SANDBOX
HUMAN -->|deny| REJECT
SANDBOX --> RESULT[Result]
RESULT --> LOG[Audit Log]
RESULT --> CONTEXT[Context Update]
MCP 的安全挑戰
- MCP server 的 tool descriptions 可能是 untrusted
- 遠端 MCP server 的資料外洩風險
- Agent-to-agent communication 的身份與授權問題
- 跨租戶 memory leakage
未來趨勢
1. Harness 標準化
- MCP 正在標準化 tool/resource/prompt 接口,已成為 de facto ecosystem center
- ACP 正在成形,標準化 agent session control
- 未來格局:MCP = 能力平面,ACP = 控制平面
2. 多模態 Harness
未來 Harness 不只管文字與 shell,還會統一管理:
- Vision tools
- Browser automation
- GUI control
- Voice I/O
- Video / sensor inputs
3. 分布式 Agent Harness
- Remote workers
- Distributed session routing
- Agent mesh / fabric
- Policy-enforced org-wide orchestration
- Cross-device persistent sessions
4. Policy-native Agent Runtime
未來的 Harness 會越來越像:
- Mini OS(資源管理、行程管理)
- Zero-trust runtime(每個操作都要驗證)
- Auditable automation layer(所有操作可追溯)
重點整理
- Harness 是 agent 系統的控制平面,不是附屬品 — 它決定了 agent 是否安全、可靠、可觀測
- Agent = Model + Harness — 模型是引擎,harness 是底盤,缺一不可
- 七個核心模組:Session Manager、Message Router、Tool Executor、Permission Layer、Context & Memory、Transport Adapters、Orchestrator
- MCP 解決能力接入;ACP 解決 agent session 控制 — 兩者互補
- 權限必須是硬邏輯層 — 不能只靠 prompt 裡的一句話
- 真正的競爭點在 Harness 品質 — 模型能力的差距在縮小,harness 工程的差距在拉大
參考資料
- OpenAI — Harness Engineering: Leveraging Codex in an Agent-First World
- Martin Fowler — Harness Engineering for Coding Agent Users
- LangChain — The Anatomy of an Agent Harness
- Agent Engineering — Harness Engineering in 2026
- Agent Client Protocol
- BeeAI ACP
- MCP 2026 Roadmap
- Thoughtworks — The Model Context Protocol’s Impact on 2025
- Cerbos — AI Agents, MCP, and Authorization Guardrails
- Microblink — What is ACP Agent Communication Protocol
- OpenAI Codex CLI (GitHub)
- Anthropic Claude Code Docs