这页解决 OpenAI Codex 的高级配置问题:Profiles 切换、自定义 model provider、项目级 .codex/config.toml、OTel 遥测、通知、历史记录和 TUI 选项。按这里改 config.toml--config--profile 后,可用启动警告、环境变量和遥测事件验证是否生效。

OpenAI Codex 高级配置:Profiles、自定义 Provider、遥测

需要更细的控制时,用这些配置项。快速上手请先看 Config basics

如果你要了解项目指导、可复用能力、自定义 slash command、subagent 工作流和集成,再看 Customization;配置键的完整清单见 Configuration Reference

Profiles

Profiles 允许你保存一组命名配置,并在 CLI 里切换。

Profiles 目前是实验性功能,未来可能变动或移除。

Profiles 目前不支持 Codex IDE extension。

config.toml 里按 [profiles.<name>] 定义,然后运行 codex --profile <name>

model = "gpt-5.4"
approval_policy = "on-request"
model_catalog_json = "/Users/me/.codex/model-catalogs/default.json"

[profiles.deep-review]
model = "gpt-5-pro"
model_reasoning_effort = "high"
approval_policy = "never"
model_catalog_json = "/Users/me/.codex/model-catalogs/deep-review.json"

[profiles.lightweight]
model = "gpt-4.1"
approval_policy = "untrusted"

把某个 profile 设为默认值,在 config.toml 顶层加上 profile = "deep-review"。Codex 会加载这个 profile,除非你在命令行里覆盖它。

Profiles 也可以覆盖 model_catalog_json。当顶层和所选 profile 同时设置 model_catalog_json 时,Codex 采用 profile 的值。

CLI 一次性覆盖

除了编辑 ~/.codex/config.toml,你还可以在单次运行时用 CLI 覆盖配置:

  • 有专用参数时优先用专用参数,例如 --model
  • 需要覆盖任意键时,用 -c / --config

示例:

# 专用 flag
codex --model gpt-5.4

# 通用 key/value 覆盖(值是 TOML,不是 JSON)
codex --config model='"gpt-5.4"'
codex --config sandbox_workspace_write.network_access=true
codex --config 'shell_environment_policy.include_only=["PATH","HOME"]'

注意:

  • 键可以用点号表示嵌套值,例如 mcp_servers.context7.enabled=false
  • --config 的值按 TOML 解析。拿不准时给值加引号,避免 shell 把空格拆开。
  • 如果值无法解析为 TOML,Codex 会把它当成字符串。

配置和状态位置

Codex 的本地状态存放在 CODEX_HOME 下,默认是 ~/.codex

常见文件包括:

  • config.toml(本地配置)
  • auth.json(如果使用基于文件的凭据存储)或操作系统 keychain/keyring
  • history.jsonl(如果启用了历史记录持久化)
  • 其他按用户保存的状态,例如 logs 和 caches

认证细节,包括凭据存储模式,见 Authentication。配置键完整列表见 Configuration Reference

共享默认值、规则和 skills 如果是提交到仓库或系统路径,见 Team Config

如果只是想把内置 OpenAI provider 指向 LLM proxy、router,或启用 data residency 的 project,直接在 config.toml 里设 openai_base_url,不要新建 provider。这样会修改内置 openai provider 的 base URL,而不需要单独的 model_providers.<id> 条目。

openai_base_url = "https://us.api.openai.com/v1"

