系统总览
1. 系统总览
这个系统可以想成一位“会开终端的代码助手”。用户可能打开聊天式终端界面,也可能用命令行让它一次性办事,或者把它当后台服务器给别的程序调用。进程一启动,入口先看自己是哪个小程序、带了什么参数;随后加上安全锁,找安装位置和用户目录,读取配置,确认登录身份,再打开本地数据库和缓存。准备好后,它会连接模型服务、插件、远程工具和服务器通道,把前台界面或脚本入口接上。运行时,所有按键、聊天请求和远程命令都会进主调度室排队;系统为每轮对话整理上下文,发给模型,模型要查文件、跑命令或改代码时,还要经过权限、审批和沙箱限制。结果会被显示、记录、同步状态。关机时,它先挡住新请求,等手头工作收尾,再断连接、保存状态。后台还有协议合同、网络通信、日志体检、数据仓库、公共工具和测试体系,像水电和安保一样支撑全局。
2. 两张 ASCII 图
图 A · 生命周期
[入口识别与模式分发]
|
v
[环境探测 / 进程加固 / 本地资源准备]
|
v
[配置 + 账号 + 权限 + 模型/插件目录装配]
|
v
[服务端 / 终端界面 / 会话建立]
|
v
[事件主循环:接收输入、定位线程、恢复上下文]
|
v
[组装提示词:历史 + 规则 + 工具 + 记忆 + 工作区]
|
v
[调用模型并处理流式输出]
|
v
[审批 / 沙箱 / 工具执行 / 文件修改 / 外部服务]
|
v
[结果归并:更新 UI、保存记录、写入状态]
|
v
[关闭收尾:阻止新任务、排空队列、保存最终状态]图 B · 一次对话回合
[用户或客户端输入]
|
v
[路由到会话/线程]
|
v
[拼上下文包和可用工具清单]
|
v
[发送给模型]
|
v
{模型需要做动作吗?}
| 否 | 是
v v
[整理回复并更新界面] [检查权限/是否要用户批准]
|
v
[在沙箱或受控环境里执行]
|
v
[把工具结果交回模型/会话]
|
v
{任务结束了吗?}
| 是 | 否
v v
[保存并收尾] [进入下一轮]3. 主流程地图
- 进程入口点和二进制分发: 这一阶段就是原生程序刚启动时的“门口分流”。用户敲下 codex,或启动 app-server、codex-exec 等小程序后,入口代码先看程序名 argv[0] 和用户写的参数;clap 这个参数解析工具会把选项整理清楚。主要入口像总服务台,决定去终端界面、一次性执行、登录或维护命令。辅助工具像旁边的工具箱,负责生成协议、打补丁、找文件、开后台服务和跑沙箱。exec 的入口还会判断自己是普通执行器,还是 Linux 沙箱工具,然后把活交给对应模块。
- 早期进程加固和运行时引导: 这一阶段发生在程序刚启动、还没真正干活之前,像出门前先锁门、检查工具箱。process-hardening 先给进程上安全锁,防止被调试、被偷偷导出内存,或被危险环境变量带偏。rustls-provider 提前选好全局 HTTPS 加密工具,免得后面联网时临时找不到可用方案。arg0 则让同一个程序能按不同名字扮演不同小工具,同时准备 PATH、读取安全的 .env,并搭好异步运行框架,方便后续阶段开始工作。
- 安装环境、主目录发现和本地环境探测: 这一阶段像开工前先认路、点工具。程序会弄清自己装在哪、家目录 CODEX_HOME 在哪、捆绑的小工具该从哪里拿,也会看当前电脑、终端、Git、云端执行环境是否可用。安装识别和托管安装文件帮更新、重启找准版本;家目录和主机名给配置加载打底;shell 快照尽量保住用户终端习惯;exec-server 和云环境选择决定命令在哪跑;doctor 检查 Git、系统和运行环境,方便出问题时快速定位。
- 配置、功能解析和启动策略组装: 这一阶段是在真正干活前的“开机配餐”。它先把本地文件、云端规则、项目要求、命令行参数和临时请求都收齐,按优先级合成一份最终配置。再把功能开关、模型列表、插件、MCP 服务、内置模板等备好。权限部分会把用户写的规则翻译成沙箱能执行的读写、联网限制,Windows 还要单独算路径和身份牌。界面和服务器也用同一套入口改配置、存配置、查调试信息,避免前后说法不一致。
- 身份验证、身份和账号就绪: 这一阶段像系统开工前的“验票和办证”。启动时先读出以前保存的登录状态;没有票或票过期,就引导用户登录、刷新,或退出时撤销旧票。登录总管把 API Key、ChatGPT 令牌、个人访问令牌、Agent 身份、Bedrock Key 统一管起来。令牌解析器看懂这串票是谁的、什么套餐、何时过期。提供商适配器再把不同服务需要的钥匙、签名和请求头装好。安装编号和 Windows 沙箱用户则帮系统认准本机和安全身份。
- 持久化和本地运行时服务启动: 这个阶段像开店前先把仓库和账本整理好。程序启动时,会打开本地 SQLite(放在电脑上的小数据库),把旧格式升级成新格式。StateRuntime 统一打开线程、日志、目标、记忆等库;rollout 的 state_db 把会话状态存进去;core 的 bridge 只是递交配置的转接头;migrations 准备升级步骤。若库坏了或被占用,恢复代码会提示用户、挪走坏文件并重建,让后面的功能能放心读写。
- 后端客户端、远程目录和启动刷新: 这一段发生在配置和登录都准备好之后,像开店前补货。它先拉云端配置,决定用缓存还是联网,并在后台刷新;再整理可选模型,既问 Codex 或模型服务商,也检查本机 Ollama、LM Studio。接着同步连接器、插件目录、MCP 工具和工作区权限,让界面能显示真实可用的东西。还会顺手查任务、额度、记忆写入安全和版本更新,尽量用缓存和后台任务,别拖慢启动。
- 传输和服务器运行时初始化: 这一阶段是在程序要当“服务器”时,先把收发消息的路铺好,属于开机启动和幕后支撑。它一边启动 app-server 和 daemon,管进程开关、日志、配置、鉴权,并把 stdio、本机 socket、WebSocket 等通道接上;另一边启动 exec-server、MCP 等外挂机器,让外部工具、远程控制和客户端都能用 JSON-RPC 这种固定格式说话。各部件像总机、门卫和转接线,先登记连接,再转发请求和通知。
- 前端会话启动和面向用户的初始化: 这一阶段把已经启动好的后端,接到用户真正能用的前台上。走聊天界面时,TUI 会读取配置和命令,处理登录、恢复旧会话、新手引导、目录信任、模型选择,再搭好聊天窗口、快捷键、通知和终端接管,像把柜台布置好再开门营业。走 exec 模式时,它不打开聊天窗口,而是为脚本准备一次性会话,接好输入和机器可读的输出,跑完后用退出码告诉外部成功还是失败。
- 主事件循环和请求分发: 这一阶段是系统跑起来后的“总调度室”,一直在主循环里值班。用户敲键、粘贴、点确认,先被界面事件流收进来,再按输入框、弹窗、聊天区、线程等位置分给对应部件。外部来的 JSON-RPC 请求,也就是带编号的远程命令,会先经过服务器解码、鉴权和排队,再交给会话、文件、插件、工具等处理。几个调度文件负责接线、排队、防止同时乱改;并行工具调度则决定哪些活能一起做、取消时怎么收尾。
- 线程和会话编排: 这一阶段像客服中心的排班台,处在真正执行每轮回答之前和过程中:先决定任务挂到哪条对话线。入口文件把能力统一摆出来;线程管理器负责新建、恢复、复制、关闭、切换线程,并接上本地记录。环境选择、会话外壳和服务工具箱准备模型、目录、权限、插件。输入队列、注入器、任务和状态记事本保证一轮一轮不串线。存储、服务器和终端界面负责保存、重连、筛选、显示;目标、技能、旁路对话等扩展再插进来一起跑。
- 提示词、上下文和扩展组装: 这个阶段发生在每次把问题交给模型之前,像开演前给演员整理台本。它先用“门面”和模板,规定提示词、便签、内嵌说明怎么登记和拼装;再从提示词库拿固定说明,把环境、命令结果、技能等包成带来源的小纸条;接着收集用户规则、项目规则、权限、插件、记忆、目标和评审要求;最后整理历史、补上新变化、控制长度,并让调试工具看到模型最终拿到的内容。
- 回合执行和模型交互: 这是系统最核心的“每一轮聊天怎么跑”。用户发来一句话后,普通任务先排队,处理取消和追加输入;回合执行器把历史、工具、钩子和环境标签装好。若聊天太长,压缩模块先把旧内容缩成摘要。模型传输部分再把请求送到模型服务,并一边收回分段结果一边处理重试。流式展示像字幕组,把碎片排成界面和历史。代码模式还提供 JavaScript 小沙盒,让脚本、定时器和外部工具在回合里协同工作。
- 工具执行、审批与受控操作: 这一阶段发生在模型说“我要动手做点事”之后,是主流程里的受控执行段。它先按统一合同看懂工具长什么样、参数是否干净,再把 MCP、插件、搜索、记忆、图片等外部工具翻译成系统能用的格式。接着安全总闸检查要不要审批,hook 可插手补查,沙箱规则限制文件、网络和权限。通过后,执行后端才真正跑命令、打补丁或调用远端工具。出错时也会分清是可告诉模型的小问题,还是必须停下来的严重故障。
- 多智能体、协作与后台流程: 这个阶段像主会话旁边的“调度室”,不是自己回答完就结束,而是在主循环中帮忙开小助手、派活、传话、等待和收尾。登记表记录有哪些代理在跑,闸门和停车场限制数量,避免资源被占满。创建、恢复、关闭、打断、发消息、等待等工具让主代理能像带团队一样协作。还有审查助手、CSV 批量派工、记忆后台整理、技能文件监视等流程,把结果再汇回主会话。
- 结果持久化、展示与状态更新: 这一阶段像“记账和播报员”,发生在每轮工作推进或结束后。核心先把模型回复、工具结果、文件改动整理成统一事件,再筛选哪些要写进会话记录和状态库;同时更新线程状态、标题、用量、归档等信息。服务器把内部事件翻译成前端通知,重连时还能补回历史。TUI 和 CLI 再把这些记录变成状态栏、聊天历史、diff、体检报告;exec 则输出 JSON,方便外部程序读取。
- 关闭、清理与收尾: 这一段像程序“打烊”。连接要断、会话要关,或后台更新要重启服务时,先别一脚拔电源。RPC 闸门先拦住新请求,让已开工的请求做完;连接清理器把断线后的扫尾丢到后台,能收就收,超时就报错或取消;老式 agent 管家先保存状态,再通知它和子任务关机,最后清掉记录;自动更新循环则挑空档下载新版并重启服务,尽量不打扰正在干活的部分。
- 协议 schema、共享类型与生成契约: 这一阶段是全系统的幕后“合同库”,不负责开机、主循环或关机,而是先规定大家怎么说话、数据长什么样。核心协议像通用词典,统一会话、权限、工具结果等说法;app-server schema 规定前端和服务器的消息信封;后端 OpenAPI、protobuf 把远程接口也对齐;扩展、hook、MCP、跟踪 schema 给插件、工具和流水账定格式;宏则在编译时自动补检查。这样各零件传话、存档、调用工具时不容易说岔。
- 通用传输、网络与客户端基础设施: 这一阶段是系统的“通信底座”,不直接干业务,却让各部分能安全说话。HTTP客户端管出网、重试、证书、Cookie和流式消息。app-server、exec-server和relay把本地管道、WebSocket、大文件和远程消息打包、加密、转发。代理和本地IPC像门卫和内线电话,管住外网访问,也连起进程、沙箱和IDE。MCP适配器统一各种通信方式,几个门面和错误文件则把入口、返回和失败原因整理好。
- 通用可观测性、分析与反馈: 这一阶段是贯穿全程的“记录和体检系统”,从启动、处理请求、跑工具到关机都在幕后工作。分析事件先把会话、报错、代码改动等记成统一格式,再归并、排队发出。OpenTelemetry 像统一仪表盘,收日志、指标和耗时。会话和专项埋点记录每次请求、工具、数据库等表现。Rollout trace 把过程写成可回放的流水账。反馈和日志持久化负责打包线索、脱敏、存本地,Windows 沙盒日志也记录命令成败,方便事后排查。
- 通用持久化抽象与数据存储: 这一阶段是系统的“后勤仓库”,不直接聊天干活,却让很多东西能长期保存、下次还能接上。rollout、消息历史和 thread-store 保存对话档案;SQLite 状态库存会话、任务、日志和“谁带起谁”的关系;各种缓存把云配置、插件目录、模型列表先放本地,少等网络;插件、密钥、记忆文件负责安全落盘;外部导入则登记、读取并转换别家的聊天记录,避免重复搬运。
- 通用工具与支持库: 这一阶段像整套系统的公共工具间,平时不站在主流程中央,却从启动、运行到排错都被反复用到。路径和文件工具负责把地址认准、把文件安全打开;文字工具负责截短、脱敏、排版;配置、认证和网络工具帮程序带对钥匙、走对门;命令、Git、插件工具负责把外部活儿跑稳。还有等待、取消、图片、构建脚本等小零件。核心 util、错误类型、模糊匹配和 hook 公用代码,则把常见规则统一起来,避免各处各写一套。
- 测试、夹具与开发者验证工具: 这一阶段像整个仓库的“总验收场”,不直接服务用户,而是在开机、聊天处理、工具执行、界面显示、保存收尾这些环节旁边反复试车。App-server 测协议和整条服务流程;Core 测会话、工具、安全边界;CLI、登录、MCP 测命令入口和开发者流程;exec-server 测远程传输、文件和沙箱;TUI 测终端画面和交互;共享库测试盯遥测、配置、路径、状态等底座。test-binary-support 还帮测试程序换“马甲”启动,安全地检查不同入口行为。
1进程入口点和二进制分发65 个文件
这一阶段就是原生程序刚启动时的“门口分流”。用户敲下 codex,或启动 app-server、codex-exec 等小程序后,入口代码先看程序名 argv[0] 和用户写的参数;clap 这个参数解析工具会把选项整理清楚。主要入口像总服务台,决定去终端界面、一次性执行、登录或维护命令。辅助工具像旁边的工具箱,负责生成协议、打补丁、找文件、开后台服务和跑沙箱。exec 的入口还会判断自己是普通执行器,还是 Linux 沙箱工具,然后把活交给对应模块。
1.1主要面向用户的启动入口19 个文件
这一层是用户敲下 codex 后最先到达的“总服务台”。main.rs 先看用户想做什么:开终端界面、跑一次性任务、登录、云任务、远程服务、桌面应用、沙箱调试或体检。各个 cli.rs 像点菜单,规定能填哪些选项;命令文件像分诊员,把参数交给真正干活的模块。doctor、archive、mcp、apply 等则把常用维护操作串成可直接使用的流程。
1.2辅助二进制和开发者工具45 个文件
这一阶段像工具箱,不是主程序的日常入口,而是给开发、测试和后台运行帮忙。配置和协议生成器负责产出“格式说明书”,让前后端和编辑器对得上;apply-patch、file-search做补丁和找文件;app-server、MCP、代理和stdio桥接负责单独启动服务或转发消息;沙箱、执行策略工具负责安全地跑命令;日志查看器、示例和假服务器则方便排查问题、演练接口和做自动测试。
2早期进程加固和运行时引导3 个文件
这一阶段发生在程序刚启动、还没真正干活之前,像出门前先锁门、检查工具箱。process-hardening 先给进程上安全锁,防止被调试、被偷偷导出内存,或被危险环境变量带偏。rustls-provider 提前选好全局 HTTPS 加密工具,免得后面联网时临时找不到可用方案。arg0 则让同一个程序能按不同名字扮演不同小工具,同时准备 PATH、读取安全的 .env,并搭好异步运行框架,方便后续阶段开始工作。
3安装环境、主目录发现和本地环境探测12 个文件
这一阶段像开工前先认路、点工具。程序会弄清自己装在哪、家目录 CODEX_HOME 在哪、捆绑的小工具该从哪里拿,也会看当前电脑、终端、Git、云端执行环境是否可用。安装识别和托管安装文件帮更新、重启找准版本;家目录和主机名给配置加载打底;shell 快照尽量保住用户终端习惯;exec-server 和云环境选择决定命令在哪跑;doctor 检查 Git、系统和运行环境,方便出问题时快速定位。
4配置、功能解析和启动策略组装105 个文件
这一阶段是在真正干活前的“开机配餐”。它先把本地文件、云端规则、项目要求、命令行参数和临时请求都收齐,按优先级合成一份最终配置。再把功能开关、模型列表、插件、MCP 服务、内置模板等备好。权限部分会把用户写的规则翻译成沙箱能执行的读写、联网限制,Windows 还要单独算路径和身份牌。界面和服务器也用同一套入口改配置、存配置、查调试信息,避免前后说法不一致。
4.1配置层摄取和要求组合42 个文件
这一层是系统开工前的“总配电和规矩汇总”。它不直接干主任务,而是先把本地 TOML 文件、云端或管理员下发的配置、项目要求、命令行临时设置都收进来。核心配置部分负责规定格式、按优先级合并、指出哪一行写错,并记录来源。需求分层部分把安全禁令、命令执行规则、hook 等硬规矩叠好,防止被随便覆盖。配置管理服务像设置柜台,给前端和后台读改保存配置。lib.rs 则是统一入口,让外部不用摸清内部细节,也能调用这些能力。
4.1.1核心配置 schema、诊断、合并和分层加载22 个文件
这一阶段像程序开机前的“配电箱”,专门把各种配置收齐、查错、排好优先级。config.toml、钩子、MCP、profile、快捷键、运行环境、代理角色等文件先规定每种配置该怎么写。云端、管理员、用户、项目、会话线程和命令行临时改动再被读成一层层配置。合并器按规则让后来的覆盖前面的,状态栈算出最终生效值;严格检查和诊断负责指出写错的文件行列;指纹和锁文件则记录来源和快照,防止配置悄悄变了。
4.1.2需求分层和执行策略组合11 个文件
这一阶段像开工前的“规矩汇总台”,属于幕后支撑。它先读 requirements.toml、企业下发配置等来源,把每一层拆清楚:普通配置普通合,读文件禁令、执行规则、hook 这些安全项按专门办法追加或校验,不能被后来的配置冲掉。最后 stack 把多层叠成最终要求;执行策略部分把“哪些命令能跑”翻成机器能检查的规则,并能安全追加白名单;网络代理配置会随文件变化重载;hook 规则则保护用户自己的启用和信任选择。
4.1.3配置管理服务和可编辑持久化表面8 个文件
这一阶段像系统的“设置柜台”,不是主循环干活儿,而是在幕后让前端和后台都能读、改、保存配置。客户端来的配置请求先到处理器,由它分发给配置读写服务;服务负责安全查看和修改设置,并说明哪些设置被更高规则盖住。修改 config.toml 时,编辑工具和 TOML 小助手会尽量保留原来的注释和排版。加载配置出错时,错误转换器把原因翻成前端看得懂的话。它还会导入外部工具的配置,迁移老用户的个性设置,并让后台服务记住自己的本地开关。
4.2功能标志、提供商目录和内置资产安装33 个文件
这一阶段像开门营业前的备货,发生在会话和界面启动之前。它先读功能开关,兼容旧名字,并用策略锁住不能乱改的项;也让用户在终端里勾选实验功能。然后安装和加载技能,放好记忆模板,按配置决定谁启用。插件市场、插件清单和 MCP 通道会被整理好。模型供应商、模型说明、协作模式、审批预设,以及界面用的模型清单、更新方式、宠物素材,也都提前准备妥当。
5身份验证、身份和账号就绪40 个文件
这一阶段像系统开工前的“验票和办证”。启动时先读出以前保存的登录状态;没有票或票过期,就引导用户登录、刷新,或退出时撤销旧票。登录总管把 API Key、ChatGPT 令牌、个人访问令牌、Agent 身份、Bedrock Key 统一管起来。令牌解析器看懂这串票是谁的、什么套餐、何时过期。提供商适配器再把不同服务需要的钥匙、签名和请求头装好。安装编号和 Windows 沙箱用户则帮系统认准本机和安全身份。
5.1交互式和持久化登录流程15 个文件
这一阶段像系统的“办证和保管处”,出现在首次使用、启动引导和账号操作时,也在后台保管通行证。命令行和终端界面负责让用户选择登录方式:开浏览器、设备码、API key 或 Bedrock key。login 库把这些入口串起来,本机小服务器接住浏览器回跳。账号处理器负责查状态、额度和退出。保存层、钥匙串和配置规则决定令牌放哪里;退出时还会尽量撤销旧令牌。MCP 登录也用同一套办法拿取、保存和刷新通行证。
5.2提供商和后端 auth 适配19 个文件
这一阶段像给全系统做一套“通行证柜台”,属于幕后支撑。模型提供方先统一入口,让 OpenAI 类服务、Bedrock 等都按同一套说法接入。Bearer 令牌、外部取令牌、AWS 配置和 SigV4 签名,负责把不同钥匙正确盖到请求上。代理身份负责给本地代理办身份证、登记任务。API、远程控制、MCP 和限额重置这些客户端,再用这些适配器检查该怎么登录、该带什么头,避免拿错钥匙或漏带凭证。
6持久化和本地运行时服务启动6 个文件
这个阶段像开店前先把仓库和账本整理好。程序启动时,会打开本地 SQLite(放在电脑上的小数据库),把旧格式升级成新格式。StateRuntime 统一打开线程、日志、目标、记忆等库;rollout 的 state_db 把会话状态存进去;core 的 bridge 只是递交配置的转接头;migrations 准备升级步骤。若库坏了或被占用,恢复代码会提示用户、挪走坏文件并重建,让后面的功能能放心读写。
7后端客户端、远程目录和启动刷新22 个文件
这一段发生在配置和登录都准备好之后,像开店前补货。它先拉云端配置,决定用缓存还是联网,并在后台刷新;再整理可选模型,既问 Codex 或模型服务商,也检查本机 Ollama、LM Studio。接着同步连接器、插件目录、MCP 工具和工作区权限,让界面能显示真实可用的东西。还会顺手查任务、额度、记忆写入安全和版本更新,尽量用缓存和后台任务,别拖慢启动。
8传输和服务器运行时初始化40 个文件
这一阶段是在程序要当“服务器”时,先把收发消息的路铺好,属于开机启动和幕后支撑。它一边启动 app-server 和 daemon,管进程开关、日志、配置、鉴权,并把 stdio、本机 socket、WebSocket 等通道接上;另一边启动 exec-server、MCP 等外挂机器,让外部工具、远程控制和客户端都能用 JSON-RPC 这种固定格式说话。各部件像总机、门卫和转接线,先登记连接,再转发请求和通知。
8.1app-server 和 daemon 传输启动23 个文件
这一阶段像给 app-server 接上电源和电话线,主要是启动和幕后支撑。daemon 管启动、停止、重启,用 PID 文件防止重复开。server 总开关装好配置、日志、数据库和退出。传输层提供标准输入输出、本机 socket、WebSocket,并做进门鉴权。远程控制负责登记本机、决定开关、断线重连和转发消息。客户端门面让 CLI、TUI 用同一套方式发请求、收事件,初始化和发信站完成握手与回信。
8.2执行与集成 sidecar 服务器17 个文件
这一阶段像给主程序配一组“外挂机器”,主要在幕后支撑执行和工具接入。exec-server 负责开门、选通道、收发 JSON-RPC(一种固定格式的命令消息),客户端把启动进程、读文件、发请求包装成简单操作。Noise relay 负责远程加密中转,stdio、WebSocket、本地 socket 像不同插头被统一接上。MCP 启动外部工具服务器并整理工具清单;HTTP 和网络代理则管转发、鉴权和出网规则,防止乱连。
9前端会话启动和面向用户的初始化41 个文件
这一阶段把已经启动好的后端,接到用户真正能用的前台上。走聊天界面时,TUI 会读取配置和命令,处理登录、恢复旧会话、新手引导、目录信任、模型选择,再搭好聊天窗口、快捷键、通知和终端接管,像把柜台布置好再开门营业。走 exec 模式时,它不打开聊天窗口,而是为脚本准备一次性会话,接好输入和机器可读的输出,跑完后用退出码告诉外部成功还是失败。
9.1TUI 启动、引导和终端所有权39 个文件
这一阶段是 Codex 终端界面的开场和接管现场。lib.rs 先读命令和配置,串起登录、恢复会话、本地模型选择、钩子信任、更新和启动提醒。新手引导负责欢迎、登录、信任目录,迁移页负责旧配置和模型切换。随后 app 和 ChatWidget 搭好聊天主界面,回放历史、显示状态和宠物。tui、绘图器、终端探测、键盘模式、暂停恢复、通知和标题模块,则负责安全占用终端,最后再干净还回去。
9.2exec 模式和脚本化会话启动2 个文件
这一阶段是给“非聊天窗口”的用法准备和跑完整个会话,主要服务于自动化脚本。用户执行 codex exec 时,exec/src/lib.rs 像总调度员:读命令参数和配置,检查是否登录,启动或连接本地服务,拿到用户提示词,设置 JSONL 这类方便机器读取的输出格式,最后根据运行结果给出退出码。若用户要接着旧会话,tui/src/session_resume.rs 会先把旧会话的线程编号、原工作目录和模型找回来,像替你翻出上次的病历,避免接错地方、用错工具。两者配合,把一次性会话从准备、执行到收尾交代清楚。
10主事件循环和请求分发137 个文件
这一阶段是系统跑起来后的“总调度室”,一直在主循环里值班。用户敲键、粘贴、点确认,先被界面事件流收进来,再按输入框、弹窗、聊天区、线程等位置分给对应部件。外部来的 JSON-RPC 请求,也就是带编号的远程命令,会先经过服务器解码、鉴权和排队,再交给会话、文件、插件、工具等处理。几个调度文件负责接线、排队、防止同时乱改;并行工具调度则决定哪些活能一起做、取消时怎么收尾。
10.1交互式事件分发96 个文件
这一阶段是终端界面的“总调度室”,属于用户正在操作时的主循环。键盘、粘贴、窗口变化和重画信号先被 event_stream 统一收进一条事件流;暂停界面时还会放开键盘输入,免得抢走 vim 之类程序的按键。之后 App 总分发决定交给谁:输入框处理打字和斜杠命令,弹窗接管确认和选择,聊天区接后台消息,线程路由切到正确对话,mention 搜索弹出候选。各小工具按需插进来,办完再退场。
10.1.1App 级事件分发与线程路由10 个文件
这一阶段是终端界面的“交通枢纽”,属于主干活儿的循环。用户按键、后台消息、审批请求都会先变成统一消息或命令,再由总分诊台分发。输入模块管全局快捷键;后台事件和请求模块把服务器来的通知、待审批事项放到正确位置;线程路由负责多条聊天线切换和回放;未完成交互只重放还在等人的提示。慢任务丢到后台跑,重画请求也被合并,保证界面不乱、不假死。
10.1.2底部面板输入器、弹窗与 mention 输入42 个文件
这一阶段是终端聊天界面最底下那块“操作台”,属于用户干活时一直陪着的主入口。输入框负责打字、粘贴、换行、光标移动、历史找回和图片附件;草稿、提示栏、弹窗状态把临时信息分开放,避免互相搅乱。斜杠命令会被拆开、提示、补全,@ 提及会搜索文件、插件和技能并弹出候选。各种列表、设置、反馈、确认窗口共用底部面板规则,像抽屉一样弹出、接键盘、办完再收起。
10.1.3Chat widget 交互与命令流程23 个文件
这一阶段是终端聊天界面的“前台大厅”,属于系统主干活儿的循环。chatwidget 主控台接住后台消息和用户按键;interaction 判断按键该交给输入框、弹窗还是任务;input_submission、input_flow、input_queue、input_restore 负责发送、排队和找回未发内容。slash_dispatch 分发 / 命令。protocol 把后台通知变成聊天记录、进度、报错。各种菜单和弹窗处理模型、用量、审查、目标、技能、连接器;rendering 最后把这些拼成完整画面。
10.1.4专用交互流程与辅助 TUI 处理器20 个文件
这一阶段像主聊天旁边的一排小工具,用户需要临时操作时才接手,不是核心干活循环。cloud-tasks 三件套负责记住任务、新建任务并画出任务界面。回溯和全屏查看器让人翻旧记录、退回重改。keymap 几个文件提供改快捷键、查按键、保存配置。多智能体导航管切换和状态展示。pets 负责选宠物、预览、加载和出错兜底。剪贴板、主题选择、外部配置导入和平台小检查,则把零散入口收拾成顺手的界面流程。
10.2RPC 请求路由37 个文件
这一阶段像系统的总机和分诊台,是主干活儿时一直运转的部分。客户端、模型或外部工具发来 JSON-RPC 消息(带编号的远程请求)后,app-server 先做初始化、鉴权和排队,再分给对话、线程、文件、插件、MCP、反馈等接待员。core 找到并执行模型要用的工具。exec-server 和 MCP server 把执行命令、读写文件、调用 Codex 等请求送到真正模块。界面分拣消息,代理、监听等小件负责把关,避免串线。
11线程和会话编排44 个文件
这一阶段像客服中心的排班台,处在真正执行每轮回答之前和过程中:先决定任务挂到哪条对话线。入口文件把能力统一摆出来;线程管理器负责新建、恢复、复制、关闭、切换线程,并接上本地记录。环境选择、会话外壳和服务工具箱准备模型、目录、权限、插件。输入队列、注入器、任务和状态记事本保证一轮一轮不串线。存储、服务器和终端界面负责保存、重连、筛选、显示;目标、技能、旁路对话等扩展再插进来一起跑。
12提示词、上下文和扩展组装74 个文件
这个阶段发生在每次把问题交给模型之前,像开演前给演员整理台本。它先用“门面”和模板,规定提示词、便签、内嵌说明怎么登记和拼装;再从提示词库拿固定说明,把环境、命令结果、技能等包成带来源的小纸条;接着收集用户规则、项目规则、权限、插件、记忆、目标和评审要求;最后整理历史、补上新变化、控制长度,并让调试工具看到模型最终拿到的内容。
12.1提示词和上下文门面模块、片段及嵌入式指令模板8 个文件
这一阶段属于幕后支撑,不是开机也不是主循环。它主要管“给模型看什么话”。几个门面文件像总入口,把用户指令、提示词库、上下文片段统一摆出来,外部代码不用到处找。协作模板文件把固定说明提前打包进程序。片段定义文件给系统塞进去的小纸条规定格式和标签,避免和用户原话混淆。扩展接口还能交来新的提示词片段,最后由核心上下文目录统一登记、拼装。
12.2上下文片段定义与提示词资产25 个文件
这一层像给模型准备“便签”和“说明书”的库,是幕后支撑部分,不直接干活。几个 prompts 文件把固定提示词打包进程序,随取随用。各种 context 文件把环境、用户规则、命令结果、技能说明、实时会话开头结尾、子代理状态等消息包成统一格式,标清来源和边界,还会限长,防止混成普通输入。另有旧警告识别器,用来读懂老会话,避免误处理。
12.3指令、skill、插件、memory 与评审提示词贡献者29 个文件
这一阶段像开工前给模型递“任务夹”,属于幕后支撑,不直接干活,但决定模型看见哪些规则和线索。它先收集用户家目录、项目 AGENTS.md、IDE 当前文件、权限边界、协作方式和说话风格;再把技能、插件、外部 App 的可用能力整理好,用户点名时还会把对应说明塞进去;同时补上图片保存位置、终端画图规则、记忆摘要、当前目标和预算。最后,评审相关文件把“审哪段代码”和结束语变成稳定提示,让模型按同一套规则行动。
12.4轮次上下文、历史与实时提示词组装12 个文件
这一阶段发生在模型每次开口前,像给演员递台本。turn_context 先装好当前目录、权限、工具等“随身资料包”;history 整理旧聊天,normalize 保证工具调用和图片等内容不乱;additional_context 和 updates 只补新变化,省位置;token_budget 提醒上下文快满了。实时部分会选好系统提示词,再补一张开场小抄。网页搜索也拿一小段近况。prompt_debug 则让开发者检查模型到底看见了什么。
13回合执行和模型交互88 个文件
这是系统最核心的“每一轮聊天怎么跑”。用户发来一句话后,普通任务先排队,处理取消和追加输入;回合执行器把历史、工具、钩子和环境标签装好。若聊天太长,压缩模块先把旧内容缩成摘要。模型传输部分再把请求送到模型服务,并一边收回分段结果一边处理重试。流式展示像字幕组,把碎片排成界面和历史。代码模式还提供 JavaScript 小沙盒,让脚本、定时器和外部工具在回合里协同工作。
13.1模型传输执行28 个文件
这一阶段是系统和模型服务真正“通话”的地方,属于主干活儿时的网络出口。它先把用户对话、工具、图片、搜索、记忆、压缩请求整理成服务端看得懂的格式,并带上会话身份信息;再由总客户端选择 HTTPS、WebSocket、WebRTC 等通道发出去。返回时,流式解码器把一段段回答、工具调用、用量和错误翻译成内部事件。若断线或限流,重试和错误映射会决定重连、换通道或报错。实时语音部分则像电话线,负责接麦克风、收字幕和转交任务。
13.2流式汇总与 UI 展示51 个文件
这一阶段是在程序干活时,把后台不断冒出来的内容变成用户看得懂的聊天界面。前面先像筛子一样解析流式文字,藏起引用、计划、Git 指令等特殊标记,只留下干净正文。中间把 Markdown、表格、代码高亮、diff 和命令输出排好版,窗口变宽变窄也能重排。后面把临时滚动的回答、计划、审批、搜索、工具调用、状态栏和 token 用量,整理成正式历史记录。它就像直播字幕组,一边接收,一边校对排版,最后归档。
14工具执行、审批与受控操作294 个文件
这一阶段发生在模型说“我要动手做点事”之后,是主流程里的受控执行段。它先按统一合同看懂工具长什么样、参数是否干净,再把 MCP、插件、搜索、记忆、图片等外部工具翻译成系统能用的格式。接着安全总闸检查要不要审批,hook 可插手补查,沙箱规则限制文件、网络和权限。通过后,执行后端才真正跑命令、打补丁或调用远端工具。出错时也会分清是可告诉模型的小问题,还是必须停下来的严重故障。
14.1审批、guardian 与 hook 协调63 个文件
这一阶段是系统干活时的安全总闸,也贯穿启动和收尾。模型想执行命令、改文件、联网、提权或问用户,都先到这里登记。策略引擎像门规,判断能放行、拒绝还是要请示;Guardian 像复查员,专门审可疑的自动批准;hook 像埋在关键路口的小脚本,能补充检查、拦停或加上下文。后台负责排队和沙箱执行,界面负责把风险说给人听并收回答案,运行时再把网络和文件访问真正卡住。
14.1.1审批策略和请求决策引擎14 个文件
这一阶段是系统的“安全门卫”,主要在工具真正执行命令、改文件、联网或放宽沙箱限制前做决定:能直接放行、必须拒绝,还是先问用户。新版 execpolicy 负责读入人写的策略、整理成规则,并按命令或网络请求逐条匹配。core 里的几个文件把这些判断接到实际工具上:命令看 exec_policy,改补丁看 safety,联网请求由 network_policy_decision 翻译成用户能懂的审批。sandboxing 则统一决定要不要审批、要不要关进“隔离间”运行。legacy 部分是旧版同类门卫,继续解析旧策略、检查程序名和参数,保证老规则还能用。
14.1.2Guardian review 和协调式审批会话6 个文件
这一段像系统动手前的“安全检查岗”,属于主流程里的把关环节。mod 是总开关,判断哪些自动批准要先送审,并在连续被拒时拉保险丝。approval_request 把命令、改文件、联网、提权等动作写成统一审批单。prompt 把上下文整理给 Guardian 模型看,再读回结论。review 和 review_session 负责拉起或复用只读审查线程,按保守规则给出批准、拒绝、超时或中止。session/review 则复制必要环境并收紧权限,让这次复查不越界。
14.1.3Hook 执行和停止-继续协调16 个文件
这一阶段像系统里的“门卫和传话员”,贯穿启动、运行到收尾。Hook 就是在关键时刻自动跑的小脚本。注册表和运行时先找到配置好的脚本,调度器决定哪个事件该叫谁。命令运行器负责真正执行,解析器读懂脚本吐出的 JSON,输出太长就先存临时文件。各事件处理器分别管会话开始、用户发话、工具前后、权限申请、上下文压缩和停止时的检查,最后汇总成放行、拦住、停止或补充上下文。
14.1.4权限和 elicitation 请求入口5 个文件
这一阶段像系统的“前台加保安”,发生在 Codex 正在干活儿时。模型想看更多文件、用更多环境权限,会走 request_permissions 统一登记和送审;想问真人问题,会走 request_user_input,把问题传到会话层再拿回答案。MCP 这边如果需要用户补充信息,elicitation 会判断能不能直接处理,或转给前端。执行命令、修改代码前,也分别由 exec_approval 和 patch_approval 去问用户准不准,避免机器偷偷做高风险动作。
14.1.5审批协调的工具编排和审批 UI12 个文件
这一阶段像“安全闸门”和“前台窗口”,主要发生在系统干活过程中。后台总调度员先判断工具能不能直接跑,要不要沙箱、审批或升级重试;MCP 模板把外部工具的风险写成用户看得懂的问题。终端界面这边负责把请求排队、弹窗、显示待处理项和最近被拦下的操作,还能收集用户回答、切换权限模式、提示 Windows 沙箱问题。hooks 联络员则帮界面向后台查询和信任检查规则。整体配合起来,就是让危险动作先说明白、再等人点头。
14.1.6审批相关的执行运行时10 个文件
这一阶段是系统运行时的“门禁和值班保安”,主程序要联网、沙箱命令要读写文件时,都在这里被检查。network-proxy 的入口先把各模块摆好;state 把用户配置和管理员硬规则合成可执行状态;network_approval 负责该问人时只问一次;network_policy 和 runtime 判断请求放行还是拦下,并记日志、热更新规则。Windows 这边则给沙箱加临时可读目录、同步禁止读取规则、保护工作区特殊目录,再用 WFP 这道系统级网络关卡拦住不该去的地址。
14.2执行后端与沙箱命令运行时91 个文件
这一阶段是系统把外部命令真正跑起来的中段,也负责给运行加护栏。上层接住 shell、改文件、启动应用等请求,补好目录、环境、超时和审批;统一执行引擎用本机终端、管道或远端 exec-server 开进程、收输出、喂输入、停进程。补丁通道先查格式和权限再改文件。各平台沙箱和提权像门禁,限制文件、网络和越权;文件系统服务让远端读写也走安全通道。sleep 工具可短暂停顿,有新输入就提前醒。
14.2.1面向执行的 app-server 和 core 命令编排15 个文件
这一阶段是系统真正“把命令跑起来”的执行通道,位于主干活儿的中段。app-server 先接住客户端请求,检查启动、输入、改窗口、终止等操作,再交给底层进程跑,并把输出送回去。TUI 的小工具把本地和远端文件、后台命令包成同一套用法。core 这边像调度室:接收用户或模型的 shell、unified-exec 请求,补好目录、环境、超时、审批、沙箱和联网规则,再调用真正的执行器;特殊 zsh 路线不合适时会退回普通执行。整体目标是能跑命令,但不让它乱跑。
14.2.2Unified-exec 会话和 PTY/进程后端17 个文件
这一层是统一执行命令的“发动机舱”,属于幕后支撑。上面只说“启动命令、继续输入、拿输出、停掉它”,这里负责真把进程管住。mod 和错误文件定规矩、统一说法;process 和 manager 把本机进程、远端 exec-server 进程包成同一种东西,并登记、读写、清理。spawn 负责安全启动外部程序。exec-server 里的本地和远端进程负责实际跑命令、缓存事件。pty、pipe 和 Windows 后端则像不同插头,让普通命令和交互式终端在各系统上都能接通。
14.2.3补丁应用引擎和补丁执行适配器9 个文件
这一阶段发生在系统干活时,专门管“让模型改文件”这件事,像一套带安检的维修通道。apply_patch_spec 先把补丁格式说明白;前台 handler 和 core/apply_patch 检查格式、权限,必要时请用户确认,再交给运行环境。runtime 负责审批后在沙箱里动手。parser 把补丁拆成改动清单,streaming_parser 边收边拆;invocation 先认出调用并预查路径和文件;lib 真正落盘;git-utils 借 git 试跑或应用,并整理冲突结果。
14.2.4沙箱选择和 Unix 平台启动器16 个文件
这一阶段是在真正运行外部命令前,先决定“要不要关进沙箱、怎么关”。入口和管家负责统一不同系统的做法,整理权限、目录、网络和环境变量。Linux 上有两套栏杆:bubblewrap 像临时隔离房间,Landlock/seccomp 像门禁和断网开关;相关文件会检查工具是否可用、找项目自带版本,并把普通命令改写成沙箱启动命令。Unix 的提权部分则像值班员:命令想跳出限制时,客户端先问服务端,服务端按规则决定放行、升级权限或拒绝。
14.2.5Exec-server 文件系统沙箱服务6 个文件
这一阶段是 exec-server 的“文件管家”,属于幕后支撑部分。它让执行任务读写文件时,不是随便碰硬盘,而是走统一通道。file_read 负责把大文件一段段读,并用编号管理。fs_helper 规定读、写、建目录、删除这些请求怎么说、怎么做。fs_sandbox 把操作关进沙盒这个隔离房间。sandboxed_file_system 戴着安全手套转交给助手。local_file_system 决定本机操作走直连还是沙盒。remote_file_system 则把同一套操作发到远端服务器执行。
14.2.6Windows 沙盒预配与进程启动内部机制27 个文件
这一层是 Windows 上“把外部命令关进小房间再启动”的幕后支撑。lib、unified_exec 和 TUI 帮手接住上层请求,决定开不开沙箱、走普通还是提权通道。setup、identity 和错误报告准备专用账号、目录、运行文件和失败记录。ACL、token、审计、防火墙像门锁和保安,限制文件和网络。最后 spawn、process、runner、管道、假终端和 stdio_bridge 开进程、接输入输出,并负责等待、超时或杀掉它。
14.3扩展与集成工具117 个文件
这一阶段是系统的“外挂工具箱”,主要在对话运行时幕后帮模型接外部能力,不是开机也不是关机。MCP 部分像接线员,把外部资料和工具接进来并管会话。插件与连接器部分像应用商店,负责发现、安装、更新和确认权限。工具运行时决定哪些工具能给模型用,比如搜索、记忆、技能、图片生成。应用服务器部分再把可用应用和文件搜索结果整理好,送给客户端看。
14.3.1MCP 运行时、资源与会话集成22 个文件
这一阶段是把 MCP(让 Codex 接外部工具和资料的协议)真正接进系统,属于运行中一直在幕后支撑的部分。配置和插件先登记哪些服务器能用,连接管理器像总接线员一样启动它们、收集工具和资源。工具整理层负责改名、去重、决定哪些给模型看。会话层在模型调用时检查参数、上传文件、必要时问用户或处理登录过期。资源工具则负责列清单、读内容。扩展层最后把这些能力和事件统一送到应用服务器。
14.3.2插件与连接器生态管理34 个文件
这一阶段像插件和连接器的“应用商店加仓库管理员”,属于系统运行时的幕后支撑,也给命令行和聊天界面提供入口。它先从插件市场、本地目录、Git 仓库或远端服务找货源,再读取 plugin.json 清单,检查路径和格式是否安全。加载器把技能、工具服务器、应用声明和钩子整理给主程序用。管理器负责安装、卸载、升级、缓存同步和分享。连接器策略会判断外部应用能不能用、是否要确认。最后,推荐工具和安装请求工具把可装内容展示出来,但真正安装前仍要让用户点头。
14.3.3基于扩展的工具运行时与命名空间56 个文件
这一阶段像系统的“工具大厅”,主要在对话进行中默默支撑模型干活。开局先由排班表决定哪些工具能露面,哪些只后台用。动态工具和扩展工具负责把外部临时能力、插件能力接进来。code-mode 让模型能跑一小段代码并等待结果。网页搜索、图片生成、记忆、技能、目标等扩展各自提供具体本事。工具搜索、看图片、查剩余上下文这些小帮手,则像标签、放大镜和油表,帮助模型安全地找到、使用、控制这些工具。
14.3.4App-server 集成发现与搜索适配器5 个文件
这一阶段像应用服务器里的“前台导购和搜索台”,客户端来问有哪些应用、想快速找文件,都由这里接住。connectors 里的几个文件先把各路连接器名单整理干净:过滤掉不该露出的,合并重复的,补齐名字、图标、说明和插件信息。apps_processor 再把登录状态、工作区配置和插件列表串起来,返回用户真正能看到的应用。fuzzy_file_search 则负责文件模糊搜索,既能查一次,也能在用户边输入时边推送新结果。
14.4沙箱策略生成和命令安全解析辅助工具17 个文件
这一阶段是幕后安全岗,守在外部命令运行前。它先把 bash、PowerShell 命令拆成程序和参数,拒绝变量替换、重定向等容易藏风险的写法,再整理成统一格式,方便和已批准命令比对。参数模板、选项和类型标签负责检查输入是否安全;安全分类器区分只读命令和删除、启动程序等危险动作。最后,沙箱工具合成真正的隔离规则,限制文件读写和联网。
15多智能体、协作与后台流程39 个文件
这个阶段像主会话旁边的“调度室”,不是自己回答完就结束,而是在主循环中帮忙开小助手、派活、传话、等待和收尾。登记表记录有哪些代理在跑,闸门和停车场限制数量,避免资源被占满。创建、恢复、关闭、打断、发消息、等待等工具让主代理能像带团队一样协作。还有审查助手、CSV 批量派工、记忆后台整理、技能文件监视等流程,把结果再汇回主会话。
16结果持久化、展示与状态更新55 个文件
这一阶段像“记账和播报员”,发生在每轮工作推进或结束后。核心先把模型回复、工具结果、文件改动整理成统一事件,再筛选哪些要写进会话记录和状态库;同时更新线程状态、标题、用量、归档等信息。服务器把内部事件翻译成前端通知,重连时还能补回历史。TUI 和 CLI 再把这些记录变成状态栏、聊天历史、diff、体检报告;exec 则输出 JSON,方便外部程序读取。
17关闭、清理与收尾4 个文件
这一段像程序“打烊”。连接要断、会话要关,或后台更新要重启服务时,先别一脚拔电源。RPC 闸门先拦住新请求,让已开工的请求做完;连接清理器把断线后的扫尾丢到后台,能收就收,超时就报错或取消;老式 agent 管家先保存状态,再通知它和子任务关机,最后清掉记录;自动更新循环则挑空档下载新版并重启服务,尽量不打扰正在干活的部分。
18协议 schema、共享类型与生成契约✕174 个文件
这一阶段是全系统的幕后“合同库”,不负责开机、主循环或关机,而是先规定大家怎么说话、数据长什么样。核心协议像通用词典,统一会话、权限、工具结果等说法;app-server schema 规定前端和服务器的消息信封;后端 OpenAPI、protobuf 把远程接口也对齐;扩展、hook、MCP、跟踪 schema 给插件、工具和流水账定格式;宏则在编译时自动补检查。这样各零件传话、存档、调用工具时不容易说岔。
18.1核心共享协议与领域类型46 个文件
这一阶段像整套系统的“通用词典”和“零件规格书”,属于幕后支撑部分,不直接干活,但大家都离不开。它先把会话号、线程号、智能体路径、工具名这些“身份证”定统一;再规定消息、权限、审批、错误、配置、用户输入、工具结果等数据该怎么写。插件、工具、技能、云任务、线程存储和界面事件也用同一套格式对齐。这样前端、后端、命令执行、存档和外部服务传话时,不会各说各话,也更不容易误放权限、读错配置或恢复不了旧会话。
18.2app-server 协议 schema 与传输契约43 个文件
这一阶段像系统的“通话说明书”,属于幕后支撑,不直接干业务活,却规定客户端、前端、服务器该怎么说话。JSON-RPC 文件先定好请求、通知、回复、错误的统一信封;common、v1、v2 各文件把账号、线程、对话、文件、权限、插件、远程控制等消息做成固定表格;辅助和转换文件负责处理空值、旧版兼容和审批格式;导出工具把这些规则打印成 TypeScript 和 schema;传输与错误文件保证消息发出去、错回来时也按同一套规矩。
18.3生成的后端与 protobuf 契约24 个文件
这一层不是主循环,也不是开关机,而是幕后“对表”的公共部分。后端接口会返回很多数据,比如额度、限流、任务、拉取请求、配置文件等,OpenAPI 生成的模型先把这些数据规定成固定样子,目录文件再统一出口给别人用。客户端的 types.rs 负责按这些样子拆包,并把复杂结果整理成文字、补丁和错误。protobuf/gRPC 文件则规定远程配置加载和中继通信的消息格式,relay_proto 再包一层,方便项目内部引用。这样各处传话都不容易说岔。
18.4API、扩展、hook、MCP 与跟踪 schema60 个文件
这一阶段是系统的幕后“合同和表格库”,不负责开机或主循环,而是让各路零件按同一种格式说话。code-mode 定好代码执行和会话消息;公共 API 规定对外请求、回复、图片、搜索怎么装;扩展和 hook 像插座,说明插件何时能插手、能拿什么数据;工具协议给命令、权限、计划等交接立规矩;MCP、exec 和沙盒画出进程通信接线图;trace 模型则把一次运行的流水账记下来,方便追踪和复盘。
18.4.1code-mode 协议契约类型5 个文件
这一阶段是幕后打地基的公共协议,不直接跑代码,而是先把“大家怎么说话”定好。lib.rs 像总入口,把常用东西摆到门口。description.rs 给工具写说明,并检查 exec 的特殊配置。response.rs 规定结果里文字、图片怎么装。runtime.rs 规定运行代码、拿输出的消息格式。session.rs 则定下会话从创建、执行、等待到停止的整套规矩,让本地或远程执行器都能按同一份合同配合。
18.4.2公共 API 请求和传输架构6 个文件
这一阶段像系统对外说话的“统一话术本”,属于幕后支撑公共部分。lib.rs 是总入口,把各类能力集中摆好;common.rs 规定请求、回复、流式消息和参数的通用信封;error.rs 把各种失败统一包装,方便上层处理。实时 WebSocket 协议文件规定长连接里每句话的格式和版本解析。images.rs、search.rs 则分别给图片生成/编辑和搜索请求结果做标准表格。它们配合起来,保证程序和外部服务收发数据时不乱套。
18.4.3扩展和 hook 接口契约22 个文件
这一阶段像给扩展和插件准备的“插座说明书”,属于幕后支撑,不直接干主流程活儿。扩展 API 先规定能借宿主做什么,比如创建子代理、发事件、往当前对话塞内容、保存自己的小数据。贡献者接口说明插件能在哪些时刻插手:线程、工具调用、对话回合、MCP 配置等。记忆库、用户指令、IDE 上下文也统一了数据样子。hooks 部分则规定钩子怎么声明、触发、返回结果,并加载命令格式模板,让外部脚本按同一套规矩安全接入。
18.4.4工具和协议契约架构18 个文件
这个阶段像后台的“说明书和表格库”,不直接干活,而是让模型、前端、后端和外部工具说同一种话。它规定工具调用时要带什么信息、接口里长什么样,再把执行结果翻译成系统能继续用的格式。提问用户、申请权限、更新计划、查剩余对话容量、跑命令、目标、技能、网页搜索、MCP 调用,都在这里有固定模板和字段名。这样各零件交接时不靠猜,少传错、少看错,也方便日志、审批和钩子稳定接上。
18.4.5MCP、exec 和沙盒线路模型6 个文件
这一阶段像系统的“接线图”,不是亲自干活,而是规定各方怎么说话。exec-server 的连接入口把 WebSocket、认证连接、标准输入输出这些路统一包起来;进程编号用专门的小盒子,避免拿错。协议文件规定启动进程、读写文件、报错等消息长什么样;exec 事件规定运行过程怎么对外汇报。沙盒和提权部分则约好被拦截命令、环境变量、输入输出和退出结果怎么传,让普通进程、提权进程和外部客户端能安全配合。
18.4.6共享扩展后端和 rollout trace 模型3 个文件
这一阶段不是系统开机或干活的主循环,而是幕后用的“记账格式”。它规定追踪记录该怎么写,方便不同模块按同一套说法交换数据。session 文件像登记簿,说明一次运行和智能体线程是进行中、成功、失败还是被打断。runtime 文件像流水账模板,记录模型执行、工具调用、终端操作、压缩历史和多智能体通信。payload 文件像附件索引,大请求、大响应、大日志不塞进主记录,只留下外部文件地址。三者配合,把一次运行的过程轻量、清楚地保存下来。
18.5API 注解宏和编译期契约支持1 个文件
这一阶段属于幕后支撑,不是系统真正干活的主循环,而是在编译时先把规矩立好。“宏”可以理解成代码生成器:开发者给某个字段或选项贴上“实验性接口”的标签,lib.rs 里的编译期宏就会自动补出检查代码。这样别的模块收到请求时,不用手写一堆重复判断,也能知道里面有没有用到还不稳定的功能,方便统一登记、提醒或限制。
19通用传输、网络与客户端基础设施✕55 个文件
这一阶段是系统的“通信底座”,不直接干业务,却让各部分能安全说话。HTTP客户端管出网、重试、证书、Cookie和流式消息。app-server、exec-server和relay把本地管道、WebSocket、大文件和远程消息打包、加密、转发。代理和本地IPC像门卫和内线电话,管住外网访问,也连起进程、沙箱和IDE。MCP适配器统一各种通信方式,几个门面和错误文件则把入口、返回和失败原因整理好。
19.1通用 HTTP 客户端、TLS、cookies 和流式传输基础21 个文件
这一层是全系统出门上网的“水电管线”,不算主流程,却一直在幕后支撑。request/transport把内部请求包成HTTP并发出去,retry负责失败后等一等再试,custom_ca和受限Cookie让企业证书、Cloudflare验证能安全通过。各类默认客户端统一加身份、请求头和日志。SSE、WebSocket负责拆流式消息。provider、session和目录文件把地址、认证、重试、上传、远端配置等能力集中给大家用。
19.2App-server、exec-server 和 relay 传输通道10 个文件
这一阶段像系统里的“管道和快递站”,主要在幕后支撑各服务互相传话。app-server 先把标准输入输出、Unix socket、WebSocket、远程控制都统一成一种收发消息的方式;大消息会被切块再拼回,远程客户端也能查询和踢下线。exec-server 这边把 HTTP 请求、本地或远端响应正文、远端文件都做成可分块读取的流。最后,Noise 加密通道和 relay 负责验身份、加密、按顺序重排、给消息分包拆包,让 JSON-RPC 消息安全穿过 WebSocket。
19.3托管代理和本地 IPC 传输基底12 个文件
这一阶段是幕后打地基的通信层,让主机、代理、沙箱、IDE、提权进程之间能安全说话。网络代理这边,先把用户和组织规则合成可执行的权限表,再决定能连哪些外部地址、是否走上游代理;需要查看 HTTPS 时,就临时发证书、拆开请求,按规则删头或加密钥,并统一返回结果。另一边,本机通信用 Unix socket、Windows 命名管道等“本地电话线”,还支持把已打开的文件句柄传给别的进程。沙箱路由则像转接线,把宿主机代理接进隔离环境;IDE 通道负责向编辑器插件取当前文件和选区信息。
19.4MCP 和执行器支持的传输适配器8 个文件
这一层像一组“转接头”,夹在 MCP 客户端的主流程和真实通信方式之间。库门面把常用入口摆出来;进程内通道负责重新连上内置服务器;执行器进程通道把标准输入输出包装成可收发 JSON 消息的管子,并分开记录错误日志。HTTP 部分有的直接发网络请求,有的把请求转交远端执行环境;适配器再把 RMCP 的发消息、开流、关会话翻译成 HTTP。遇到认证失败时会读权限提示;流式连接不稳时会先重试。
20通用可观测性、分析与反馈✕81 个文件
这一阶段是贯穿全程的“记录和体检系统”,从启动、处理请求、跑工具到关机都在幕后工作。分析事件先把会话、报错、代码改动等记成统一格式,再归并、排队发出。OpenTelemetry 像统一仪表盘,收日志、指标和耗时。会话和专项埋点记录每次请求、工具、数据库等表现。Rollout trace 把过程写成可回放的流水账。反馈和日志持久化负责打包线索、脱敏、存本地,Windows 沙盒日志也记录命令成败,方便事后排查。
20.1分析事件建模、归约与发送器8 个文件
这一阶段是分析上报系统的核心,属于幕后支撑部分。它不直接干主任务,而是把系统里发生的事记清楚,再安全地发出去。facts.rs 和 events.rs 先规定“账单”格式:会话、报错、工具调用、权限请求都按统一样子记录。accepted_lines.rs 专门看代码改动,统计用户接受了多少行,同时用匿名指纹避免上传真实代码。reducer.rs 像记账员,把零散动作拼成完整事件。client.rs 负责排队和发送,尽量不拖慢程序。lib.rs 提供统一入口和小工具。app-server 与 goal 的适配文件,则把登录、配置和目标变化接到这套上报流程里。
20.2OpenTelemetry 运行时、提供方与指标基础22 个文件
这一阶段像给系统装仪表盘和记录仪,启动时先接好线,之后在后台持续帮忙。配置部分把观测开关、地址、凭证整理成可用设置,写错了只警告不阻止启动;初始化和提供器把日志、指标、追踪接到 OpenTelemetry(统一观测出口),再由 OTLP 配好网络发送。指标模块管名字、标签、校验、计时器和汇总。追踪上下文把一次请求串起来,事件和请求回调记录耗时、状态和结果。
20.3会话遥测与功能专项埋点16 个文件
这一阶段像系统的“黑匣子”和仪表盘,属于幕后支撑,不直接干活,却把一次会话里发生了什么记清楚。会话遥测记录请求、用户输入、工具调用和连接事件;回合计时拆出模型慢、工具慢还是调度慢;登录环境只报“配没配”,不泄露密钥。app-server、沙箱、工具分发给请求和运行环境贴标签。Guardian、云配置、目标、记忆功能各自记成功失败、耗时和用量。SQLite 启动和指标则记录数据库健康状况。
20.4Rollout trace 记录、schema 与 replay reducers24 个文件
这一阶段像系统的“行车记录仪”和“案卷整理员”,属于幕后支撑。运行时,配置先说明项目和数据放哪;bundle 定好一包轨迹在磁盘上的样子;writer 把原始事件和大块内容不断写下。thread、inference、tool、code cell、compaction、MCP 等模块分别盯住线程、模型请求、工具、代码执行、历史压缩和外部调用。事后 reducer 再把流水账按顺序整理成可回放的对话、线程、工具和终端时间线。
20.5反馈捕获、调试产物与日志持久化10 个文件
这一阶段是幕后支撑,不直接干主业务,而是在出问题时留下线索。反馈模块把日志、标签和网络诊断打包,反馈医生再附一份报告,但不阻塞提交。报错提取器只捞安全的上下文,脱敏器把密钥、口令换成占位符。代理请求、分析事件、终端会话会按需落成本地记录。最后日志数据库负责稳稳写入、按条件查询,并定期清掉过旧内容,方便事后复盘。
21通用持久化抽象与数据存储✕54 个文件
这一阶段是系统的“后勤仓库”,不直接聊天干活,却让很多东西能长期保存、下次还能接上。rollout、消息历史和 thread-store 保存对话档案;SQLite 状态库存会话、任务、日志和“谁带起谁”的关系;各种缓存把云配置、插件目录、模型列表先放本地,少等网络;插件、密钥、记忆文件负责安全落盘;外部导入则登记、读取并转换别家的聊天记录,避免重复搬运。
21.1Rollout 文件和 thread-store 持久化19 个文件
这一阶段像系统的“记事本和档案柜”,在幕后把对话长期保存好,重启后还能找回。rollout 负责把每次会话写成文件、压缩旧记录、列出和搜索历史,还用名字索引本加快查找。message-history 另存全局消息流水,避免多窗口写乱。thread-store 则规定统一的存取接口,并提供本机实现:写入时先落盘再更新索引,读取、分页列表、搜索、删除时在文件和数据库之间核对,尽量避免记录不一致。
21.2SQLite 运行时状态和 agent graph 存储18 个文件
这一层是系统运行时的本地记账本,属于幕后支撑。SQLite,就是一个小文件数据库,用来记住会话、目标、任务、记忆、日志、远程控制和导入结果,重启后还能接着用。model 文件规定数据长什么样,并把库里的文字数字转成安全对象;runtime 文件负责存取、更新、归档、加锁和记进度。audit 只读检查,lib 统一入口。agent-graph-store 则用统一接口,把“谁启动了谁”的父子关系也存进同一套状态库。
21.3缓存和本地持久化查找数据6 个文件
这一阶段是幕后支撑,不是主流程干活,而是给系统准备“本地小抄”。云端配置、连接器目录、远程插件目录、可用模型列表,都会先存一份到磁盘,下次启动或刷新时先看本地,少等网络。每份缓存都会查用户、服务器、版本、过期时间和格式,发现不对就丢掉。另有一张表记录远程插件对应本机哪个文件夹,还有更新提示缓存,记住上次检查和“不再提示”,避免反复打扰用户。
21.4插件、密钥和记忆文件存储9 个文件
这个阶段像系统的本地库房,属于幕后支撑:把会长期留下来的东西安全、整齐地放到磁盘上。插件仓库管家决定插件装哪、怎么装卸,避免半成品和版本混乱。密钥部分用 Windows 的加密保险箱和本机钥匙串,把 token、密码等锁进文件。记忆部分把记忆限制在指定文件夹里,可读、搜、追加;写入模块再把数据库结果同步成 Markdown,并负责清空旧记忆、清理过期资源,防止误删和堆垃圾。
21.5外部会话导入持久化2 个文件
这个阶段是幕后支撑导入功能的一层,专门帮系统把“别人家的聊天记录”安全搬进来。ledger.rs 像一本登记簿,记下哪些外部会话文件已经导入过,并给内容做版本识别,避免同一份文件反复搬;如果文件改了,也能当成新版本处理。records.rs 像翻译员,负责打开外部会话日志,挑出真正有用的聊天消息、标题、目录和时间,再整理成 Codex 能看懂的格式。两者配合,一个管“有没有导过、是不是新版”,一个管“内容怎么读、怎么转”,让后续导入流程能稳稳接着用。
22通用工具与支持库✕175 个文件
这一阶段像整套系统的公共工具间,平时不站在主流程中央,却从启动、运行到排错都被反复用到。路径和文件工具负责把地址认准、把文件安全打开;文字工具负责截短、脱敏、排版;配置、认证和网络工具帮程序带对钥匙、走对门;命令、Git、插件工具负责把外部活儿跑稳。还有等待、取消、图片、构建脚本等小零件。核心 util、错误类型、模糊匹配和 hook 公用代码,则把常见规则统一起来,避免各处各写一套。
22.1路径、文件系统、环境与沙箱支持工具31 个文件
这一层像后台工具箱,不是主流程,却支撑启动命令、读写文件、沙箱运行和终端界面。路径工具先把各种 Windows、Linux、WSL、URI 写法统一成可靠地址;文件系统工具负责安全打开文件、监听变化、判断新旧。环境工具给子进程和沙箱整理变量,找可执行程序,避免泄密或找错。沙箱和平台专用代码再处理 macOS、Linux、Windows 的权限、链接、SSH 配置、剪贴板和终端颜色,让上层代码少操心系统差异。
22.2文本、解析、截断与渲染辅助工具57 个文件
这一阶段是全代码库共用的“文字和显示工具箱”,属于幕后支撑,不是主干流程。它先把普通字符串整理好:数字、时间、路径、JSON、命令输出该变短就变短,该脱敏就脱敏。遇到一边传一边来的文字,会先安全拼字节、凑整行,再识别隐藏标记、表格、引用等暗号。到了终端界面,它又负责算宽度、换行、截断、保留颜色链接,把长文本和 diff 画得不乱。最后还提供样式、弹窗、列表、进度和小动画,让界面像拼积木一样稳定好看。
22.2.1通用字符串、格式化、截断和模板工具12 个文件
这一阶段像全系统共用的“文字工具箱”,不是主流程,而是在后台帮各处把内容变得安全、短、好读。数字和耗时会改成 12,345、250ms 这类顺眼写法;JSON、标签、UUID、代码位置等字符串会被整理,中文表情也能转成安全写法。长文本、命令输出、对话历史和终端路径会保留头尾再剪短,防止塞爆屏幕或模型。命令行会隐藏环境变量真值,并安全生成 resume 命令;网页搜索动作会翻成人话;严格模板负责替换变量并抓出填错。
22.2.2流式、行分帧和隐藏标记解析器9 个文件
这个阶段是幕后工具箱,专管“文字还没收完就要先看懂”的情况。数据常一小块一小块来,utf8_stream先把字节安全拼成文字,line_buffer再按换行凑整行。stream_text定好边显示边抽取隐藏内容的规矩;inline_hidden_tag抓内联暗号,tagged_line_parser切出带标签的块。table_detect认 Markdown 表格,mention_codec保住提及背后的真实指向,citations整理记忆引用。lib.rs像柜台,把工具统一交给别处用。
22.2.3TUI 文本布局、换行和文本渲染原语10 个文件
这一阶段是终端界面的幕后排版工,不管业务,只保证文字画得稳。render 和 line_utils 管边距、空行、加前缀等基础小活;width 算正文还剩多宽。ansi-escape 处理颜色加粗,truncation 负责截短长行。Markdown 合并器保留原文位置,链接模块让可点击链接不扰乱排版。wrapping 和 live_wrap 按真实宽度换行,尽量不断网址;scrollable_diff 让长文本和 diff 能安全滚动。
22.2.4TUI 展示模型、样式和轻量视图辅助21 个文件
这一阶段不是主流程干活儿,而是终端界面背后的“装配台”。底层文字能排好后,这里负责把它变得好看、好懂、好操作:颜色和样式保证不同背景下看得清,统一宽度和可渲染零件让文字、空白、横竖布局像积木一样拼起来。页脚、弹窗、选项卡、选择列表和滚动状态负责提示用户按什么、当前选哪项。状态、目标、技能、迁移清单、连接信息和历史记录则把机器数据整理成人能读的短句,并避免警告刷屏或敏感地址泄露。
22.2.5TUI 动画、运动、终端媒体和临时进度输出5 个文件
这一阶段是给终端界面“加动态”的幕后工具箱,不是主流程本身,而是让等待、检查、引导这些时刻更好看也更稳。motion 像总开关,统一决定能不能用闪烁、发光等动效,用户不想看动画时就换成安静可读的显示。shimmer 负责文字扫光,让“正在运行”更醒目。ascii_animation 负责字符小动画该播哪一帧,frames 则把动画素材提前装进程序里。doctor 的 progress 只在合适时临时显示检查进度,避免污染最终报告。
22.3配置、元数据、schema、认证与网络衔接工具26 个文件
这一阶段像系统的工具箱,平时不在主流程中央,却让开机、联网、登录和排错都不乱。配置工具把命令行临时改项、旧名新名、审批和沙盒权限统一起来,并拦住危险值。认证和网络工具准备请求“标签”、PKCE 防冒用密钥、API key 和可信主机规则,避免走错门或泄密。其他工具整理连接器资料、数据格式说明书、版本、插件开关和错误位置,给各模块一套可靠小零件。
22.4Shell、命令、git、插件与执行支持工具24 个文件
这一层像后台工具间,不是主流程本身,却支撑很多地方干活。它先认出该用 bash、PowerShell 还是 cmd,整理命令、环境变量和安全检查,再把命令交给普通进程、伪终端或沙箱去跑,并收好输出、退出码和子进程。Git 部分负责看仓库、分支、差异和安全调用 Git。插件部分负责打包、解包、安装和升级市场目录。还有外部编辑器、补丁定位等小工具,帮上层功能少踩坑。
22.5异步原语、图像处理与其他小型支持库25 个文件
这一阶段是后台工具箱,不是主流程本身,却让系统跑得稳。异步工具负责“等到就绪”和“随时取消”;倒计时、刷新限速、缓存、防休眠让任务别卡住、别太耗电、别中途睡着。图片工具负责读图、缩图、缓存、转成模型或终端能接受的格式,还能把宠物动画切帧显示。另有运行时值转换、聊天事件重放筛选、沙箱和配置摘要,以及一个 V8 连接试验。它们像一盒小零件,被各处按需拿来用。
22.6构建脚本和构建期资源/平台衔接4 个文件
这一阶段不是程序运行时干活,而是在“出厂前装配”。Cargo 编译时会先跑这些小脚本,把不同平台需要的零件补齐。bwrap 会在 Linux 上把 bubblewrap 这套沙箱工具的 C 代码一起编进去;windows-sandbox-rs 会把 Windows 权限清单塞进辅助程序,免得权限行为出错;cli 给 macOS 补上 Objective-C 链接参数;skills 像哨兵盯着样例资源,资源一变就提醒重新构建。它们合起来保证成品在各系统上能正确编出、正确启动。
23测试、夹具与开发者验证工具✕659 个文件
这一阶段像整个仓库的“总验收场”,不直接服务用户,而是在开机、聊天处理、工具执行、界面显示、保存收尾这些环节旁边反复试车。App-server 测协议和整条服务流程;Core 测会话、工具、安全边界;CLI、登录、MCP 测命令入口和开发者流程;exec-server 测远程传输、文件和沙箱;TUI 测终端画面和交互;共享库测试盯遥测、配置、路径、状态等底座。test-binary-support 还帮测试程序换“马甲”启动,安全地检查不同入口行为。
23.1App-server 测试套件和协议验证115 个文件
这一阶段是 app-server 的“质检总车间”,不参与正常服务用户,而是在上线前反复验货。协议验证像检查双方暗号,确保传来传去的 JSON 和说明书没走样;单元测试盯住配置、启动参数、远程控制等小零件;集成套件把登录、连接、对话、工具调用、存档串起来彩排;daemon、传输和测试客户端则假扮外部环境,检查后台服务、通信通道和插件记录是否可靠。
23.1.1协议 schema 和线格式验证4 个文件
这一阶段不是系统开机或干活的主循环,而是幕后“验收口令”的测试区。它专门检查服务端和客户端在网上传的话是不是一直长一个样。common_tests 看 JSON-RPC 返回里哪些放正文、哪些另发事件;remote_control_tests 查远程控制参数和结果变成 JSON 后字段对不对;v2/tests 覆盖大量 v2 请求、响应、通知,防止兼容性被改坏;schema_fixtures 则把当前代码生成的协议说明书和仓库里存的文件对照,提醒别忘了更新。
23.1.2Daemon、传输和测试客户端支持测试13 个文件
这一阶段是幕后质检,不是正式对用户干活。它给后台服务、通信通道和测试客户端做体检:pid、版本、更新测试防止服务状态认错、该重启不重启;socket 和消息测试确认本机连接安全、握手收发正常、慢客户端不拖全局;远程控制用假服务器查配对、撤销和重试。测试客户端能启动服务、发消息、模拟审批,再配合假接口和埋点工具,核对插件安装、启用、卸载记录是否完整。
23.1.3App-server 单元测试和共享集成夹具20 个文件
这一阶段不是用户平时会看到的主流程,而是幕后“质检车间”。一部分测试直接检查 app-server 的关键小零件:配置迁移会不会搬丢东西,config.toml 读写会不会乱改,启动参数能不能生效,追踪链路能不能接上,远程控制、线程处理、会话摘要在出错和边角情况里是否靠谱。另一部分是集成测试的公用道具:假登录、假配置、假模型服务器、假分析服务器、假回复、假历史会话和假客户端,让测试像真跑服务一样检查,又不用碰真实外部服务。最后几个入口文件把这些测试登记成套件,方便一次跑全。
23.1.4App-server 集成套件78 个文件
这一阶段像给 app-server 做一次上线前总彩排,不写新功能,而是把客户端从连上来、登录、读配置,到真正对话、调工具、保存记录都跑一遍。认证和配置先检查门禁和开机设置;传输和协议确认 WebSocket、退出、握手这些“通道规矩”靠谱;插件、MCP 和工具测试外接能力能装、能用、能收场;thread、turn 等测试则盯住会话档案和每轮对话的状态,确保前端看到的、数据库存的、磁盘写的都一致。
23.1.4.1App-server 集成套件 — 认证、配置、发现和核心 RPC 表面16 个文件
这一阶段像给 app-server 做一轮“总验收”,重点不在具体业务,而在客户端刚连上服务器后能不能安全、正确地使用基础能力。认证和账号测试先守住登录、退出、令牌刷新和限额入口;初始化、严格配置、配置读写和实验开关测试确保启动时读到的设置不乱。模型、权限、协作模式等列表接口负责告诉客户端“有哪些可选项”。文件、进程、Windows 沙箱和远程控制测试则检查服务器能不能按规矩操作本机资源,并在出错或受限制时及时拦住。
23.1.4.2App-server 集成套件 — 传输、协议契约和客户端连接行为5 个文件
这一阶段不是主干活儿,而是 app-server 上线前的联调验收,专盯客户端连进来后的路和规矩。WebSocket 测试检查 JSON-RPC 收发、鉴权、健康检查和重连;Unix 信号测试确认 Ctrl-C 等退出时能安全收尾。证明令牌测试保证握手时把身份/环境凭据带给后端;实验 API 测试拦住未声明支持的新接口;实时对话测试用假后端和假客户端,把语音、文字、WebRTC、代理交接、错误和配置开关一起跑通。
23.1.4.3App-server 集成套件 — 插件、marketplace、MCP 和工具/执行器集成24 个文件
这一阶段像一套总验收,专门检查 app-server 的“扩展和工具”入口会不会坏。插件相关测试负责看安装、读取、分享、卸载、缓存和权限;marketplace 测试看插件来源能不能添加、删除、升级;MCP,也就是外接工具服务器,测试工具、资源、追问确认和状态列表;hooks、skills 和执行器测试确保能力只在该出现的地方出现;命令、搜索、图片、sleep 等测试则检查具体工具能跑、能记录、能安全收尾。
23.1.4.4App-server 集成套件 — thread、turn、review 和会话状态生命周期33 个文件
这一阶段像给对话服务器做全流程体检,主要发生在系统干活儿时和保存状态时。它检查新建、读取、列出、恢复、复制、归档、删除会话这些“档案柜”动作;也检查一轮对话的开始、中断、临时追加指令、权限申请、向用户追问和工具调用。还有改名、改设置、元数据、记忆开关、摘要、压缩、代码审查和安全提示等测试,确保客户端看到的通知、数据库和磁盘里的记录三边一致。
23.2核心运行时和会话测试工具179 个文件
这一阶段是 Core 的“总质检车间”,不是用户直接使用的功能,而是在幕后反复演练,保证聊天主流程可靠。运行时测试盯会话启动、恢复、历史压缩、状态保存和安全边界;工具与 unified-exec 测试专查命令、补丁、联网、沙箱和审批有没有越权;集成工具提供临时目录、假服务器、假会话等脚手架;端到端套件把请求模型、传输消息、调用工具、保存结果整条链跑一遍,确保系统真上场时顺、稳、安全。
23.2.1Core src 运行时、会话、策略和状态测试40 个文件
这一阶段不是系统真正“干活”的代码,而是给核心运行时做体检的测试区,属于幕后守门员。它从一次会话怎么启动、恢复、压缩历史,到模型输出怎么变成消息,再到代理线程、子任务、插件改写、图片和实时对话交接,都逐项检查。另一大块盯安全:命令能不能跑、文件能不能改、联网和工具调用要不要审批,Guardian 和执行策略是否拦得住。还有状态、Git、Shell、配置迁移等杂项检查,确保前台聊天顺畅,后台边界不乱。
23.2.2Core src 工具和 unified-exec 测试39 个文件
这一阶段主要是给“工具调用”和“统一执行命令”做验收,属于幕后质检,不是开机或关机。它像一套安全检查台:先校对各类工具的说明书,保证模型按正确格式调用;再检查路由、注册表、追踪记录,确保工具不被派错、漏记;同时盯住补丁、命令、联网、沙箱和审批,防止越权。最后用 unified-exec 的测试模拟本地和远程跑命令、超时、截断输出、清理进程,保证真正干活时稳住。
23.2.3Core 集成工具和通用测试支持15 个文件
这一阶段不是系统真正“干活”的功能,而是给 core 做端到端测试的后台脚手架。all.rs 和 suite/mod.rs 像总开关,把分散测试接起来并做好开场伪装。common 里的工具箱负责临时目录、环境判断、进程等待、可信 hooks、追踪检查、上下文快照等杂活。另一些文件搭假服务器、假 Codex 会话和干净的 codex-exec,让测试不用连真实服务、不碰用户环境,也能稳定复现各种流程。
23.2.4Core 端到端会话、传输、工具和功能套件85 个文件
这一阶段是 Core 的“全流程体检”,主要在幕后验证一次对话从发起、请求模型、执行工具到保存状态都不会掉链子。传输套件查网络通道和模型服务能不能稳定收发;历史套件管聊天记忆、压缩和恢复;请求套件负责把提示词和模型选对;协作套件检查子助手和远程环境别乱跑;审批、权限和 hooks 像门卫,拦住危险动作;工具套件则验 shell、插件、MCP、图片等能力能用且不越权。整体就是确保用户看到的运行过程顺、准、安全。
23.2.4.1传输、流式处理与提供方协议套件16 个文件
这一阶段是幕后质检,专门盯住 Codex 和模型服务“怎么通信”。它像检查电话线和快递单:普通 HTTP、流式 SSE、WebSocket 长连接、实时语音/文字都要能发、能收、能断线重试。各测试分别查请求内容、身份头、压缩规则、模型列表更新、代理标记、单轮状态、远程摘要、额度和安全降级提示。WebSocket 坏了还要能改走 HTTP,出错后下一轮也不能卡死。
23.2.4.2会话历史、压缩、恢复与持久状态套件13 个文件
这一阶段像给聊天系统做“记忆体检”,属于幕后支撑,但会影响重启后能不能接着聊。它检查长对话变短摘要时不丢重点,旧会话恢复、分叉、回滚时历史不乱;用户半路追加输入时能排队或打断得当。还会验 rollout 记录和 SQLite 状态库,确保文字、图片、工具、线程设置都保存对;临时换模型只影响本次,不改长期配置。请求头、模型变化提醒、旧记录查找这些细节,也一起防止系统把不同对话串线。
23.2.4.3模型请求构造、提示词组装与运行时模型选择套件17 个文件
这一阶段是在真正调用模型前,给模型“装信封、选收件人”。它检查用户的话、项目说明、AGENTS.md、技能、额外上下文、权限、人格、协作模式等有没有按正确顺序放进请求里,也盯着版面、缓存、token 余量和 JSON 格式要求别出错。另一部分负责按配置选择远程模型、切换模型、打开网页搜索等工具,并确保自动审查用专门模型。整体是幕后把关,避免模型拿错说明或用错能力。
23.2.4.4多智能体、协作与远程环境套件6 个文件
这一阶段像一套“多人协作演练”,属于幕后把关,不是正式干活儿本身。它检查系统能不能安全地让主助手派出子助手:说明文字别误导,子助手数量不能无限膨胀;委托审查时,批准命令、改文件这类关键消息要传回主流程;子助手的启动、结束、通知和配置继承不能乱;批量 CSV 任务要能派发、回写和停止;远程环境也要确认连得对、文件写在对的机器上、权限拦得住。
23.2.4.5审批、权限、hooks 与评审调解套件13 个文件
这一阶段像系统干活时的“门卫和裁判”,不在开机或关机,而是在模型要执行命令、改文件、联网、调工具、问用户时把关。审批和执行策略测试负责确认危险动作会被拦住,批准后也只放开该放的范围;临时权限和技能脚本测试防止权限越滚越大;用户追问、通知、代码评审和 Guardian 检查负责把人与自动审查接好;hook 和 MCP 元数据测试则确保外部工具前后都有记录、拦截和路由,不让安全规则漏掉。
23.2.4.6工具、shell/exec、MCP/app、插件与运行时项套件20 个文件
这一阶段像给“助手动手干活”做全套验收,属于主流程背后的安全网。它检查模型能看到哪些工具、能不能跑 shell 命令、改补丁、看图片、搜工具、装插件、调用 MCP 和 app。各测试还盯住沙盒权限、超时中断、并行执行、长输出截短、结果格式、事件顺序。简单说,就是确保工具既能用、好用,又不能越权乱动机器。
23.3CLI、exec、登录和 MCP server 开发者验证73 个文件
这一阶段不是产品正式干活,而是给一批可执行程序做“出厂验收”。它从用户会碰到的入口开始试:codex CLI、codex-exec、apply-patch 都要实际跑命令,看参数、输出、改文件和报错是否对。登录测试像试钥匙,检查凭证能存、能续、能退出。execpolicy 像安全门,判断命令该放行还是拦住。MCP server 测试则启动真服务和假 AI 对话,确认开发者工作流能跑通。
23.3.1apply-patch 可执行文件集成测试5 个文件
这一阶段是在给 apply-patch 这个独立命令行小工具做“上机验收”,属于幕后保证质量的测试部分。all.rs 和 mod.rs 像点名册,把真正的测试都登记进来。cli.rs 检查用户把补丁写在命令里,或从标准输入喂进去时,能不能正确改文件。tool.rs 像功能清单,逐项验证新增、修改、移动、删除和报错提示。scenarios.rs 则按真实案例跑完整流程,只看最后文件夹是不是变成该有的样子。
23.3.2顶层 codex CLI 命令验证14 个文件
这一阶段像是给 codex 命令行入口做总验收,属于系统跑起来后面向用户的外壳检查。它会实际敲各种命令,看反应对不对:app-server、exec-server 要能拦住写错的配置;delete、update、debug 命令不能走错流程;features 检查功能开关和配置提示;plugin 和 marketplace 测插件安装源的增删升级;MCP 命令要正确读写服务器配置;最后还有少量真人真机测试,确认真连服务时也能跑通。
23.3.3codex-exec 二进制验证22 个文件
这一阶段不是程序正式干活,而是给 codex-exec 这个命令行工具做“出厂检查”。它从用户最外层能碰到的地方下手:先测终端参数会不会读错,尤其是 resume、目录、配置和提示词;再测服务端事件能不能正确翻成人看的文字、JSON 或 JSONL;还会检查会话能否保存和恢复,标准输入、AGENTS.md、输出格式要求有没有带上;最后盯住认证头、审批策略、MCP 启动失败、hooks、服务器报错退出码,以及打补丁改文件流程,确保这些零件合在一起时,用户看到的行为稳定可靠。
23.3.4旧版和当前 execpolicy 可执行文件测试13 个文件
这一阶段不是系统正式干活儿,而是给“能不能执行命令”的安全门做体检。当前测试会直接跑 execpolicy check,看它是否用 JSON 正确回答放行、提醒或禁止,也检查网络规则。旧版测试像一套老题库:good、bad 先查默认规则的大方向,cp、ls、pwd、head、sed 等再逐个盯常见命令的参数细节。all 和 mod 负责把这些题目串起来一起跑,防止新旧策略被改坏。
23.3.5登录流程集成测试12 个文件
这一阶段不是程序给用户干活的主流程,而是开发者用来“验收登录系统”的试车场。all.rs 和 mod.rs 像总开关,把各项测试集中跑起来。令牌、个人令牌、Bedrock Key、存储和通用认证测试,检查凭证能不能认对、存好、删干净。命令行、设备码、浏览器登录服务器测试,模拟真实登录。刷新和登出测试则盯住过期续签和退出清理,防止账号状态留下隐患。
23.3.6MCP server 可执行文件集成测试7 个文件
这一阶段是给 codex MCP server 这个可执行程序做端到端体检,属于幕后保证质量的测试部分。all.rs 和 mod.rs 像总开关,把整套测试串起来。common/lib.rs 提供公共工具箱;mcp_process.rs 真正启动服务器子进程,用 JSON-RPC 这种“按格式传纸条”的方式对话;mock_model_server.rs 和 responses.rs 假扮外部 AI,并吐出预设流式回复。最后 codex_tool.rs 检查危险命令、代码补丁和用户指令传递是否都按规矩走。
23.4Exec-server、沙箱和远程传输测试工具49 个文件
这一阶段不是正式干活的主流程,而是一整套“试车场”和测试工具,专门检查 exec-server、远程连接、文件读写、进程执行和沙箱安全有没有坏。公共工具先负责启动假服务器、真服务器、Wine 里的 Windows 服务器,帮测试连上、发消息、收尾。另一批测试检查 WebSocket、初始化、健康检查、HTTP、Noise 加密和中继传输。文件系统测试盯住路径、链接、权限和大文件读取。沙箱测试则分别在 Linux、macOS、Windows 上确认命令被关进安全围栏,输入输出桥和清理工作也不掉链子。
23.5TUI 交互和渲染测试52 个文件
这一阶段不是用户真正使用时的主流程,而是幕后给终端界面做“体检”。先用测试工具和假终端搭好舞台,让程序以为自己在真实窗口里运行,再把画面收起来对照。App 和 ChatWidget 的测试负责检查启动、会话恢复、输入提交、审批弹窗、权限、状态栏、斜杠命令等操作会不会乱。渲染、Markdown、历史消息、用量图和布局测试则盯住每一块显示是否对齐、换行正确。最后集成和 VT100 测试模拟真实终端滚动、缩放和历史回放,防止小改动把界面体验悄悄改坏。
23.6跨领域库测试、夹具及遥测或 rollout 支持190 个文件
这一阶段是后台“质检台”,不参与开机、主循环或关机,专门给各类共享小库和外接能力做本地检查。测试入口和目录页负责把分散测试接上;假客户端、假服务器、假文件环境像演练道具。它会查埋点遥测、配置策略、插件工具、API 通信、记忆和状态保存,也会测路径转换、文件监听、终端识别、长输出落盘、字符串截断、图片处理和 token 记账,确保这些底座改动后不丢数、不误报、不弄坏用户数据。
23.6.1Analytics 和 telemetry 测试18 个文件
这一阶段不是系统真正干活的主流程,而是幕后“质检台”,专门检查分析埋点和遥测数据靠不靠谱。入口和目录文件负责把测试接进来;harness 像假监控台,方便造指标、取结果、核对内容。各类 otel 测试检查名字标签是否合法、耗时和计数是否写对、快照和导出是否正常、敏感内容有没有走错通道。analytics、server、core、state 的测试则盯住事件收集、开关行为、任务指标、日志过滤,防止数据丢、错、脏。
23.6.2配置、策略和环境测试43 个文件
这一阶段主要是在幕后做“体检”,不是用户真正干活的主循环。它反复检查配置这条链路:本地、系统、企业云端和项目配置怎么读取、排序、合并,写错时能不能报清楚;再检查权限、网络、沙箱、hooks 小脚本、功能开关和提示文字有没有按安全规则生效。还有一批测试专门造假环境、假云端、假文件,像试车场一样模拟升级、缓存损坏、路径差异和额度不足,防止改代码时把用户设置或安全边界弄坏。
23.6.3插件、扩展、技能、MCP 和工具测试50 个文件
这一阶段不是系统开机或干活的主流程,而是一大块“质检台”。它用假目录、假市场、假服务器和临时仓库,反复检查插件能不能安全发现、安装、加载、分享和推荐;扩展接口能不能按顺序接入;技能会不会被正确找到、隐藏、点名调用;MCP 这种外部工具服务器能不能按配置连接、授权和过滤;最后还核对各种工具说明转换成接口格式时不丢字段、不乱改。它们合在一起,防止外接能力这条链路被改坏。
23.6.4API 客户端、模型、协议、提示词和传输支持测试38 个文件
这一阶段像后台质检车间,不直接给用户干活,而是反复检查“和外部服务说话”这套底座稳不稳。模型配置和缓存测试管模型名单、默认值、登录后刷新;API、登录、证书和代理测试管请求地址、身份、重试和安全连接;协议、提示词、工具测试管错误说明、文字编码、模板和参数别变形;WebSocket、HTTP、Unix socket 等测试管消息能顺利收发。假客户端和假服务器则像演练道具,让这些检查不用真连云端也能跑。
23.6.5Memories、rollout、状态和持久化测试26 个文件
这一阶段主要是幕后“质检”和测试工具,不是用户直接看到的主流程。它像给系统做体检:先用假事件搭出现场,检查 rollout 追踪能不能把模型回复、工具调用、终端、子代理和对话历史整理清楚;再测记忆功能能不能启动、写盘、引用、清理资源;还会检查状态数据库、消息历史、线程存储、外部代理账本和会话记录文件。重点是保证断电、文件坏掉、压缩、改名、旧格式等麻烦情况里,记录不丢、不串、不乱删。
23.6.6路径/URI 与输出截断辅助工具的 utility crate 测试3 个文件
这一阶段不是程序开机、干活或关机的主流程,而是在幕后给公共小工具做“体检”。它用自动测试反复检查两类容易出错的基础能力:一类看路径和 file: URI 能不能互相转对,覆盖 Windows、Unix、特殊字符、坏输入等坑;另一类看给 API 用的路径字符串会不会被误解。还有一组测试专盯长输出截断,确保文字、emoji、图片、加密内容混在一起时,截得安全、可读,也会正确提示被截短。
System Handbook
Codex System Handbook
140 stages · 2267 files documented · State-flow registers → · Function index →
System overview
1. System Overview
This system is a Rust application that can wear several faces. You can use it as an interactive terminal chat app, a one-shot command-line tool, a background app server, a remote execution helper, or a set of developer utilities. A good mental picture is a workshop with one shared engine in the back and several front doors. No matter which door you enter, the system prepares the same core machinery for talking with models, running tools, saving work, and showing results.
At startup, the program first decides which mode was requested from the command name and flags. It then hardens the process, sets up secure networking, finds the user’s Codex home folder, inspects the local machine, and loads layered configuration from policy, project files, user settings, and command-line options. It checks who the user is, prepares local databases, refreshes model and plugin catalogs, and starts any needed servers or sidecar helpers. If the user opens the terminal interface, it draws the screen and resumes or creates a chat. If a script runs exec mode, it prepares one controlled session and predictable output.
During normal work, events flow through a central dispatch loop. Keyboard input, server requests, and automation messages are routed to live conversation threads. Before each model turn, the system builds a prompt from the chat history, project instructions, permissions, tools, memories, plugins, and current workspace facts. It sends that package to a model service, streams the answer back, and safely handles any requested actions. Commands, file edits, web or plugin calls, and background agents pass through approval and sandbox rules before they can affect the outside world.
As work happens, the system saves transcripts, summaries, tool results, thread state, and visible UI updates. When a session or server ends, it blocks new work, lets safe tasks finish, flushes state, stops agents, and releases connections.
Behind the scenes, shared contracts keep every part speaking the same message language. Networking, storage, telemetry, diagnostics, utilities, and tests support the whole lifecycle, like wiring, filing cabinets, gauges, and inspection tools for the workshop.
2. Two ASCII Diagrams
Diagram A · Lifecycle
[entrypoint + runtime-mode dispatch]
|
v
[environment discovery / hardening / local resources]
|
v
[config + auth + permissions + model/plugin catalogs]
|
v
[server / TUI / session startup]
|
v
[event loop: receive input, locate thread, restore context]
|
v
[prompt assembly: history + rules + tools + memory + workspace]
|
v
[model call and streaming response handling]
|
v
[approval / sandbox / tool execution / file edits / external services]
|
v
[result projection: UI updates, transcripts, persisted state]
|
v
[shutdown: block new work, drain queues, save final state]Diagram B · One Conversation Turn
[user or client input]
|
v
[route to session/thread]
|
v
[build context bundle and tool catalog]
|
v
[send request to model]
|
v
{does the model need action?}
| no | yes
v v
[format reply + update UI] [check permission / ask user if needed]
|
v
[run in sandbox or controlled environment]
|
v
[feed tool result back to session/model]
|
v
{is the task done?}
| yes | no
v v
[persist + end] [next turn]3. Main Flow Map
- Process entrypoints and binary dispatch: This stage is the system’s set of starting doors.
- Early process hardening and runtime bootstrap: This stage happens at the very start, before Codex begins its real work.
- Installation context, home discovery, and local environment probing: This stage is early setup and shared support.
- Configuration, feature resolution, and startup policy assembly: This stage is the startup control room.
- Authentication, identity, and account readiness: This stage is the system’s “who are you and what can you use?” checkpoint.
- Persistence and local runtime services startup: This stage runs during startup and prepares the app’s local storage so the rest of Codex can work safely.
- Backend clients, remote catalogs, and startup refreshes: This stage runs during startup and early background setup.
- Transport and server runtime initialization: This stage sets up the communication roads used by server-style runs of the system.
- Frontend session startup and user-facing initialization: This stage happens after the backend services are ready, but before the user can really start working.
- Main event loop and request dispatch: This stage is the system’s normal working loop, after startup is finished.
- Thread and session orchestration: This stage is the traffic desk for long-running conversations.
- Prompt, context, and extension assembly: This stage is the prompt-building workshop.
- Turn execution and model interaction: This stage is the heart of the session’s main work loop.
- Tool execution, approvals, and guarded side effects: This stage is the system’s guarded action layer.
- Multi-agent, collaboration, and background workflows: This stage is the system’s “extra workers” layer.
- Result persistence, projection, and user-visible state updates: This stage is the system’s “make it real and show it” step.
- Shutdown, cleanup, and teardown: This stage covers the “put everything away safely” part of the system.
- Protocol schemas, shared types, and generated contracts: This stage is shared behind-the-scenes support for the whole system.
- Cross-cutting transport, networking, and client infrastructure: This stage is shared behind-the-scenes infrastructure.
- Cross-cutting observability, analytics, and feedback: This stage is the project’s shared “instrument panel.” It runs across startup, normal request handling, streaming, tool use, and shutdown, watching what happens so developers and operators can understand problems and usage without interrupting the main work.
- Cross-cutting persistence abstractions and data stores: This stage is the system’s long-term memory and filing system.
- Cross-cutting utility and support libraries: This stage is the shared toolbox used across the whole system, not one user-facing feature.
- Testing, fixtures, and developer verification harnesses: This stage is the project’s test workshop.
1Process entrypoints and binary dispatch65 files
This stage is the system’s set of starting doors. It runs at process startup, when the operating system has launched a native binary and passed in the command name and arguments. Its job is to read what was invoked, understand the flags and subcommands, and hand control to the right runtime mode.
The primary user-facing launch surfaces are the main front desk. They route everyday commands into the text interface, one-shot exec mode, cloud tasks, desktop app launch, sandbox tools, remote control, doctor checks, MCP server commands, or session archive tools. They also define the options each mode accepts before the real work begins.
The auxiliary binaries and developer tools are the side workbench. They generate schemas, refresh protocol files, apply patches, search files, inspect logs, start helper services, run test clients, and launch commands inside safer restricted environments.
The directly assigned exec/src/main.rs is a small but important switch. It starts codex-exec, then decides whether to run the normal non-interactive agent or behave like the codex-linux-sandbox helper.
1.1Primary user-facing launch surfaces19 files
This stage is the set of front doors users enter through. It sits at startup: before Codex can chat, run a task, open a desktop window, or diagnose a problem, these files read the command the user typed and route it to the right tool. The main CLI entry point chooses between the text interface, non-interactive exec mode, cloud tasks, desktop launch, sandbox tools, remote control, doctor checks, MCP server management, and session archive commands. The TUI and exec CLI files define the flags and prompts those modes accept, then their main files start the actual work and print final messages. Cloud task files connect terminal commands to cloud APIs, branch detection, task lists, diffs, and applying changes. Desktop files open or install the macOS or Windows app for the chosen workspace. Remote-control code starts or stops the app-server for outside access. Sandbox files run debug commands safely or prepare the Windows sandbox. Doctor files inspect local setup and conversation records. MCP and apply-command code connect Codex to external tools and bring agent-made code changes into the user’s checkout.
1.2Auxiliary binaries and developer tools45 files
This stage is the toolbox beside the main Codex program. These binaries are run directly by developers, tests, editors, or helper processes, rather than through the normal user command. Some tools produce machine-readable descriptions: config_schema and schema.rs describe valid config.toml settings, protocol exporters write TypeScript and JSON Schema files, hook and app-server fixture writers refresh checked-in schemas, and generate-proto rebuilds Rust code from Protocol Buffers. Some tools do focused user work: apply_patch edits files from a patch, file-search finds likely matching paths, md-events shows how Markdown is parsed, and state logs_client watches stored logs like tail -f. Others start services or bridges: the app server, MCP server, Responses API proxy, stdio-to-socket bridge, exec server, filesystem helper, and test MCP/app clients. Several are samples or test probes, including extension examples, notification capture helpers, custom certificate checks, and Wine or Windows exec-server runners. The remaining tools enforce safe execution: execpolicy checkers decide whether commands are allowed, while Linux, Bubblewrap, Unix execve, and Windows sandbox launchers set up restricted environments before running commands.
2Early process hardening and runtime bootstrap3 files
This stage happens at the very start, before Codex begins its real work. It is like locking the workshop, choosing the right power supply, and arranging the tool bench before anyone starts building. The process-hardening code tightens the running program’s defenses. On supported operating systems, it blocks or limits common ways another tool might inspect memory, create crash dumps, or tamper with the process. The rustls-provider code sets up the cryptography engine used by rustls, the library that makes secure TLS network connections. This matters because more than one engine may be available, and the program must choose one global provider early and consistently. The arg0 code shapes how the executable presents itself at launch. A single Codex binary can act like different helper programs depending on the name or hidden startup argument used. It also prepares early environment details, such as PATH aliases and .env variables, so later runtime setup can start from a predictable state.
3Installation context, home discovery, and local environment probing12 files
This stage is early setup and shared support. Before Codex can load settings or run tools, it must learn “where am I, what machine is this, and what helpers can I use?” The home-dir code chooses the user’s Codex folder, using CODEX_HOME if set or ~/.codex otherwise. The install-context and managed-install code identify how Codex was installed, where bundled resources are, which executable is managed by the app, and on Unix can check its real path, version, and file fingerprint.
Several pieces probe the local working conditions. The shell snapshot code captures the user’s shell setup, like aliases and exported variables, so later commands feel like they ran in the user’s normal terminal. The environment and environment-provider code define available places to run commands: local machine, remote exec server, or neither. Windows helper materialization copies needed helper programs into a sandbox bin folder safely.
Diagnostics then report what was found. Doctor checks cover Git, system settings, launch details, and search-helper availability. Cloud environment detection finds suitable cloud workspaces. Hostname lookup gives the rest of Codex a consistent machine name for matching rules.
4Configuration, feature resolution, and startup policy assembly105 files
This stage is the startup control room. It gathers every setting that can affect Codex before real work begins, then produces the final runtime configuration used by the app, server, tools, sandbox, and TUI.
First, the config ingestion parts read layered sources: managed policy, cloud settings, user and project files, thread overrides, and command-line flags. Shared CLI options, project-root markers, app-server config loading, and the central core config builder all feed into this. Requirements and permission files then turn human settings into concrete rules for files, network access, hooks, and sandbox limits.
Next, feature and catalog parts decide what is available: feature flags, models, providers, plugins, marketplaces, MCP tool servers, skills, presets, and bundled assets. Editing helpers safely update config files for plugins, marketplaces, and MCP servers, and migration code imports compatible external-agent settings.
Finally, the stage prepares policies for real execution. It resolves Windows sandbox permissions, executable paths, tool settings, service tiers, keymaps, and TUI persistence. Debug and config-lock files make the result explainable and repeatable, so later sessions can prove they used the same effective rules.
4.1Config layer ingestion and requirements composition42 files
This stage is the system’s configuration intake and assembly line. It runs mostly during startup, and again whenever settings must be refreshed. Its job is to read settings from user files, administrator-managed files, cloud policy, command-line options, and session overrides, then turn them into one effective set of rules the rest of Codex can trust.
The core config loading part defines what valid settings look like, reads each layer, reports precise mistakes, merges layers in priority order, and records where each value came from. The requirements layering part does the same for safety rules: command permissions, sandbox limits, hooks, network policy, and allow or deny rules. It combines them carefully so security-sensitive settings are not accidentally weakened.
The configuration service part is the editing and support desk. It lets the app and daemon inspect or change settings, writes files safely, explains errors, and imports older settings when possible. Finally, config/src/lib.rs is the public front door for this whole library. It gathers the internal pieces and exposes the configuration tools other parts of the codebase should use.
4.1.1Core config schemas, diagnostics, merge, and layered loading22 files
This stage is the behind-the-scenes configuration workshop. It runs during startup and whenever Codex needs to rebuild its settings. First, schema files define what valid settings look like: config_toml, profile_toml, hook_config, mcp_types, tui_keymap, environment_toml, agent_roles, and schema cover normal settings, reusable profiles, hooks, MCP servers, keyboard shortcuts, execution environments, agent roles, and tests around those shapes. Next, strict_config and diagnostics check files carefully and explain mistakes with exact line and column locations.
The loading side gathers settings from many places. loader/mod is the main coordinator. layer_io and macos read administrator-managed settings. cloud_config_bundle, cloud_config_layers, and cloud validation turn cloud-delivered policy into ordinary layers. thread_config adds per-session settings, and overrides converts command-line flags into the same TOML-like shape.
Finally, state, merge, and fingerprint stack all layers in priority order, normalize names, remember where values came from, and detect changes. config_lock can save and later compare the exact resolved configuration, making runs repeatable.
4.1.2Requirements layering and execution-policy composition11 files
This stage is behind-the-scenes setup work. Before Codex starts running commands, it reads requirements.toml and other managed sources, then builds one clear rule set for what is allowed. config_requirements defines these high-level limits and keeps track of where each setting came from, so errors can point to the right source. requirements_layers/mod is the entry point for this combining system. layer cleans one raw requirements layer and separates normal settings from special ones, like execution policy, hooks, permissions, and sandbox rules. stack then assembles all layers into the final result.
Some fields need safer merging than simple “last one wins.” permissions keeps every denied read path from every layer. hooks combines hook event lists while preventing unsafe hook directory conflicts. rules preserves rule priority, keeping higher-priority rules first.
Execution policy is the command safety rulebook. requirements_exec_policy parses and validates it from requirements.toml. amend safely adds new allow or deny lines when a user approves something. network_proxy_loader turns config and policy into live network proxy settings and reloads them when files change. hooks/config_rules decides which saved hook settings are trusted enough to use.
4.1.3Configuration management services and editable persistence surfaces8 files
This stage is the system’s configuration “service desk.” It sits behind the main app and daemon, letting clients read settings, change them safely, import old settings, and get understandable errors when configuration loading fails. The app server request processor is the front desk: it accepts configuration requests, reports policy rules, applies changes, and refreshes running work so new settings take effect. The service layer behind it checks whether requested edits are valid, writes them to the right files, and warns when another configuration layer will override them.
The core edit code is the careful pen. It updates the user’s config.toml file, a human-editable settings file, while preserving formatting where possible and writing atomically, meaning it avoids leaving a half-written broken file. Its document helpers convert between TOML text and typed settings. Error handling turns configuration failures into clear JSON-RPC replies, with special guidance for cloud bundle sign-in problems. Migration code imports Claude-style agent settings and adds a default personality only when safe. The daemon settings file separately saves its small remote-control option as JSON.
4.2Feature flags, provider catalogs, and built-in asset installation33 files
This stage is startup preparation. Before Codex opens a session or draws major UI screens, it builds the “menu of available things”: enabled features, known models, skills, plugins, tools, presets, and bundled assets.
The feature files define all feature flags, read them from TOML config, keep old flag names working, and enforce any flags that must stay on or off. The terminal experimental-features view lets users change some of those choices safely.
The skills files configure skills, install built-in system skills into CODEX_HOME, create default memory-extension instructions, then find, read, filter, and cache usable skill files from user, project, system, admin, plugin, and extra folders.
The plugin and marketplace files locate installed marketplaces, manage them from the command line, recognize plugins, and turn loaded plugin features into usable lists. MCP files then combine plugin, user, built-in, extension, and login-controlled tool servers into one catalog.
The model files define provider and model catalogs, apply local limits and defaults, and keep old preset keys working. Collaboration and approval preset files provide built-in working modes and permission levels. Finally, TUI files prepare model choices, update commands, and terminal pet images before the interface needs them.
5Authentication, identity, and account readiness40 files
This stage is the system’s “who are you and what can you use?” checkpoint. It runs during startup, onboarding, account changes, and before network features need permission. First, the interactive and persisted login flows get the user signed in, refresh or store saved tokens, report status, and cleanly log out. They support browser login, device-code login, MCP login, and several safe storage places for secrets.
Next, provider and backend auth adaptation turns that identity into the right kind of badge for each service. Some requests use ChatGPT tokens, some use provider API keys, some use OAuth, and Amazon Bedrock may need AWS request signing, which proves a request came from a valid AWS identity.
The shared files tie this together. The auth manager loads, saves, refreshes, and rejects bad credentials. Token helpers identify personal tokens or agent identity tokens, validate personal access tokens, and decode ChatGPT ID tokens into plain account facts like email and plan. The installation ID gives this local Codex install a stable name. On Windows, sandbox user setup prepares special accounts so isolated work can run safely.
5.1Interactive and persisted login flows15 files
This stage is the system’s sign-in and sign-out machinery. It is used during setup, onboarding, and later whenever the user checks status or changes accounts. The command-line entry point runs login, logout, and status commands, while the app server’s account processor answers account requests from the interface, such as auth state, limits, token use, and warning emails.
There are two main ways to sign in. The browser flow starts a tiny local web server, waits for the browser to return a temporary code, trades it for tokens, then saves them. The device-code flow shows a short code in the terminal, asks the user to enter it in a browser, and waits for approval; the terminal onboarding screen presents this same flow and ignores stale replies from old attempts. MCP server logins use a similar browser OAuth flow.
Behind the scenes, the login modules expose the right building blocks and shared error types. Storage code decides whether credentials go in an auth file, the operating-system keyring, encrypted local storage, or memory. Logout tries to revoke remote tokens, then removes local secrets.
5.2Provider and backend auth adaptation19 files
This stage is shared behind-the-scenes support. It prepares the “ID badges” that later network clients attach to HTTP, websocket, and RPC requests. The model-provider front door and provider definition describe what a model service needs: its address, credentials, models, and features. The auth files then turn saved logins, provider API keys, external token commands, account routing IDs, and FedRAMP markers into bearer-token headers.
For Amazon Bedrock, the Bedrock files choose between a simple bearer token and AWS SigV4, Amazon’s method of signing a request to prove who sent it and that it was not changed. The AWS helper files load credentials and region settings, check they are usable, and add those signatures.
Agent identity files create or read cryptographic keys, register the running agent task, verify identity tokens, and build signed headers proving which agent made a request. The API auth and attestation files give the rest of the system one simple plug-in point for auth and optional proof metadata. Remote-control and MCP auth files decide when ChatGPT, bearer, or OAuth login is needed. The rate-limit reset processor uses backend auth to safely call an account action.
6Persistence and local runtime services startup6 files
This stage runs during startup and prepares the app’s local storage so the rest of Codex can work safely. It is like opening a workshop before the day begins: checking the filing cabinets, updating their labels, and repairing any damaged drawers.
The main entry point is state/src/runtime.rs. It opens the local SQLite databases, which are small file-based databases, applies needed schema updates, and hands usable store objects to the rest of the program. state/src/migrations.rs defines those updates in a careful way so different Codex versions can share the same database without older versions crashing on newer changes.
Rollout data has its own path. core/src/state_db_bridge.rs gives core code a simple place to start and refer to the rollout state database. rollout/src/state_db.rs connects older session files on disk with the faster SQLite index, waits for copying to finish, and offers helpers to read or fix thread metadata.
If storage is broken, recovery code steps in. cli/src/state_db_recovery.rs explains startup failures to the user or moves bad state aside. state/src/runtime/recovery.rs backs up only damaged database files so fresh ones can be created.
7Backend clients, remote catalogs, and startup refreshes22 files
This stage runs during startup and early background setup. Its job is to make the app ready to talk to outside services and local model tools before users depend on them. The cloud-config files load cloud-delivered settings: lib exposes the small public API, backend fetches bundles from the service, service chooses cache or network, and bundle_loader wires in login and starts refreshes. The model files ask Codex, OpenAI-compatible providers, Amazon Bedrock, Ollama, and LM Studio what models are available, then models-manager combines bundled, cached, live, and login-based choices into one usable menu. The OSS, Ollama, and LM Studio helpers check local model servers and prepare them when requested. Connector and plugin code fetches ChatGPT connector directories, workspace plugin settings, local plugin connectors, and the built-in plugin catalog, using caches and fallbacks so startup stays reliable. The MCP client starts or connects to tool servers and manages sessions and tokens. Smaller backend clients fetch ChatGPT tasks, rate-limit reset data, memory-write safety checks, and update notices, so the app can avoid wasted quota and show useful maintenance information.
8Transport and server runtime initialization40 files
This stage sets up the communication roads used by server-style runs of the system. It happens during startup and then stays active during the main work loop, carrying requests, replies, and notifications between clients, servers, and helper processes. Most of these messages use JSON-RPC, a simple pattern where one side sends a named request in JSON and the other side sends back a matching response.
One part brings up the main app server and its daemon, which is a background process that can be started, stopped, checked, and reused. It opens transports such as standard input/output, Unix sockets, and WebSockets, then routes messages through the server and remote-control connections.
The other part starts sidecar servers: small helper services that sit beside the main process. Exec servers run commands through shared channels, encrypted relays connect remote clients safely, MCP servers expose tools, and proxy bridges connect local programs or network traffic under controlled rules. Together, these pieces form the switchboard that lets the rest of the system talk reliably.
8.1App-server and daemon transport bring-up23 files
This stage is the system’s “switchboard” for bringing the app server to life and letting other parts talk to it. The daemon files manage a background server process: the main daemon coordinates start, stop, restart, setup, updates, and configuration; the backend helpers add shared setup and clearer errors; the PID backend uses a process-ID file to prevent duplicate servers and remove stale records. The daemon client, remote-control client, and doctor check connect to the local control socket to inspect status, check versions, or enable and watch remote control without unsafe side effects.
Inside the app server, the runtime loads configuration, opens transports, routes JSON-RPC messages, performs the initialize handshake, sends outgoing replies, tracks pending answers, and can also run embedded inside the caller. Transport files provide the roads: standard input/output pipes, a private Unix socket, WebSockets, and WebSocket authentication. Remote-control files enroll the server, remember whether remote control should be enabled, maintain the remote WebSocket, track remote clients, reconnect, pair, revoke, and preserve messages. Client facades then give CLI and TUI code one simple way to send requests and receive events.
8.2Execution and integration sidecar servers17 files
This stage is the “sidecar” layer: helper servers and bridges that run beside the main Codex process. They expose Codex abilities over specific communication routes during startup and the main work loop. The exec-server files define the public library, choose how clients connect, and turn WebSockets, standard input/output, child processes, or encrypted relays into one JSON-RPC channel, meaning structured request-and-response messages. Its client code sends command and file requests and safely routes process output back.
The Noise relay and remote files add encrypted WebSocket plumbing, so a cloud rendezvous service can connect clients to executors without reading or forging their messages. MCP files start tool servers, describe their runtime environment, connect over standard input/output locally or remotely, load available tools, filter them, and shut down cleanly. The prototype MCP server wires terminal streams into Codex’s message processor.
Other sidecars are practical bridges. stdio-to-uds connects terminal-style programs to Unix sockets. The Responses API proxy forwards only approved local HTTP requests with real credentials. The network proxy starts HTTP and SOCKS listeners, assigns safe ports, sets child-process environment variables, and enforces network rules before traffic leaves.
9Frontend session startup and user-facing initialization41 files
This stage happens after the backend services are ready, but before the user can really start working. It is where Codex turns its prepared engine into something a person or script can use.
For the interactive terminal app, the TUI startup path opens the front door. It loads settings, connects to the app server, guides first-time users through sign-in and trust choices, checks project setup, and builds or resumes the visible chat. It also takes careful control of the terminal window: drawing the interface, reading keys, handling resize and suspend, showing notifications, and restoring the shell when finished.
For non-interactive use, exec mode starts a single scripted session instead of a full screen app. It gathers the prompt, configuration, saved session details, or review request, then runs once and writes predictable output, such as JSON lines for other programs to read. The resume helper makes sure an old conversation restarts with the right folder and model. Together, these parts make Codex ready for either a human at a terminal or an automation script.
9.1TUI startup, onboarding, and terminal ownership39 files
This stage is the front door of the terminal app. It runs before the main chat loop, then keeps owning the terminal safely while the app is open. The startup code loads settings, connects to or starts the app server, chooses local AI providers when needed, checks changed project hooks, offers updates, model moves, working-directory choices, and imports from other agents. Onboarding screens guide first-time users through welcome, sign-in, and trusting the project folder, using built-in keys so the flow works before custom settings exist.
Once startup choices are settled, the App builds or resumes a chat thread, can show a session picker, constructs the main chat widget, replays old conversations without rerunning actions, and displays startup cards, tips, MCP server progress, collaboration modes, pets, and status previews. The terminal layer is the machinery underneath: it probes terminal abilities, enables safer keyboard input, draws efficiently, handles resizing, title changes, suspend/resume, stderr noise, clipboard-style notifications, bells, and desktop notification escape codes. Together these pieces turn a normal shell window into Codex’s interactive workspace, then restore it cleanly afterward.
9.2Exec-mode and scripted session startup2 files
This stage is about starting a one-shot, non-interactive Codex run. Instead of opening a long-running text interface, it prepares one session, feeds in the prompt or resume information, runs the work, and finishes. It is mainly used by scripts, automation, or commands like codex exec, where output must be predictable.
exec/src/lib.rs is the main driver for this mode. It gathers instructions from command-line flags, config files, standard input, and saved session data. It can start a new request, continue an old session, or run a review. It also arranges output so that normal results can be read safely by other programs, for example as structured JSONL, which means one JSON record per line.
tui/src/session_resume.rs supports the resume path. It works out which saved conversation to use, which folder it belonged to, and which model should continue it. If the saved folder is not the user’s current folder, it asks what to do. Together, these pieces make sure a scripted run starts with the right context and can proceed without an interactive work loop.
10Main event loop and request dispatch137 files
This stage is the system’s normal working loop, after startup is finished. It is the traffic control center for everything that happens while the app is running. On the user side, interactive event dispatch turns keyboard input, paste events, terminal resizing, redraw requests, and background updates into clear app actions, then sends them to the right screen area or chat thread.
On the server side, RPC request routing handles JSON-RPC messages, which are structured requests with names, data, and replies. It checks each request, chooses the right subsystem, and sends back results or errors. The exec server processor does this for each remote execution connection, reading requests, dispatching actions, writing replies, and cleaning up afterward.
Inside a live Codex session, session handlers act like a command desk for user messages, approvals, setting changes, rollbacks, reviews, voice input, and shutdown. Request serialization keeps requests that touch the same resource in a safe order, while allowing unrelated work to continue. Parallel tool handling decides which tool calls can run together, formats their results, and makes cancellation reliable.
10.1Interactive event dispatch96 files
Interactive event dispatch is the terminal app’s live traffic system during normal use. It takes raw activity from the keyboard, paste buffer, terminal window, server, and background tasks, then sends each event to the right place.
At the outer edge, event_stream turns low-level terminal signals into app-friendly events like key press, paste, resize, focus change, or redraw request. It also fully releases the terminal input reader when the TUI is paused, so another program can safely read from standard input.
App-level dispatch is the main switchboard. It receives these events, routes them to the correct chat thread, tracks pending server questions, and asks for screen redraws without wasting work. The bottom-pane stage handles the message composer, slash commands, popups, prompts, history search, and “@” mention search. The chat widget stage applies events to the visible conversation: sending messages, queuing drafts, showing streaming replies, running commands, and managing interrupts. Specialized handlers cover side flows such as task lists, thread navigation, backtracking, pagers, keymap editing, theme picking, pets, clipboard actions, and imports.
10.1.1App-level event dispatch and thread routing10 files
This stage is the TUI’s main traffic system during normal use. It sits between the user, the screen, the app server, and multiple chat threads. app_event_sender gives other UI code a simple way to send actions into the main loop. app_command defines the allowed kinds of actions, so messages have clear meaning. event_dispatch is the central switchboard: it receives each event and sends it to the right handler.
User key presses go through input, which handles global shortcuts such as switching threads, opening views, clearing the screen, or backing out with Escape. frame_requester asks for screen redraws in a careful way, combining repeated requests so the UI does not waste work.
Messages from the app server go through app_server_events. Server requests that need a later user answer are tracked by app_server_requests. pending_interactive_replay remembers which prompts are still unresolved when a thread is replayed. thread_routing keeps events and actions tied to the correct conversation thread. background_requests runs slower server queries off to the side, then returns their results as normal app events.
10.1.2Bottom-pane composer, popups, and mention input42 files
This stage is the control center for the terminal app’s bottom pane, where the user types messages, chooses suggestions, answers prompts, and changes small settings. It is part of the main work loop. The bottom pane decides whether each key press belongs to the chat composer, a popup, a modal form, or an interrupt action.
At its core are the shared bottom-pane view contract, the pane controller, the reusable composer widget, and the text area. These keep typing, cursor movement, wrapping, paste detection, Vim-style edits, attachments, draft text, footer hints, and popup state working together. History files add Up/Down recall and Ctrl+R search. Slash-command files parse commands like “/status”, decide which ones are allowed, show suggestions, and run the chosen command.
Mention and search pieces power “@” style insertion. They build searchable candidates from files, skills, and plugins, filter them, and draw the popup and footer. Reusable picker views provide lists, multi-select menus, and search panels. The remaining popup views handle settings, skills, memories, hooks, custom prompts, feedback, app-link requests, server questions, and user-input overlays, all using the same bottom-pane machinery.
10.1.3Chat widget interaction and command flows23 files
This stage is the main control room for the terminal chat screen. It runs during normal use, after startup, while the user is talking to the agent. The central chat widget keeps the transcript, input box, status messages, popups, and streaming replies in sync. Rendering turns that state into terminal rows. Protocol files listen for server events and turn them into visible changes, such as approvals, tool prompts, review results, and notices.
User input passes through several gates. Interaction handles keys, paste, images, copy, interrupt, and quit. Input submission and input flow decide whether text is sent now, queued, treated as a slash command, or held until the current turn finishes. The queue and restore code protect drafts, rejected messages, steering instructions, and attachments from being lost.
Other parts add focused features. Slash dispatch runs commands like /new or /diff. Skills, connectors, IDE context, goals, hooks, usage, tokens, reviews, model popups, plan implementation, and reasoning shortcuts build the small menus and actions around chat. Interrupt and notification helpers make sure prompts and alerts appear in a useful order.
10.1.4Specialized interactive flows and auxiliary TUI handlers20 files
This stage covers special side flows in the terminal interface. These are not the main chat loop, but popups, pickers, previews, and helpers that users open while working. The cloud-tasks files form a small app inside the app: one file stores the task list, selected row, popups, and loaded details; another stores the “new task” form; the UI file draws the list, editor, overlays, confirmations, and spinners.
Several files support navigation through complex conversations. Agent navigation and multi-agent display keep agent threads in a stable order, show readable status rows, and let users switch agents. Backtrack lets a user return to an earlier prompt and roll the conversation back. Pager overlays show long transcripts or help pages.
Other files customize the interface. The keymap files provide the shortcut editor, action catalog, searchable picker, and keypress inspector. Theme picker previews and saves color themes. Pet files handle selecting, previewing, drawing, disabling, and cleaning up the companion pet.
Finally, platform actions, clipboard paste, and external import flows connect the app to the outside world: operating-system checks, pasted images or paths, and importing settings from Claude Code.
10.2RPC request routing37 files
This stage is the system’s set of switchboards during normal operation. Messages arrive as JSON-RPC requests, meaning named messages with parameters and replies, and these files send each one to the right worker. The app server’s message processor checks that a client is ready, then request_processors fans out to specialists for catalogs, environments, external-agent imports, MCP servers, conversation turns, threads and goals, thread deletion, Windows sandbox setup, files and file watching, feedback, Git diffs, marketplace changes, plugins, remote control, and search. Small helpers shape model lists, attestation headers, dynamic tool results, and clear error replies.
The core tool router and registry do the same job inside conversations: validate a requested tool, run safety checks, call the tool, and return a readable result. The TUI routing map decides which thread should receive each update. The exec server has its own RPC wiring, registry, connection handler, file-system handler, and process handler for remote execution work. The MCP server routes MCP messages and runs Codex tool calls, while RMCP client handlers pass logging and user-question requests onward. The HTTP proxy routes network requests through policy checks.
11Thread and session orchestration44 files
This stage is the traffic desk for long-running conversations. It sits between startup and the main work loop: before the agent can answer, it must know which thread it belongs to, what history to load, where to run commands, and who is listening for events.
The library entry files expose the stable “front doors” to this core machinery. The thread manager and Codex thread wrapper create, resume, fork, switch, and shut down conversations. Session files then build the live workspace: model access, permissions, tools, environment, history, input queues, turn state, and background task control. Storage files create local records, keep live thread handles, trim history at safe turn boundaries, and update searchable metadata.
Server-side files attach clients to running threads, support reconnects, refresh MCP configuration, filter visible threads, and clean up unused sessions. Import files detect outside agent histories and decide whether they are safe to bring in. Extension files add goals, skills, and plugin-provided MCP servers. Tool handlers let the model request a new context window or update its plan. TUI files keep the terminal’s view, settings, side chats, goals, and active-turn display synchronized with the live thread.
12Prompt, context, and extension assembly74 files
This stage is the prompt-building workshop. Just before the system sends a turn to the model, it gathers everything the model is allowed to see and shapes it into one clear input package. Some parts provide the raw shelves and labels: shared prompt templates, context fragment formats, and extension hooks so built-in code and add-ons can add text in predictable places.
Other parts create the actual note cards that go into the prompt. They turn settings and events into model-readable messages: project instructions, permissions, network rules, available skills, memories, goals, IDE details, plugin and app connectors, review requests, and warnings about space limits. They also keep older saved warning formats understandable.
The turn assembly parts then combine these pieces with the conversation history. They trim old messages when the model’s memory space is limited, remove items the chosen model cannot use, and send only changed context when possible. Realtime startup and developer prompt-debugging use the same machinery to build their own opening briefings.
12.1Prompt and context facade modules, fragments, and embedded instruction templates8 files
This stage is shared behind-the-scenes support for building what the model sees. It does not run the main work itself. Instead, it provides the shelves and labels for prompt text and context snippets, so later code can assemble them safely and in the right order.
The codex-home front door exposes the provider for user instructions, hiding the internal layout. collaboration-mode-templates bundles ready-made collaboration instructions into the program, like built-in note cards. The prompts front door collects prompt text, helper code for building prompts, and review-related types into one place.
The context-fragments files define and export the common shape of a context fragment: a small piece of information injected into the conversation. They also let the system recognize its own injected fragments later. The extension prompt contributor file gives add-ons a labeled way to contribute prompt text to specific prompt sections. Finally, the core context files re-export permission instructions and other context pieces from convenient locations, making them easy for the rest of the system to use.
12.2Context fragment definitions and prompt assets25 files
This stage supplies the raw “building blocks” that later prompt assembly uses before the model is called. It is shared behind-the-scenes support, like labeled note cards that can be slipped into a conversation. The prompt asset files expose fixed template text for hierarchical agents, apply_patch instructions, compact summaries, and realtime start, backend, and end prompts, so Rust code can use stable names instead of reading files directly. The context fragment files turn real events and settings into clearly labeled messages: extra context, loaded skills, hidden internal guidance, available skills, saved command prefixes, environment facts, guardian review reminders, hook text, model-switch instructions, network rules, token budget warnings, aborted turns, project user instructions, user shell commands, realtime opening and closing instructions, and subagent status updates. Each wrapper chooses the right speaker role, tags, and wording so the model can tell what the information means. A few files recognize old warning formats for apply_patch, model mismatch, and process limits, so older saved conversations can still be read safely. Together, these pieces make prompt content consistent and recognizable.
12.3Instruction, skill, plugin, memory, and review prompt contributors29 files
This stage is behind-the-scenes prompt assembly. It gathers all the extra guidance the model should see before or during the main work loop, like notes placed on a workbench before starting a task. Some files load standing instructions: global Codex instructions, project AGENTS.md files, collaboration mode, personality style, terminal formatting, IDE context, image-save notes, and permission rules. Others describe optional capabilities. Skills code selects skills named by the user, removes duplicates, bridges Codex data into the skills system, and renders available or enabled skills within a size limit. App and plugin code similarly lists connectors, plugin tools, servers, and plugin-specific guidance only when they exist or are mentioned. Code-mode support reshapes tool descriptions for a stricter runtime format. Extension examples show how prompt snippets can be added with shared state. Memory files decide when memories apply, summarize saved memories, and build prompts for writing or merging them. Goal files create reminders about objectives and budgets. Review files turn review requests and endings into clear prompts. Together, these pieces make the model’s context accurate, relevant, and not overloaded.
12.4Turn context, history, and realtime prompt assembly12 files
This stage prepares the exact package of information the model sees before it answers. It sits in the main work loop, just before a new turn is sent, and it also supports realtime startup and debugging.
The turn context builder creates one reliable snapshot of the session: model choice, file locations, allowed tools, permissions, and settings. The history manager keeps earlier conversation turns, trims them to fit the model’s limited memory space, and can roll back or clean them. Normalization keeps tool requests matched with their results and removes data the selected model cannot use, such as images for a text-only model.
Additional context and context update code work like change notices. They send only what changed, such as new permissions or environment details, instead of repeating the whole setup. Token budgeting adds warnings when the conversation is filling up the available space.
Special user-message context is separated from normal human text. Realtime files build the startup briefing and choose the realtime instruction prompt. Prompt debugging assembles a visible test prompt for developers. Web search history extracts only recent useful text for standalone searches.
13Turn execution and model interaction88 files
This stage is the heart of the session’s main work loop. It begins when the user sends a turn and ends when the assistant has answered, run needed tools, or prepared another model pass. The regular task starts a normal turn, while session/turn.rs coordinates the whole path: gather input, attach tools and context, call the model, stream updates, run tool calls, and finish bookkeeping. turn_metadata.rs adds useful background to each request, such as workspace and safety settings.
When a conversation grows too large, the compact task, compact.rs, and compact_remote.rs shrink it into a shorter summary, either locally or through the model service, so the session can continue.
Model transport execution is the “phone line” to model services. It builds requests, sends them over HTTP, server-sent events, WebSocket, or realtime audio links, decodes streamed replies, and handles retries or failures.
Streaming reduction and UI projection turn many tiny raw events into readable transcript cards, live text, tool statuses, diffs, and final history.
The code-mode runtime files run user JavaScript inside V8, load the main module, block unsupported imports, and provide timers like setTimeout.
13.1Model transport execution28 files
This stage is the network layer for talking to model services during the main work of a session, with a little startup help. Shared request plumbing in client_common, responses_metadata, responses.rs, and tools/responses_api shapes Codex turns, IDs, metadata, and tool descriptions before they leave the app. The main client chooses HTTP streaming or WebSocket, adds authentication, sends the request, records telemetry, and uses retry policy when a stream fails.
Endpoint clients are the doorways to specific remote jobs: Responses, compact history, memories, images, search, and realtime calls. Their companion decoders turn raw server streams, JSON, SSE events, WebSocket messages, or WebRTC answers into clear Codex events and typed results. api_bridge makes network and HTTP failures understandable to the rest of the program.
Realtime files are the live conversation machinery. They hide protocol version differences, build outgoing voice/text messages, decode incoming events, and run WebSocket or WebRTC audio sessions. Higher-level orchestration starts realtime conversations, prewarms connections during session startup, and runs remote compaction so long chats stay usable.
13.2Streaming reduction and UI projection51 files
This stage is the live “make it readable” part of the main work loop. As the assistant, tools, and server send small events, it turns them into clean text, stable transcript entries, and status messages the user can understand. The stream parsers strip hidden citation, plan, and Git-action markers from assistant text while saving their structured meaning. Markdown streaming and table holdback delay unsafe fragments, especially half-built tables, until they can be rendered without flicker or bad wrapping. Markdown, syntax highlighting, diff rendering, and table conversion then turn text, code, and file changes into styled terminal lines.
The streaming controller, chunking, and commit-tick code decide when queued text becomes permanent history and when it stays as a live tail. History-cell and exec-cell files define the many transcript “cards”: user and assistant messages, plans, approvals, searches, tool calls, notices, patches, hooks, commands, and MCP activity. Chat-widget files keep the active turn, command lifecycle, hooks, user drafts, status line, token usage, and live assistant output in sync. Resize and consolidation code rebuild final transcript state safely, while API and watcher helpers translate rate limits, process output, and other low-level events into user-facing updates.
14Tool execution, approvals, and guarded side effects294 files
This stage is the system’s guarded action layer. It runs during the main work loop whenever the model asks to do something outside plain text, such as run a command, edit a file, call a web or MCP tool, use memory, or ask the user for approval. It is like a workshop with a front desk, safety officer, tool shelves, and locked work areas.
The approval, guardian, and hook parts decide whether an action may continue, needs user permission, or must be blocked. The execution backends then do the hands-on work: shell commands, interactive programs, file patches, sleeps, and remote or sandboxed file access. The extension tools connect extra equipment, including MCP servers, plugins, web, images, skills, and code cells. The policy and parsing helpers inspect commands and build the sandbox rules that limit what a tool can touch.
The shared tool files define the common shape of tools, their input schemas, MCP conversions, and error types. The handler front door routes each requested tool to the right runner and turns the result back into protocol messages the model can understand.
14.1Approval, guardian, and hook mediation63 files
This stage is the system’s safety and permission hub. It sits mostly in the main work loop, just before the assistant does something with side effects, such as running a command, editing files, using the network, calling an external tool, or stopping a session.
Its policy engines are the rulebook. They read configured rules and decide whether an action is allowed, denied, or needs a prompt. Guardian review is the careful supervisor: for risky requests, it can run a separate review session and turn that review into a clear yes, no, timeout, or abort. Hook mediation is the checkpoint network. It discovers trusted user hooks, runs them at moments like prompt submit or tool use, and turns their output into “continue,” “block,” “warn,” or “change this” decisions.
Permission ingress is the front desk for “may I?” requests from the model or connected MCP tools. Tool orchestration and the approval UI then show requests to the user and route answers back. Finally, enforcement runtimes make decisions real by limiting network access and sandbox behavior while commands run.
14.1.1Approval policy and request-decision engines14 files
This stage is the system’s safety gate. It works behind the scenes whenever a shell command, code patch, network request, or sandbox change is about to happen. Its job is to answer: allow it, block it, or ask the user first.
The newer execpolicy library is the main rule engine. Its front door exposes the useful pieces. Its parser reads policy files written in a small Starlark-based language, meaning a simple scripting format for rules. The rule and policy files define what rules look like, check examples, match commands or hosts, and produce allow, deny, or prompt decisions.
The core files connect those decisions to real tools. sandboxing defines the shared approval and sandbox contract. exec_policy loads and updates command and network rules. network_policy_decision turns network events into clear approval prompts and saved rules. safety does the same kind of gatekeeping for file-writing patches.
The legacy execpolicy library keeps older rule formats working. It parses old policies, matches program arguments, checks per-program rules, validates examples, and ensures commands cannot read or write outside approved folders.
14.1.2Guardian review and mediated approval sessions6 files
This stage is a behind-the-scenes safety checkpoint in the main work loop. Before Codex takes a risky action, such as running a command, changing files, using the network, or calling an external MCP tool, Guardian may review it instead of immediately asking the user. It acts like a careful supervisor beside the main worker.
The front door in guardian/mod.rs decides when Guardian can automatically allow or deny a request, and includes a safety brake if too many actions are rejected. approval_request.rs describes the kinds of actions that may need approval and reshapes them for prompts, logs, safety checks, and conversation records. prompt.rs builds the message sent to the Guardian reviewer and reads the reviewer’s structured JSON answer.
The review itself runs as a separate mini-session. session/review.rs sets up that special review turn with its own model, limits, tools, and user-interface signal. review_session.rs manages whether to reuse an existing reviewer or start a temporary one, then handles timeouts and cancellation. Finally, review.rs turns the reviewer’s decision into an approved, denied, timed-out, or aborted result for the session, interface, and analytics.
14.1.3Hook execution and stop-continue mediation16 files
This stage is the system’s checkpoint network. It runs user-configured hooks, which are small external commands, at key moments in the conversation: session start, prompt submit, tool use, permission checks, compaction, and stopping. The registry and engine module are the front desk. They build the hook system, list hooks, preview them, and route events to the right runner, while still supporting the older notify path. Discovery finds hook definitions in config, policy, and plugins, then checks whether they are trusted. The dispatcher chooses which hooks match an event. The command runner starts those hooks as real processes, sends them JSON input, and captures results. The output parser turns their printed text into decisions the system understands, and output spill saves oversized output to a temp file with a short preview. The runtime connects all this back to the main conversation, progress reporting, telemetry, and added context. Event handlers apply the decisions: start and prompt hooks may add context or stop work; pre- and post-tool hooks may block, rewrite, warn, or continue; permission hooks approve or deny; compaction hooks guard history shrinking; stop hooks decide whether to end, block, or continue.
14.1.4Permission and elicitation request ingress5 files
This stage is the front desk for requests that need a human or policy decision. It sits in the main work loop, when the assistant or an outside MCP integration needs permission, confirmation, or extra information before continuing. MCP means “Model Context Protocol,” a way for other tools to connect to Codex.
The permission request handler lets the model ask for broader access, such as using a file or action that is currently blocked. It checks the request, connects it to the correct workspace, and sends it into the session’s approval path. The user input handler does a similar job when the assistant must pause and ask the human a question, then returns the answer as tool output.
For MCP traffic, elicitation decides whether an outside request is safe to accept, must be rejected by policy, or should be forwarded for review. The exec approval code asks an MCP client before running a shell command. The patch approval code asks before applying code edits. Together, these pieces normalize many kinds of “may I?” and “please answer” moments into the same review machinery.
14.1.5Approval-mediated tool orchestration and approval UI12 files
This stage sits in the main work loop, whenever the assistant wants to do something that may affect the user’s machine or data. The core orchestrator is the traffic controller: it checks whether a tool needs permission, chooses a safety sandbox, runs the tool, and may ask again with broader access if the sandbox blocks it. MCP tool approval templates turn external tool-server requests into plain questions instead of raw names and JSON.
The terminal UI then makes those decisions visible. Approval events store requests in a safe displayable form, while the approval overlay shows the actual pop-up and sends back approve or deny. Tool requests puts these decisions into the chat screen. Permission popups and the permissions menu let users choose or change how much freedom the assistant has, including reviewing automatic denials. Auto-review denials keeps a recent list of blocked actions with readable labels. Pending thread approvals warns when background agent threads are waiting. Request user input handles structured questions and typed answers. Windows sandbox prompts guide Windows users through safe setup. Hooks RPC checks server-side hooks and records the user’s trust choices.
14.1.6Approval-adjacent enforcement runtimes10 files
This stage is shared execution-time protection. It sits behind tool runs and approval-gated actions, making sure decisions about network access and sandbox safety are actually enforced while commands are running.
The network proxy pieces act like a guarded doorway to the internet. The library front door exposes the proxy parts other code may use. Its state builder turns requested settings into safe live settings, rejecting anything that would break central limits. The approval code handles “unknown host” cases by asking the right reviewer, remembering session-wide answers, and returning clear errors when access is denied. The network policy code decides allow, deny, or ask, and records why. The runtime is the proxy’s live rulebook: it checks hosts, HTTP methods, Unix sockets, and interception hooks, reloads changes, and logs blocked requests.
The Windows sandbox pieces enforce similar limits at the operating-system level. One file grants safe extra read access when needed. Others track and clean up read-deny rules, make protected workspace folders read-only, and install Windows Filtering Platform firewall rules. The setup wrapper applies that network lockdown defensively and records whether it worked.
14.2Execution backends and sandboxed command runtimes91 files
This stage is the system’s safe command-running workshop. It is used in the main work loop when the assistant needs to run a shell command, edit files with apply_patch, start an interactive program, or pause briefly with the built-in sleep tool. It also provides shared support behind the scenes so those actions work locally, remotely, and across operating systems.
The command orchestration pieces act like the front desk: they receive requests, check rules, start commands, stream output, accept input, cancel work, and clean up. The unified-exec and PTY/process backends are the engine room, keeping interactive sessions alive through pipes or terminal-like connections. The patch engine is the file-editing arm: it recognizes patch requests, parses them, applies changes, and reports what happened.
Sandbox selection and platform launchers are the safety cage. On Unix they choose Linux or macOS restrictions and handle permission escalation. On Windows they create restricted users, permissions, firewall rules, and process settings. Exec-server filesystem services let local, sandboxed, or remote commands read and write files safely. The sleep tool simply waits, but can be interrupted when new user input arrives.
14.2.1Execution-facing app-server and core command orchestration15 files
This stage is the system’s command-running control room. It sits in the main work loop, where user or assistant requests become real programs running on the computer, but with checks and safety rules in between.
On the app-server side, command_exec_processor.rs, command_exec.rs, and process_exec_processor.rs translate client messages into process actions: start a command, send input, resize a terminal, stop it, watch its output, and clean up afterward. The TUI helpers, fs.rs and workspace_command.rs, let the text interface ask the app server to read or write files and run small workspace commands, whether the workspace is local or remote.
In core, exec.rs is the actual child-process runner, while sandboxing/mod.rs packages commands for restricted execution. user_shell.rs runs explicit user shell commands and records their progress. The shell handlers and runtimes check permissions, prepare environments, emit progress, support cancellation and hooks, and then launch commands safely. unified_exec.rs and exec_command.rs provide a newer single front door for execution requests. zsh_fork_backend.rs adds a special supported zsh path when needed.
14.2.2Unified-exec sessions and PTY/process backends17 files
This stage is the low-level machinery that lets the system run interactive commands, keep them alive, talk to them, and stop them safely. It sits behind the main tool loop: when a command is approved, these pieces turn that request into a real process and stream its output back.
The unified_exec front door defines the shared request shapes, limits, and helpers, while its errors file gives the whole area one clear failure language. process and process_manager are the control room: they start commands, reuse sessions, collect output, send later input, track exits, cancel work, and clean up. The write_stdin handler is the small inlet that sends more text into an already-running command.
On the exec-server side, process defines the common process contract. local_process runs commands on the server machine, and remote_process makes a remote command look local. spawn is the safe doorway for launching programs with the right folder, environment, network, and input/output setup.
The pty utilities provide the actual plumbing: pipes for simple programs, PTYs, or “fake terminals,” for interactive ones, process groups for cleanup, and Windows ConPTY bridges for terminal behavior on Windows.
14.2.3Patch application engine and patch-execution adapters9 files
This stage is the editing engine for the system. It is used during the main work loop when the assistant wants to change files. First, apply_patch_spec defines the “apply_patch” tool: its name, description, and the exact patch format the assistant must use. The parser and streaming_parser read that patch text. The normal parser waits for the whole patch and turns it into clear actions like add, delete, update, or move a file. The streaming parser can understand the patch while it is still arriving, so progress can be shown early.
The invocation code decides whether some command text is truly an apply_patch request, not just an ordinary shell command. The core apply-patch library then performs the actual file edits and records what succeeded or failed. The core handlers and runtime adapters act like safety gates: they validate the request, check policy, ask for user approval if needed, choose the right sandboxed environment, run the edit, and report results. For Git-based patches, git-utils applies them through Git and explains which files applied, skipped, or conflicted.
14.2.4Sandbox selection and Unix platform launchers16 files
This stage is shared behind-the-scenes support for running commands safely on Unix systems. It sits just before a tool or shell command is launched. Its job is to choose the right sandbox, rewrite the launch request, and, when needed, ask for permission to run with more power.
The sandboxing front door and manager provide the common entry point. They hide Linux and macOS differences, decide if a sandbox is needed, and turn a normal command into a sandbox-ready one. On Linux, the Bubblewrap and Landlock pieces check what sandbox tools are available, build the restricted filesystem and network rules, and start the helper process. The launcher picks a system Bubblewrap if possible, or a bundled copy if not, and reports clear setup problems.
The shell-escalation pieces handle commands that may need extra permission. A patched Unix shell can ask an escalation server what to do. The policy says allow, deny, or escalate. The client and server carry that request and connect it to the real process launcher. The runtime files prepare shells, environments, sandbox inputs, and the special Unix shell path that ties approval and sandboxing together.
14.2.5Exec-server filesystem sandbox services6 files
This stage is shared behind-the-scenes support for the exec server when it needs to work with files. The exec server may be running commands locally, in a restricted sandbox, or on another machine, but the rest of the system should be able to ask for simple actions like read, write, list, copy, or delete.
The local file system layer is the front desk for files on the same machine. It either performs the action directly or sends it through a sandbox, which is a locked-down area that limits which paths can be touched. The sandboxed file system layer is the safe version of those same operations, enforcing the sandbox rules. The filesystem sandbox runner starts helper work inside that restricted space and carefully controls what environment and file access the helper receives.
The helper protocol is the messenger format for filesystem actions. It turns requests into real file operations and turns results or failures back into replies. Remote file system support uses a similar idea to make files on another machine look local. File-read support handles long reads in small chunks, tracking open reads and rejecting unsafe or stale requests.
14.2.6Windows sandbox provisioning and process-launch internals27 files
This stage is the Windows-only machinery that prepares a safe “guest room” for commands and then starts them inside it. The public entry points choose the right sandbox path: the newer elevated runner or the older legacy runner, while the TUI asks for the requested sandbox level. Setup code creates or refreshes sandbox Windows users, stores and checks their identity, reports setup errors, hides those users from normal Windows screens, and fixes access to bundled runtime tools. Permission code edits Windows access-control lists, which are file permission rules, to allow workspace writes, deny reads to sensitive paths, and reduce risky “Everyone can write” folders. Token and desktop code decide what powers and screen environment the child process gets. Firewall and WFP rule code block or narrow network access. Spawn preparation turns the requested read, write, and network policy into these concrete Windows settings. Process-launch code then creates the command with the right user, environment, pipes, and optional ConPTY fake terminal. The elevated runner uses locked-down named pipes to talk to its child, and the stdio bridge connects the sandboxed program back to the user’s terminal until it exits.
14.3Extension and integration tools117 files
This stage gives Codex its “extra equipment” beyond the core chat and code loop. It is mostly shared behind-the-scenes support, used during startup, while choosing tools during a turn, and when clients ask to discover apps or files.
The MCP runtime is the bridge to outside programs that use the Model Context Protocol, a standard way for other apps to offer tools and resources. It starts those servers, lists what they provide, checks permissions, and sends tool results back to the session.
Plugin and connector management is the supply chain. It finds, installs, updates, disables, and removes plugins, while deciding which connectors are visible and safe for a user.
Extension-backed tool runtimes turn those add-ons into usable tools for the model, such as web search, image generation, memories, skills, and long-running code cells. They build the tool menu, run selected tools, and report progress.
App-server discovery and search adapters are the front desk. They gather connector, app, and file-search results, clean and merge them, then return useful lists to the client.
14.3.1MCP runtime, resources, and session integration22 files
This stage is the bridge between Codex and MCP, the Model Context Protocol, which lets outside programs offer tools, files, and other resources to the assistant. It is mostly behind-the-scenes support used during session startup and the main work loop. The app-server and ext/mcp files register MCP as an extension, discover MCP servers from plugins, and pass extension events to the right client. The codex-mcp library defines what an MCP server is, builds usable server configs, supports hosted Codex Apps, and keeps user app-tool caches separate. Its connection manager is the switchboard: it starts servers, checks readiness, collects tools and resources, and routes calls. Resource clients and handlers let the model list templates, list resources, and read one resource in a consistent way. Tool preparation code filters and renames tools, limits what the model sees, adapts file inputs, and uploads local files when a tool expects hosted files. Tool-call code checks permissions, asks for approval, records results, and reports back. Session and skill-dependency code connect MCP servers to each user session, refresh them when needed, and handle login prompts safely.
14.3.2Plugin and connector ecosystem management34 files
This stage is the plugin “supply chain” for Codex. It is shared support used during startup, tool discovery, installation, and user interaction. The core plugin files define the public API, read plugin.json manifests safely, load installed plugins into skills, apps, hooks, MCP servers, and telemetry, and coordinate installs, removals, cache refreshes, and marketplace rules. Marketplace files add, validate, upgrade, and remove catalogs from local folders or Git, while remote bundle and remote service files download, sync, install, uninstall, share, and check out plugins from ChatGPT-backed services, including older APIs.
Connector files decide which app connectors and tools are visible, enabled, and safe enough to run, combining login state, user settings, managed policy, and tool safety hints. Discovery and mention files find plugins the user may want, or ones the user explicitly referenced in chat. Install-suggestion tool files let the assistant list possible plugins and ask for user approval before installing. Finally, the CLI and terminal UI provide the human control panels: commands and popups for adding marketplaces, browsing plugins, installing, disabling, upgrading, and removing them.
14.3.3Extension-backed tool runtimes and namespaces56 files
This stage is shared support for the model’s “extra hands.” On each turn, spec_plan builds the tool menu and the router that runs the chosen tool. hosted_spec adds provider-side abilities like web search or image creation. Dynamic-tool files adapt tools supplied during the conversation, while extension_tools lets installed extensions behave like built-in tools and report progress.
Several helper tools make the menu easier to use: tool_search lets the model find hidden tools by text, view_image loads an image file for inspection, get_context_remaining reports remaining conversation space, and small spec files describe plan updates, new contexts, and worker-agent jobs.
Code mode is the long-running script area. Its runtime prepares a safe JavaScript world, callbacks let scripts talk back to Rust, and execute/wait tools start, monitor, or stop script cells.
The extension registry is the sign-up sheet. Web search, image generation, goals, memories, and skills plug into it. Memories safely list, read, search, and write local notes. Skills gather packages from the host, executor, orchestrator, or remote service, then expose safe list and read tools.
14.3.4App-server integration discovery and search adapters5 files
This stage is part of the app server’s main work: answering client requests when a user wants to discover apps, connectors, or files. It acts like a front desk that gathers information from several shelves, cleans it up, and returns a usable list.
The connector helpers prepare app discovery data. accessible.rs takes raw connector tools and turns them into user-facing apps, grouping duplicates and adding friendly names and descriptions. filter.rs decides what should be visible, hiding blocked connectors and avoiding suggestions for apps the user already has. merge.rs combines several connector lists into one best version, keeping the strongest name, description, logo, install link, and access state.
apps_processor.rs is the coordinator. It receives app-list requests from clients, checks whether app access is allowed, pulls data from cached and live sources, reports progress, and returns results in pages.
fuzzy_file_search.rs supports searching files and folders by approximate text matches, like typing a few letters into an editor’s “open file” box. It can run a single search or maintain a live session that updates as the query changes.
14.4Sandbox policy generation and command-safety parsing helpers17 files
This stage is shared safety support used before running tools. It helps answer two questions: “What is this command really doing?” and “What should the sandbox allow it to touch?” The legacy policy files define the building blocks for allowed command arguments: argument shapes, option objects, argument types, and a narrow safe form of sed line-printing commands. The sandbox files then turn requested permissions into actual confinement rules. On macOS, seatbelt.rs writes Seatbelt rules for sandbox-exec. On Linux, build.rs makes sure sandbox build checks notice the expected bubblewrap hash.
The shell-command files inspect command text before execution. bash.rs parses only simple Bash or Zsh forms into plain argument lists. powershell.rs and the PowerShell parser helper understand Windows PowerShell scripts without repeatedly starting a new parser. parse_command.rs summarizes common actions, while command_canonicalization.rs normalizes commands so approval decisions can be reused. The command_safety files are the gatekeepers: they recognize safe read-only commands, flag dangerous ones like forceful deletion, and apply stricter Windows-specific safe and dangerous command rules.
15Multi-agent, collaboration, and background workflows39 files
This stage is the system’s “extra workers” layer. It sits behind the main conversation loop and lets one session start helpers, send them messages, wait for them, stop them, or run background work. The agent files define the shared machinery: the module front door, roles and instructions, the registry of live agents, name-to-thread lookup, completion messages, and short status notes. The control files act like a dispatch desk: they limit how many agents run, keep only some threads loaded, and create, fork, reload, resume, or connect agents.
The multi-agent tool files expose this machinery to the assistant. Version 1 and Version 2 tools cover spawning, messaging, follow-up tasks, waiting, listing, interrupting, resuming, and closing agents, with shared helpers for validation and errors. Delegation, review mode, code-mode work, and the Guardian extension use the same pattern to run supervised child agents.
Other background workflows reuse the idea at larger scale: agent jobs split CSV rows across workers and collect results; memory startup extracts and consolidates long-term notes; the skills watcher refreshes available skills when files change.
16Result persistence, projection, and user-visible state updates55 files
This stage is the system’s “make it real and show it” step. After the assistant, a tool, or an imported session produces progress, these files decide what should be saved, what should be shown, and what status other parts of the app should see. Rollout and thread-store code saves useful events, rebuilds old sessions, imports external chats, archives or restores threads, and keeps fast database summaries in sync with older transcript files. State and summary code turns raw event logs into searchable thread details like title, preview, model, folder, Git state, and token use.
Event-mapping code translates detailed core activity into simpler messages for app clients, exec JSONL output, and terminal displays. Tool, shell-command, diff, review, agent-status, and lifecycle code turn work into clear records: commands started or ended, files changed, approvals waited on, or agents finished. The TUI files then project that state into visible transcript cells, status lines, headers, pending-input previews, rate-limit warnings, goal indicators, and restored history. Together, they turn internal activity into durable records and understandable user-facing state.
17Shutdown, cleanup, and teardown4 files
This stage covers the “put everything away safely” part of the system. It happens when a connection, session, agent, or daemon is ending, and its job is to stop new work, let safe in-progress work finish, and release anything the system was holding.
The connection RPC gate is like a door monitor for one client connection. RPC means “remote procedure call”: a request sent over the connection asking the server to do something. During shutdown, the gate blocks new request handlers from starting, but allows ones already running to complete.
The connection cleanup tracker manages jobs that continue briefly after a connection ends. It starts these cleanup tasks, records whether they succeed or fail, and can cancel them if the whole server is shutting down.
The legacy agent control code handles older paths for stopping agents. It asks live agents to shut down cleanly, flushes their saved work, and removes their stored parent-child relationship.
The daemon update loop is also part of teardown in practice: after downloading updates, it detects changed binaries and restarts the daemon in a controlled way.
18Protocol schemas, shared types, and generated contracts✕174 files
This stage is shared behind-the-scenes support for the whole system. It defines the “contracts” that clients, servers, plugins, storage, and tools all rely on when they exchange data. A contract is the agreed shape of a message, like a standard form everyone fills out the same way.
The core protocol and domain types provide the common vocabulary: sessions, threads, events, approvals, tools, permissions, errors, settings, plugins, and saved conversation state. The app-server schemas define how the desktop or web client talks to the app server, including JSON-RPC envelopes, which are simple wrappers for requests, replies, and errors. The generated backend and protobuf contracts cover messages produced from outside specifications, such as OpenAPI web models and protobuf service messages. The API, extension, hook, MCP, sandbox, and trace schemas define public and cross-process messages for tools, plugins, execution, realtime streams, and saved run histories. Finally, the annotation macros run during compilation to mark experimental API pieces consistently. Together, these parts keep every component speaking the same language.
18.1Core shared protocol and domain types46 files
This stage is shared behind-the-scenes support. It is the project’s common dictionary: the names, message shapes, settings, and status labels that many crates use so they do not invent different versions of the same idea. The main protocol files define stable IDs for threads and sessions, safe agent and tool names, user input, conversation items, client requests, agent events, account data, approvals, permissions, errors, model info, MCP data, dynamic tools, command categories, memory citations, and network decisions. Config files describe user-visible settings and defaults. Plugin, tool, and skill files define how add-ons are named, described, discovered, filtered, and shown. Execution and network policy files describe allowed, blocked, or approval-needed actions and the reason codes used when something is refused. State, thread-store, and graph files define how conversations, spawned threads, memories, and process results are saved and reported. The TUI, cloud task, and startup error types give user interfaces and services the same event and error vocabulary. Together, these files act like standard forms that every department fills out the same way.
18.2App-server protocol schemas and transport contracts43 files
This stage is the shared rulebook for how the app server and its clients talk. It sits behind the main work loop: before any feature can send a request, reply, warning, file update, or command output, both sides need to agree on the exact message shape. The JSON-RPC files define the basic envelope, like an addressed letter with a request, response, notification, or error inside. The common, v1, and v2 protocol files define the actual “forms” that go in those envelopes: startup, login, threads, turns, items, reviews, realtime sessions, accounts, models, apps, permissions, config, plugins, hooks, feedback, files, processes, MCP, remote control, and more. Helper and mapper files smooth over format details and keep older v1 command requests working with v2. The export and fixture tools turn Rust types into TypeScript and JSON Schema so other clients can use the same contract and detect accidental changes. Transport files describe outgoing messages, remote-control websocket rules, and JSON-RPC errors. Small bridge files translate approvals and MCP messages into the shapes other parts of the system expect.
18.3Generated backend and protobuf contracts24 files
This stage is shared behind-the-scenes support. It is the system’s set of “forms” that different parts agree to fill out the same way. Most of it is generated from contracts: OpenAPI for web JSON APIs, and protobuf/gRPC for compact service messages sent between programs.
The backend client types describe the data the Codex backend sends back, such as accounts, usage limits, tasks, diffs, messages, errors, and token counts, with helpers to turn awkward responses into readable text. The OpenAPI crate exposes generated model modules, then gathers the needed types in one place. Those models cover rate limits, credit and spend controls, task details and task lists, pull requests, paginated results, and delivered configuration files or TOML fragments.
The protobuf files do the same job for internal services. The thread-config file defines requests, responses, and provider settings for asking another component for configuration. The exec-server relay file defines messages for handshakes, heartbeats, reconnects, resets, acknowledgements, and data transfer. The relay wrapper hides the generated details behind cleaner names.
18.4API, extension, hook, MCP, and trace schemas60 files
This stage is shared behind-the-scenes support. It does not drive startup, the main agent loop, or shutdown by itself. Instead, it defines the public message shapes that many parts of the system must agree on, like standard forms used by different departments.
The code-mode contract types describe how code execution sessions, runtime messages, tool descriptions, and results such as text or images are represented. The public API schemas define requests, responses, errors, streaming events, search payloads, image payloads, and realtime WebSocket messages for outside services. The extension and hook contracts give plugins safe, stable ways to receive events, store state, add context, and declare hook commands. The tool and protocol schemas describe model-visible tool calls, permission requests, plans, human questions, and shared result formats. The MCP, exec, and sandbox wire models define exact messages that cross process boundaries, including command execution, event streams, and permission escalation. Finally, the rollout trace models describe saved histories of agent runs, with sessions, runtime events, and references to large payloads. Together, these schemas keep independent pieces speaking the same language.
18.4.1Code-mode protocol contract types5 files
This stage is shared behind-the-scenes support. It does not run code itself. Instead, it defines the public “contract” that other parts of the system agree to use when they talk about code mode. Think of it like the standard set of forms and labels used by everyone in an office.
The crate front door, lib.rs, gathers the important names from the internal files and re-exports them so other code can import them from one simple place. description.rs explains the available code-mode tools in human-readable text, including TypeScript-style examples, and reads small settings placed at the top of JavaScript input. response.rs defines common result content, such as text and images, and keeps their JSON shape consistent. runtime.rs defines the request and response messages exchanged with the runtime, the worker that actually executes code cells and reports progress or final results. session.rs defines the longer-lived session contract: how to start code, wait for answers, call tools, send updates, and shut everything down cleanly.
18.4.2Public API request and transport schemas6 files
This stage is the public “language” of the Codex API layer. It is shared behind-the-scenes support used whenever the program sends requests to external services or reads their replies. Instead of each caller inventing its own message format, these files define the agreed shapes of those messages.
The library front door, lib.rs, decides what parts of this API package are visible to the rest of the codebase. common.rs provides the everyday forms for the Responses API: requests, responses, streamed events, and extra metadata such as tracing details used to follow a request through the system. error.rs gives all API code one common way to describe failures, such as bad requests, network trouble, or rate limits.
The remaining files cover specific transports or features. protocol.rs defines realtime WebSocket messages, which are two-way live messages, and selects the right parser for different protocol versions. images.rs defines image generation and editing payloads. search.rs defines request and reply formats for web, image, finance, weather, sports, time, and page-navigation searches.
18.4.3Extension and hook interface contracts22 files
This stage is shared behind-the-scenes support for people who add plugins, extensions, or hooks. It defines the stable “contracts” they can rely on, so outside code does not need to know the host’s private machinery. The extension API front doors gather and re-export the public pieces. Capability files describe powers the host may give an extension: starting a subagent, sending events, or adding extra items to the model’s current turn, with safe no-op versions when unsupported. Contributor files define the callback data for MCP server changes, thread and turn lifecycle moments, tool calls, and turn input. The main contributors file lists the plug-in points themselves. State gives extensions a safe typed storage box, and user instructions define how startup instruction text is reported. Goal events package goal changes in the standard event form. The memories backend defines a storage contract, while IDE context describes editor-provided file and selection data for the terminal UI. The hooks files define declared hook handlers, event modules, shared hook types, JSON wire formats, schema generation, and schema loading, making hook commands predictable and checkable.
18.4.4Tool and protocol contract schemas18 files
This stage is shared behind-the-scenes support. It defines the “contracts” for tools and protocol messages: the agreed shapes of data that the model, Codex core, extensions, hooks, MCP clients, and user interfaces pass to each other. Like blank forms, these schemas say what fields are allowed, what names to use, and how results should be reported safely.
The tools files describe model-visible calls: generic tool inputs, tool-call packages, OpenAI Responses API tool specs, shell tools, context-count tools, user-input tools, goal tools, web search, skills, and MCP Codex session tools. They do not usually perform the work; they describe how to ask for it. The core context and code-mode adapter files translate real tool results, including text, images, commands, patches, and MCP outputs, into shared messages for the model, logs, hooks, and code mode. The protocol files define common payloads for permission requests, human questions, plan updates, and MCP approval labels, so Rust, JSON schemas, and generated TypeScript stay in agreement. Small support files forward shared errors and keep hook tool names consistent.
18.4.5MCP, exec, and sandbox wire models6 files
This stage defines the “wire models” for parts of the system that talk across a boundary. A wire model is the exact shape of messages sent between programs, processes, or tools, usually as JSON or another stream format. These files are shared behind-the-scenes support: they do not run the main agent themselves, but they make sure both sides of a conversation agree on what each message means.
The exec-server files describe how clients connect to an executor, how running processes are named, and what requests and replies look like for starting commands, reading output, accessing files, or making HTTP calls. The exec events file defines the JSON-lines event stream produced by codex exec, so outside tools can follow an agent run step by step. The Unix escalation protocol defines the messages exchanged when a shell command may need different sandbox permissions. The Windows framed IPC file does the same for communication with an elevated command runner, and also wraps messages into length-marked packets so they can be read safely from a stream.
18.4.6Shared extension backends and rollout trace models3 files
This stage provides shared behind-the-scenes data models rather than main work-loop behavior. It defines the common “forms” that other parts of the system fill in when they record or read rollout traces. A rollout trace is a saved history of what an agent did, useful for debugging, review, or replay.
The session model describes the overall run. It records whether a rollout is still active or finished, which agent threads joined in, and the start and end times of pieces of runtime work. This is like the cover sheet and timeline for a job.
The runtime model describes the events inside that job: code cells, tool calls, terminal commands, checkpoints where context was compacted, and links between trace objects. It gives the trace system a shared vocabulary for the moving parts of execution.
The payload model keeps the trace lightweight. Instead of putting large raw logs or request and response bodies directly into the main records, it stores small references that point to those larger payloads elsewhere in the rollout bundle.
18.5API annotation macros and compile-time contract support1 files
This stage is behind-the-scenes support that runs while the code is being built, not while the program is doing its main work. Its job is to help the project keep track of “experimental” API features, meaning parts of the interface that may still change and should be used with care.
The source file codex-experimental-api-macros/src/lib.rs defines a Rust derive macro. A derive macro is build-time code that writes repetitive code for developers automatically. Here, it lets a struct or enum learn how to say whether it contains any experimental API pieces. Instead of every developer manually writing the same checking logic, they can place small annotations on fields or enum variants. During compilation, the macro reads those annotations and generates the needed checking code.
In the larger system, this acts like a labeling machine on an assembly line. It marks API shapes consistently before the program ever runs.
19Cross-cutting transport, networking, and client infrastructure✕55 files
This stage is shared behind-the-scenes infrastructure. It is the system’s networking toolbox, used during startup, normal work, remote control, and tool communication whenever one part needs to send requests, stream data, or connect safely.
The generic HTTP layer provides common clients, request and response shapes, retries, streaming support, cookies, proxy settings, and TLS certificate handling, which is the security layer used for HTTPS. The app-server, exec-server, and relay transports are the longer-distance pipes: they carry messages, files, and encrypted WebSocket traffic between clients, servers, and remote machines. Managed proxying and local IPC, meaning communication between processes on the same computer, add controlled network forwarding, sandbox bridges, Unix sockets, Windows named pipes, and IDE links. MCP transport adapters connect the client to tool servers through memory, process input/output, or HTTP.
The direct library front doors, such as backend-client, chatgpt, and cloud-tasks-client, expose these tools in clean packages so callers do not need to know the internal layout. The Codex client error file gives all of this networking code a shared way to describe failures like timeouts, bad responses, and exhausted retries.
19.1Generic HTTP client, TLS, cookies, and streaming transport foundations21 files
This stage is shared behind-the-scenes networking support. It is the set of pipes, valves, and adapters that lets Codex safely talk to web services. The core client files define a common request and response shape, turn JSON or compressed bodies into bytes, send them with reqwest, retry temporary failures with backoff, and decode long-lived Server-Sent Events streams. The library front doors re-export these pieces so other crates use the same tools.
Several files add safety and environment support: custom certificate authorities for company proxies, a narrow Cloudflare cookie jar that avoids sharing private session cookies, and default clients that add tracing, user-agent, proxy, residency, and authentication headers. Backend, ChatGPT, cloud task, remote config, LM Studio, and file-upload clients build on these foundations to call their specific services and translate replies into project types.
The API provider and session code centralize endpoint URLs, headers, retries, telemetry, normal requests, and streaming requests. Endpoint, request, and SSE modules act as organized entry points, while realtime WebSocket helpers translate raw live messages into internal events.
19.2App-server, exec-server, and relay transport channels10 files
This stage is shared behind-the-scenes plumbing. It is the set of “pipes” that lets different parts of the system talk to each other, whether they are on the same machine, behind an app server, or reached through a remote exec server.
The app-server transport module defines the common events for connections: a client opens a link, sends a message, or receives a reply. Remote-control segmenting acts like cutting a large parcel into numbered boxes, then rebuilding it safely while rejecting bad pieces. The remote-control clients code uses authenticated HTTP calls to list connected devices and revoke them.
On the exec-server side, the HTTP client module gathers the ways to make requests, while the response-body stream reads replies a chunk at a time and matches remote chunks to the right request. The remote file stream does the same for files, reading safe-sized pieces and closing the remote file afterward.
The relay pieces carry messages over WebSockets. Noise channels encrypt and authenticate them. Framing splits large JSON-RPC messages into allowed record sizes, and ordered ciphertext makes sure encrypted records arrive in the exact order needed.
19.3Managed proxying and local IPC transport substrates12 files
This stage is shared behind-the-scenes transport work. It gives the system safe ways to send traffic outward and to talk between local processes. The proxy configuration code takes user proxy settings and security rules, checks them, and turns them into a plan that can start or update the managed network proxy. The proxy then uses certificates to inspect HTTPS when allowed, applies MITM hook rules to selected decrypted requests, blocks unsafe connections to private or local addresses unless permitted, and builds clear HTTP responses when requests are allowed, denied, or fail. Its upstream transport sends approved requests to the real server, either directly, through an environment proxy, or through a platform-specific socket.
Other files provide local “pipes” for parts of the program to communicate on the same machine. The Unix-domain socket layer hides operating-system differences. Shell escalation sockets can also pass open file handles between processes. Linux sandbox proxy routing builds small bridges so sandboxed code can reach a host-side proxy without opening the host network. The Windows named-pipe and IDE IPC code let the terminal UI safely ask a local IDE what the user is viewing.
19.4MCP and executor-backed transport adapters8 files
This stage is shared transport support for MCP, the Model Context Protocol, which is how the client talks to tool servers. It sits underneath the main client flow and turns high-level MCP messages into the actual ways bytes move: memory, process pipes, or HTTP. The crate front door, lib.rs, exposes the pieces other code should use. in_process_transport.rs creates a local, in-memory link to a server running in the same program, like connecting two parts with a short internal wire. executor_process_transport.rs connects to a separate server process managed by the executor, translating structured JSON-RPC messages into newline-based stdin and stdout traffic. For HTTP, reqwest_http_client.rs sends real network requests, while rpc_http_client.rs lets another runtime send them remotely, including streamed bodies. http_client_adapter.rs maps RMCP’s streamable HTTP protocol onto that shared HTTP interface. www_authenticate.rs reads authentication failure headers to detect missing permission scopes. streamable_http_retry.rs makes startup over streamable HTTP sturdier by retrying short-lived handshake failures.
20Cross-cutting observability, analytics, and feedback✕81 files
This stage is the project’s shared “instrument panel.” It runs across startup, normal request handling, streaming, tool use, and shutdown, watching what happens so developers and operators can understand problems and usage without interrupting the main work.
Analytics event modeling turns scattered facts, such as errors, tool runs, settings, and accepted code changes, into safe summary events and sends them in the background. OpenTelemetry setup provides standard observability: logs, traces, and metrics. A trace is a linked timeline for one piece of work; metrics are counted or timed measurements. Session telemetry adds more detailed trip-recording for each conversation, request, tool call, login state, database startup, and feature outcome.
Rollout tracing is the flight recorder. It can save raw events from conversations, tools, model calls, terminals, and threads, then reduce them into a replayable story. Feedback and debug capture gathers recent logs, failed response details, diagnostics, and local evidence, while sanitizing secrets before anything is stored or sent. The Windows sandbox logging file adds a simple daily text trail for sandbox command starts, successes, failures, and debug notes.
20.1Analytics event modeling, reduction, and emitters8 files
This stage is shared behind-the-scenes support for understanding how Codex is used. It does not do the main user work itself. Instead, it watches important moments, turns them into safe structured records, combines related pieces, and sends them out without slowing the app.
The process starts with facts.rs, which defines “facts”: small records such as an error, a tool run, a setting, or a turn result. events.rs defines the final analytics “vocabulary,” meaning the event shapes that can be sent. lib.rs is the public doorway that other code imports, with a few shared helpers.
accepted_lines.rs measures accepted code changes as line counts, and hashes repository identity so raw remote URLs are not exposed. reducer.rs acts like an assembler: it remembers context across requests, responses, turns, tools, reviews, and threads, then reduces scattered facts into meaningful events. client.rs sends those events in the background. app-server/src/analytics_utils.rs wires the client to the server’s login and configuration. ext/goal/src/analytics.rs adapts goal activity into the same event system.
20.2OpenTelemetry runtime, provider, and metrics foundations22 files
This stage is shared behind-the-scenes support, used mostly during startup and then throughout the main work loop. It sets up observability: traces, metrics, and logs that help operators see what the program is doing. The core OpenTelemetry config cleans user settings, adds safe defaults, and rejects bad trace labels. The init code then turns those settings into a running setup. The otel crate config decides whether telemetry is enabled and where it goes, while its lib file exposes the pieces. The provider builds the real exporters, filters, global hooks, and shutdown path. The OTLP transport prepares HTTP or gRPC clients, certificates, headers, and timeouts. Targets decide which events may become logs or traces, and trace context carries a work ID across services. Metrics files define errors, names, config, safe tags, validation, the shared client, timers, one-time process-start reporting, and readable runtime summaries. Event helpers add consistent details like time, version, model, and session. Finally, Codex client and API telemetry hooks measure request attempts, retries, streaming, and WebSocket activity without mixing that reporting code into the networking logic.
20.3Session telemetry and feature-specific instrumentation16 files
This stage is behind-the-scenes instrumentation for a running session. It does not make the assistant smarter by itself. Instead, it acts like a dashboard and trip recorder, noting what happened, how long it took, and where problems appeared.
The central session telemetry file records session events, results, durations, and safe context. Turn timing adds finer stopwatch data for each assistant reply, such as time to first output and time spent waiting on tools. App-server tracing wraps incoming requests in trace spans, which are linked log sections that let one request be followed across the system. Tool dispatch tracing records tool calls without cluttering the tool runner itself.
Several files add safe labels and counters for specific features. Auth environment telemetry notes which login settings exist without recording secrets. Sandbox tags summarize permission mode. Guardian, cloud-config, goals, and memories files count feature activity and outcomes using stable metric names and labels. Memory usage code detects when commands read memory-related files. Finally, SQLite telemetry records database startup, fallback behavior, counts, and timings, including lightweight metrics for rollout and state startup.
20.4Rollout trace recording, schema, and replay reducers24 files
This stage is the project’s flight recorder. During the main run, it can write down what Codex does, then later turn that raw diary into a clean story that can be replayed or inspected. The bundle and raw event files define the trace package: a table of contents plus an ordered event log. The model files define the replay-friendly shapes for conversations, tool calls, threads, terminal work, code cells, compaction checkpoints, model requests, and stored payloads. The crate front door exports these pieces, while rollout configuration supplies the few settings tracing needs.
The writer, thread, code cell, compaction, inference, tool dispatch, MCP, and protocol event files are the recording adapters. They sit beside normal work, assign trace IDs, save large payloads, and keep running even if tracing is off or a write fails.
The reducer files are the replay workshop. They read the raw bundle in order and build one compact RolloutTrace. Separate reducers clean up conversations, normalize JSON messages, track model calls, compaction, threads, code cells, tools, agent handoffs, and terminal sessions, linking scattered events into one understandable run history.
20.5Feedback capture, debug artifacts, and log persistence10 files
This stage is shared behind-the-scenes support for troubleshooting. It captures clues when something goes wrong, makes them safe to keep or send, and stores them for later inspection. The feedback library gathers recent Codex logs and context into a user feedback report, then packages it for Sentry, an error-reporting service. Feedback diagnostics add network clues, such as proxy settings, and the doctor report can run a diagnostic command and attach only valid JSON results. Response debug context extracts safe details from failed API replies and turns errors into short messages without exposing private response bodies. The secret sanitizer is the safety screen: it removes likely API keys, bearer tokens, and similar credentials before text is logged or shared. Several parts persist raw evidence locally. The response proxy can dump HTTP exchanges as JSON while hiding sensitive headers. Analytics capture writes events as one JSON line per record. The TUI session log records interface traffic when explicitly enabled. Finally, the log database layers collect live tracing logs into SQLite, then store, trim, and read them so debugging data stays useful without growing forever.
21Cross-cutting persistence abstractions and data stores✕54 files
This stage is the system’s long-term memory and filing system. It is shared support used throughout startup, normal work, recovery, and cleanup, rather than one single user-facing flow. Its parts save different kinds of information so the app can resume work, avoid repeats, and keep private data safe.
Rollout files and thread-store persistence keep conversation records: raw session logs, searchable indexes, live writers for active chats, and tools to list, rebuild, archive, or delete threads. SQLite runtime state and agent graph storage keep structured records in a small local database, such as thread summaries, goals, agent jobs, progress checkpoints, audit views, and “which agent started which thread.” Caches and local lookup files store reusable facts like cloud settings, connector lists, plugin catalogs, models, update notices, and local plugin paths, while checking age, account, and version before trusting them. Plugin, secrets, and memory stores manage installed plugins, encrypted secret values, and saved user memories. External session import persistence reads conversation files from other tools and keeps a ledger so the same outside session is not imported twice.
21.1Rollout files and thread-store persistence19 files
This stage is the system’s local memory for conversations. It runs behind the scenes during normal use, so chats can be resumed, listed, searched, archived, or deleted later. The rollout files are the raw diary: recorder.rs writes each session as JSON Lines, meaning one JSON record per line, while compression.rs can read old diaries even after they are packed into smaller .zst files. list.rs, search.rs, and session_index.rs help find those diaries by time, thread ID, name, or text match. core/src/rollout.rs and rollout/src/lib.rs make these tools easy for the rest of the app to reach.
The thread-store layer is the cleaner front desk on top of those files. store.rs defines the shared “save, read, list, update, archive, delete” contract, error.rs defines common failure messages, and lib.rs exports it all. The local store ties rollout logs, optional SQLite metadata, and live writers together. Its helpers validate paths and convert old metadata. live_writer.rs keeps active chats being saved, read_thread.rs rebuilds a thread, list_threads.rs and search_threads.rs support browsing, and delete_thread.rs removes saved files. message-history separately stores the user’s global prompt history safely across processes.
21.2SQLite runtime state and agent graph storage18 files
This stage is the system’s durable notebook. It is shared behind-the-scenes support used while the app runs, and also during startup or recovery, so important runtime facts survive a restart. Most data is kept in SQLite, a small local database stored as files.
The state crate is the main entry point. It defines safe data shapes for thread summaries, thread goals, agent jobs, backfill progress, and logs, then pairs them with runtime code that reads and writes those records. The thread runtime catalogs conversation threads, including parent and child links. The goal runtime records what a thread is trying to do and its budget. The memories runtime schedules memory extraction work. Agent job storage tracks queued, running, finished, and failed work items. Backfill storage remembers catch-up progress and prevents two workers from doing the same job.
Other pieces store imported external-agent configuration, remote-control server enrollments, and read-only audit views for diagnostics. The agent graph store adds a common interface for “which agent spawned which thread,” with a local SQLite implementation that reuses the same state database.
21.3Caches and local persisted lookup data6 files
This stage is shared behind-the-scenes support. It gives the app a local memory on disk, so it can start faster, work offline in some cases, and avoid asking servers the same questions again and again. These caches are small saved files, like notes the app leaves for its future self, but they are checked carefully before use.
The cloud-config cache stores cloud settings for the signed-in account. It rejects old, corrupted, edited, or wrong-user data. The connector directory cache saves lists of available connectors under the Codex home folder, so the app can reuse a valid list. The plugin catalog cache stores remote plugin lists separately for each server and account, preventing one user’s data from leaking into another’s view. The model cache keeps the available model list and ignores it when it is too old or from a different client version. The local plugin paths file remembers which shared plugin IDs map to folders on this machine. The update cache remembers the latest version seen and whether its notice was dismissed.
21.4Plugin, secrets, and memory file stores9 files
This stage is shared behind-the-scenes support for data that must survive after the app closes. It is the system’s set of local “filing cabinets” for plugins, secrets, and memories. The plugin store decides where downloaded plugins are kept, checks their labels, installs them into versioned folders, finds the active version, and removes old copies. The secrets layer defines safe secret names and groups, then uses a local encrypted file store to save, read, list, and delete secret values without writing plain text to disk. On Windows, the DPAPI wrapper uses Windows’ built-in data protection service to encrypt and decrypt small secret blobs safely.
The memories files do similar durable storage for user memory. The local memory store turns requests such as list, read, search, and add note into safe folder operations. The memory write front door defines the standard folders and paths. Its storage code materializes saved memory records as Markdown files and keeps raw combined files and per-thread summaries in sync. Cleanup code clears memory contents safely, avoids following symbolic links, and prunes old extension resource notes so storage does not grow forever.
21.5External session import persistence2 files
This stage is shared behind-the-scenes support for bringing in conversation history from another agent tool. It does not run the main chat loop itself. Instead, it helps the import feature answer two questions: “What is inside this outside session file?” and “Have we already imported this exact version?”
The records file is the reader and translator. It opens saved external conversation logs, parses their contents, and reshapes them into this project’s normal conversation format. It also creates short summaries, so the rest of the system can show a safe list of possible sessions before importing them.
The ledger file is the memory book. It stores a small record on disk of external session files that were already imported. If the same file content appears again, the system can skip it and avoid duplicates. If the file has changed, the ledger allows it to be imported again. Together, these parts make external imports repeatable, safe, and understandable.
22Cross-cutting utility and support libraries✕175 files
This stage is the shared toolbox used across the whole system, not one user-facing feature. It supports startup, the main work loop, tool execution, display, and build time. Path, filesystem, environment, terminal, and sandbox utilities give safe, portable ways to name files, watch changes, copy text, find programs, and run restricted commands. Text helpers clean, parse, shorten, wrap, style, and render output as it streams in. Configuration, metadata, auth, and network helpers turn user settings, login data, schemas, and proxy rules into safe internal forms. Shell, command, Git, plugin, and execution utilities run external programs, inspect repositories, package plugins, and manage process output. Async, image, sleep, cache, and summary helpers smooth long-running work and terminal display. Build scripts prepare platform-specific pieces before compilation.
The direct files are small entry points and shared vocabularies: core utility helpers, module “front doors” for core, CLI, and plugin utilities, structured errors for execution policy and Git failures, a fuzzy matcher for search-style highlighting, and common hook-event rules so hooks behave consistently.
22.1Path, filesystem, environment, and sandbox support utilities31 files
This stage is shared behind-the-scenes support. It gives the rest of the system safe ways to talk about files, folders, programs, terminals, and sandboxes without each feature reinventing the rules. The path helpers form the base layer: PathUri, ApiPathString, AbsolutePathBuf, app-server paths, path-utils, WSL path conversion, memory path helpers, and timestamp helpers all clean, compare, display, and translate paths across Unix, Windows, WSL, remotes, and saved data. Filesystem pieces build on that: regular_file protects reads from special files, file-watcher reports disk changes, file-system defines common read/write/list operations, and symlink helpers hide platform differences. Build and execution helpers find binaries under Cargo or Bazel, resolve program names on Windows, and shape the environment variables passed to child commands. Terminal support detects the host terminal, chooses usable colors, and copies text safely through SSH, tmux, WSL, or local clipboards. Sandbox utilities prepare restricted runs on Linux, macOS, and Windows by finding sandbox tools, reporting denied permissions, normalizing paths, setting up safe working folders, environment variables, SSH dependencies, mutexes, and Windows-specific system details.
22.2Text, parsing, truncation, and rendering helpers57 files
This stage is shared behind-the-scenes support for almost every place the project reads, prepares, or shows text. It is not one main feature. It is more like the workshop that cuts, labels, cleans, and paints text before other parts use it, especially in the command-line and terminal interface.
The generic text utilities shorten long output, format numbers and times, fill simple templates, protect private values, and make strings safe for terminals, metrics, or JSON. The streaming parsers handle text that arrives piece by piece, such as live model output or process logs. They join split characters, wait for complete lines, remove hidden markup, and keep useful metadata separate from visible words.
The layout and rendering helpers then make text fit on screen. They measure width, wrap lines, preserve colors and links, truncate safely, and support scrollable views such as diffs. Above that, the presentation helpers choose consistent styles, colors, rows, popups, footers, warnings, and status labels. Finally, the animation and progress helpers add small motion effects and temporary “working” messages without cluttering the final output.
22.2.1Generic string, formatting, truncation, and templating utilities12 files
This stage is shared behind-the-scenes support for making text safe, short, and easy to read across the project. It is like a set of measuring cups and labels used by many kitchens, not the main cooking itself.
The string utilities clean and convert text safely. They can produce ASCII-only JSON for places that may reject Unicode, shorten long strings without breaking emoji or non-English characters, and prepare safe metric tags or terminal-friendly code links. Number and elapsed-time formatters turn raw values into labels people can scan, like “12,000”, “12K”, or “1m 15s”. CLI helpers display environment variable names without leaking their values, and build copy-safe “resume” commands for old threads.
Several tools keep text from overwhelming the system. Output truncation preserves useful beginning and ending context, while response-history trimming keeps conversations within a reusable size budget. The strict template helper fills placeholders such as “{{ name }}” and catches missing or mistaken fields. Web search formatting and TUI text helpers turn actions, paths, JSON, and long tool output into compact readable labels for narrow displays.
22.2.2Streaming, line framing, and hidden-markup parsers9 files
This stage is shared behind-the-scenes support for reading text that arrives in pieces, such as live assistant output or process logs. Its job is to turn messy chunks into clean, useful events without losing hidden information. The stream-parser front door gathers these helpers for the rest of the project. Its common result model separates visible text from hidden parts, like citations or metadata, so the app can show only what users should see while still keeping machine-readable details. The UTF-8 stream reader safely joins raw bytes into text even when one character is split across chunks. The line buffer does a similar job for process output, waiting until a full newline-ended line is ready. Other parsers remove inline hidden tags, detect tagged blocks that start and end on their own lines, and extract structured memory citations. The table detector recognizes Markdown tables and code fences so display and cleanup code agree. The mention codec turns user-friendly tool mentions into stored links and back again. Together, these pieces act like filters on a conveyor belt for streamed text.
22.2.3TUI text layout, wrapping, and text-rendering primitives10 files
This stage is shared behind-the-scenes support for drawing text in the terminal interface. It is used whenever the app needs to show output, Markdown, diffs, links, or styled lines inside a limited screen area.
The geometry helper in render/mod.rs lets drawing code add padding inside a rectangle, like leaving margins in a page. line_utils.rs prepares display lines so they can be safely stored, copied, and given prefixes. width.rs checks whether there is any usable space left after those prefixes. ansi-escape/src/lib.rs converts colored terminal output into drawable text and expands tabs so columns line up.
Several files then shape text to fit. line_truncation.rs measures and cuts styled text without splitting wide characters such as emoji. wrapping.rs wraps rich terminal text while preserving styling, indentation, byte positions, and whole clickable URLs. live_wrap.rs does similar wrapping for incoming plain text. markdown_text_merge.rs joins adjacent Markdown text pieces after parsing so rendering sees smoother text. terminal_hyperlinks.rs keeps link targets separate from visible words until the final drawing step. scrollable_diff.rs uses these pieces to show wrapped diffs and messages with a valid scroll position.
22.2.4TUI presentation models, styling, and lightweight view helpers21 files
This stage is shared behind-the-scenes support for the terminal user interface. It sits above the low-level text drawing code and prepares what the user will see: colors, labels, rows, popups, footers, and status text. The color, style, chart palette, and spacing files choose readable colors, symbols, and margins so screens stay consistent on different terminals. The renderable building blocks let text and containers report their size and draw themselves.
Several files shape common controls. Key hints make shortcuts display consistently. Scroll state, selection rows, selection popups, and selection tabs keep lists, tabs, highlights, wrapping, and disabled choices predictable. The footer, action-required title, and popup constants build the bottom-pane messages that guide the user.
Other helpers turn internal data into friendly display models. Warning logic avoids repeated chat warnings. Migration, goal, skill, status, and remote-connection helpers convert raw settings, paths, counts, times, server details, and skill metadata into short readable text. History cells provide reusable transcript pieces, including wrapped text and links.
22.2.5TUI animation, motion, terminal media, and transient progress output5 files
This stage is shared behind-the-scenes support for making the command-line interface feel alive without getting in the way. It is used while the program is running, especially when the interface needs to show that work is happening.
The motion file is the central switchboard for small movement effects, such as loading dots or animated highlights. It also respects reduced-motion settings, meaning users who prefer less animation still see clear, steady feedback. The shimmer file supplies one of those effects: it breaks text into styled pieces and changes their brightness over time, like a light sweeping across a sign. The ASCII animation file is the frame driver. It decides which text-art picture to show next and asks the interface to redraw at the right moments. The frames file is the art library, packaging those pictures and their normal playback speed into the program. Finally, the doctor progress file shows temporary “checking…” messages during health checks, sending them somewhere safe so they do not mix into the final report or JSON output.
22.3Configuration, metadata, schema, auth, and network glue utilities26 files
This stage is shared behind-the-scenes support. It is the toolbox other features reach for when they need clean settings, safe network rules, login helpers, or small bits of display data. The cloud tasks, login, API, proxy, MCP, and Ollama helpers prepare authentication, headers, URLs, readable errors, and server environment values so requests leave the app with the right context and fewer secret-handling mistakes. The configuration helpers explain where settings came from, enforce allowed values, rename old keys, convert JSON to TOML, and turn command-line options such as approval mode, sandbox mode, and key=value overrides into the internal settings the program uses. Metadata helpers give connectors, plugins, skills, mentions, memories, and execution-policy errors consistent names, schemas, counts, symbols, and messages. The network proxy files turn user-facing allow and deny rules into normalized host and IP policies, blocking risky local targets and choosing safe listen addresses. Finally, the TUI version helpers read baked-in version data, compare releases, and check npm registry records before treating an update as real. Together, these files act like adapters and gauges that keep the larger machine understandable and safe.
22.4Shell, command, git, plugin, and execution support utilities24 files
This stage is behind-the-scenes support used whenever the app must run outside programs, inspect Git, or package plugins. The shell pieces provide one common view of bash, zsh, PowerShell, sh, and cmd: they detect a safe shell, turn a command string into the right arguments, build the variables a program receives while filtering secrets, and format commands for display without changing their meaning. The Git pieces wrap the git program to ask safe, timed questions about repositories, roots, remotes, branches, commits, changes, filesystem monitoring, and diffs, including the TUI /diff view and shared-starting-commit checks.
The plugin pieces package plugin folders into bounded, safe archives, clone marketplace content into a temporary staging area, keep writes inside the install folder, and activate a prepared marketplace only when its recorded source and revision match. The execution pieces are the plumbing for tools and sandboxes: they normalize executable names, prepare Linux arguments and input/output handles, communicate with Windows sandbox runners, track process families, mirror command exit status, open an external editor, and provide a common interface for interactive child processes. Output helpers keep command logs useful by preserving the start and end when text is huge. The patch helper finds matching text flexibly.
22.5Async primitives, image handling, and miscellaneous small support libraries25 files
This stage is a toolbox of small behind-the-scenes helpers used by many larger parts of the system. The image pieces prepare pictures for safe use: pet files split spritesheets, choose terminal image protocols, and encode Sixel frames; image utilities read, resize, validate, and report clear errors; core and tool helpers manage “original detail” image requests and replace unusable images with text placeholders. Async helpers act like traffic signals: cancellation stops waiting work, readiness lets tasks wait for a safe start, the pauseable stopwatch enforces time limits, and the frame-rate limiter avoids excessive terminal redraws. Sleep-inhibitor files keep the computer awake during an active turn, with separate implementations for macOS, Linux, Windows, and a harmless dummy fallback. Other utilities translate V8 JavaScript results into Rust-friendly values, prove basic V8 linking, cache recent async values with SHA-1 keys, filter replayed interface events, and turn sandbox or configuration settings into compact human-readable summaries. Together these pieces do not drive the main story, but they make startup, display, tool output, and long-running work smoother and safer.
22.6Build scripts and build-time asset/platform glue4 files
This stage runs before the main program is built. It is behind-the-scenes setup for Cargo, Rust’s build tool, so the final binaries are assembled correctly on each platform and stay up to date when bundled files change. The Bubblewrap build script prepares a Linux sandbox helper: it checks whether Bubblewrap can be built, compiles its C source code when appropriate, and tells Cargo how to link that compiled code into the Rust crate. The Windows sandbox build script does a similar kind of platform glue for Windows, but instead of compiling code it attaches an application manifest, a small settings file Windows reads to know how the helper should run. The CLI build script adds a special macOS linker option so code that depends on Objective-C-related system pieces can link cleanly. The skills build script watches sample asset folders and tells Cargo to rebuild if those files change. Together, these scripts act like workshop notes for the compiler, adjusting the build for each operating system and for bundled assets.
23Testing, fixtures, and developer verification harnesses✕659 files
This stage is the project’s test workshop. It is not used by normal users during startup, daily work, or shutdown. Instead, developers and automated checks use it to make sure every major part still behaves correctly before changes are shipped.
The app-server tests prove the server starts, speaks the expected message formats, and supports real client workflows. The core runtime tests check conversations, tools, permissions, saved history, recovery, and safe stopping. The CLI, exec, login, and MCP tests run the command-line programs like real users would, including patching files, signing in, streaming results, and handling failures. The exec-server, sandbox, and remote transport tests protect command execution, file access, encrypted connections, relays, and platform-specific safety rules. The TUI tests draw the terminal interface into fake screens and check chat behavior, popups, layout, scrolling, and rendering. The cross-cutting library tests cover shared pieces such as telemetry, configuration, plugins, APIs, persistence, and utilities.
The direct support file, test-binary-support/lib.rs, lets tests imitate different installed command names using temporary aliases and a temporary home folder, then cleans everything up afterward.
23.1App-server test suites and protocol verification115 files
This stage is the app server’s safety workshop. It is not part of normal startup, daily work, or shutdown. Instead, it runs during development and continuous testing to prove that the server still speaks the right language, starts correctly, connects to clients, and supports real workflows.
The protocol tests act like a ruler for messages. They check that JSON-RPC and remote-control data keep the exact shapes clients expect, and that generated schemas have not changed by accident. The daemon and transport tests check the background server process, update decisions, socket connections, client routing, and the special test client used to exercise the system safely.
The unit tests look inside the app server’s smaller parts, such as configuration import, command-line overrides, tracing, error reporting, and conversation state. Shared fixtures build a pretend world with fake accounts, models, saved sessions, and AI responses, so tests do not need real services.
Finally, the integration suites put everything together. They start the server like a real client would, send requests, run conversations, use tools and plugins, and verify the visible behavior from end to end.
23.1.1Protocol schema and wire-format verification4 files
This stage is a behind-the-scenes safety check for the project’s communication rules. It does not run the app’s main work. Instead, it makes sure the messages sent between the app server and its clients keep the same shape over time. That “wire format” is the agreed JSON layout used on the network, like a shared form both sides know how to fill in.
The common protocol tests check how client response data becomes JSON-RPC response parts. JSON-RPC is a simple request-and-response message style using JSON. These tests confirm when a response should also create an internal client response object, and when it should remain only a plain JSON-RPC result.
The version 2 remote-control tests focus on remote-control messages, checking that Rust data structures turn into exactly the expected JSON and can be read back correctly. The broader version 2 protocol tests cover app-server messages, older accepted JSON shapes, and conversions to and from core Codex protocol types.
Finally, the schema fixture test compares generated protocol schemas with the checked-in copies, catching accidental protocol changes.
23.1.2Daemon, transport, and test-client support tests13 files
This stage is the safety net around the app server’s background service, its communication pipes, and its special test client. It is shared behind-the-scenes support: it does not run the product itself, but it proves that startup, messaging, updates, and test-only tools behave correctly.
The daemon tests check the background server’s “PID file,” a small record saying which process is running. They cover starting, stopping, stale records, launch arguments, log reading, managed install version checks, and update decisions. One key rule is protected: if the updater program itself changes, that is more urgent than an ordinary version change.
The transport tests check how clients connect and receive messages. Unix-socket tests cover local WebSocket connections, socket-file protection, message forwarding, and avoiding double startup races. Other transport tests make sure messages go only to suitable clients and that one slow client cannot block the rest. Remote-control tests check pairing, client listing, revoking, refreshed authentication, and useful error details.
The test-client files provide a realistic command-line client, fake local HTTP service, and plugin analytics checks, including smoke tests for install, update, use, and removal events.
23.1.3App-server unit tests and shared integration fixtures20 files
This stage is shared test support for the app server. It is not part of the running product path; it is the safety net used while building and changing the server. The unit tests check important behaviors inside the app-server crate: importing external agent settings without losing or duplicating data, managing config files safely, accepting command-line overrides, keeping tracing links across JSON-RPC requests, refreshing runtime state after config migration, reporting remote-control errors clearly, preserving conversation thread state, and creating summaries from the right user message.
The integration-test helpers act like a small pretend world around the server. They provide fake analytics, authentication files, config files, model lists, saved sessions, and AI service responses, so tests can run without real accounts, networks, or production services. The mock model server and test app-server client let tests start a real server process, send JSON-RPC commands, read replies, and shut it down cleanly. Finally, the suite index files are the test runner’s table of contents, gathering the right test groups so they compile and run together.
23.1.4App-server integration suites78 files
This stage is the broad end-to-end test bench for the app server. It treats the server like a real client would: start it, connect to it, send requests, run conversations, use tools, and check that the answers and side effects are correct. It is mostly about the server’s public behavior, not small internal parts.
One group tests the basic “front desk”: login, accounts, rate limits, configuration, startup handshakes, model discovery, safe file and process access, and remote-control pairing. Another group tests the live connection pipes, such as WebSockets, authentication, reconnects, shutdown behavior, desktop proof tokens, experimental features, and realtime text or audio sessions.
A third group checks extensions: plugins, marketplace installs, connector apps, hooks, skills, MCP tool servers, shell commands, file search, image generation, sleep, and web search. These tests make sure outside tools appear only when allowed and run safely.
The final group follows the conversation lifecycle: creating threads, running turns, interrupting work, asking permissions, saving history, summarizing, reviewing code, reopening sessions, and deleting or archiving old work.
23.1.4.1App-server integration suites — auth, config, discovery, and core RPC surfaces16 files
This stage checks the app server from the outside, the way a real editor or tool would use it. It is mostly shared support for startup and everyday server work, not the plugin system or conversation loop. These tests call RPCs, meaning request-and-reply commands sent to the server, and verify the public promises clients depend on.
The auth and account tests cover login state, API keys, ChatGPT tokens, device-code login, logout, token refresh, workspace limits, and Bedrock account reporting. The rate-limit tests check reading usage limits, asking owners for more credits, and spending reset credits, including bad logins and backend failures. Strict config and config RPC tests protect configuration: the server must reject unknown settings when asked, read settings with their sources, and write changes safely. Initialize tests check the first handshake between client and server.
The discovery tests make sure clients can list models, collaboration modes, permission profiles, experimental features, and provider capabilities in stable shapes. The filesystem, process, and Windows sandbox tests check safe local file access, running and stopping commands, and sandbox setup. Remote-control tests verify pairing, revoking, policy rules, and fake network behavior.
23.1.4.2App-server integration suites — transport, protocol contracts, and client connection behavior5 files
This stage is a set of integration tests for the app server’s live client connections. It checks the “front door” behavior: how desktop clients connect, prove who they are, exchange messages, use realtime features, and disconnect. These tests sit around the main work loop, where the server is already running and must behave predictably while clients talk to it.
The WebSocket tests check the basic pipe between client and server. They make sure separate clients do not leak into each other, authentication is enforced, health checks work, and reconnecting clients can recover recent work. The Unix WebSocket shutdown tests add pressure: they send Ctrl-C-style signals while a request is active and confirm the server waits, exits fast on a second signal, and closes cleanly.
The attestation test follows a proof token from the desktop client into the outgoing ChatGPT connection handshake. The experimental API test makes sure new features stay locked unless the client opts in. The realtime conversation tests cover the full live experience: text, audio, WebRTC setup, feature flags, handoffs to background agents, and expected error behavior.
23.1.4.3App-server integration suites — plugins, marketplace, MCP, and tool/executor integrations24 files
This stage is a behind-the-scenes safety net for the app server’s extension system. It tests the places where the server lets outside add-ons, tools, and local commands become part of a conversation. The plugin tests cover the full plugin life cycle: listing, reading details and skills, installing, sharing, uninstalling, and syncing with local or remote catalogs. The marketplace tests check adding, removing, and upgrading collections of plugins. App listing checks that connector apps and fake tool servers appear correctly.
Other tests check discovery features. Hooks tests make sure startup or project actions can be listed, trusted, enabled, or disabled. Skills tests confirm that instruction packs from users, workspaces, plugins, or executor choices are found without the wrong one taking over. MCP tests cover outside tool servers: their status, tools, resources, permission questions, and thread-specific visibility.
The remaining tests exercise tool execution. They check shell commands, packaged zsh commands, fuzzy file search, image generation, sleep, and web search. Together, these tests make sure extensions behave like well-labeled tools in a workshop: visible when allowed, hidden when not, and safe to use.
23.1.4.4App-server integration suites — thread, turn, review, and session-state lifecycle33 files
This stage is the app server’s “conversation lifecycle” test area. It checks the main work loop that clients use every day: create a thread, run assistant turns, pause or interrupt them, save history, reopen it later, and eventually archive or delete it. The thread tests act like a filing system inspection: start, list, read, resume, fork, rename, roll back, archive, unarchive, delete, and summarize conversations, whether they live on disk, in memory, or in a remote store. Other tests check per-thread details such as settings, memory mode, Git metadata, loaded-thread lists, subscriptions, and live status messages.
The turn tests check the moving parts during an active assistant response: starting a turn, steering it with a new user message, asking for permissions or user input, using dynamic tools, enforcing output schemas, injecting saved items, and interrupting safely. Review and compaction tests cover special workflows: code review and shrinking long chats into summaries. Finally, client metadata, safety notifications, memory reset, and external-agent import tests make sure surrounding state and policy messages stay accurate for connected clients.
23.2Core runtime and session test harnesses179 files
This stage is the main safety-check area for the core system. It is not part of what users directly see. Instead, it proves that the conversation engine can start, run, use tools, save its place, recover later, and stop safely. One group of tests watches the runtime itself: sessions, history, state, permissions, compaction, agents, realtime behavior, and other internal records. Another group focuses on tools, such as running shell commands, editing files, calling outside services, asking for approval, and shutting down long-running work. A shared integration harness acts like a test workshop. It builds fake folders, fake model servers, fake app services, and controlled streams so tests can run without touching real user data. The end-to-end suites then put everything together, checking full sessions from model request to streamed reply, tool use, approvals, saved history, plugins, remote work, and helper agents. Together, these parts make sure the core behaves reliably before real users depend on it.
23.2.1Core src runtime, session, policy, and state tests40 files
This stage is a behind-the-scenes safety net for the core runtime. It does not add user features itself. Instead, these tests check that the main conversation engine starts, runs turns, saves state, resumes later, and shuts work down safely. The session tests cover conversation setup, history, settings refresh, hooks, metrics, network rules, plan-mode messages, user shell commands, and worker-failure messages. Rollout, thread, history, compaction, event-mapping, stream, image, and client-request tests make sure saved or streaming conversation data is cleaned, shortened, restored, and sent to APIs in the right shape. Agent tests cover parent and child agents: spawning, roles, registries, delegation, concurrency limits, memory residency, cancellation, and resuming agent trees. Guardian, MCP, execution-policy, sandbox, and patch-safety tests check the permission system that decides what commands, tools, and file edits may run. State, metadata, timing, diff-tracking, Git, shell, AGENTS.md, personality migration, and realtime tests check supporting records and environment details. Together, these tests act like gauges around the engine, warning when lifecycle, safety, or saved-state behavior changes unexpectedly.
23.2.2Core src tools and unified-exec tests39 files
This stage is a broad safety check for Codex’s tool system, the behind-the-scenes machinery that lets the model edit files, run commands, ask the user, call external MCP tools, manage sub-agents, and use hosted features like web search or image generation. Most files here are tests that protect the public “tool contract”: the exact names, descriptions, inputs, and outputs the model or outside clients depend on. That includes specs for shell, patching, MCP resources, multi-agent tools, user input, plugin installs, hosted tools, and agent jobs.
Other tests check the moving parts that execute those tools. The registry finds and runs tools. The router sends each requested call to the right local, MCP, dynamic, or extension handler. Context and trace tests make sure results and history are recorded clearly. Approval, sandboxing, network, command-canonicalization, and runtime tests guard the rules for when commands or file edits are allowed. The test synchronization tool helps timing-sensitive tests coordinate reliably. Finally, the unified-exec tests cover the newer command runner: streaming output, long-running processes, remote exec servers, timeouts, cleanup, and safe shutdown.
23.2.3Core integration harness and common test support15 files
This stage is shared behind-the-scenes support for testing the core crate. It is not a feature being tested; it is the workshop that lets all the feature tests run safely and repeatably. The main entry files, all.rs and suite/mod.rs, gather the integration tests into one runnable test program and let that program pretend to be helper binaries when needed. The common toolbox supplies temporary folders, default settings, sandbox checks, hook approval setup, tracing setup, and helpers for waiting on background processes. Other helpers decide whether tests run locally, in Docker, or through Wine, and prepare special zsh fork tests when that path is available. Several files build fake outside services: mock Codex Apps, OpenAI Responses and Models APIs, WebSocket or HTTP replies, and controlled Server-Sent Event streams. Snapshot helpers turn large request data into stable readable text. The Codex test builders create a complete fake conversation world, while the exec helper runs codex-exec without touching real user files. Together, these pieces make end-to-end tests reliable, isolated, and understandable.
23.2.4Core end-to-end session, transport, tool, and feature suites85 files
This stage is a large end-to-end test area for Codex’s live user sessions. It checks the main work loop and the shared support around it: sending requests to AI models, receiving streamed replies, remembering conversation state, choosing models, using tools, asking for approvals, and working with helper agents or remote machines.
The transport suites test the “wires” to model providers, including HTTP, WebSocket, realtime, retries, headers, quotas, and streamed responses. The history and persistence suites test Codex’s memory: saving sessions, compacting long chats, resuming, forking, and restoring tool logs. The prompt and model-selection suites check that each model request is packed with the right instructions, context, tools, and limits. The multi-agent suites test child agents, delegation, shared limits, job queues, and remote environments. The approvals and hooks suites test safety gates that pause, block, review, or modify actions. The tool and runtime item suites test shell commands, patches, plugins, external app tools, images, searches, and the user-visible event stream. Together, these tests prove the whole session behaves safely and predictably.
23.2.4.1Transport, streaming, and provider protocol suites16 files
This stage tests the network edge of Codex: the place where a user turn becomes a request to a model service, and where streamed answers come back. It is mainly behind-the-scenes support for the main work loop. The large client suite checks the basic machinery: request shape, auth headers, history, reasoning options, token counts, and provider differences. Header-focused tests make sure turn, sub-agent, workspace, and proxy identity labels are carried correctly. Compression, model-list ETag refresh, quota errors, and safety-check downgrade tests protect specific provider rules and user-facing failures.
Several tests cover streaming paths. HTTP streaming recovery tests make sure Codex can retry if a stream ends early and can continue after a failed turn. WebSocket tests check long-lived connections for normal model replies, agent messages, warmups, retries, tracing, service tiers, and fallback to plain HTTP when WebSockets fail. Realtime conversation tests cover live audio/text sessions and handoffs back to the normal agent. Other tests cover remote compaction of long chats, the lighter Responses Lite request path, and temporary turn state that must be used for one turn only.
23.2.4.2Session history, compaction, resume, and persisted state suites13 files
This stage tests Codex’s memory: how a conversation survives long chats, restarts, branches, and saved state. It is shared support for the main chat loop and for reopening old sessions. The compaction tests check that long history can be squeezed into a shorter summary without losing key instructions, whether done manually, automatically, remotely, after a model switch, or during replay. Resume and fork tests check that saved conversations reopen with the right messages, warnings, settings, and request history, and that a copied branch keeps or drops messages exactly where asked. Pending-input tests make sure messages that arrive during an active model turn wait for the next turn instead of being lost. Window-header tests verify the backend can still identify the right conversation “window” after compacting, resuming, or forking. Rollout and SQLite tests cover the storage layer: finding saved sessions, saving images, preserving tool logs, restored tools, and safety flags. Model override tests ensure temporary thread settings do not quietly rewrite user config or history until a real new turn records them.
23.2.4.3Model request shaping, prompt assembly, and runtime model-selection suites17 files
This stage checks the “package” Codex sends to the AI model before each turn, and the model choices that shape that package. It is behind-the-scenes support for the main conversation loop: like packing a briefing folder, it must include the right notes, tools, limits, and rules without confusing them with the user’s own words. Tests cover added context from browsers or automation, saved project guidance from AGENTS.md, nested AGENTS.md rules, collaboration instructions, repository skills, prompt-debug basics, and snapshots of the model-visible layout. Other tests make sure permission messages, assistant personality, token-budget guidance, and cache-friendly prompt ordering appear once, change when settings change, and survive resumed or forked sessions. Request-shaping tests check strict JSON replies and web-search tool fields. The model-selection side verifies remote model catalogs, runtime selectors, automatic review models, and mid-conversation model switching, including service tier, image support, token limits, and special switch instructions. Together, these suites guard the boundary between Codex and the model so the model receives clear, current instructions tailored to the selected model.
23.2.4.4Multi-agent, collaboration, and remote-environment suites6 files
This stage checks the system’s collaborative “many helpers” behavior. It is part of the test suite, so it does not run the product itself; it proves that the main work loop stays safe and understandable when one session starts child sessions, delegates work, or uses a remote machine.
The spawn agent description tests make sure the model is shown the right instructions for creating helper agents, including which models are allowed and when not to use them. The agent execution tests check the traffic limit: nested helpers all share one cap, so a child cannot quietly create too many more children. The delegation tests confirm that a sub-agent’s approval requests appear in the parent conversation, without duplicate status messages. The subagent notification tests cover the “wiring” between parent and child sessions: settings, roles, skills, lifecycle messages, and multi-agent communication. The agent jobs tests treat CSV rows like a work queue, sending each row to workers and collecting results safely. The remote environment tests ensure the same rules hold when files, commands, patches, and approvals happen on another machine.
23.2.4.5Approvals, permissions, hooks, and review-mediation suites13 files
This stage tests the safety gates that sit around Codex while it is doing its main work. These gates decide when an action can run, when the user must be asked, and when something must be blocked. The approval, exec policy, skill approval, and zsh-fork approval tests check shell commands, patches, file writes, network access, and sandbox limits. The permission request tests check the path where Codex asks for extra access, receives a limited grant, and then must obey exactly that grant.
Other tests cover human and reviewer mediation. The request-user-input tests check that Codex can pause to ask a question and resume correctly. The review and Guardian review tests check separate reviewer flows, including automatic safety review, without leaking private review details. MCP metadata tests ensure tool calls to external app servers carry the right approval and review information.
The hook and hook-MCP tests cover small user or plugin scripts that can inspect, block, rewrite, or add context around actions. The notification test checks the final “turn finished” message sent to a user command.
23.2.4.6Tool, shell/exec, MCP/app, plugin, and runtime item suites20 files
This stage is a broad end-to-end safety check for Codex’s tool system, the part of the main work loop where the model asks the program to do real things. The tool tests check which tools are shown to the model, how custom tools run, and how blocked or unsafe actions are reported. The shell and exec suites cover local commands, long-running sessions, login shells, pipes, timeouts, Unicode, macOS sandbox limits, user-typed commands, aborts, saved shell setup, parallel tool calls, and readable result formatting. The patch tests make sure file edits are applied clearly and stay inside the workspace. Other suites check large-output truncation, image viewing and generation permissions, and file upload routing for app-style MCP tools, meaning external tools connected through a shared protocol. Plugin and search tests verify that Codex can discover plugins, apps, install options, and hidden tools only when needed. Code mode tests the JavaScript-like exec path that can call other tools. Finally, item tests make sure messages, reasoning, plans, searches, images, and tool events are emitted in the right user-visible stream.
23.3CLI, exec, login, and MCP server developer verification73 files
This stage is a broad test bench for the programs developers and users run from the terminal. It is not the normal work loop; it is behind-the-scenes verification that the finished executables behave correctly when used like real tools.
The apply-patch tests feed patch text to the standalone patch program and check that files are created, edited, renamed, deleted, or rejected as expected. The top-level CLI tests exercise Codex’s main command entry point, checking config errors, plugin commands, MCP server settings, JSON output, and special debug commands. The codex-exec tests focus on the program that asks Codex to perform work, making sure flags, prompts, permissions, streamed events, resume behavior, hooks, and server failures are handled predictably. The execpolicy tests verify the rule system that decides whether shell commands are allowed, blocked, or need approval. The login tests rehearse signing in, refreshing credentials, storing secrets, and logging out. The MCP server tests start the server as a real child process and talk to it with JSON messages, using a mock AI server to check tool behavior safely.
23.3.1apply-patch executable integration tests5 files
This stage checks the standalone apply-patch program from the outside, as if it were being used by a real person in a terminal. It is part of the project’s testing support, not the normal startup or work loop. Its job is to prove that the finished executable accepts patch input correctly and leaves the filesystem in the right state.
The suite starts in all.rs, which acts like the front door and loads the shared test tree. mod.rs is the table of contents. It selects the test groups to run and leaves out one group on Windows where the behavior does not apply. cli.rs focuses on command-line use: it runs apply_patch with patch text passed either as an argument or through standard input, then checks that files are created or changed. tool.rs goes deeper into real folder effects, testing edits, overwrites, renames, deletes, and clear failures for bad patches. scenarios.rs runs complete example patches and compares the final folder contents with the expected results.
23.3.2top-level codex CLI command verification14 files
This stage checks the front door of the Codex command-line program. These are integration tests, meaning they run commands much like a real user would and check the visible results: exit codes, printed text, JSON output, and saved configuration files. The app-server and exec-server tests make sure strict config mode rejects unknown settings instead of ignoring mistakes. The delete test confirms Codex will not ask for deletion confirmation when the target session is missing. The update test makes sure debug builds fail clearly instead of dropping into the normal prompt. Debug tests cover clearing stored memories safely and printing model lists as valid JSON. Feature tests check command-line feature flags and config writing. Plugin tests cover plugin commands, marketplace add, remove, and upgrade behavior, including local folders, cleanup, and error messages. MCP tests cover adding, listing, getting, and removing MCP server entries, including hiding secrets in friendly output while preserving full JSON data. Finally, the live CLI smoke test can exercise the real program against the OpenAI API, but it is normally skipped to avoid network cost and outside-service failures.
23.3.3codex-exec binary verification22 files
This stage is the safety check for codex-exec, the command-line program people run to ask Codex to do work. It is behind-the-scenes support, run by tests to make sure startup options, the main request flow, and failure exits behave reliably. The CLI and main tests check that flags, configuration options, and resume prompts are read the way users expect. The library tests cover deeper defaults such as logging, permissions, review setup, prompt decoding, and session startup. The event processor tests check how server messages become user-visible output: readable text for humans, JSONL lines for streaming tools, and simpler JSON events for automation. The integration suite then tests the whole machine assembled: extra writable directories, AGENTS instruction files, API keys and Originator headers, JSON output schemas, stdin prompts, approval modes, ephemeral sessions, hooks, required MCP tool startup failures, patch application, resume behavior, server error exit codes, and real streaming against a mock server. Together these tests make sure codex-exec is predictable for both people and scripts.
23.3.4legacy and current execpolicy executable tests13 files
This stage is behind-the-scenes safety checking for the execution policy, the part of the system that decides whether a shell command may run, must be blocked, or needs user approval. It is not the main work loop itself; it is the test harness that proves the rules behave as expected.
The current tests check both the policy engine and its command-line face. One test runs codex execpolicy check and confirms it reports JSON correctly when a rule blocks something risky like git push. Another checks policy files directly, making sure commands are sorted into allowed, denied, forbidden, or prompt-needed results.
The legacy tests act like an older library of examples that must still pass. A top-level test file and module list gather the suite. “Good” and “bad” command lists protect broad expectations. Command-specific tests then inspect known Unix tools: cp, head, ls, pwd, literal subcommands, and narrow safe forms of sed. Together they form a regression net, catching accidental changes that would make the policy too strict or too loose.
23.3.5login workflow integration tests12 files
This stage is the safety net for the login system. It runs during testing, not during normal use, and checks the full journey of signing in, staying signed in, and signing out. The test entry files gather the separate test modules so Rust can run them as one suite.
The smaller auth tests check the building blocks: whether different token text formats are recognized, whether personal access tokens fetch complete user data, whether API keys and environment settings are accepted safely, and whether Amazon Bedrock credentials can replace older OpenAI-style credentials. Storage tests make sure saved logins can move between files, memory, and the system keyring, which is the operating system’s secure password store.
The larger workflow tests act more like rehearsals. Command-line login tests check API-key and device-code login, where a terminal asks the user to approve access in a browser. Browser-server end-to-end tests exercise the local login server from the outside. Refresh tests confirm expired ChatGPT tokens are renewed without overwriting newer data. Logout tests ensure remote revocation is attempted and local credentials are cleaned up even if revocation fails.
23.3.6MCP server executable integration tests7 files
This stage tests the MCP server as a real program, not just as separate pieces. It belongs to the “prove the system works end to end” part of the story. The tests start the codex MCP server as a child process, send it JSON-RPC messages, and check the replies. JSON-RPC is a simple request-and-response format written as JSON.
The test entry point, all.rs, gathers the integration tests so Rust can run them together. suite/mod.rs points to the codex_tool tests, like a small table of contents. common/lib.rs provides shared test tools, including a way to turn raw JSON replies into normal Rust values.
mcp_process.rs is the main wiring harness. It starts the server, talks to it, and shuts it down cleanly. mock_model_server.rs plays the role of the remote AI model, returning prepared answers instead of making real network calls. responses.rs builds those prepared streamed answers. Finally, codex_tool.rs uses all of these pieces to check real codex tool behavior, including permission prompts, approved file changes, and instruction forwarding.
23.4Exec-server, sandbox, and remote transport harnesses49 files
This stage is the test workshop for the system’s execution and remote-connection machinery. It is mostly behind-the-scenes support, but it protects the main work loop where Codex starts commands, reads files, talks to remote servers, and keeps those actions boxed in safely. The shared exec-server test helpers start real or pretend servers, connect over WebSocket or standard input/output, send JSON-RPC messages, and clean everything up. Other tests check the server’s first handshake, health checks, process control, terminal handling, file access, streamed file reads, HTTP requests, and path rules on Unix and Windows.
A second group tests the secure transport pipes: Noise encryption, relay registration, message splitting, ordering, reconnects, and remote-control routing. These make sure messages are private, complete, and delivered to the right place. Another group tests sandboxing on Linux, macOS, and Windows, including filesystem permissions, network blocking, proxy use, command-line wrappers, and signal or input/output forwarding. Wine-based tests bridge into Windows behavior from non-Windows hosts. Finally, RMCP client tests check that remote HTTP-style tool calls and process cleanup still work when routed through the exec-server.
23.5TUI interaction and rendering tests52 files
This stage is the safety net for the terminal user interface, or TUI: the text screen users see in a terminal. It is shared behind-the-scenes support, not product startup or shutdown code. The test support files provide fake paths, fake models, ready-made App objects, and a fake terminal screen so tests can draw UI into memory instead of a real window. The main app tests check startup, session resume, thread handling, summaries, update prompts, configuration changes, authentication, and status feeds. The chat widget tests act like a workshop for the main chat screen: they send fake server events, press keys, open popups, submit messages, approve commands, replay history, test slash commands, permissions, goals, planning, reviews, side chats, usage, and layout. Rendering-focused tests protect Markdown, history cells, token charts, status panels, colors, titles, and flexible layouts. The integration tests tie everything together, including simulated VT100 terminals, resize behavior, scrollback history, ANSI cleanup, and dependency tripwires.
23.6Cross-cutting library tests, fixtures, and telemetry or rollout support190 files
This stage is the project’s shared test workshop. It is not one user-facing flow. Instead, it checks many behind-the-scenes parts that other areas depend on: reporting, settings, add-ons, service connections, saved state, and small utility helpers.
The analytics and telemetry tests make sure activity is measured, labeled, filtered, and exported safely. Configuration and policy tests check that startup settings, enterprise rules, sandboxes, permissions, paths, and environment variables are read and enforced correctly. Plugin, extension, skills, MCP, and tool tests protect the add-on system, so extra abilities are found, loaded, displayed, and called predictably. API, model, prompt, and transport tests verify fake network clients, login, streaming, prompt text, schemas, proxies, sockets, and security setup. Memories, rollout, state, and persistence tests check saved conversations, replay logs, databases, recovery, and stored memory files. Utility tests cover file URI handling and safe shortening of long output.
The directly included files add entry points and focused checks: integration test wiring, mock Cloud Tasks access, test rendering hooks, goal token accounting, file watching, hook output spilling, line buffering, terminal detection, UTF-8 string truncation, image preparation, and image-loading performance.
23.6.1Analytics and telemetry tests18 files
This stage is a behind-the-scenes safety check for observability: the code that records what the system is doing. “Telemetry” means measurements, logs, and traces that help developers understand sessions without inspecting them by hand. The OpenTelemetry test entry files, tests.rs and suite/mod.rs, assemble the test suite, while harness/mod.rs provides an in-memory fake metrics collector. The validation, timing, send, snapshot, runtime_summary, manager_metrics, export-routing, and HTTP loopback tests check that metrics reject bad input, record durations, flush correctly, can be read immediately, summarize runtime activity, carry the right labels, route sensitive details safely, and can be exported to a local fake collector. The analytics client tests check that app-server activity becomes the right analytics events, with batching and privacy limits. The app-server analytics tests decide when analytics should run and provide HTTP capture helpers. Core task and utility tests verify telemetry tags for proxy use, memory, compaction, feedback, authentication failures, and thread names. The main core OpenTelemetry test checks session logs and traces. The state log filter test keeps noisy low-level SDK messages out of the user-facing log database.
23.6.2Configuration, policy, and environment tests43 files
This stage is a safety check area for Codex’s behind-the-scenes rules: how it reads settings, applies policy, and builds the environment before real work begins. The configuration tests check that TOML and JSON files are parsed, merged, edited, and rejected correctly when they contain typos, old names, unsafe values, or conflicting profiles. Cloud-config tests add the organization-managed layer: they build fake bundles, load cached or downloaded settings, verify signatures and account ownership, and make sure enterprise rules override user settings in the right order.
Other tests cover the policy machinery. Permission, sandbox, Windows sandbox, Bubblewrap, and network proxy tests make sure file access, internet access, and approval prompts are safe and predictable. Feature-flag and tool-config tests check which experimental or model-dependent abilities turn on. Hook, prompt, MCP, instruction, and memory-guard tests verify the smaller “control panels” around tools, user instructions, external servers, and quota safety. Environment, path, Git, and test-runner tests ensure commands run with the right variables, paths, and platform assumptions. Together, these tests keep startup choices and safety boundaries from drifting silently.
23.6.3Plugins, extensions, skills, MCP, and tools tests50 files
This stage is the test safety net for Codex’s add-on system. It covers the parts that let Codex find extra abilities, load them safely, show them to users, and turn them into tools the model can call. The plugin tests build fake home folders, marketplaces, caches, and executor file systems, then check discovery, loading, storage, curated startup syncing, remote sharing, app routing, mentions, rendering, and install requests. The skills tests do the same for skill folders: they check selection by user input, loading from user, project, plugin, and system locations, caching, enable rules, and safe executor-owned file access. The extension tests protect the public extension interface and specific extensions such as goals, image generation, and memories. The MCP tests cover Model Context Protocol, a standard way for Codex to talk to external tool servers, including configuration, catalogs, connection caching, hosted apps, executor plugins, and real client/server calls. The tool tests make sure tool definitions, schemas, search text, code-mode forms, and API JSON stay stable. Together, these tests keep the add-on “plugboard” predictable and safe.
23.6.4API clients, models, protocol, prompts, and transport support tests38 files
This stage is a behind-the-scenes test bench for the parts of the system that talk to services, choose AI models, build prompts, and move data over the network. It is not the main user workflow; it is the safety lab that keeps that workflow reliable.
The model tests check provider settings, built-in defaults, user overrides, collaboration presets, model caching, and offline test model data. Together they make sure the app picks and describes models without stale data or unsafe limits. The client and login tests check HTTP requests, authentication tokens, headers, error translation, certificates, rate-limit calls, and model-list fetching, using fake servers instead of real ones. Streaming tests cover server-sent events and realtime WebSocket sessions, including retries, audio flow, and clean shutdowns.
Prompt and tool tests protect the exact text and schemas sent to AI models, including reviews, goals, memory prompts, image detail, and JSON Schema cleanup. Protocol, code-mode, RMCP, proxy, socket, TLS, and mock-cloud-task tests check error messages, streamed output, retries, authorization recovery, blocked requests, local sockets, security setup, and fake service behavior.
23.6.5Memories, rollout, state, and persistence tests26 files
This stage is the project’s safety net for saved history and recovery. It is not the main user-facing work loop. Instead, it checks the behind-the-scenes machinery that records conversations, rebuilds them later, and keeps stored state usable after mistakes or damage.
The rollout trace tests feed fake event logs into the trace “reducer,” which is the part that turns noisy raw events into a clean replay of a session. They cover conversations, model calls, cancellations, code cells, terminal commands, child agents, protocol events, and thread tracing. The rollout storage tests then check the files and indexes that keep past sessions searchable, compressible, repairable, and linked to saved metadata.
The state and external-agent tests check the small databases and ledgers that remember threads, imported agent sessions, and completed configuration imports. Recovery tests make sure broken database files are moved aside safely.
The memories tests cover startup, prompt text, citations, file naming, cleanup, and workspace diffs. Message-history and thread-store helpers check that saved messages and fake local thread data can be read, appended, trimmed, and reused reliably in tests.
23.6.6Utility crate tests for path/URI and output truncation helpers3 files
This stage is a behind-the-scenes safety check for shared utility code. It is not part of startup, the main work loop, or shutdown. Instead, it makes sure small helper libraries behave correctly before other parts of the system rely on them.
The output truncation tests check the helper that shortens large results. This is like trimming a long receipt while keeping the important warning labels intact. The tests cover plain long text, mixed text and images, encrypted content, line limits, token estimates, and odd edge cases, so shortened output stays predictable and safe.
The PathUri tests protect the type that represents local file paths as file:// addresses. They verify converting, saving, loading, joining, and parsing paths on Unix, Windows, and unusual inputs.
The API path string tests check compatibility with an older path format. They make sure file URIs can move to and from that format, including spaces, percent-escaped characters, network shares, and invalid text. Together, these tests keep path handling and output trimming reliable across the whole project.