Delegate tasks to an independent Codex session via Codex CLI.
The default entry point for Codex CLI is codex(interactive REPL). Automated calls go through codex exec(headless subcommand), printing the final result or event stream to stdout. To get parseable output, add --json; to continue a historical session, use codex exec resume。
Prerequisites
- Install Codex CLI:
npm install -g @openai/codex - Make sure Codex login authentication is complete (
codexwill guide you through login on first run) - It is recommended to run in the target project directory, or explicitly pass
-C /path/to/project
Invocation methods
New session (default)
codex exec --json --sandbox workspace-write --skip-git-repo-check --model <flagship> "你的任务描述"
The above only suitsshort prompts. When the prompt exceeds about 500 characters or contains multiple lines/special characters, do not keep using positional arguments; using stdin is more reliable.
Output is JSONL, one event per line. Current common events:
{"type":"thread.started","thread_id":"019d32fc-..."}
{"type":"turn.started"}
{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"回复内容"}}
{"type":"turn.completed","usage":{"input_tokens":46879,"cached_input_tokens":2432,"output_tokens":54}}
- From the
thread.startedevent, extractthread_id, for subsequent multi-turn conversations - From the
item.completedevent (item.type == "agent_message"), extracttextas Codex's reply - From
turn.completed, extractusage, to record token usage
Automation scripts should only parse JSON lines. If your runtime environment merges stderr 's warning and stdout , first filter out JSON lines starting with { , or redirect away stderr .
Use stdin pipe for long prompts
When the prompt exceeds about 500 characters or contains multiple lines/special characters, do not keep using positional arguments. In practice, such input may get stuck at Reading additional input from stdin..., and even manually closing stdin is unstable. It is recommended to write the prompt directly to a file, then let codex exec read from stdin using - :
codex exec --json --sandbox workspace-write --full-auto --model <flagship> \
--skip-git-repo-check - < /tmp/task-prompt.txt > /tmp/task-out.jsonl 2>&1
Positional arguments are still suitable for short prompts, such as one-sentence Q&A, very short follow-up questions, or temporary command-line experiments.
Continue a specified session
codex exec resume --json --model <flagship> "thread_id" "后续提问"
Continue the most recent session (shortcut)
codex exec resume --json --model <flagship> --last "后续提问"
--lastby default only looks at the most recently recorded session in the current directory- When you need to search across directories, add
--all
⚠️ --ephemeral: session cannot be recovered
After adding --ephemeral , this sessionwill not be written to disk(not persisted to ~/.codex/sessions/), so afterwardit cannot be codex exec resume or --last recovered. Use it only in the following scenarios:
- One-off quick Q&A, where you are sure there will be no follow-up
- Temporary calls in CI / scripts, to avoid polluting the session list
- Sensitive tasks, where you do not want to leave local records
As long as follow-up questions may be needed later, do not add --ephemeral。 and claude -p --no-session-persistence are semantically equivalent.
codex exec parameters
Output and results
| Flag | Description |
|---|---|
--json |
JSONL format output, convenient for parsing event streams |
--output-schema FILE |
Use JSON Schema to constrain the structure of the last message |
-o, --output-last-message FILE |
Write the last message directly to a file |
--color COLOR |
Color output:always / never / auto |
Runtime environment
| Flag | Description |
|---|---|
-s, --sandbox MODE |
Sandbox mode:read-only / workspace-write / danger-full-access |
--full-auto |
Currently equivalent to --sandbox workspace-write convenience shorthand |
--dangerously-bypass-approvals-and-sandbox |
Skip all confirmations and sandboxing, extremely dangerous |
-C, --cd DIR |
Specify working directory |
--skip-git-repo-check |
Allow running in a non-git directory |
--add-dir DIR |
Extra writable directories (repeatable) |
Model and configuration
| Flag | Description |
|---|---|
-m, --model MODEL |
Specify model, recommended to pass explicitly |
-p, --profile PROFILE |
Use config.toml profile in |
-c, --config key=value |
Override config.toml configuration item |
--enable FEATURE |
Enable feature flag (repeatable) |
--disable FEATURE |
Disable feature flag (repeatable) |
--oss |
Use local open-source model provider |
--local-provider PROVIDER |
Specify local provider (e.g. lmstudio / ollama) |
Input
| Flag / Method | Description |
|---|---|
-i, --image FILE |
Attach image (repeatable) |
PROMPT |
Pass a short task directly as a command-line argument; recommended only for short prompts |
- or stdin |
Do not pass a prompt, or write the prompt as -, to read from stdin; prefer this method for long prompts, Markdown, and multiline structures |
codex exec resume parameters
| Flag | Description |
|---|---|
--json |
JSONL format output |
-m, --model MODEL |
Specify model |
--full-auto |
Convenience shorthand, equivalent to workspace-write sandbox |
--dangerously-bypass-approvals-and-sandbox |
Skip confirmations and sandboxing |
--skip-git-repo-check |
Allow non-git directories |
--ephemeral |
Do not persist |
-i, --image FILE |
Attach image |
-o, --output-last-message FILE |
Write last message to file |
-c, --config key=value |
Override config.toml configuration item |
--enable FEATURE |
Enable feature (repeatable) |
--disable FEATURE |
Disable feature (repeatable) |
--last |
Resume the most recent session (no ID needed) |
--all |
Find all sessions (not limited to current directory) |
codex exec review parameters
Built-in code review subcommand, performs a review on the current repository:
codex exec review [OPTIONS] [PROMPT]
| Flag | Description |
|---|---|
--uncommitted |
Review staged, unstaged, and untracked changes |
--base BRANCH |
Compare against a specified base branch |
--commit SHA |
Review the changes introduced by a specified commit |
--title TITLE |
Title displayed in the review summary |
-m, --model MODEL |
Specify model |
--json |
JSONL format output |
--full-auto |
Convenience shorthand, equivalent to workspace-write sandbox |
--ephemeral |
Do not persist |
-o, --output-last-message FILE |
Write last message to file |
Multi-turn conversation
- First
codex exec --json ...obtainthread_id - For follow-ups use
codex exec resume --json "thread_id" "prompt" - Automatically track
thread_id, no need for the user to worry about it - Create new sessions for different tasks, multiple
thread_iddo not interfere with each other
Model selection
Choose a model tier based on task complexity:
| Task complexity | model | Applicable scenarios |
|---|---|---|
| High | <flagship> |
Architecture design, complex refactoring, multi-file coding |
| Medium/Low | <mini> |
Single-file feature implementation, bug fixes, Q&A and code explanation |
In the documentation
<flagship>/<mini>is a placeholder, not a real model ID. For the specific ID, query viacodex --helpor the OpenAI announcement, and it is recommended to lock it once in the~/.codex/config.tomlprofile to avoid hardcoding the version number everywhere in commands.
Recommended parameter combinations
| Scenario | model | sandbox | Other flags |
|---|---|---|---|
| Complex coding | <flagship> |
workspace-write |
--full-auto |
| General coding | <mini> |
workspace-write |
--full-auto |
| Read-only Q&A / analysis | <mini> |
read-only |
--skip-git-repo-check(when not in a git directory) |
| Browser research / Computer Use | <flagship> |
read-only |
-C "$PWD" -o /tmp/result.txt, and add --json |
| Code review | <mini> |
read-only |
codex exec --json ... "Review ..." |
| Repository review | <mini> |
— | codex exec review --base main |
| Quick Q&A | <mini> |
read-only |
--skip-git-repo-check --ephemeral(⚠️ irreversible) |
| Structured output | <mini> |
read-only |
--output-schema schema.json -o result.json |
Usage rules
- Always add for automated calls
--json: ensure the output is parseable, extractthread_idand the reply content - It is recommended to explicitly pass
--model, or lock it in the~/.codex/config.tomlprofile: avoid default model drift between different commands; do not hardcode the specific version number in every command - Always run in the target project directory: prefer
cd /path/to/projector-C /path/to/project - For coding tasks use
workspace-write: usually just use--sandbox workspace-writeor--full-auto - For review tasks use
read-onlyorcodex exec review: prevent accidental modifications - Keep the conversation continuous: reuse for follow-ups on the same task
thread_id;As long as follow-ups are possible, do not add--ephemeral - When stable downstream parsing is needed, use
--output-schema+-o: constrain the final result into a machine-consumable structure - Use stdin piping for long prompts: when the prompt exceeds about 500 characters or contains multiple lines/special characters, do not keep using positional arguments; first write it to a file, then pass it in with
- < file.txtto avoid getting stuck atReading additional input from stdin... - Report results to the user: after each call, extract the final reply from the JSONL and briefly summarize it for the user
- Distinguish between
-oand--jsonresponsibilities:-ois responsible for writing the last reply to a file;--jsonis responsible for printing the entire event stream to stdout. A common combination in scripts is to use both together. - For non-coding local browser tasks, prefer
read-only: if you are just having Codex use Computer Use to open Chrome, browse web pages, and summarize content, you do not need--full-auto; add one more line in the promptDo not modify local files.as a double safeguard.
Prompt References
Load the corresponding reference as needed based on the task type; do not stuff all default prompts into the main context at once:
- Coding / diagnosis / planning / narrow fixes: read references/task-prompt-recipes.md
- Code review / adversarial review / test gap checks: read references/review-prompt-recipes.md
- Local browser research / Reddit or community sampling / evidence-based summaries: read references/browser-research-prompt-recipes.md
These references provide default prompt templates that can be reused directly or with slight modifications; prefer copying the closest template, then delete the blocks you do not need.
Examples
Coding task
用户:用 Codex 在当前项目里实现一个 TODO API
步骤 1 - 新建会话:
cd /path/to/project && codex exec --json --full-auto --model <flagship> "Implement a REST API for TODO items with CRUD endpoints. Use Express.js."
→ 解析输出,获得 thread_id: "xxx",回复: "Implemented server.js ..."
用户:加上单元测试
步骤 2 - 继续会话:
cd /path/to/project && codex exec resume --json --model <mini> "xxx" "Add unit tests for all the TODO API endpoints using vitest."
Continue the most recent session
cd /path/to/project && codex exec resume --json --model <mini> --last "Continue the refactor and remove the dead helper functions."
Suitable for scenarios like "continue the task from just now" where you do not want to manually save thread_id .
Code review
# 通用只读审查
cd /path/to/project && codex exec --json --sandbox read-only --model <mini> "Review the changes in git diff HEAD~1. Focus on correctness, security, and missing tests."
# 内置 review:对比 main
cd /path/to/project && codex exec review --json --model <mini> --base main
# 审查未提交变更
cd /path/to/project && codex exec review --json --model <mini> --uncommitted
Structured output written to a file
cd /path/to/project && codex exec --json --sandbox read-only --model <mini> \
--output-schema ./review-schema.json \
-o /tmp/review-result.json \
"Review src/todo.ts and output summary, risks, and suggested tests."
Suitable for scenarios where the results need to be fed to scripts, CI, or other agents.
Local browser research (final answer only)
codex exec \
-m <flagship> \
--sandbox read-only \
--skip-git-repo-check \
-C "$PWD" \
-o /tmp/codex-last.txt \
"Use Computer Use on my Mac. Open Google Chrome, go to Reddit, search for 'Duolingo review', open 3 representative posts (one positive, one negative, one long-term review), then summarize the findings in Chinese. Do not modify local files."
Suitable for scenarios where a human reviews the final conclusion and does not care about the intermediate event stream.
Local browser research (both the event stream and the final answer written to disk)
codex exec \
-m <flagship> \
--sandbox read-only \
--skip-git-repo-check \
-C "$PWD" \
--json \
-o /tmp/codex-last.txt \
"Use Computer Use on my Mac. Open Google Chrome, search Reddit for Duolingo reviews, open a few representative posts, and then summarize them in Chinese. Do not modify local files."
Suitable for scripts or higher-level agents: read the JSONL event stream from stdout,/tmp/codex-last.txt read the final natural-language conclusion.
Image input
cd /path/to/project && codex exec --json --sandbox read-only --model <mini> \
-i ./screenshots/login-bug.png \
"Describe the UI issue in this screenshot and propose a minimal fix plan."
Suitable for visual regression, error screenshot diagnosis, and design mockup difference analysis.
Long-task prompt (recommended)
# 1. 把复杂 prompt 写进文件
cat > /tmp/task-prompt.txt <<'PROMPT_EOF'
请在当前仓库完成以下任务:
1. 先阅读 README 和 tests
2. 只修改与 issue 直接相关的文件
3. 先补测试,再改实现,最后运行验证
PROMPT_EOF
# 2. 用 - 从 stdin 读取,避免长位置参数卡住
codex exec --json --sandbox workspace-write --full-auto --model <flagship> \
--skip-git-repo-check - < /tmp/task-prompt.txt > /tmp/task-out.jsonl 2>&1
Suitable for market research, multi-paragraph Markdown constraints, script-assembled prompts, or any task description that already exceeds one screen.
Pass a long prompt via stdin
cat ./prompt.md | codex exec --json --sandbox workspace-write --model <flagship> -
Suitable for long prompts, templated prompts, or dynamically assembled instructions in scripts piped directly to Codex. If reused long-term in a shell script, prefer the - < file.txt approach from the previous section, which is more readable and easier to troubleshoot.