codex
将编码、代码库探索、实现、评审和验证任务委托给持久化 Codex CLI Agent。仅当用户明确要求“用 Codex”“让 Codex 执行”,或要求继续某个 Codex Agent 任务时使用。
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/oil-oil--codex)HTML
<a href="/listings/oil-oil--codex"><img src="/api/listings/oil-oil--codex/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
npx skills add oil-oil/codex -g -y
运行前需要准备:
- 已安装并登录 [Codex CLI](https://github.com/openai/codex),或在 macOS 上已安装并登录内置 Codex 的 `ChatGPT.app`(脚本在 macOS 上默认优先使用 `ChatGPT.app/Contents/Resources/codex-cli/bin/codex`,不存在时回退到 `PATH` 中的 `codex`,也可通过 `CODEX_BIN` 指定可执行文件)。 - macOS、Linux 或 Windows。 - `jq`。包装脚本使用它处理 Codex 的 JSONL 事件。
安装后,其他 Agent 可以在用户明确要求“使用 Codex”时调用这个 Skill。
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 173 lines
- ---
- name: codex
- description: 将编码、代码库探索、实现、评审和验证任务委托给持久化 Codex CLI Agent。仅当用户明确要求“用 Codex”“让 Codex 执行”,或要求继续某个 Codex Agent 任务时使用。
- ---
- # Codex CLI Agent
- 命令中的 `SKILL_DIR` 为当前已安装 codex Skill 的绝对目录,不是固定宿主路径。
- ## 核心规则
- - 通过内置包装脚本调用 Codex,不要直接执行 `codex exec`。包装脚本负责捕获 JSONL、显示有效进度、记录会话 ID,并生成精简的 Markdown 结果。macOS 上若已安装 `ChatGPT.app`,脚本优先使用应用内置的 `Contents/Resources/codex-cli/bin/codex`,不存在时回退到 `PATH` 中的 `codex`(可用 `CODEX_BIN` 覆盖)。
- - 常规调用不选择或传递模型、思考强度与模型提供商,由本机默认 Codex 配置决定。
- - 每个任务先调用一次包装脚本。成功后读取 `output_path`,检查工作区结果,再判断是否需要继续同一会话。
- - 委托提示词应包含目标、完成标准、约束和必要背景,不要规定每一个实现步骤,也不要粘贴大段文件内容。
- - 使用 `--file` 提供 1–4 个重要入口文件,其余路径让 Codex 自己探索。
- - 调用方仍负责范围、安全和最终验收。
- ## 委托契约
- 每次只委托一个边界清楚的任务。提示词应简短覆盖:
- - 目标:要修改或查明什么,以及明确不应改动的范围。
- - 完成标准:预期行为、必须覆盖的边界情况。
- - 验证:从仓库配置中确认真实的测试、检查或构建命令,不要只写“运行测试”。
- - 安全边界:不执行 `git add`、`git commit`,不顺手重构无关代码。
- - 最终报告:说明改动与原因、涉及文件、验证结果,以及仍需决定或未完成的事项。
- 缺少的仓库事实应先查找;无法确认时明确报告,不要猜测。评审或诊断任务要求结论引用代码证据,并区分事实与推断。
- ## 包装脚本
- macOS 与 Linux:
- ```text
- "$SKILL_DIR"/scripts/ask_codex.sh
- ```
- Windows:
- ```text
- "$SKILL_DIR"/scripts/ask_codex.ps1
- ```
- `~/.claude/skills/codex` 可以作为兼容软链接指向同一个 Skill。
- ## 常用调用
- 新任务:
- ```bash
- "$SKILL_DIR"/scripts/ask_codex.sh "实现请求的改动"
- ```
- 指定工作区和入口文件:
- ```bash
- "$SKILL_DIR"/scripts/ask_codex.sh "重构这些组件并完成验证" \
- --workspace "/path/to/repo" \
- --file "src/components/UserList.tsx" \
- --file "src/components/UserDetail.tsx"
- ```
- 探索或评审:
- ```bash
- "$SKILL_DIR"/scripts/ask_codex.sh "追踪当前请求路径并引用文件和行号" \
- --workspace "/path/to/repo"
- ```
- 继续已有会话:
- ```bash
- "$SKILL_DIR"/scripts/ask_codex.sh "继续修复刚才发现的问题" \
- --session <session_id>
- ```
- 使用默认 Codex 时,附加图片并要求结构化结果:
- ```bash
- "$SKILL_DIR"/scripts/ask_codex.sh "比较截图与当前实现" \
- --image "/path/to/screenshot.png" \
- --output-schema "/path/to/result.schema.json"
- ```
- ## 工作流程
- 1. 读取足够的本地上下文,明确目标和重要限制。
- 2. 默认使用最高权限运行 Codex;只有用户明确要求限制权限时,才为新会话指定只读或其他沙箱模式。
- 3. 使用包装脚本派发一段聚焦的提示词,通常控制在 500 字以内。
- 4. 读取脚本返回的 `output_path`。
- 5. 先检查测试是否被删除、跳过或弱化,再检查工作区改动是否越界。
- 6. 重新运行真实验证命令;Codex 的“测试通过”只是报告,不能替代调用方验收。
- 7. 检查硬编码成功结果、吞掉异常、未经确认的 API、死代码和无调用方的抽象。
- 8. 需要返工时继续原会话,只发送新发现和修正要求,不重复整个任务。
- 包装脚本默认替新会话和续接会话给 Codex 传入 `--dangerously-bypass-approvals-and-sandbox`,使 Codex 不受自身沙箱和审批限制,调用包装脚本时不用再传。不要因任务是分析、探索或评审就自动加 `--read-only`;只读是用户明确要求时的权限选项。一次性测试可以使用 `--ephemeral`。调用方仍须检查 Codex 的改动与验证结果。
- ## 思考强度
- 正常调用不要传 `--reasoning`,由运行环境使用默认的 `high`。只有确实需要改变默认行为时才指定:
- - `high`:默认档位,适合绝大多数编码、探索、实现和评审任务;无需显式传递。
- - `max`:仅用于跨模块架构、疑难故障、复杂安全评审,或 `high` 已尝试但结论仍明显不足的任务。
- - `low`:仅当用户明确优先考虑速度或成本,并且任务是简单、机械、低风险操作时使用。
- 不要仅因为任务描述较长就自动使用 `max`;先收窄目标和上下文。
- ## 输出
- 成功后脚本输出:
- ```text
- session_id=<thread_id>
- runtime=default
- output_path=<path>
- result_path=<path>
- events_path=<path>
- elapsed=<seconds>s
- ```
- Markdown 结果包含:
- - `## Summary`:Codex 的最终结论。
- - `## Details`:有意义的命令、写入、补丁和中间消息;纯读取与搜索会被省略。
- - 耗时、命令数和可用的 token 使用信息。
- 使用 `--output-schema` 时,`Summary` 包含符合指定 JSON Schema 的结果。
- 每次运行使用独立目录,避免并行任务覆盖结果。`result_path` 是原子写入的结构化状态,包含 `completed` 或 `failed`、退出码、运行环境、会话 ID、最终消息、耗时及错误尾部;`events_path` 保留原始 JSONL,便于失败诊断和恢复。调用方平时只需读取 `output_path`,出现异常时再读取另外两个文件。
- ## 图片
- `--image` 通过默认 Codex 运行环境发送给 Codex。
- 需要透明背景图片时:
- 1. 先明确要求生成透明背景 PNG。
- 2. 指定最终输出路径,并要求 Codex 报告该路径。
- 3. 只有原生透明效果不可靠时,才使用灰底抠图工具:
- ```bash
- python3 "$SKILL_DIR"/scripts/cutout.py input.png output.png
- ```
- 使用该后备方案时,让图像生成在纯 `#808080` 背景上,执行抠图后确认输出为 RGBA,并检查边缘质量。
- ## 对外参数
- - `--workspace <path>`:工作目录,默认使用当前目录。
- - `--file <path>`:优先入口文件,可重复使用。
- - `--image <path>`:附加图片,可重复使用。
- - `--session <id>`:继续已有会话。
- - `--reasoning <low|high|max>`:特殊情况下覆盖默认思考强度,常规调用不要传递。
- - `--sandbox <mode>`:为新会话显式指定沙箱模式。
- - `--read-only`:创建只读新会话。
- - `--full-auto`:默认的最高权限,可省略;`--dangerously-bypass-approvals-and-sandbox` 是它的别名。
- - `--ephemeral`:不持久化会话。
- - `--output-schema <path>`:约束最终输出结构。
- - `--notify`:长任务结束后发送通知。
- - `--output <path>`:指定 Markdown 结果路径。
- ## 会话约束
- 续接会话保留原工作区上下文,但包装脚本会再次显式传入最高权限参数。`--read-only` 和 `--sandbox` 不能与 `--session` 同时使用;需要受限权限时开启新会话。续接会话使用本机默认 Codex 配置。
- ## 失败处理
- - 非零退出码、`turn.failed` 或明确错误事件都视为失败。
- - 失败运行也会输出 `result_path` 与 `events_path`;先读取结构化错误和事件尾部,再决定缩小任务、修正配置或续接会话。
- - 退出码 137 通常表示进程被中断或终止;先检查资源压力或缩小任务范围,再决定是否重试。
- - Skill 或插件加载警告通常不影响任务,除非 Codex 回合本身失败。
- - Bash 包装脚本会检测 PTY 支持;不支持时回退到直接执行,任务仍可完成,但进度可能集中在结束时返回。
README.md · README · 170 lines
- <p align="center">
- <img src="./assets/readme/hero.svg" width="100%" alt="codex:让其他 Agent 把 Codex CLI 作为可持续对话的编码子 Agent">
- </p>
- 把代码探索、实现、修复、评审和测试交给持久化编码 Agent,支持继续同一任务。
- 调用方负责说明目标、约束和验收方式;Codex 负责在指定工作区内完成任务。一次任务结束后,调用方可以检查结果,也可以继续同一个会话处理后续问题。
- ## 适合处理的任务
- - 探索代码库,追踪入口、依赖和调用链。
- - 实现边界清楚的功能或修复。
- - 评审代码,并引用具体文件和行号。
- - 运行测试、类型检查或构建,整理验证结果。
- - 继续已有 Codex 会话,不重复传递完整背景。
- ## 安装
- ```bash
- npx skills add oil-oil/codex -g -y
- ```
- 运行前需要准备:
- - 已安装并登录 [Codex CLI](https://github.com/openai/codex),或在 macOS 上已安装并登录内置 Codex 的 `ChatGPT.app`(脚本在 macOS 上默认优先使用 `ChatGPT.app/Contents/Resources/codex-cli/bin/codex`,不存在时回退到 `PATH` 中的 `codex`,也可通过 `CODEX_BIN` 指定可执行文件)。
- - macOS、Linux 或 Windows。
- - `jq`。包装脚本使用它处理 Codex 的 JSONL 事件。
- 安装后,其他 Agent 可以在用户明确要求“使用 Codex”时调用这个 Skill。
- ## 让 Agent 调用 Codex
- 可以直接向支持 Skill 的 Agent 提出要求:
- ```text
- 使用 Codex 检查这个项目的登录流程,修复刷新失败的问题,并运行相关测试。
- ```
- Agent 会整理任务目标、完成标准、重要文件和安全边界,再调用包装脚本。调用方仍然负责检查工作区改动和重新运行真实验证命令。
- ## 包装脚本
- macOS 与 Linux:
- ```bash
- ~/.agents/skills/codex/scripts/ask_codex.sh \
- "检查登录流程,修复刷新失败的问题,并运行相关测试" \
- --workspace "/path/to/repo" \
- --file "src/auth.ts"
- ```
- Windows:
- ```powershell
- ~/.agents/skills/codex/scripts/ask_codex.ps1 `
- "检查登录流程,修复刷新失败的问题,并运行相关测试" `
- -Workspace "C:\path\to\repo" `
- -File "src\auth.ts"
- ```
- 脚本默认以最高权限创建和续接会话,并跳过 Codex 自身的沙箱和审批。只有明确需要限制权限时,才为新会话指定只读模式:
- ```bash
- ~/.agents/skills/codex/scripts/ask_codex.sh \
- "追踪请求路径,并引用涉及的文件和行号" \
- --workspace "/path/to/repo" \
- --read-only
- ```
- ## 调用流程
- <p align="center">
- <img src="./assets/readme/workflow.svg" width="100%" alt="调用方 Agent 通过包装脚本派发 Codex CLI 会话、读取运行产物并使用 session_id 继续任务">
- </p>
- 每次运行都会建立独立的产物目录,避免并行任务互相覆盖。脚本成功后输出:
- ```text
- session_id=<thread_id>
- runtime=default
- output_path=<path>
- result_path=<path>
- events_path=<path>
- elapsed=<seconds>s
- ```
- 调用方通常先读取 `output_path`,再检查工作区和验证结果。运行失败时,可以通过 `result_path` 和 `events_path` 判断失败原因。
- | 产物 | 内容 | 使用场景 |
- | --- | --- | --- |
- | `output_path` | 精简的 Markdown 结果 | 阅读结论、改动与有效执行记录 |
- | `result_path` | 结构化运行状态 | 判断成功、失败、退出码和会话信息 |
- | `events_path` | Codex 原始 JSONL 事件 | 诊断中断、错误和恢复问题 |
- ## 继续已有会话
- 首次任务返回 `session_id` 后,可以继续同一个 Codex 会话:
- ```bash
- ~/.agents/skills/codex/scripts/ask_codex.sh \
- "继续修复刚才发现的问题,并补充回归测试" \
- --session <session_id>
- ```
- 续接会话保留原工作区,包装脚本会再次传入最高权限参数。续接时不能指定 `--read-only` 或新的 `--sandbox`;需要受限权限时开启新会话。
- ## 运行环境
- 包装脚本始终使用 Codex CLI 当前生效的默认配置,不会根据其他目录中的配置自动切换运行环境。模型和 Provider 由 Codex CLI 配置决定。常规调用不需要指定模型、Provider 或思考强度;默认思考强度为 `high`,只有任务确实需要时才使用 `--reasoning low` 或 `--reasoning max` 覆盖。
- ## 常用参数
- | 参数 | 作用 |
- | --- | --- |
- | `--workspace <path>` | 指定 Codex 工作目录 |
- | `--file <path>` | 提供优先阅读的入口文件,可以重复使用 |
- | `--read-only` | 创建只读会话 |
- | `--sandbox <mode>` | 为新会话指定沙箱模式 |
- | `--full-auto` | 默认的最高权限,可省略;`--dangerously-bypass-approvals-and-sandbox` 是它的别名 |
- | `--session <id>` | 继续已有会话 |
- | `--ephemeral` | 不持久化新会话 |
- | `--output-schema <path>` | 使用 JSON Schema 约束最终结果 |
- | `--image <path>` | 向 Codex 附加图片 |
- | `--reasoning <level>` | 在必要时覆盖默认思考强度 |
- | `--notify` | 长任务结束后发送桌面通知 |
- | `--output <path>` | 指定 Markdown 结果路径 |
- 完整参数可以通过脚本的 `--help` 查看。
- ## 委托和验收
- 每次只委托一个边界清楚的任务。提示词应当说明:
- 1. 需要修改或查明什么,以及不应改动的范围。
- 2. 预期行为和必须覆盖的边界情况。
- 3. 需要运行的真实测试、检查或构建命令。
- 4. 不执行 `git add`、`git commit`,不顺手重构无关代码。
- 5. 最终报告需要包含改动原因、涉及文件、验证结果和未完成事项。
- Codex 返回“测试通过”不能替代调用方验收。调用方需要检查测试是否被删除、跳过或弱化,并重新运行仓库中的真实验证命令。
- ## 开发验证
- macOS 与 Linux 包装脚本的回归测试:
- ```bash
- bash tests/test_ask_codex.sh
- ```
- 测试覆盖成功运行、完整失败和已经返回会话 ID 的中途失败。
- ## 配置、依赖与使用边界
- 需要 Codex CLI 与官方登录;macOS/Linux 使用 Bash,Windows 使用 PowerShell。包装脚本可从任意实际 Skill 目录调用。
- 仅在用户明确要求委托时使用。任务文件与指令会交给 CLI 配置的模型;继续原会话时核对会话与目录,避免混入无关任务。
- 使用示例:
- ```text
- 用 Codex 处理这个明确的代码修改。
- ```
- ## 延伸阅读
- 关于主从 Agent 怎么分工、Codex 底层循环怎么运转,可以参考 Oil Book 里的几篇文章与译文:
- - [《怎样用好子 Agent》](https://book.oiloil.org/articles/subagent-workflow?utm_source=github&utm_medium=referral&utm_campaign=codex-readme)
- - [《拆解 Codex 的 Agent 核心循环》](https://book.oiloil.org/articles/unrolling-the-codex-agent-loop?utm_source=github&utm_medium=referral&utm_campaign=codex-readme)
- - [《Harness Engineering:在 Agent 优先的世界中用好 Codex》](https://book.oiloil.org/articles/harness-engineering?utm_source=github&utm_medium=referral&utm_campaign=codex-readme)
scripts/ask_codex.sh · Bundled script · 515 lines · 1 finding marked
- #!/usr/bin/env bash
- set -euo pipefail
- usage() {
- cat <<'USAGE'
- Usage:
- ask_codex.sh <task> [options]
- ask_codex.sh -t <task> [options]
- Task input:
- <task> First positional argument is the task text
- -t, --task <text> Alias for positional task (backward compat)
- (stdin) Pipe task text via stdin if no arg/flag given
- File context (optional, repeatable):
- -f, --file <path> Priority file path
- -i, --image <path> Image to attach to Codex
- Multi-turn:
- --session <id> Resume a previous session (thread_id from prior run)
- Options:
- -w, --workspace <path> Workspace directory (default: current directory)
- --reasoning <level> Optional reasoning override; normally use configured high
- --sandbox <mode> Explicit sandbox mode override
- --read-only Read-only sandbox (no file changes)
- --full-auto Full access (default); alias: --dangerously-bypass-approvals-and-sandbox
- --ephemeral Do not persist the Codex session
- --output-schema <path> Require the final response to match a JSON Schema
- --notify Desktop notification when a long run finishes (macOS/Linux; opt-in)
- -o, --output <path> Output file path
- -h, --help Show this help
- Output (on success):
- session_id=<thread_id> Use with --session for follow-up calls
- runtime=default Uses the local default Codex configuration
- output_path=<file> Path to response markdown
- result_path=<file> Structured run status and metadata
- events_path=<file> Raw Codex JSONL events for diagnostics
- Examples:
- # New task (positional)
- ask_codex.sh "Add error handling to api.ts" -f src/api.ts
- # With explicit workspace
- ask_codex.sh "Fix the bug" -w /other/repo
- # Continue conversation
- ask_codex.sh "Also add retry logic" --session <id>
- # Structured analysis with an attached image
- ask_codex.sh "Compare the screenshot with the implementation" \
- --image screenshot.png --output-schema result.schema.json
- USAGE
- }
- require_cmd() {
- if ! command -v "$1" >/dev/null 2>&1; then
- echo "[ERROR] Missing required command: $1" >&2
- exit 1
- fi
- }
- trim_whitespace() {
- awk 'BEGIN { RS=""; ORS="" } { gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, ""); print }' <<<"$1"
- }
- to_abs_if_exists() {
- local target="$1"
- if [[ -e "$target" ]]; then
- local dir
- dir="$(cd "$(dirname "$target")" && pwd)"
- echo "$dir/$(basename "$target")"
- return
- fi
- echo "$target"
- }
- resolve_file_ref() {
- local workspace="$1" raw="$2" cleaned
- cleaned="$(trim_whitespace "$raw")"
- [[ -z "$cleaned" ]] && { echo ""; return; }
- if [[ "$cleaned" =~ ^(.+)#L[0-9]+$ ]]; then cleaned="${BASH_REMATCH[1]}"; fi
- if [[ "$cleaned" =~ ^(.+):[0-9]+(-[0-9]+)?$ ]]; then cleaned="${BASH_REMATCH[1]}"; fi
- if [[ "$cleaned" != /* ]]; then cleaned="$workspace/$cleaned"; fi
- to_abs_if_exists "$cleaned"
- }
- append_file_refs() {
- local raw="$1" item
- IFS=',' read -r -a items <<< "$raw"
- for item in "${items[@]}"; do
- local trimmed
- trimmed="$(trim_whitespace "$item")"
- [[ -n "$trimmed" ]] && file_refs+=("$trimmed")
- done
- }
- # --- Parse arguments ---
- workspace="${PWD}"
- task_text=""
- model=""
- reasoning_effort=""
- sandbox_mode=""
- read_only=false
- fast=false
- ephemeral=false
- notify=false
- output_path=""
- output_schema=""
- session_id=""
- file_refs=()
- image_refs=()
- while [[ $# -gt 0 ]]; do
- case "$1" in
- -w|--workspace) workspace="${2:-}"; shift 2 ;;
- -t|--task) task_text="${2:-}"; shift 2 ;;
- -f|--file|--focus) append_file_refs "${2:-}"; shift 2 ;;
- -i|--image) image_refs+=("${2:-}"); shift 2 ;;
- --model) model="${2:-}"; shift 2 ;;
- --reasoning) reasoning_effort="${2:-}"; shift 2 ;;
- --fast) fast=true; shift ;;
- --sandbox) sandbox_mode="${2:-}"; [[ -n "$sandbox_mode" ]] || { echo "[ERROR] --sandbox requires a mode." >&2; exit 1; }; read_only=false; shift 2 ;;
- --read-only) read_only=true; sandbox_mode=""; shift ;;
- --full-auto|--dangerously-bypass-approvals-and-sandbox)
- read_only=false; sandbox_mode=""; shift ;;
- --ephemeral) ephemeral=true; shift ;;
- --output-schema) output_schema="${2:-}"; shift 2 ;;
- --notify) notify=true; shift ;;
- --session) session_id="${2:-}"; shift 2 ;;
- -o|--output) output_path="${2:-}"; shift 2 ;;
- -h|--help) usage; exit 0 ;;
- -*) echo "[ERROR] Unknown option: $1" >&2; usage >&2; exit 1 ;;
- *) if [[ -z "$task_text" ]]; then task_text="$1"; shift; else echo "[ERROR] Unexpected argument: $1" >&2; usage >&2; exit 1; fi ;;
- esac
- done
- selected_runtime="default"
- require_cmd codex
- require_cmd jq
- # --- Validate inputs ---
- if [[ ! -d "$workspace" ]]; then
- echo "[ERROR] Workspace does not exist: $workspace" >&2; exit 1
- fi
- workspace="$(cd "$workspace" && pwd)"
- if [[ -z "$task_text" && ! -t 0 ]]; then
- task_text="$(cat)"
- fi
- task_text="$(trim_whitespace "$task_text")"
- if [[ -z "$task_text" ]]; then
- echo "[ERROR] Request text is empty. Pass a positional arg, --task, or stdin." >&2; exit 1
- fi
- # --- Build file context block ---
- file_block=""
- if (( ${#file_refs[@]} > 0 )); then
- file_block=$'\nPriority files (read these first before making changes):'
- for ref in "${file_refs[@]}"; do
- resolved="$(resolve_file_ref "$workspace" "$ref")"
- [[ -z "$resolved" ]] && continue
- exists_tag="missing"
- [[ -e "$resolved" ]] && exists_tag="exists"
- file_block+=$'\n- '"${resolved} (${exists_tag})"
- done
- fi
- # --- Build prompt ---
- prompt="$task_text"
- if [[ -n "$file_block" ]]; then
- prompt+=$'\n'"$file_block"
- fi
- # --- Validate optional reasoning override ---
- if [[ -n "$reasoning_effort" ]]; then
- case "$reasoning_effort" in
- minimal|low|medium|high|xhigh|max|ultra) ;;
- *) echo "[ERROR] Unsupported reasoning effort: $reasoning_effort" >&2; exit 1 ;;
- esac
- fi
- if [[ -n "$session_id" && ( "$read_only" == true || -n "$sandbox_mode" ) ]]; then
- echo "[ERROR] Codex resume does not support --read-only or --sandbox here. Start a new session for a restricted run." >&2
- exit 1
- fi
- if [[ -n "$output_schema" ]]; then
- output_schema="$(resolve_file_ref "$workspace" "$output_schema")"
- [[ -f "$output_schema" ]] || { echo "[ERROR] Output schema not found: $output_schema" >&2; exit 1; }
- fi
- resolved_images=()
- if (( ${#image_refs[@]} > 0 )); then
- for image_ref in "${image_refs[@]}"; do
- resolved_image="$(resolve_file_ref "$workspace" "$image_ref")"
- [[ -f "$resolved_image" ]] || { echo "[ERROR] Image not found: $resolved_image" >&2; exit 1; }
- resolved_images+=("$resolved_image")
- done
- fi
- # --- Prepare unique run artifacts ---
- timestamp="$(date -u +"%Y%m%d-%H%M%S")"
- state_root="${CODEX_SKILL_STATE_HOME:-${XDG_STATE_HOME:-$HOME/.local/state}/codex-skill}"
- mkdir -p "$state_root"
- run_dir="$(mktemp -d "$state_root/run-${timestamp}-XXXXXX")"
- result_path="$run_dir/result.json"
- events_path="$run_dir/events.jsonl"
- stderr_path="$run_dir/stderr.log"
- if [[ -z "$output_path" ]]; then
- output_path="$run_dir/result.md"
- fi
- mkdir -p "$(dirname "$output_path")"
- # --- Build codex command ---
- common_args=(--json --skip-git-repo-check)
- if [[ -n "$reasoning_effort" ]]; then
- common_args+=(-c "model_reasoning_effort=\"$reasoning_effort\"")
- fi
- if [[ "$fast" == true ]]; then
- common_args+=(-c 'service_tier="fast"' -c 'features.fast_mode=true')
- fi
- if [[ -n "$session_id" ]]; then
- # Current Codex resume supports JSON, model/image/schema overrides, and non-git workspaces.
- cmd=(codex exec resume "${common_args[@]}" --dangerously-bypass-approvals-and-sandbox)
- Note: Starts a coding agent with its permission prompts off
- Line 235 on GitHub
- [[ -n "$model" ]] && cmd+=(-m "$model")
- [[ "$ephemeral" == true ]] && cmd+=(--ephemeral)
- [[ -n "$output_schema" ]] && cmd+=(--output-schema "$output_schema")
- if (( ${#resolved_images[@]} > 0 )); then
- for resolved_image in "${resolved_images[@]}"; do cmd+=(--image "$resolved_image"); done
- fi
- cmd+=("$session_id" -)
- else
- # New session
- cmd=(codex exec --cd "$workspace" "${common_args[@]}")
- if [[ "$read_only" == true ]]; then
- cmd+=(--sandbox read-only)
- elif [[ -n "$sandbox_mode" ]]; then
- cmd+=(--sandbox "$sandbox_mode")
- else
- cmd+=(--dangerously-bypass-approvals-and-sandbox)
- fi
- [[ -n "$model" ]] && cmd+=(-m "$model")
- [[ "$ephemeral" == true ]] && cmd+=(--ephemeral)
- [[ -n "$output_schema" ]] && cmd+=(--output-schema "$output_schema")
- if (( ${#resolved_images[@]} > 0 )); then
- for resolved_image in "${resolved_images[@]}"; do cmd+=(--image "$resolved_image"); done
- fi
- fi
- # --- Progress watcher function ---
- print_progress() {
- local line="$1"
- local item_type cmd_str preview
- # Fast string checks before calling jq
- case "$line" in
- *'"item.started"'*'"command_execution"'*)
- cmd_str=$(printf '%s' "$line" | jq -r '.item.command // empty' 2>/dev/null | sed 's|^/bin/zsh -lc ||; s|^/bin/bash -c ||' | cut -c1-100)
- [[ -n "$cmd_str" ]] && echo "[codex] > $cmd_str" >&2
- ;;
- *'"item.completed"'*'"agent_message"'*)
- preview=$(printf '%s' "$line" | jq -r '.item.text // empty' 2>/dev/null | head -1 | cut -c1-120)
- [[ -n "$preview" ]] && echo "[codex] $preview" >&2
- ;;
- esac
- }
- write_result() {
- local status="$1" exit_code="$2" error_message="${3:-}"
- local finished_at stderr_tail result_tmp
- finished_at="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
- stderr_tail=""
- if [[ "$status" != "completed" ]]; then
- stderr_tail="$(tail -n 20 "$stderr_file" 2>/dev/null || true)"
- fi
- result_tmp="$result_path.tmp.$$"
- jq -n \
- --arg status "$status" \
- --argjson exit_code "$exit_code" \
- --arg runtime "$selected_runtime" \
- --arg run_id "$(basename "$run_dir")" \
- --arg workspace "$workspace" \
- --arg session_id "${thread_id:-}" \
- --arg final_message "${summary_text:-}" \
- --arg output_path "$output_path" \
- --arg events_path "$events_path" \
- --arg stderr_path "$stderr_path" \
- --argjson elapsed "${elapsed:-0}" \
- --arg started_at "$started_at" \
- --arg finished_at "$finished_at" \
- --arg stderr_tail "$stderr_tail" \
- --arg error "$error_message" \
- '{
- schema: "codex-skill.run.v1",
- status: $status,
- exit_code: $exit_code,
- runtime: $runtime,
- run_id: $run_id,
- workspace: $workspace,
- session_id: (if $session_id == "" then null else $session_id end),
- final_message: $final_message,
- output_path: $output_path,
- events_path: $events_path,
- stderr_path: $stderr_path,
- elapsed_seconds: $elapsed,
- started_at: $started_at,
- finished_at: $finished_at,
- stderr_tail: (if $stderr_tail == "" then null else $stderr_tail end),
- error: (if $error == "" then null else $error end)
- }' > "$result_tmp"
- mv "$result_tmp" "$result_path"
- }
- # --- Execute and capture output ---
- stderr_file="$stderr_path"
- json_file="$events_path"
- prompt_file="$(mktemp)"
- trap 'rm -f "$prompt_file"' EXIT
- : > "$stderr_file"
- : > "$json_file"
- # Write prompt to a temp file and pipe from there to avoid shell argument
- # length issues and encoding problems with very long or multi-byte prompts.
- printf "%s\n" "$prompt" > "$prompt_file"
- # Run codex and capture its output.
- # We prefer `script` to allocate a pseudo-TTY, which forces codex to line-buffer
- # its output so progress events arrive in real time. However, `script` requires a
- # real controlling terminal and fails with "tcgetattr/ioctl: Operation not supported
- # on socket" in socket-based environments (e.g. some Claude Code sandboxes). We
- # detect this upfront and fall back to direct execution — output may arrive all at
- # once at the end, but the task still completes correctly.
- run_codex() {
- # BSD script (macOS): script [-q] [file [command...]]
- # util-linux script (Linux): script [-q] -c <command> [file]
- # Probe the local variant and use matching syntax for PTY allocation.
- # Falls back to direct execution if neither probe succeeds (e.g. socket stdin).
- local os
- os="$(uname -s)"
- if [[ "$os" == "Darwin" ]]; then
- if script -q /dev/null true >/dev/null 2>&1; then
- script -q /dev/null /bin/bash -c \
- "cd $(printf '%q' "$workspace") && $(printf '%q ' "${cmd[@]}") < $(printf '%q' "$prompt_file") 2>$(printf '%q' "$stderr_file")"
- return
- fi
- else
- if script -q -c "true" /dev/null >/dev/null 2>&1; then
- script -q -c \
- "cd $(printf '%q' "$workspace") && $(printf '%q ' "${cmd[@]}") < $(printf '%q' "$prompt_file") 2>$(printf '%q' "$stderr_file")" \
- /dev/null
- return
- fi
- fi
- # Fallback: direct execution (no PTY; progress events arrive in batch)
- (cd "$workspace" && "${cmd[@]}" < "$prompt_file" 2>"$stderr_file")
- }
- # Errexit is relaxed around the streaming pipeline so a non-zero codex exit still
- # lets us surface captured output / a clear error instead of aborting silently.
- started_at="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
- start_ts=$SECONDS
- codex_status=0
- set +e
- run_codex | while IFS= read -r line; do
- cleaned="${line//$'\r'/}"
- cleaned="${cleaned//$'\004'/}"
- [[ -z "$cleaned" ]] && continue
- if [[ "$cleaned" != \{* ]]; then
- if [[ "$cleaned" =~ (\{\"type\":.*)$ ]]; then
- cleaned="${BASH_REMATCH[1]}"
- else
- continue
- fi
- fi
- jq -e . >/dev/null 2>&1 <<<"$cleaned" || continue
- printf '%s\n' "$cleaned" >> "$json_file"
- case "$cleaned" in
- *'"item.started"'*|*'"item.completed"'*) print_progress "$cleaned" ;;
- esac
- done
- codex_status=${PIPESTATUS[0]}
- set -e
- elapsed=$(( SECONDS - start_ts ))
- # Extract the session and latest agent message before checking status so failed
- # runs still leave useful recovery metadata.
- thread_id="$(jq -r 'select(.type == "thread.started") | (.thread_id // .threadId // empty)' < "$json_file" | head -1)"
- [[ -z "$thread_id" ]] && thread_id="$session_id"
- summary_text="$(jq -rs 'map(select(.type == "item.completed" and .item.type == "agent_message") | .item.text) | (last // "")' < "$json_file" 2>/dev/null)"
- failure_text="$(jq -rs 'map(select(.type == "turn.failed" or .type == "error")) | (last // {}) | (.error.message // .message // "")' < "$json_file" 2>/dev/null)"
- if (( codex_status != 0 )) || [[ -n "$failure_text" ]]; then
- result_exit_code="$codex_status"
- (( result_exit_code == 0 )) && result_exit_code=1
- error_message="$failure_text"
- [[ -z "$error_message" ]] && error_message="Codex exited with code $result_exit_code"
- write_result "failed" "$result_exit_code" "$error_message"
- echo "[ERROR] Codex command failed (exit $result_exit_code)" >&2
- [[ -n "$failure_text" ]] && echo "$failure_text" >&2
- [[ -s "$stderr_file" ]] && cat "$stderr_file" >&2
- echo "status=failed"
- echo "runtime=$selected_runtime"
- [[ -n "$thread_id" ]] && echo "session_id=$thread_id"
- echo "result_path=$result_path"
- echo "events_path=$events_path"
- exit "$result_exit_code"
- fi
- if [[ -s "$stderr_file" ]]; then
- cat "$stderr_file" >&2
- fi
- # --- Process JSON output for new and resumed sessions ---
- # Execution trace: command executions (skipping pure file-reading/searching commands),
- # file write/patch operations, and any intermediate agent messages (the final one is
- # already shown as the summary above). Captured into a var so the section is omitted
- # entirely when empty (e.g. a pure read-only discussion).
- #
- # Note: zsh wraps commands in quotes, so after stripping the shell prefix the command
- # may start with " or ' — the regex accounts for this with [\"']?.
- details="$(
- {
- jq -r '
- select(.type == "item.completed" and .item.type == "command_execution")
- | .item
- | ((.command // "") | gsub("^/bin/zsh -lc "; "") | gsub("^/bin/bash -c "; "")) as $cmd
- | select($cmd | test("^[\"'"'"']?(sed |cat |head |tail |nl |rg |grep |awk |wc |find |ls )") | not)
- | "### Shell: `" + ($cmd[0:200]) + "`\n" + (.aggregated_output // "" | .[0:800])
- ' < "$json_file" 2>/dev/null
- jq -r '
- select(.type == "item.completed" and .item.type == "tool_call")
- | .item
- | if .name == "write_file" then
- "### File written: " + (.arguments | fromjson | .path // "unknown")
- elif .name == "patch_file" then
- "### File patched: " + (.arguments | fromjson | .path // "unknown")
- elif .name == "shell" then
- "### Shell: `" + (.arguments | fromjson | .command // "unknown")[0:200] + "`\n" + (.output // "" | .[0:800])
- else empty
- end
- ' < "$json_file" 2>/dev/null
- jq -rs 'map(select(.type == "item.completed" and .item.type == "agent_message") | .item.text) | .[:-1] | .[]' < "$json_file" 2>/dev/null
- }
- )"
- # Run metrics: command count + token usage (from the turn.completed event).
- cmd_count="$(jq -rs '[.[] | select(.type == "item.completed" and .item.type == "command_execution")] | length' < "$json_file" 2>/dev/null)"
- usage_footer="$(jq -rs '
- (map(select(.type == "turn.completed")) | last | .usage) as $u
- | if $u then "tokens in=\($u.input_tokens) (cached \($u.cached_input_tokens)) out=\($u.output_tokens) reasoning=\($u.reasoning_output_tokens)" else "" end
- ' < "$json_file" 2>/dev/null)"
- {
- [[ -n "$summary_text" ]] && printf '## Summary\n\n%s\n\n' "$summary_text"
- [[ -n "$details" ]] && printf '## Details\n\n%s\n\n' "$details"
- printf -- '---\nelapsed %ss · %s cmds' "$elapsed" "${cmd_count:-0}"
- [[ -n "$usage_footer" ]] && printf -- ' · %s' "$usage_footer"
- printf '\n'
- } > "$output_path"
- # If nothing was captured, write a fallback
- if [[ ! -s "$output_path" ]]; then
- echo "(no response from codex)" > "$output_path"
- fi
- write_result "completed" 0 ""
- # --- Desktop notification for long runs (opt-in via --notify or CODEX_NOTIFY=1) ---
- # Only fires past a minimum duration (default 30s) so quick tasks stay quiet.
- maybe_notify() {
- [[ "${CODEX_NOTIFY:-0}" == "1" || "$notify" == true ]] || return 0
- (( elapsed >= ${CODEX_NOTIFY_MIN_SECONDS:-30} )) || return 0
- local title="Codex done (${elapsed}s)"
- local body
- body="$(printf '%s' "${summary_text:-task complete}" | tr '\n' ' ' | cut -c1-120)"
- case "$(uname -s)" in
- Darwin)
- if command -v terminal-notifier >/dev/null 2>&1; then
- terminal-notifier -title "$title" -message "$body" >/dev/null 2>&1 || true
- else
- osascript -e "display notification \"${body//\"/\'}\" with title \"${title//\"/\'}\" sound name \"Glass\"" >/dev/null 2>&1 || true
- fi
- ;;
- Linux)
- command -v notify-send >/dev/null 2>&1 && notify-send "$title" "$body" >/dev/null 2>&1 || true
- ;;
- esac
- }
- maybe_notify
- # --- Output results ---
- if [[ -n "$thread_id" ]]; then
- echo "session_id=$thread_id"
- fi
- echo "runtime=$selected_runtime"
- echo "output_path=$output_path"
- echo "result_path=$result_path"
- echo "events_path=$events_path"
- echo "elapsed=${elapsed}s"
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.