CODEX-RS · CORE HARNESS

Codex 核心 Harness 架构图

模型之外的一切驱动逻辑:会话/线程管理 · Op/Event 协议 · turn 状态机 · 流式采样 · 工具调度 · 审批沙箱 · 上下文压缩 · rollout 持久化

source: codex-rs/core · codex-rs/protocol · codex-rs/tools · 配套文档 HARNESS_DESIGN.md
01总体分层架构
L0 · HOST
宿主前端
TUI
ratatui 终端界面 codex-tui
CLI
codex cli · !cmd
app-server
JSON-RPC(v2 API)· SDK
exec / exec-server
非交互执行 · 远程环境
L1 · WIRE
线协议
protocol crate
Op 枚举
TurnInput · Interrupt · ExecApproval · Compact · Shutdown …
Event / EventMsg
TurnItem · TokenCount · 审批请求 · TurnComplete …
Submission
{id(UUIDv7), op, trace}
ResponseItem
message · reasoning · function_call / output
▼ Op 提交(mpsc,容量 512)Event 下发 / agent_status watch ▲
L2 · MANAGER
线程管理
ThreadManager
创建/恢复/fork/列出线程;持有 AuthManager · McpManager · ModelsManager · ThreadStore
AgentControl
并发容量 · spawn 深度限制 · 多 agent 注册
L3 · HANDLE
会话句柄
CodexThread
薄句柄(每线程一个):submit · next_event · start_or_steer_turn · rollout 读写
SessionIo
tx_sub / rx_event / agent_status / loop-termination;drop sender 即终止循环
L4 · CORE
Harness 内核
Session(单 task 串行)
submission_loop
while recv(Op) 顺序 match 分发;并发只在内部 spawn
ActiveTurn
至多 1 个运行 turn;RunningTask + CancellationToken
TurnState
pending 审批/提问/elicitation 的 oneshot 续体表
InputQueue
steer 输入 · 子 agent 邮箱邮件
SessionState
配置态:模型 · approval policy · permission profile · cwd · base instructions
SessionServices
MCP 运行时 · 进程管理器 · ApprovalStore · ModelClient · telemetry · 插件/skills · ThreadStore · 网络代理
L5 · TURN
轮次驱动
run_turn
agentic 主循环:采样 → 工具 → 回灌 → 再采样
TurnContext / StepContext
turn 级快照 + 每次采样的 model/tools/env/mcp 冻结快照
ContextManager
历史只追加;for_prompt() 产出请求 input
ContextualUserFragment
40+ 有界标记片段:world state · 预算 · 多 agent · 策略提醒
compaction
新 context window / 远程压缩 V2·V1 / 本地摘要
hooks 生命周期
session-start · pre/post tool use · stop · turn-end
L6 · CAPS
能力子系统
tools/
ToolRegistry · ToolRouter · ToolCallRuntime(并行/按序回灌)· spec_plan 按 step 建表
内置工具
shell/exec · apply_patch · update_plan · view_image · request_user_input/permissions · 多 agent · web search
unified_exec
PTY 进程 · 后台终端 · head/tail 截断输出(1 MiB 上限)
审批 & Guardian
hooks → 自动审查 → 用户;决策可沉淀为 policy amendment
沙箱 / 策略
Seatbelt(macOS) · bwrap/Landlock(Linux) · Windows token;execpolicy;网络代理域授权
MCP / 插件 / skills
外部工具运行时 · tool_search 延迟发现 · 连接器
持久化 & 观测
rollout 事件流 · thread-store / state DB(SQLite) · OTel spans · analytics
L7 · MODEL
模型提供商
Responses API
POST /responses · SSE 流 / WebSocket(turn 级复用 + sticky routing)
ModelClientSession
重试退避 · 增量请求 · 速率限制
02run_turn · Agentic 主循环
flowchart TB
  A["🧾 TurnInput  start / steer / recover
(turn_input.rs 唯一路由决策点)"]:::start B["📸 捕获 StepContext
model · tools · env · mcp 同一份快照"]:::step C{"⚡ pre-sampling
需要压缩?"}:::dec C1["🗜 run_auto_compact
新窗口 / 远程压缩 V2·V1 / 本地摘要"]:::compact D["📦 build_prompt
历史 for_prompt() + ToolSpec[] + base_instructions"]:::step E["🌊 Responses API 流式采样
SSE / WebSocket · turn-scoped session · 重试"]:::model F{"🔽 输出 item"}:::dec H["🛠 ToolCallRuntime
并行 spawn(FuturesOrdered)"]:::tool I["🔐 审批:hooks → Guardian → 用户
沙箱 / execpolicy / 网络策略"]:::sec J["⚙️ 执行
shell · apply_patch · MCP · spawn_agent …"]:::tool K["📥 工具输出按调用顺序
record 进历史(FunctionCallOutput)"]:::step G{"🔁 needs_follow_up?
(工具待续 / pending input / end_turn=false)"}:::dec L["🏁 stop hooks → TurnComplete"]:::done A --> B --> C C -- 是 --> C1 --> D C -- 否 --> D D --> E --> F F -- "function / custom tool call" --> H --> I --> J --> K --> G F -- "assistant / reasoning 消息" --> G G -- "是 → 排空 steer/邮件 后继续" --> D G -- "否" --> L classDef start fill:#1e293b,stroke:#e8b84b,color:#fde68a,stroke-width:1.5px classDef step fill:#172033,stroke:#22d3ee,color:#a5f3fc classDef dec fill:#1c1930,stroke:#a78bfa,color:#ddd6fe classDef compact fill:#2a1f14,stroke:#fb923c,color:#fed7aa classDef model fill:#14241d,stroke:#34d399,color:#a7f3d0 classDef tool fill:#172033,stroke:#60a5fa,color:#bfdbfe classDef sec fill:#2a1720,stroke:#fb7185,color:#fecdd3 classDef done fill:#14241d,stroke:#34d399,color:#6ee7b7,stroke-width:1.5px
session/turn.rs · run_turn / try_run_sampling_request / drain_in_flight
03工具调用 · 审批与沙箱流
flowchart LR
  TC["模型发出 tool call
shell · apply_patch · MCP · 网络"]:::tool ORCH["ToolOrchestrator
(unified_exec / approvals)"]:::step H1{"❶ PreToolUse
hooks 决策?"}:::dec G1{"❷ StrictAutoReview
或 Guardian 启用?"}:::dec GR["🤖 Guardian 自动审查
(模型 reviewer)"]:::sec U1{"用户批准
被拒动作重试?"}:::dec U2["📨 审批请求事件
→ 前端弹窗"]:::step DEC["❸ 用户决策
ExecApproval / PatchApproval Op"]:::start RUN["▶️ 沙箱内执行
Seatbelt / bwrap / Win token
+ execpolicy + 网络代理"]:::model REJ["⛔ 拒绝 / 中止"]:::sec OUT["📤 ToolOutput → 历史
→ 下一次采样带回模型"]:::done TC --> ORCH --> H1 H1 -- "allow" --> RUN H1 -- "deny" --> REJ H1 -- "无决策" --> G1 G1 -- "是" --> GR GR -- "批准" --> RUN GR -- "拒绝" --> U1 U1 -- "是(可带规则修订)" --> RUN U1 -- "否" --> REJ G1 -- "否" --> U2 --> DEC DEC -- "批准(+ policy amendment 沉淀)" --> RUN DEC -- "拒绝 / Abort" --> REJ RUN --> OUT REJ --> OUT classDef tool fill:#172033,stroke:#60a5fa,color:#bfdbfe classDef step fill:#172033,stroke:#22d3ee,color:#a5f3fc classDef dec fill:#1c1930,stroke:#a78bfa,color:#ddd6fe classDef sec fill:#2a1720,stroke:#fb7185,color:#fecdd3 classDef model fill:#14241d,stroke:#34d399,color:#a7f3d0 classDef start fill:#1e293b,stroke:#e8b84b,color:#fde68a classDef done fill:#14241d,stroke:#34d399,color:#6ee7b7,stroke-width:1.5px
tools/approvals.rs · request_approval(优先级:hooks → Guardian → 用户)· unified_exec/mod.rs · sandboxing/
04关键设计不变量

I-1单循环串行化

一个 session 一个 submission_loop task 顺序处理所有 Op;并发仅在 turn/工具内部显式 spawn,状态机无锁竞争。

I-2一切皆消息

前端与 core 之间只有 Op/Event;core 内部"问用户"(审批/提问/elicitation)统一为 oneshot + 应答 Op。

I-3快照驱动

turn 有 TurnContext、每次采样有 StepContext:工具集、MCP、环境、权限按 step 冻结,请求自洽且可重放。

I-4上下文有界且增量

历史只追加不重写;环境信息以带标记 ContextualUserFragment 差异注入;超限走压缩/新窗口,硬上限兜底。

I-5安全内建于工具路径

审批、permission profile、平台沙箱、execpolicy、网络代理在 orchestrator 层统一收口,工具 handler 不自行决策。

I-6工具并行、结果按序

同一响应内多个工具调用并行 spawn,FuturesOrdered 按模型发出顺序回灌,兼顾并发与上下文确定性。

I-7持久化即事件流

rollout 是唯一真相源;fork / resume / rollback / review 都是对事件流的读取、截断或重放。

I-8薄句柄 + 厚内核

CodexThread 是唯一对外面,Session/services 全部 crate-private,crate API 面最小化。