Code Mode¶
Code Mode 是 Codex 工具系统中的一个特殊执行模式:模型不是调用一组普通 JSON function tools,而是通过一个 freeform exec 工具提交代码单元,再用 wait 等待或终止该单元。
工具形态¶
codex-rs/core/src/tools/code_mode/execute_spec.rs 创建 freeform tool:
- tool name 来自
codex_code_mode::PUBLIC_TOOL_NAME。 - format 是 Lark grammar。
- 支持普通 source,也支持
// @exec:pragma line。
wait_spec.rs 创建普通 function tool:
cell_idyield_time_msmax_tokensterminate
CodeModeService¶
codex-rs/core/src/tools/code_mode/mod.rs 中的 CodeModeService 包装 codex_code_mode::CodeModeService,并挂上 CodeModeDispatchBroker。它支持:
executewaitterminateshutdownmark_cell_ready_for_dispatchfinish_cell_dispatch
Nested Tool Call¶
Code Mode 的强点是 nested tool call。delegate.rs 中的 CoreTurnHost 和 CodeModeDispatchBroker 可以让 code cell 内部请求调用 Codex 工具。broker 会等 cell ready 后再 dispatch,避免 runtime 尚未进入可接收状态时就把 nested tool 发出去。
Nested tool 仍然走:
ToolCallRuntime -> ToolRouter -> ToolRegistry
因此 code cell 里的工具调用也受 hook、权限、沙箱、telemetry 管控。
Cell 生命周期¶
CodeModeExecuteHandler 执行流程:
- 解析 exec source。
- 收集 code mode enabled tools。
- 调用 code mode service execute。
- 建立 code cell trace。
- 标记 cell ready for dispatch。
- 等待 initial response。
- 如果不是 yielded,记录 cell ended 并关闭 dispatch gate。
- 把 runtime response 转成模型可见 tool output。
CodeModeWaitHandler 负责等待 yielded cell、终止 cell,并在 terminal response 时记录 trace ended。
输出处理¶
Code Mode 输出会经过 truncation policy。图片输出会通过 response_adapter.rs 转成 protocol 的 FunctionCallOutputContentItem,并处理 image detail。
可学习的设计¶
Code Mode 展示了 Codex 对工具协议的扩展能力:
- freeform grammar tool 适合代码单元。
- yielded cell 支持长运行任务。
- nested tool call 让代码 runtime 仍能访问 Codex 工具。
- dispatch gate 避免生命周期竞态。
- trace 将 code cell 与模型-visible output 关联起来。