项目配置文件(.codex/config.toml

除了用户配置,Codex 还会读取仓库内的项目级覆盖项:.codex/config.toml。Codex 会从项目根走到当前工作目录,加载路径中找到的每一个 .codex/config.toml。如果多个文件定义了同一个键,离当前工作目录最近的文件优先生效。

出于安全原因,只有受信任的 project 才会加载项目级 config 文件。如果 project 不受信任,Codex 会忽略项目 .codex/ 层,包括 .codex/config.toml、项目本地 hooks 和项目本地 rules。用户层和系统层仍然独立加载。

项目 config 里的相对路径,例如 model_instructions_file,会相对于包含 config.toml.codex/ 文件夹解析。

项目 config 不能覆盖会重定向凭据、修改 provider 认证,或运行机器本地通知/遥测命令的设置。Codex 会忽略项目级 .codex/config.toml 中的这些键,并在启动时警告:openai_base_urlchatgpt_base_urlmodel_providermodel_providersnotifyprofileprofilesexperimental_realtime_ws_base_urlotel。这些键要放在用户级 ~/.codex/config.toml 里。

Hooks

Codex 也可以从 hooks.json 文件,或紧挨着当前配置层的 inline [hooks] 表中加载生命周期 hooks。

实际最常用的四个位置是:

  • ~/.codex/hooks.json
  • ~/.codex/config.toml
  • <repo>/.codex/hooks.json
  • <repo>/.codex/config.toml

项目本地 hooks 只有在项目 .codex/ 层受信任时才会加载。用户级 hooks 不受项目信任状态影响。

inline TOML hooks 使用的事件结构与 hooks.json 相同:

[[hooks.PreToolUse]]
matcher = "^Bash$"

[[hooks.PreToolUse.hooks]]
type = "command"
command = '/usr/bin/python3 "$(git rev-parse --show-toplevel)/.codex/hooks/pre_tool_use_policy.py"'
timeout = 30
statusMessage = "Checking Bash command"

如果同一层同时包含 hooks.json 和 inline [hooks],Codex 会同时加载并发出警告。每一层建议只用一种表示方式。

当前事件列表、输入字段、输出行为和限制见 Hooks

Agent roles(config.toml 里的 [agents]

关于 subagent role 配置([agents]),见 Subagents

项目根目录检测

Codex 会从工作目录向上查找项目配置,例如 .codex/ 层和 AGENTS.md,直到找到项目根目录。

默认情况下,包含 .git 的目录会被当作项目根。要改这个行为,在 config.toml 里设置 project_root_markers

# 当目录包含任意一个 marker 时,将其视为项目根。
project_root_markers = [".git", ".hg", ".sl"]

project_root_markers = [] 设为空数组,就会跳过向上搜索,并把当前工作目录当作项目根。

自定义 model providers

model provider 定义了 Codex 如何连接模型,包括 base URL、wire API、认证和可选 HTTP headers。自定义 provider 不能复用内置保留 ID:openaiollamalmstudio

定义额外 provider,并把 model_provider 指向它们:

model = "gpt-5.4"
model_provider = "proxy"

[model_providers.proxy]
name = "OpenAI using LLM proxy"
base_url = "http://proxy.example.com"
env_key = "OPENAI_API_KEY"

[model_providers.local_ollama]
name = "Ollama"
base_url = "http://localhost:11434/v1"

[model_providers.mistral]
name = "Mistral"
base_url = "https://api.mistral.ai/v1"
env_key = "MISTRAL_API_KEY"

需要请求头时可以这样加:

[model_providers.example]
http_headers = { "X-Example-Header" = "example-value" }
env_http_headers = { "X-Example-Features" = "EXAMPLE_FEATURES" }

如果 provider 需要 Codex 从外部 credential helper 里获取 bearer token,用命令认证:

[model_providers.proxy]
name = "OpenAI using LLM proxy"
base_url = "https://proxy.example.com/v1"
wire_api = "responses"

[model_providers.proxy.auth]
command = "/usr/local/bin/fetch-codex-token"
args = ["--audience", "codex"]
timeout_ms = 5000
refresh_interval_ms = 300000

认证命令不会收到 stdin,必须把 token 打到 stdout。Codex 会去掉前后空白,把空 token 视为错误,并在 refresh_interval_ms 到期前主动刷新;把 refresh_interval_ms = 0 设为只在认证重试后刷新。[model_providers.<id>.auth] 不能和 env_keyexperimental_bearer_tokenrequires_openai_auth 一起用。

Amazon Bedrock provider

Codex 内置了 amazon-bedrock model provider。直接把它设为 model_provider 即可;和自定义 provider 不同,这个内置 provider 只支持嵌套的 AWS profile 和 region 覆盖。

model_provider = "amazon-bedrock"
model = "<bedrock-model-id>"

[model_providers.amazon-bedrock.aws]
profile = "default"
region = "eu-central-1"

如果省略 profile,Codex 会使用标准 AWS credential chain。region 要设置为处理请求的、受支持的 Bedrock region。

OSS mode(local providers)

当你传入 --oss 时,Codex 可以连接本地的 “open source” provider,例如 Ollama 或 LM Studio。如果传了 --oss 但没指定 provider,Codex 会把 oss_provider 作为默认值。

# 与 `--oss` 搭配使用的默认本地 provider
oss_provider = "ollama" # 或 "lmstudio"

Azure provider 和每个 provider 的调优

[model_providers.azure]
name = "Azure"
base_url = "https://YOUR_PROJECT_NAME.openai.azure.com/openai"
env_key = "AZURE_OPENAI_API_KEY"
query_params = { api-version = "2025-04-01-preview" }
wire_api = "responses"
request_max_retries = 4
stream_max_retries = 10
stream_idle_timeout_ms = 300000

要改内置 OpenAI provider 的 base URL,使用 openai_base_url,不要创建 [model_providers.openai],因为内置 provider ID 不能覆盖。

使用 data residency 的 ChatGPT 用户

启用了 data residency 的项目,可以创建一个 model provider,用正确的前缀更新 base_url

model_provider = "openaidr"
[model_providers.openaidr]
name = "OpenAI Data Residency"
base_url = "https://us.api.openai.com/v1" # 把 'us' 换成对应的域名前缀

模型推理、详细程度和限制

model_reasoning_summary = "none"          # 禁用摘要
model_verbosity = "low"                   # 缩短回复
model_supports_reasoning_summaries = true # 强制推理
model_context_window = 128000             # 上下文窗口大小

model_verbosity 只作用于使用 Responses API 的 provider。Chat Completions provider 会忽略这个设置。

审批策略和沙箱模式

选择审批严格度(影响 Codex 何时暂停)和 sandbox 级别(影响文件和网络访问)。

编辑 config.toml 时要记住这些运行细节,见 Common sandbox and approval combinationsProtected paths in writable rootsNetwork access

如果要看把文件系统和网络访问一起配置的 beta permission profile,见 Permissions

你也可以使用更细粒度的审批策略(approval_policy = { granular = { ... } }),允许或自动拒绝单独的 prompt category。这个配置适合大多数情况仍保留交互式审批,但让某些类别,例如 request_permissions 或 skill-script prompts,自动 fail closed。

approvals_reviewer = "auto_review" 设为让符合条件的交互式审批请求走自动审核。这改变的是 reviewer,不是 sandbox 边界。

[auto_review].policy 用来写本地 reviewer policy 指令。Managed 的 guardian_policy_config 优先级更高。

approval_policy = "untrusted"   # 其他选项:on-request、never,或 { granular = { ... } }
approvals_reviewer = "user"     # 或 "auto_review" 走自动审核
sandbox_mode = "workspace-write"
allow_login_shell = false       # 可选加固:禁止 shell tools 使用 login shell

# 细粒度审批策略示例:
# approval_policy = { granular = {
#   sandbox_approval = true,
#   rules = true,
#   mcp_elicitations = true,
#   request_permissions = false,
#   skill_approval = false
# } }

[sandbox_workspace_write]
exclude_tmpdir_env_var = false  # 允许 $TMPDIR
exclude_slash_tmp = false       # 允许 /tmp
writable_roots = ["/Users/YOU/.pyenv/shims"]
network_access = false          # 显式开启出站网络

[auto_review]
policy = """
Use your organization's automatic review policy.
"""

命名 permission profiles

内置 profiles、自定义 profile 语法、完整的文件系统和网络配置模型,见 Permissions

完整 key 列表,包括 profile 级覆盖和 requirements 约束,见 Configuration ReferenceManaged configuration

workspace-write 模式下,有些环境会把 .git/.codex/ 保持为只读,即使工作区其余部分可写也是如此。这也是为什么像 git commit 这样的命令,仍可能需要在 sandbox 外审批。如果你想让 Codex 跳过特定命令,例如阻止 git commit 在 sandbox 外运行,请使用 rules

完全关闭 sandbox(仅在你的环境本身已经隔离进程时使用):

sandbox_mode = "danger-full-access"

Shell 环境变量策略

shell_environment_policy 控制 Codex 启动子进程时传递哪些环境变量,例如模型提出的 tool-command。建议从干净环境开始(inherit = "none")或精简环境开始(inherit = "core"),再通过 excludes、includes 和 overrides 补齐路径、key 或 flags,同时避免泄露 secrets。

[shell_environment_policy]
inherit = "none"
set = { PATH = "/usr/bin", MY_FLAG = "1" }
ignore_default_excludes = false
exclude = ["AWS_*", "AZURE_*"]
include_only = ["PATH", "HOME"]

模式匹配是大小写不敏感的 glob(*?[A-Z]);ignore_default_excludes = false 会先保留默认的 KEY/SECRET/TOKEN 过滤,再应用你的 includes/excludes。

MCP servers

配置细节见专门的 MCP documentation

可观测性和遥测

启用 OpenTelemetry(OTel)日志导出,用来追踪 Codex 运行过程中的 API requests、SSE/events、prompts、tool approvals/results。默认关闭;通过 [otel] 显式启用:

[otel]
environment = "staging"   # 默认是 "dev"
exporter = "none"         # 设为 otlp-http 或 otlp-grpc 才会发送事件
log_user_prompt = false   # 除非明确开启,否则会脱敏用户 prompt

选择 exporter:

[otel]
exporter = { otlp-http = {
  endpoint = "https://otel.example.com/v1/logs",
  protocol = "binary",
  headers = { "x-otlp-api-key" = "${OTLP_TOKEN}" }
}}
[otel]
exporter = { otlp-grpc = {
  endpoint = "https://otel.example.com:4317",
  headers = { "x-otlp-meta" = "abc123" }
}}

如果 exporter = "none",Codex 仍会记录事件,但不会发出去。exporter 会异步批量发送,并在退出时 flush。事件元数据包含 service name、CLI version、env tag、conversation id、model、sandbox/approval 设置,以及每个事件自己的字段(见 Config Reference)。

会发出什么事件

Codex 会为运行和工具使用发出结构化日志事件。常见事件类型包括:

  • codex.conversation_starts(model、reasoning settings、sandbox/approval policy)
  • codex.api_request(attempt、status/success、duration、error details)
  • codex.sse_event(stream event kind、success/failure、duration,response.completed 还包含 token counts)
  • codex.websocket_requestcodex.websocket_event(request duration,以及每条消息的 kind/success/error)
  • codex.user_prompt(长度;除非明确开启,否则内容会脱敏)
  • codex.tool_decision(approved/denied,以及决策来自 config 还是 user)
  • codex.tool_result(duration、success、output snippet)

OTel 指标

启用 OTel metrics pipeline 时,Codex 会为 API、stream 和 tool activity 发出 counters 和 duration histograms。

每个指标都包含默认元数据标签:auth_modeoriginatorsession_sourcemodelapp.version

Metric Type Fields Description
codex.api_request counter status, success API request count by HTTP status and success/failure.
codex.api_request.duration_ms histogram status, success API request duration in milliseconds.
codex.sse_event counter kind, success SSE event count by event kind and success/failure.
codex.sse_event.duration_ms histogram kind, success SSE event processing duration in milliseconds.
codex.websocket.request counter success WebSocket request count by success/failure.
codex.websocket.request.duration_ms histogram success WebSocket request duration in milliseconds.
codex.websocket.event counter kind, success WebSocket message/event count by type and success/failure.
codex.websocket.event.duration_ms histogram kind, success WebSocket message/event processing duration in milliseconds.
codex.tool.call counter tool, success Tool invocation count by tool name and success/failure.
codex.tool.call.duration_ms histogram tool, success Tool execution duration in milliseconds by tool name and outcome.

更多安全和隐私建议见 Security

Metrics

默认情况下,Codex 会定期向 OpenAI 发送少量匿名使用和健康数据。这用于发现 Codex 什么时候没有正常工作,以及哪些功能和配置选项被使用,帮助 Codex 团队优先处理最重要的问题。这些 metrics 不包含任何 PII。Metrics collection 和 OTel log/trace export 相互独立。

如果想在一台机器上对所有 Codex surface 完全关闭 metrics collection,在配置里设置 analytics flag:

[analytics]
enabled = false

每个 metric 都会包含自己的字段,以及下面这些默认上下文字段。

默认上下文字段(适用于每个 event/metric)

  • auth_mode: swic | api | unknown
  • model: 使用的模型名
  • app.version: Codex 版本

Metrics catalog

每个 metric 都包含所需字段和上面的默认上下文字段。下面的 metric 名称省略了 codex. 前缀。 大部分 metric 名称集中在 codex-rs/otel/src/metrics/names.rs;文件外发出的特定功能 metrics 也列在这里。 如果 metric 包含 tool 字段,表示的是内部使用的 tool(例如 apply_patchshell),不会包含 codex 正在尝试执行的实际 shell command 或 patch。

Runtime and model transport

Metric Type Fields Description
api_request counter status, success API request count by HTTP status and success/failure.
api_request.duration_ms histogram status, success API request duration in milliseconds.
sse_event counter kind, success SSE event count by event kind and success/failure.
sse_event.duration_ms histogram kind, success SSE event processing duration in milliseconds.
websocket.request counter success WebSocket request count by success/failure.
websocket.request.duration_ms histogram success WebSocket request duration in milliseconds.
websocket.event counter kind, success WebSocket message/event count by type and success/failure.
websocket.event.duration_ms histogram kind, success WebSocket message/event processing duration in milliseconds.
responses_api_overhead.duration_ms histogram Responses API overhead timing from WebSocket responses.
responses_api_inference_time.duration_ms histogram Responses API inference timing from WebSocket responses.
responses_api_engine_iapi_ttft.duration_ms histogram Responses API engine IAPI time-to-first-token timing.
responses_api_engine_service_ttft.duration_ms histogram Responses API engine service time-to-first-token timing.
responses_api_engine_iapi_tbt.duration_ms histogram Responses API engine IAPI time-between-token timing.
responses_api_engine_service_tbt.duration_ms histogram Responses API engine service time-between-token timing.
transport.fallback_to_http counter from_wire_api WebSocket-to-HTTP fallback count.
remote_models.fetch_update.duration_ms histogram Time to fetch remote model definitions.
remote_models.load_cache.duration_ms histogram Time to load the remote model cache.
startup_prewarm.duration_ms histogram status Startup prewarm duration by outcome.
startup_prewarm.age_at_first_turn_ms histogram status Startup prewarm age when the first real turn resolves it.
cloud_requirements.fetch.duration_ms histogram Workspace-managed cloud requirements fetch duration.
cloud_requirements.fetch_attempt counter See note Workspace-managed cloud requirements fetch attempts.
cloud_requirements.fetch_final counter See note Final workspace-managed cloud requirements fetch outcome.
cloud_requirements.load counter trigger, outcome Workspace-managed cloud requirements load outcome.

The cloud_requirements.fetch_attempt metric includes trigger, attempt, outcome, and status_code fields. The cloud_requirements.fetch_final metric includes trigger, outcome, reason, attempt_count, and status_code fields.

Turn and tool activity

Metric Type Fields Description
turn.e2e_duration_ms histogram End-to-end time for a full turn.
turn.ttft.duration_ms histogram Time to first token for a turn.
turn.ttfm.duration_ms histogram Time to first model output item for a turn.
turn.network_proxy counter active, tmp_mem_enabled Whether the managed network proxy was active for the turn.
turn.memory counter read_allowed, feature_enabled, config_use_memories, has_citations Per-turn memory read availability and memory citation usage.
turn.tool.call histogram tmp_mem_enabled Number of tool calls in the turn.
turn.token_usage histogram token_type, tmp_mem_enabled Per-turn token usage by token type (total, input, cached_input, output, or reasoning_output).
tool.call counter tool, success Tool invocation count by tool name and success/failure.
tool.call.duration_ms histogram tool, success Tool execution duration in milliseconds by tool name and outcome.
tool.unified_exec counter tty Unified exec tool calls by TTY mode.
approval.requested counter tool, approved Tool approval request result (approved, approved_with_amendment, approved_for_session, denied, abort).
mcp.call counter See note MCP tool invocation result.
mcp.call.duration_ms histogram See note MCP tool invocation duration.
mcp.tools.list.duration_ms histogram cache MCP tool-list duration, including cache hit/miss state.
mcp.tools.fetch_uncached.duration_ms histogram Duration of MCP tool fetches that miss the cache.
mcp.tools.cache_write.duration_ms histogram Duration of Codex Apps MCP tool-cache writes.
hooks.run counter hook_name, source, status Hook run count by hook name, source, and status.
hooks.run.duration_ms histogram hook_name, source, status Hook run duration in milliseconds.

The mcp.call and mcp.call.duration_ms metrics include status; normal tool-call emissions also include tool, plus connector_id and connector_name when available. Blocked Codex Apps MCP calls may emit mcp.call with only status.

Threads, tasks, and features

Metric Type Fields Description
feature.state counter feature, value Feature values that differ from defaults (emit one row per non-default).
status_line counter Session started with a configured status line.
model_warning counter Warning sent to the model.
thread.started counter is_git New thread created, tagged by whether the working directory is in a Git repo.
conversation.turn.count counter User/assistant turns per thread, recorded at the end of the thread.
thread.fork counter source New thread created by forking an existing thread.
thread.rename counter Thread renamed.
thread.side counter source Side conversation created.
thread.skills.enabled_total histogram Number of skills enabled for a new thread.
thread.skills.kept_total histogram Number of enabled skills kept after prompt rendering.
thread.skills.truncated histogram Whether skill rendering truncated the enabled skills list (1 or 0).
task.compact counter type Number of compactions per type (remote or local), including manual and auto.
task.review counter Number of reviews triggered.
task.undo counter Number of undo actions triggered.
task.user_shell counter Number of user shell actions (! in the TUI for example).
shell_snapshot counter See note Whether taking a shell snapshot succeeded.
shell_snapshot.duration_ms histogram success Time to take a shell snapshot.
skill.injected counter status, skill Skill injection outcomes by skill.
plugins.startup_sync counter transport, status Curated plugin startup sync attempts.
plugins.startup_sync.final counter transport, status Final curated plugin startup sync outcome.
multi_agent.spawn counter role Agent spawns by role.
multi_agent.resume counter Agent resumes.
multi_agent.nickname_pool_reset counter Agent nickname pool resets.

The shell_snapshot metric includes success and, on failures, failure_reason.

Memory and local state

Metric Type Fields Description
memory.phase1 counter status Memory phase 1 job counts by status.
memory.phase1.e2e_ms histogram End-to-end duration for memory phase 1.
memory.phase1.output counter Memory phase 1 outputs written.
memory.phase1.token_usage histogram token_type Memory phase 1 token usage by token type.
memory.phase2 counter status Memory phase 2 job counts by status.
memory.phase2.e2e_ms histogram End-to-end duration for memory phase 2.
memory.phase2.input counter Memory phase 2 input count.
memory.phase2.token_usage histogram token_type Memory phase 2 token usage by token type.
memories.usage counter kind, tool, success Memory usage by kind, tool, and success/failure.
external_agent_config.detect counter See note External agent config detections by migration item type.
external_agent_config.import counter See note External agent config imports by migration item type.
db.backfill counter status Initial state DB backfill results (upserted, failed).
db.backfill.duration_ms histogram status Duration of the initial state DB backfill.
db.error counter stage Errors during state DB operations.

The external_agent_config.detect and external_agent_config.import metrics include migration_type; skills migrations also include skills_count.

Windows sandbox

Metric Type Fields Description
windows_sandbox.setup_success counter originator, mode Windows sandbox setup successes.
windows_sandbox.setup_failure counter originator, mode Windows sandbox setup failures.
windows_sandbox.setup_duration_ms histogram result, originator, mode Windows sandbox setup duration.
windows_sandbox.elevated_setup_success counter Elevated Windows sandbox setup successes.
windows_sandbox.elevated_setup_failure counter See note Elevated Windows sandbox setup failures.
windows_sandbox.elevated_setup_canceled counter See note Canceled elevated Windows sandbox setup attempts.
windows_sandbox.elevated_setup_duration_ms histogram result Elevated Windows sandbox setup duration.
windows_sandbox.elevated_prompt_shown counter Elevated sandbox setup prompt shown.
windows_sandbox.elevated_prompt_accept counter Elevated sandbox setup prompt accepted.
windows_sandbox.elevated_prompt_use_legacy counter User chose legacy sandbox from the elevated prompt.
windows_sandbox.elevated_prompt_quit counter User quit from the elevated prompt.
windows_sandbox.fallback_prompt_shown counter Fallback sandbox prompt shown.
windows_sandbox.fallback_retry_elevated counter User retried elevated setup from the fallback prompt.
windows_sandbox.fallback_use_legacy counter User chose legacy sandbox from the fallback prompt.
windows_sandbox.fallback_prompt_quit counter User quit from the fallback prompt.
windows_sandbox.legacy_setup_preflight_failed counter See note Legacy Windows sandbox setup preflight failure.
windows_sandbox.setup_elevated_sandbox_command counter Elevated sandbox setup command invoked.
windows_sandbox.createprocessasuserw_failed counter error_code, path_kind, exe, level Windows CreateProcessAsUserW failures.

如果能拿到 Windows setup failure details,elevated setup failure metrics 会包含 codemessage;从共享 setup 路径发出时,还可能包含 originatorwindows_sandbox.legacy_setup_preflight_failed 从共享 setup 路径发出时会带 originator,但 fallback-prompt preflight failures 可能不带任何字段。

反馈控制

默认情况下,Codex 允许用户通过 /feedback 发送反馈。要在一台机器上关闭所有 Codex surface 的反馈收集,更新配置:

[feedback]
enabled = false

关闭后,/feedback 会显示禁用提示,Codex 也会拒绝提交反馈。

隐藏或显示 reasoning events

如果你想减少 noisy 的 “reasoning” 输出,比如在 CI logs 里,可以隐藏它:

hide_agent_reasoning = true

如果你希望模型输出原始 reasoning 内容,可以显示它:

show_raw_agent_reasoning = true

只有在你的工作流能接受时才启用原始 reasoning。某些模型/provider(例如 gpt-oss)不会输出原始 reasoning,这时这个设置不会产生可见效果。

通知

notify 可以在 Codex 发出支持的事件时调用外部程序,目前只有 agent-turn-complete。这适合桌面 toast、chat webhook、CI 更新,或任何内置 TUI 通知覆盖不到的旁路提醒。

notify = ["python3", "/path/to/notify.py"]

示例 notify.py(已截断),响应 agent-turn-complete

#!/usr/bin/env python3
import json, subprocess, sys

def main() -> int:
    notification = json.loads(sys.argv[1])
    if notification.get("type") != "agent-turn-complete":
        return 0
    title = f"Codex: {notification.get('last-assistant-message', 'Turn Complete!')}"
    message = " ".join(notification.get("input-messages", []))
    subprocess.check_output([
        "terminal-notifier",
        "-title", title,
        "-message", message,
        "-group", "codex-" + notification.get("thread-id", ""),
        "-activate", "com.googlecode.iterm2",
    ])
    return 0

if __name__ == "__main__":
    sys.exit(main())

脚本会收到一个 JSON 参数。常见字段包括:

  • type(当前为 agent-turn-complete
  • thread-id(会话标识)
  • turn-id(turn 标识)
  • cwd(工作目录)
  • input-messages(触发这次 turn 的用户消息)
  • last-assistant-message(最后一条 assistant 消息文本)

把脚本放到磁盘上的某个位置,然后把 notify 指向它。

notifytui.notifications 的区别

  • notify 会运行外部程序,适合 webhook、桌面通知器、CI hooks。
  • tui.notifications 是 TUI 内置功能,还可以按事件类型过滤,例如 agent-turn-completeapproval-requested
  • tui.notification_method 控制 TUI 怎么发终端通知(autoosc9bel)。
  • tui.notification_condition 控制通知只在终端 unfocused 时触发,还是 always 触发。

auto 模式下,Codex 优先使用 OSC 9 notifications(某些终端会把它解释为桌面通知),否则回退到 BEL(\x07)。

精确 key 见 Configuration Reference

历史记录持久化

默认情况下,Codex 会把本地会话 transcript 存到 CODEX_HOME 下,例如 ~/.codex/history.jsonl。要关闭本地历史记录持久化:

[history]
persistence = "none"

要限制历史文件大小,设置 history.max_bytes。文件超过上限时,Codex 会丢弃最旧条目并压缩文件,同时保留最新记录。

[history]
max_bytes = 104857600 # 100 MiB

可点击引用

如果你使用的终端或编辑器集成支持,Codex 可以把文件引用渲染成可点击链接。配置 file_opener 可以指定 Codex 使用的 URI scheme:

file_opener = "vscode" # or cursor, windsurf, vscode-insiders, none

例如,/home/user/project/main.py:42 这样的引用可以被改写成可点击的 vscode://file/...:42 链接。

项目指令发现

Codex 会读取 AGENTS.md 和相关文件,并在会话第一轮里带入有限量的项目指导。这里有两个控制项:

  • project_doc_max_bytes:每个 AGENTS.md 文件最多读取多少内容
  • project_doc_fallback_filenames:当某一级目录没有 AGENTS.md 时,额外尝试哪些文件名

详细流程见 Custom instructions with AGENTS.md

TUI 选项

不带子命令直接运行 codex 会打开交互式 terminal UI(TUI)。Codex 在 [tui] 下提供一些专用于 TUI 的配置,包括:

  • tui.notifications:启用/禁用通知,或限制为特定类型
  • tui.notification_method:选择 autoosc9bel
  • tui.notification_condition:选择 unfocusedalways
  • tui.animations:启用/禁用 ASCII 动画和 shimmer 效果
  • tui.alternate_screen:控制是否使用 alternate screen(设为 never 可保留终端滚动缓冲)
  • tui.show_tooltips:控制欢迎页上的 onboarding tooltips 显示或隐藏

tui.notification_method 默认是 auto。在 auto 模式下,Codex 会优先使用 OSC 9 notifications;如果终端似乎不支持,就回退到 BEL(\x07)。

完整 key 列表见 Configuration Reference

常见问题

OpenAI Codex 怎么切换 Profiles

config.toml 里先定义 [profiles.<name>],运行时用 codex --profile <name> 切换。要设默认值,就在顶层写 profile = "<name>"。Profiles 目前是实验性功能,而且 IDE extension 暂不支持。

OpenAI Codex 怎么接入自定义 model provider

config.toml 里定义 [model_providers.<id>],再把 model_provider 指向这个 id。需要代理认证时,可以用 [model_providers.<id>.auth] 的命令认证;如果只是改内置 OpenAI provider 的 base URL,直接用 openai_base_url

Codex 的 OTel 遥测会记录用户 prompt 吗

默认不会。[otel] 里的 log_user_prompt 默认是 false,只有你明确开启才会记录 prompt 内容。其他遥测数据仍会包含请求、事件、工具调用和耗时等结构化字段。