Codex Agent Skill
Operate Codex CLI as a managed coding agent — from worktree setup through PR merge.
Prerequisites
CODEBLOCK0
CLI Quick Reference
| Flag | Effect |
|---|
| INLINECODE0 | Non-interactive one-shot, exits when done |
| INLINECODE1 |
Alias for
-s workspace-write (auto-approve file edits) |
|
-s workspace-write | Read + write files in workspace |
|
-s read-only | Analysis only, no modifications (default for
exec) |
|
-s danger-full-access | Full access including network and system |
|
--dangerously-bypass-approvals-and-sandbox | Skip all prompts + no sandbox (safe in containers/VMs) |
|
-m <model> | Model selection — only use when user explicitly requests a model (e.g.
gpt-5.1-codex-max). Omit to use Codex default. |
|
-c "model_reasoning_effort=high" | Reasoning effort:
low,
medium,
high |
|
--json | Structured JSON Lines output |
|
-o <file> | Write final output to file |
|
-C <dir> /
--cd <dir> | Set working directory |
|
--add-dir <dir> | Allow writing to additional directories |
|
--skip-git-repo-check | Run in non-git directories |
|
resume --last | Resume last session with new prompt |
Execution Modes
Quick Mode — Small Tasks
For trivial fixes, one-file changes, or analysis. Use exec (non-interactive):
CODEBLOCK1
Adaptive Timeout (Poll-and-Extend)
Do NOT use timeout= for codex tasks. Instead, use background execution
with periodic polling. This prevents premature kills on long-running tasks:
- 1. Launch with
background=true (no timeout) - Poll every ~5 min with INLINECODE25
- If process is still running → it's making progress, keep waiting
- If process exited → check logs, done
- Safety net: if no new output for 12 hours, ask user before killing
CODEBLOCK2
This way tasks that need 5 min or several hours both work without premature kills.
Quick Mode caveats:
- - Session output is held in memory only — lost on OpenClaw restart (no disk persistence).
For truly critical tasks, prefer Full Mode (tmux + log file).
- - In-memory output is capped by
PI_BASH_MAX_OUTPUT_CHARS. Very verbose codex tasks may
lose early output from
process log. Use
process log offset:0 limit:50 to check if
the beginning is still available; if not, the cap was hit.
- -
process is scoped per agent — you can only see sessions you started.
Full Mode — Features, Bugfixes, Refactors
For non-trivial tasks, use the full workflow below. This gives you:
- - Isolated worktree — no conflicts with other work
- tmux session — mid-task steering without killing the agent
- Task tracking — know what's running at all times
- Quality gates — Definition of Done checklist
- Smart retries — don't waste tokens on repeated failures
Full Workflow: Task → Merged PR
Step 1: Create Worktree
Isolate each task in its own worktree and branch:
CODEBLOCK3
Step 2: Launch Agent in tmux
Start Codex in interactive mode (no exec) so you can steer mid-task.
Important: Use tmux pipe-pane to log output — do NOT use | tee because it
turns stdout into a pipe, which breaks interactive mode (codex detects !isatty(stdout)
and may disable interactive features, breaking send-keys steering).
CODEBLOCK4
Why this order (session → pipe-pane → send-keys)?
- - No race condition — if you pass the command directly to
tmux new-session, output
produced before
pipe-pane attaches is lost from the log file
- - Exit code captured —
echo "CODEX_EXIT=$?" appends the exit code to the log,
so you can distinguish success from crash (otherwise tmux discards it on session close)
- - Line-buffered logging —
stdbuf -oL ensures tail -f $LOG_FILE works in real time
Why interactive mode (no exec)?
- - Allows mid-task steering via INLINECODE41
- Agent can be redirected without killing and restarting
- INLINECODE42 is safe in container/sandbox environments
Step 3: Register Task
Track all active tasks in a JSON registry:
CODEBLOCK5
Step 4: Monitor & Steer
CODEBLOCK6
Monitoring cadence: Check every 5–10 minutes, not every 30 seconds. Agents need time to work.
Step 5: Definition of Done
A PR is NOT ready for review until all checks pass:
CODEBLOCK7
Quick inline check:
CODEBLOCK8
Step 6: Multi-Model Code Review
Review with a different model than the one that wrote the code. Different models catch different issues:
CODEBLOCK9
Post review results to PR:
CODEBLOCK10
Update task registry:
CODEBLOCK11
Step 7: Notify
If you included the notify command in the agent prompt (Step 2), the agent self-notifies on completion.
Otherwise, notify after DoD passes:
CODEBLOCK12
Update task status:
CODEBLOCK13
Step 8: Cleanup
After PR is merged:
git worktree remove "$WORKTREE" 2>/dev/null
git branch -d "$BRANCH" 2>/dev/null
# Remove from registry
jq --arg id "$TASK_ID" '.tasks = [.tasks[] | select(.id != $id)]' \
"$TASKS_FILE" > /tmp/tasks.$$.json && mv /tmp/tasks.$$.json "$TASKS_FILE"
Smart Retry Strategy
When an agent fails, analyze the failure and adapt the prompt — don't just re-run blindly.
| Failure Type | Symptom | Retry Strategy |
|---|
| Context overflow | Agent loops, produces garbage, or stops mid-task | Narrow scope: "Focus only on files X, Y, Z" |
| Wrong direction |
Agent implements something unrelated to intent | Correct intent:
"Stop. Customer wanted X, not Y. Spec: ..." |
| Missing info | Agent makes wrong assumptions about architecture | Add context:
"Auth uses JWT, see src/auth/jwt.ts" |
| CI failure | Tests, lint, or typecheck fail after PR | Attach CI log:
"Fix these test failures: ..." |
| Build failure | Dependencies missing or incompatible | Pre-install deps before retry |
Max 3 retries. After that, escalate to human.
CODEBLOCK15
Parallel Execution
Run multiple agents simultaneously on different tasks:
CODEBLOCK16
Codex-Specific Features
Reasoning Effort
Control how much the model "thinks" before acting:
CODEBLOCK17
Sandbox Modes
| Mode | Use Case |
|---|
| INLINECODE43 | Code review, analysis, documentation |
| INLINECODE44 / INLINECODE45 |
Feature implementation, bug fixes, refactors |
|
danger-full-access | Installing dependencies, network access needed |
|
--dangerously-bypass-approvals-and-sandbox | Full auto in containers (recommended for tmux workflow) |
JSON Output
CODEBLOCK18
Resume Session
CODEBLOCK19
Best Practices
Prompt Quality
- - Include file paths: "The entry point is src/index.ts, config in src/config/"
- Include schemas/types: Paste relevant type definitions into the prompt
- Include test commands: "Verify with: npm test -- --grep auth"
- Include commit convention: "Use conventional commits: feat:, fix:, chore:"
- Include error logs: When retrying, always attach the failure output
Scope Management
- - One task per agent — don't ask for "refactor everything"
- Pre-install dependencies before launching the agent
- Be specific — "Add rate limiting to POST /api/users" not "improve the API"
- Use high reasoning effort for complex tasks, low for mechanical ones
When to Interrupt (Ask Human)
- - Destructive operations (drop tables, force push main)
- Security decisions (expose credentials, change auth)
- Ambiguous requirements with significant trade-offs
- All other decisions: proceed autonomously
Codex 代理技能
将 Codex CLI 作为托管编码代理进行操作——从工作树设置到 PR 合并。
前置条件
bash
codex --version # 验证是否已安装
安装: npm i -g @openai/codex 或 brew install codex
tmux -V # 完整工作流程需要 tmux
CLI 快速参考
| 标志 | 作用 |
|---|
| exec 提示 | 非交互式一次性执行,完成后退出 |
| --full-auto |
-s workspace-write 的别名(自动批准文件编辑) |
| -s workspace-write | 在工作区中读写文件 |
| -s read-only | 仅分析,不进行修改(exec 的默认值) |
| -s danger-full-access | 完全访问权限,包括网络和系统 |
| --dangerously-bypass-approvals-and-sandbox | 跳过所有提示 + 无沙箱(在容器/虚拟机中安全) |
| -m <模型> | 模型选择——仅在用户明确指定模型时使用(例如 gpt-5.1-codex-max)。省略则使用 Codex 默认值。 |
| -c model
reasoningeffort=high | 推理努力程度:low、medium、high |
| --json | 结构化 JSON Lines 输出 |
| -o <文件> | 将最终输出写入文件 |
| -C <目录> / --cd <目录> | 设置工作目录 |
| --add-dir <目录> | 允许写入额外目录 |
| --skip-git-repo-check | 在非 git 目录中运行 |
| resume --last | 使用新提示恢复上次会话 |
执行模式
快速模式 — 小任务
适用于琐碎修复、单文件更改或分析。使用 exec(非交互式):
bash
通过 OpenClaw exec — 使用 background=true + pty=true,无硬超时
pty=true 确保 codex CLI 正确刷新输出(无缓冲问题)
(硬超时会杀死进程;我们改为轮询并延长)
exec(command=codex exec --full-auto 修复 README.md 中的拼写错误,
workdir=/path/to/project, background=true, pty=true)
使用高推理努力程度
exec(command=codex exec -c model
reasoningeffort=high --full-auto 修复认证错误,
workdir=/path/to/project, background=true, pty=true)
自适应超时(轮询并延长)
不要对 codex 任务使用 timeout=。 相反,使用后台执行配合定期轮询。这可以防止长时间运行的任务被过早杀死:
- 1. 使用 background=true 启动(无 timeout)
- 每约 5 分钟使用 process(action=poll, sessionId=, timeout=300000) 轮询一次
- 如果进程仍在运行 → 表示正在推进,继续等待
- 如果进程已退出 → 检查日志,完成
- 安全网:如果连续 12 小时没有新输出,在杀死前询问用户
轮询循环(代理行为,非脚本):
poll_interval = 5 分钟(300000 毫秒)
maxsilentrounds = 144(= 12 小时无新输出 → 询问用户)
重复:
result = process(action=poll, sessionId=, timeout=300000)
如果 result.completed:
→ 检查退出码,读取日志,报告结果
→ 跳出循环
否则:
new_output = process(action=log, sessionId=, limit=20)
如果 new_output 自上次检查后发生变化:
silent_rounds = 0 # 仍在产生输出,继续
否则:
silent_rounds += 1
如果 silentrounds >= maxsilent_rounds:
→ 通知用户:Codex 已静默 12 小时,杀死还是继续等待?
→ 等待用户决定
这样,需要 5 分钟或数小时的任务都能正常工作,不会过早被杀死。
快速模式注意事项:
- - 会话输出仅保存在内存中——OpenClaw 重启后丢失(无磁盘持久化)。
对于真正关键的任务,优先使用完整模式(tmux + 日志文件)。
- - 内存中输出受 PIBASHMAXOUTPUTCHARS 限制。非常冗长的 codex 任务可能会
丢失 process log 的早期输出。使用 process log offset:0 limit:50 检查
开头是否仍然可用;如果不可用,说明已达到上限。
- - process 的作用域限定在每个代理内——你只能看到自己启动的会话。
完整模式 — 功能、错误修复、重构
对于非平凡任务,使用下面的完整工作流程。这为你提供:
- - 隔离的工作树 — 不会与其他工作冲突
- tmux 会话 — 无需杀死代理即可在任务中进行引导
- 任务跟踪 — 随时了解正在运行的内容
- 质量门 — 完成定义检查清单
- 智能重试 — 不在重复失败上浪费 token
完整工作流程:任务 → 合并的 PR
步骤 1:创建工作树
将每个任务隔离在自己的工作树和分支中:
bash
TASK_ID=feat-custom-templates
BRANCH=feat/$TASK_ID
REPO_ROOT=$(git rev-parse --show-toplevel)
WORKTREE=/tmp/worktrees/$TASK_ID
git worktree add -b $BRANCH $WORKTREE origin/main
cd $WORKTREE
安装依赖(根据你的技术栈调整)
pnpm install # 或:npm install / go mod tidy / pip install -r requirements.txt
步骤 2:在 tmux 中启动代理
以交互模式(无 exec)启动 Codex,以便在任务中进行引导。
重要: 使用 tmux pipe-pane 记录输出——不要使用 | tee,因为它
会将 stdout 转换为管道,这会破坏交互模式(codex 检测到 !isatty(stdout)
并可能禁用交互功能,破坏 send-keys 引导)。
bash
LOGFILE=/tmp/worktrees/$TASKID/codex-output.log
1. 创建会话(启动一个 shell — codex 尚未启动)
tmux new-session -d -s $TASK_ID -c $WORKTREE
2. 在启动 codex 之前附加日志记录 — 防止丢失早期输出
stdbuf -oL = 行缓冲写入,因此 tail -f 实时显示进度
(普通 cat 在写入文件时会缓冲,导致监控延迟)
tmux pipe-pane -t $TASK
ID -o stdbuf -oL cat >> $LOGFILE
3. 通过 send-keys 启动 codex — 从一开始就捕获所有输出
完成时退出码会追加到日志中,以便可靠检测状态
tmux send-keys -t $TASK_ID \
codex -c model
reasoningeffort=high \
--dangerously-bypass-approvals-and-sandbox \
在此处输入你的详细提示。
完全完成后:
- 1. 使用描述性消息提交所有更改
- 推送分支:git push -u origin $BRANCH
- 创建 PR:gh pr create --fill
- 通知:openclaw system event --text 完成:$TASK_ID --mode now \
; echo CODEX
EXIT=$? >> $LOGFILE Enter
为什么是这个顺序(会话 → pipe-pane → send-keys)?
- - 无竞态条件 — 如果你直接将命令传递给 tmux new-session,在 pipe-pane 附加之前产生的输出会从日志文件中丢失
- 捕获退出码 — echo CODEX_EXIT=$? 将退出码追加到日志中,
这样你可以区分成功和崩溃(否则 tmux 在会话关闭时会丢弃它)
- - 行缓冲日志记录 — stdbuf -oL 确保 tail -f $LOG_FILE 实时工作
为什么是交互模式(无 exec)?
- - 允许通过 tmux send-keys 在任务中进行引导
- 无需杀死和重启即可重定向代理
- --dangerously-bypass-approvals-and-sandbox 在容器/沙箱环境中安全
步骤 3:注册任务
在 JSON 注册表中跟踪所有活动任务:
bash
mkdir -