Skip to content
Back to search

codex

SkillWorks with Claude CodeGitHub

将编码、代码库探索、实现、评审和验证任务委托给持久化 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.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/oil-oil--codex/badge.svg)](/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

i

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
  1. ---
  2. name: codex
  3. description: 将编码、代码库探索、实现、评审和验证任务委托给持久化 Codex CLI Agent。仅当用户明确要求“用 Codex”“让 Codex 执行”,或要求继续某个 Codex Agent 任务时使用。
  4. ---
  5. # Codex CLI Agent
  6. 命令中的 `SKILL_DIR` 为当前已安装 codex Skill 的绝对目录,不是固定宿主路径。
  7. ## 核心规则
  8. - 通过内置包装脚本调用 Codex,不要直接执行 `codex exec`。包装脚本负责捕获 JSONL、显示有效进度、记录会话 ID,并生成精简的 Markdown 结果。macOS 上若已安装 `ChatGPT.app`,脚本优先使用应用内置的 `Contents/Resources/codex-cli/bin/codex`,不存在时回退到 `PATH` 中的 `codex`(可用 `CODEX_BIN` 覆盖)。
  9. - 常规调用不选择或传递模型、思考强度与模型提供商,由本机默认 Codex 配置决定。
  10. - 每个任务先调用一次包装脚本。成功后读取 `output_path`,检查工作区结果,再判断是否需要继续同一会话。
  11. - 委托提示词应包含目标、完成标准、约束和必要背景,不要规定每一个实现步骤,也不要粘贴大段文件内容。
  12. - 使用 `--file` 提供 1–4 个重要入口文件,其余路径让 Codex 自己探索。
  13. - 调用方仍负责范围、安全和最终验收。
  14. ## 委托契约
  15. 每次只委托一个边界清楚的任务。提示词应简短覆盖:
  16. - 目标:要修改或查明什么,以及明确不应改动的范围。
  17. - 完成标准:预期行为、必须覆盖的边界情况。
  18. - 验证:从仓库配置中确认真实的测试、检查或构建命令,不要只写“运行测试”。
  19. - 安全边界:不执行 `git add`、`git commit`,不顺手重构无关代码。
  20. - 最终报告:说明改动与原因、涉及文件、验证结果,以及仍需决定或未完成的事项。
  21. 缺少的仓库事实应先查找;无法确认时明确报告,不要猜测。评审或诊断任务要求结论引用代码证据,并区分事实与推断。
  22. ## 包装脚本
  23. macOS 与 Linux:
  24. ```text
  25. "$SKILL_DIR"/scripts/ask_codex.sh
  26. ```
  27. Windows:
  28. ```text
  29. "$SKILL_DIR"/scripts/ask_codex.ps1
  30. ```
  31. `~/.claude/skills/codex` 可以作为兼容软链接指向同一个 Skill。
  32. ## 常用调用
  33. 新任务:
  34. ```bash
  35. "$SKILL_DIR"/scripts/ask_codex.sh "实现请求的改动"
  36. ```
  37. 指定工作区和入口文件:
  38. ```bash
  39. "$SKILL_DIR"/scripts/ask_codex.sh "重构这些组件并完成验证" \
  40. --workspace "/path/to/repo" \
  41. --file "src/components/UserList.tsx" \
  42. --file "src/components/UserDetail.tsx"
  43. ```
  44. 探索或评审:
  45. ```bash
  46. "$SKILL_DIR"/scripts/ask_codex.sh "追踪当前请求路径并引用文件和行号" \
  47. --workspace "/path/to/repo"
  48. ```
  49. 继续已有会话:
  50. ```bash
  51. "$SKILL_DIR"/scripts/ask_codex.sh "继续修复刚才发现的问题" \
  52. --session <session_id>
  53. ```
  54. 使用默认 Codex 时,附加图片并要求结构化结果:
  55. ```bash
  56. "$SKILL_DIR"/scripts/ask_codex.sh "比较截图与当前实现" \
  57. --image "/path/to/screenshot.png" \
  58. --output-schema "/path/to/result.schema.json"
  59. ```
  60. ## 工作流程
  61. 1. 读取足够的本地上下文,明确目标和重要限制。
  62. 2. 默认使用最高权限运行 Codex;只有用户明确要求限制权限时,才为新会话指定只读或其他沙箱模式。
  63. 3. 使用包装脚本派发一段聚焦的提示词,通常控制在 500 字以内。
  64. 4. 读取脚本返回的 `output_path`。
  65. 5. 先检查测试是否被删除、跳过或弱化,再检查工作区改动是否越界。
  66. 6. 重新运行真实验证命令;Codex 的“测试通过”只是报告,不能替代调用方验收。
  67. 7. 检查硬编码成功结果、吞掉异常、未经确认的 API、死代码和无调用方的抽象。
  68. 8. 需要返工时继续原会话,只发送新发现和修正要求,不重复整个任务。
  69. 包装脚本默认替新会话和续接会话给 Codex 传入 `--dangerously-bypass-approvals-and-sandbox`,使 Codex 不受自身沙箱和审批限制,调用包装脚本时不用再传。不要因任务是分析、探索或评审就自动加 `--read-only`;只读是用户明确要求时的权限选项。一次性测试可以使用 `--ephemeral`。调用方仍须检查 Codex 的改动与验证结果。
  70. ## 思考强度
  71. 正常调用不要传 `--reasoning`,由运行环境使用默认的 `high`。只有确实需要改变默认行为时才指定:
  72. - `high`:默认档位,适合绝大多数编码、探索、实现和评审任务;无需显式传递。
  73. - `max`:仅用于跨模块架构、疑难故障、复杂安全评审,或 `high` 已尝试但结论仍明显不足的任务。
  74. - `low`:仅当用户明确优先考虑速度或成本,并且任务是简单、机械、低风险操作时使用。
  75. 不要仅因为任务描述较长就自动使用 `max`;先收窄目标和上下文。
  76. ## 输出
  77. 成功后脚本输出:
  78. ```text
  79. session_id=<thread_id>
  80. runtime=default
  81. output_path=<path>
  82. result_path=<path>
  83. events_path=<path>
  84. elapsed=<seconds>s
  85. ```
  86. Markdown 结果包含:
  87. - `## Summary`:Codex 的最终结论。
  88. - `## Details`:有意义的命令、写入、补丁和中间消息;纯读取与搜索会被省略。
  89. - 耗时、命令数和可用的 token 使用信息。
  90. 使用 `--output-schema` 时,`Summary` 包含符合指定 JSON Schema 的结果。
  91. 每次运行使用独立目录,避免并行任务覆盖结果。`result_path` 是原子写入的结构化状态,包含 `completed` 或 `failed`、退出码、运行环境、会话 ID、最终消息、耗时及错误尾部;`events_path` 保留原始 JSONL,便于失败诊断和恢复。调用方平时只需读取 `output_path`,出现异常时再读取另外两个文件。
  92. ## 图片
  93. `--image` 通过默认 Codex 运行环境发送给 Codex。
  94. 需要透明背景图片时:
  95. 1. 先明确要求生成透明背景 PNG。
  96. 2. 指定最终输出路径,并要求 Codex 报告该路径。
  97. 3. 只有原生透明效果不可靠时,才使用灰底抠图工具:
  98. ```bash
  99. python3 "$SKILL_DIR"/scripts/cutout.py input.png output.png
  100. ```
  101. 使用该后备方案时,让图像生成在纯 `#808080` 背景上,执行抠图后确认输出为 RGBA,并检查边缘质量。
  102. ## 对外参数
  103. - `--workspace <path>`:工作目录,默认使用当前目录。
  104. - `--file <path>`:优先入口文件,可重复使用。
  105. - `--image <path>`:附加图片,可重复使用。
  106. - `--session <id>`:继续已有会话。
  107. - `--reasoning <low|high|max>`:特殊情况下覆盖默认思考强度,常规调用不要传递。
  108. - `--sandbox <mode>`:为新会话显式指定沙箱模式。
  109. - `--read-only`:创建只读新会话。
  110. - `--full-auto`:默认的最高权限,可省略;`--dangerously-bypass-approvals-and-sandbox` 是它的别名。
  111. - `--ephemeral`:不持久化会话。
  112. - `--output-schema <path>`:约束最终输出结构。
  113. - `--notify`:长任务结束后发送通知。
  114. - `--output <path>`:指定 Markdown 结果路径。
  115. ## 会话约束
  116. 续接会话保留原工作区上下文,但包装脚本会再次显式传入最高权限参数。`--read-only` 和 `--sandbox` 不能与 `--session` 同时使用;需要受限权限时开启新会话。续接会话使用本机默认 Codex 配置。
  117. ## 失败处理
  118. - 非零退出码、`turn.failed` 或明确错误事件都视为失败。
  119. - 失败运行也会输出 `result_path` 与 `events_path`;先读取结构化错误和事件尾部,再决定缩小任务、修正配置或续接会话。
  120. - 退出码 137 通常表示进程被中断或终止;先检查资源压力或缩小任务范围,再决定是否重试。
  121. - Skill 或插件加载警告通常不影响任务,除非 Codex 回合本身失败。
  122. - Bash 包装脚本会检测 PTY 支持;不支持时回退到直接执行,任务仍可完成,但进度可能集中在结束时返回。
README.md · README · 170 lines
  1. <p align="center">
  2. <img src="./assets/readme/hero.svg" width="100%" alt="codex:让其他 Agent 把 Codex CLI 作为可持续对话的编码子 Agent">
  3. </p>
  4. 把代码探索、实现、修复、评审和测试交给持久化编码 Agent,支持继续同一任务。
  5. 调用方负责说明目标、约束和验收方式;Codex 负责在指定工作区内完成任务。一次任务结束后,调用方可以检查结果,也可以继续同一个会话处理后续问题。
  6. ## 适合处理的任务
  7. - 探索代码库,追踪入口、依赖和调用链。
  8. - 实现边界清楚的功能或修复。
  9. - 评审代码,并引用具体文件和行号。
  10. - 运行测试、类型检查或构建,整理验证结果。
  11. - 继续已有 Codex 会话,不重复传递完整背景。
  12. ## 安装
  13. ```bash
  14. npx skills add oil-oil/codex -g -y
  15. ```
  16. 运行前需要准备:
  17. - 已安装并登录 [Codex CLI](https://github.com/openai/codex),或在 macOS 上已安装并登录内置 Codex 的 `ChatGPT.app`(脚本在 macOS 上默认优先使用 `ChatGPT.app/Contents/Resources/codex-cli/bin/codex`,不存在时回退到 `PATH` 中的 `codex`,也可通过 `CODEX_BIN` 指定可执行文件)。
  18. - macOS、Linux 或 Windows。
  19. - `jq`。包装脚本使用它处理 Codex 的 JSONL 事件。
  20. 安装后,其他 Agent 可以在用户明确要求“使用 Codex”时调用这个 Skill。
  21. ## 让 Agent 调用 Codex
  22. 可以直接向支持 Skill 的 Agent 提出要求:
  23. ```text
  24. 使用 Codex 检查这个项目的登录流程,修复刷新失败的问题,并运行相关测试。
  25. ```
  26. Agent 会整理任务目标、完成标准、重要文件和安全边界,再调用包装脚本。调用方仍然负责检查工作区改动和重新运行真实验证命令。
  27. ## 包装脚本
  28. macOS 与 Linux:
  29. ```bash
  30. ~/.agents/skills/codex/scripts/ask_codex.sh \
  31. "检查登录流程,修复刷新失败的问题,并运行相关测试" \
  32. --workspace "/path/to/repo" \
  33. --file "src/auth.ts"
  34. ```
  35. Windows:
  36. ```powershell
  37. ~/.agents/skills/codex/scripts/ask_codex.ps1 `
  38. "检查登录流程,修复刷新失败的问题,并运行相关测试" `
  39. -Workspace "C:\path\to\repo" `
  40. -File "src\auth.ts"
  41. ```
  42. 脚本默认以最高权限创建和续接会话,并跳过 Codex 自身的沙箱和审批。只有明确需要限制权限时,才为新会话指定只读模式:
  43. ```bash
  44. ~/.agents/skills/codex/scripts/ask_codex.sh \
  45. "追踪请求路径,并引用涉及的文件和行号" \
  46. --workspace "/path/to/repo" \
  47. --read-only
  48. ```
  49. ## 调用流程
  50. <p align="center">
  51. <img src="./assets/readme/workflow.svg" width="100%" alt="调用方 Agent 通过包装脚本派发 Codex CLI 会话、读取运行产物并使用 session_id 继续任务">
  52. </p>
  53. 每次运行都会建立独立的产物目录,避免并行任务互相覆盖。脚本成功后输出:
  54. ```text
  55. session_id=<thread_id>
  56. runtime=default
  57. output_path=<path>
  58. result_path=<path>
  59. events_path=<path>
  60. elapsed=<seconds>s
  61. ```
  62. 调用方通常先读取 `output_path`,再检查工作区和验证结果。运行失败时,可以通过 `result_path` 和 `events_path` 判断失败原因。
  63. | 产物 | 内容 | 使用场景 |
  64. | --- | --- | --- |
  65. | `output_path` | 精简的 Markdown 结果 | 阅读结论、改动与有效执行记录 |
  66. | `result_path` | 结构化运行状态 | 判断成功、失败、退出码和会话信息 |
  67. | `events_path` | Codex 原始 JSONL 事件 | 诊断中断、错误和恢复问题 |
  68. ## 继续已有会话
  69. 首次任务返回 `session_id` 后,可以继续同一个 Codex 会话:
  70. ```bash
  71. ~/.agents/skills/codex/scripts/ask_codex.sh \
  72. "继续修复刚才发现的问题,并补充回归测试" \
  73. --session <session_id>
  74. ```
  75. 续接会话保留原工作区,包装脚本会再次传入最高权限参数。续接时不能指定 `--read-only` 或新的 `--sandbox`;需要受限权限时开启新会话。
  76. ## 运行环境
  77. 包装脚本始终使用 Codex CLI 当前生效的默认配置,不会根据其他目录中的配置自动切换运行环境。模型和 Provider 由 Codex CLI 配置决定。常规调用不需要指定模型、Provider 或思考强度;默认思考强度为 `high`,只有任务确实需要时才使用 `--reasoning low` 或 `--reasoning max` 覆盖。
  78. ## 常用参数
  79. | 参数 | 作用 |
  80. | --- | --- |
  81. | `--workspace <path>` | 指定 Codex 工作目录 |
  82. | `--file <path>` | 提供优先阅读的入口文件,可以重复使用 |
  83. | `--read-only` | 创建只读会话 |
  84. | `--sandbox <mode>` | 为新会话指定沙箱模式 |
  85. | `--full-auto` | 默认的最高权限,可省略;`--dangerously-bypass-approvals-and-sandbox` 是它的别名 |
  86. | `--session <id>` | 继续已有会话 |
  87. | `--ephemeral` | 不持久化新会话 |
  88. | `--output-schema <path>` | 使用 JSON Schema 约束最终结果 |
  89. | `--image <path>` | 向 Codex 附加图片 |
  90. | `--reasoning <level>` | 在必要时覆盖默认思考强度 |
  91. | `--notify` | 长任务结束后发送桌面通知 |
  92. | `--output <path>` | 指定 Markdown 结果路径 |
  93. 完整参数可以通过脚本的 `--help` 查看。
  94. ## 委托和验收
  95. 每次只委托一个边界清楚的任务。提示词应当说明:
  96. 1. 需要修改或查明什么,以及不应改动的范围。
  97. 2. 预期行为和必须覆盖的边界情况。
  98. 3. 需要运行的真实测试、检查或构建命令。
  99. 4. 不执行 `git add`、`git commit`,不顺手重构无关代码。
  100. 5. 最终报告需要包含改动原因、涉及文件、验证结果和未完成事项。
  101. Codex 返回“测试通过”不能替代调用方验收。调用方需要检查测试是否被删除、跳过或弱化,并重新运行仓库中的真实验证命令。
  102. ## 开发验证
  103. macOS 与 Linux 包装脚本的回归测试:
  104. ```bash
  105. bash tests/test_ask_codex.sh
  106. ```
  107. 测试覆盖成功运行、完整失败和已经返回会话 ID 的中途失败。
  108. ## 配置、依赖与使用边界
  109. 需要 Codex CLI 与官方登录;macOS/Linux 使用 Bash,Windows 使用 PowerShell。包装脚本可从任意实际 Skill 目录调用。
  110. 仅在用户明确要求委托时使用。任务文件与指令会交给 CLI 配置的模型;继续原会话时核对会话与目录,避免混入无关任务。
  111. 使用示例:
  112. ```text
  113. 用 Codex 处理这个明确的代码修改。
  114. ```
  115. ## 延伸阅读
  116. 关于主从 Agent 怎么分工、Codex 底层循环怎么运转,可以参考 Oil Book 里的几篇文章与译文:
  117. - [《怎样用好子 Agent》](https://book.oiloil.org/articles/subagent-workflow?utm_source=github&utm_medium=referral&utm_campaign=codex-readme)
  118. - [《拆解 Codex 的 Agent 核心循环》](https://book.oiloil.org/articles/unrolling-the-codex-agent-loop?utm_source=github&utm_medium=referral&utm_campaign=codex-readme)
  119. - [《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
  1. #!/usr/bin/env bash
  2. set -euo pipefail
  3. usage() {
  4. cat <<'USAGE'
  5. Usage:
  6. ask_codex.sh <task> [options]
  7. ask_codex.sh -t <task> [options]
  8. Task input:
  9. <task> First positional argument is the task text
  10. -t, --task <text> Alias for positional task (backward compat)
  11. (stdin) Pipe task text via stdin if no arg/flag given
  12. File context (optional, repeatable):
  13. -f, --file <path> Priority file path
  14. -i, --image <path> Image to attach to Codex
  15. Multi-turn:
  16. --session <id> Resume a previous session (thread_id from prior run)
  17. Options:
  18. -w, --workspace <path> Workspace directory (default: current directory)
  19. --reasoning <level> Optional reasoning override; normally use configured high
  20. --sandbox <mode> Explicit sandbox mode override
  21. --read-only Read-only sandbox (no file changes)
  22. --full-auto Full access (default); alias: --dangerously-bypass-approvals-and-sandbox
  23. --ephemeral Do not persist the Codex session
  24. --output-schema <path> Require the final response to match a JSON Schema
  25. --notify Desktop notification when a long run finishes (macOS/Linux; opt-in)
  26. -o, --output <path> Output file path
  27. -h, --help Show this help
  28. Output (on success):
  29. session_id=<thread_id> Use with --session for follow-up calls
  30. runtime=default Uses the local default Codex configuration
  31. output_path=<file> Path to response markdown
  32. result_path=<file> Structured run status and metadata
  33. events_path=<file> Raw Codex JSONL events for diagnostics
  34. Examples:
  35. # New task (positional)
  36. ask_codex.sh "Add error handling to api.ts" -f src/api.ts
  37. # With explicit workspace
  38. ask_codex.sh "Fix the bug" -w /other/repo
  39. # Continue conversation
  40. ask_codex.sh "Also add retry logic" --session <id>
  41. # Structured analysis with an attached image
  42. ask_codex.sh "Compare the screenshot with the implementation" \
  43. --image screenshot.png --output-schema result.schema.json
  44. USAGE
  45. }
  46. require_cmd() {
  47. if ! command -v "$1" >/dev/null 2>&1; then
  48. echo "[ERROR] Missing required command: $1" >&2
  49. exit 1
  50. fi
  51. }
  52. trim_whitespace() {
  53. awk 'BEGIN { RS=""; ORS="" } { gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, ""); print }' <<<"$1"
  54. }
  55. to_abs_if_exists() {
  56. local target="$1"
  57. if [[ -e "$target" ]]; then
  58. local dir
  59. dir="$(cd "$(dirname "$target")" && pwd)"
  60. echo "$dir/$(basename "$target")"
  61. return
  62. fi
  63. echo "$target"
  64. }
  65. resolve_file_ref() {
  66. local workspace="$1" raw="$2" cleaned
  67. cleaned="$(trim_whitespace "$raw")"
  68. [[ -z "$cleaned" ]] && { echo ""; return; }
  69. if [[ "$cleaned" =~ ^(.+)#L[0-9]+$ ]]; then cleaned="${BASH_REMATCH[1]}"; fi
  70. if [[ "$cleaned" =~ ^(.+):[0-9]+(-[0-9]+)?$ ]]; then cleaned="${BASH_REMATCH[1]}"; fi
  71. if [[ "$cleaned" != /* ]]; then cleaned="$workspace/$cleaned"; fi
  72. to_abs_if_exists "$cleaned"
  73. }
  74. append_file_refs() {
  75. local raw="$1" item
  76. IFS=',' read -r -a items <<< "$raw"
  77. for item in "${items[@]}"; do
  78. local trimmed
  79. trimmed="$(trim_whitespace "$item")"
  80. [[ -n "$trimmed" ]] && file_refs+=("$trimmed")
  81. done
  82. }
  83. # --- Parse arguments ---
  84. workspace="${PWD}"
  85. task_text=""
  86. model=""
  87. reasoning_effort=""
  88. sandbox_mode=""
  89. read_only=false
  90. fast=false
  91. ephemeral=false
  92. notify=false
  93. output_path=""
  94. output_schema=""
  95. session_id=""
  96. file_refs=()
  97. image_refs=()
  98. while [[ $# -gt 0 ]]; do
  99. case "$1" in
  100. -w|--workspace) workspace="${2:-}"; shift 2 ;;
  101. -t|--task) task_text="${2:-}"; shift 2 ;;
  102. -f|--file|--focus) append_file_refs "${2:-}"; shift 2 ;;
  103. -i|--image) image_refs+=("${2:-}"); shift 2 ;;
  104. --model) model="${2:-}"; shift 2 ;;
  105. --reasoning) reasoning_effort="${2:-}"; shift 2 ;;
  106. --fast) fast=true; shift ;;
  107. --sandbox) sandbox_mode="${2:-}"; [[ -n "$sandbox_mode" ]] || { echo "[ERROR] --sandbox requires a mode." >&2; exit 1; }; read_only=false; shift 2 ;;
  108. --read-only) read_only=true; sandbox_mode=""; shift ;;
  109. --full-auto|--dangerously-bypass-approvals-and-sandbox)
  110. read_only=false; sandbox_mode=""; shift ;;
  111. --ephemeral) ephemeral=true; shift ;;
  112. --output-schema) output_schema="${2:-}"; shift 2 ;;
  113. --notify) notify=true; shift ;;
  114. --session) session_id="${2:-}"; shift 2 ;;
  115. -o|--output) output_path="${2:-}"; shift 2 ;;
  116. -h|--help) usage; exit 0 ;;
  117. -*) echo "[ERROR] Unknown option: $1" >&2; usage >&2; exit 1 ;;
  118. *) if [[ -z "$task_text" ]]; then task_text="$1"; shift; else echo "[ERROR] Unexpected argument: $1" >&2; usage >&2; exit 1; fi ;;
  119. esac
  120. done
  121. selected_runtime="default"
  122. require_cmd codex
  123. require_cmd jq
  124. # --- Validate inputs ---
  125. if [[ ! -d "$workspace" ]]; then
  126. echo "[ERROR] Workspace does not exist: $workspace" >&2; exit 1
  127. fi
  128. workspace="$(cd "$workspace" && pwd)"
  129. if [[ -z "$task_text" && ! -t 0 ]]; then
  130. task_text="$(cat)"
  131. fi
  132. task_text="$(trim_whitespace "$task_text")"
  133. if [[ -z "$task_text" ]]; then
  134. echo "[ERROR] Request text is empty. Pass a positional arg, --task, or stdin." >&2; exit 1
  135. fi
  136. # --- Build file context block ---
  137. file_block=""
  138. if (( ${#file_refs[@]} > 0 )); then
  139. file_block=$'\nPriority files (read these first before making changes):'
  140. for ref in "${file_refs[@]}"; do
  141. resolved="$(resolve_file_ref "$workspace" "$ref")"
  142. [[ -z "$resolved" ]] && continue
  143. exists_tag="missing"
  144. [[ -e "$resolved" ]] && exists_tag="exists"
  145. file_block+=$'\n- '"${resolved} (${exists_tag})"
  146. done
  147. fi
  148. # --- Build prompt ---
  149. prompt="$task_text"
  150. if [[ -n "$file_block" ]]; then
  151. prompt+=$'\n'"$file_block"
  152. fi
  153. # --- Validate optional reasoning override ---
  154. if [[ -n "$reasoning_effort" ]]; then
  155. case "$reasoning_effort" in
  156. minimal|low|medium|high|xhigh|max|ultra) ;;
  157. *) echo "[ERROR] Unsupported reasoning effort: $reasoning_effort" >&2; exit 1 ;;
  158. esac
  159. fi
  160. if [[ -n "$session_id" && ( "$read_only" == true || -n "$sandbox_mode" ) ]]; then
  161. echo "[ERROR] Codex resume does not support --read-only or --sandbox here. Start a new session for a restricted run." >&2
  162. exit 1
  163. fi
  164. if [[ -n "$output_schema" ]]; then
  165. output_schema="$(resolve_file_ref "$workspace" "$output_schema")"
  166. [[ -f "$output_schema" ]] || { echo "[ERROR] Output schema not found: $output_schema" >&2; exit 1; }
  167. fi
  168. resolved_images=()
  169. if (( ${#image_refs[@]} > 0 )); then
  170. for image_ref in "${image_refs[@]}"; do
  171. resolved_image="$(resolve_file_ref "$workspace" "$image_ref")"
  172. [[ -f "$resolved_image" ]] || { echo "[ERROR] Image not found: $resolved_image" >&2; exit 1; }
  173. resolved_images+=("$resolved_image")
  174. done
  175. fi
  176. # --- Prepare unique run artifacts ---
  177. timestamp="$(date -u +"%Y%m%d-%H%M%S")"
  178. state_root="${CODEX_SKILL_STATE_HOME:-${XDG_STATE_HOME:-$HOME/.local/state}/codex-skill}"
  179. mkdir -p "$state_root"
  180. run_dir="$(mktemp -d "$state_root/run-${timestamp}-XXXXXX")"
  181. result_path="$run_dir/result.json"
  182. events_path="$run_dir/events.jsonl"
  183. stderr_path="$run_dir/stderr.log"
  184. if [[ -z "$output_path" ]]; then
  185. output_path="$run_dir/result.md"
  186. fi
  187. mkdir -p "$(dirname "$output_path")"
  188. # --- Build codex command ---
  189. common_args=(--json --skip-git-repo-check)
  190. if [[ -n "$reasoning_effort" ]]; then
  191. common_args+=(-c "model_reasoning_effort=\"$reasoning_effort\"")
  192. fi
  193. if [[ "$fast" == true ]]; then
  194. common_args+=(-c 'service_tier="fast"' -c 'features.fast_mode=true')
  195. fi
  196. if [[ -n "$session_id" ]]; then
  197. # Current Codex resume supports JSON, model/image/schema overrides, and non-git workspaces.
  198. cmd=(codex exec resume "${common_args[@]}" --dangerously-bypass-approvals-and-sandbox)
  199. [[ -n "$model" ]] && cmd+=(-m "$model")
  200. [[ "$ephemeral" == true ]] && cmd+=(--ephemeral)
  201. [[ -n "$output_schema" ]] && cmd+=(--output-schema "$output_schema")
  202. if (( ${#resolved_images[@]} > 0 )); then
  203. for resolved_image in "${resolved_images[@]}"; do cmd+=(--image "$resolved_image"); done
  204. fi
  205. cmd+=("$session_id" -)
  206. else
  207. # New session
  208. cmd=(codex exec --cd "$workspace" "${common_args[@]}")
  209. if [[ "$read_only" == true ]]; then
  210. cmd+=(--sandbox read-only)
  211. elif [[ -n "$sandbox_mode" ]]; then
  212. cmd+=(--sandbox "$sandbox_mode")
  213. else
  214. cmd+=(--dangerously-bypass-approvals-and-sandbox)
  215. fi
  216. [[ -n "$model" ]] && cmd+=(-m "$model")
  217. [[ "$ephemeral" == true ]] && cmd+=(--ephemeral)
  218. [[ -n "$output_schema" ]] && cmd+=(--output-schema "$output_schema")
  219. if (( ${#resolved_images[@]} > 0 )); then
  220. for resolved_image in "${resolved_images[@]}"; do cmd+=(--image "$resolved_image"); done
  221. fi
  222. fi
  223. # --- Progress watcher function ---
  224. print_progress() {
  225. local line="$1"
  226. local item_type cmd_str preview
  227. # Fast string checks before calling jq
  228. case "$line" in
  229. *'"item.started"'*'"command_execution"'*)
  230. 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)
  231. [[ -n "$cmd_str" ]] && echo "[codex] > $cmd_str" >&2
  232. ;;
  233. *'"item.completed"'*'"agent_message"'*)
  234. preview=$(printf '%s' "$line" | jq -r '.item.text // empty' 2>/dev/null | head -1 | cut -c1-120)
  235. [[ -n "$preview" ]] && echo "[codex] $preview" >&2
  236. ;;
  237. esac
  238. }
  239. write_result() {
  240. local status="$1" exit_code="$2" error_message="${3:-}"
  241. local finished_at stderr_tail result_tmp
  242. finished_at="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
  243. stderr_tail=""
  244. if [[ "$status" != "completed" ]]; then
  245. stderr_tail="$(tail -n 20 "$stderr_file" 2>/dev/null || true)"
  246. fi
  247. result_tmp="$result_path.tmp.$$"
  248. jq -n \
  249. --arg status "$status" \
  250. --argjson exit_code "$exit_code" \
  251. --arg runtime "$selected_runtime" \
  252. --arg run_id "$(basename "$run_dir")" \
  253. --arg workspace "$workspace" \
  254. --arg session_id "${thread_id:-}" \
  255. --arg final_message "${summary_text:-}" \
  256. --arg output_path "$output_path" \
  257. --arg events_path "$events_path" \
  258. --arg stderr_path "$stderr_path" \
  259. --argjson elapsed "${elapsed:-0}" \
  260. --arg started_at "$started_at" \
  261. --arg finished_at "$finished_at" \
  262. --arg stderr_tail "$stderr_tail" \
  263. --arg error "$error_message" \
  264. '{
  265. schema: "codex-skill.run.v1",
  266. status: $status,
  267. exit_code: $exit_code,
  268. runtime: $runtime,
  269. run_id: $run_id,
  270. workspace: $workspace,
  271. session_id: (if $session_id == "" then null else $session_id end),
  272. final_message: $final_message,
  273. output_path: $output_path,
  274. events_path: $events_path,
  275. stderr_path: $stderr_path,
  276. elapsed_seconds: $elapsed,
  277. started_at: $started_at,
  278. finished_at: $finished_at,
  279. stderr_tail: (if $stderr_tail == "" then null else $stderr_tail end),
  280. error: (if $error == "" then null else $error end)
  281. }' > "$result_tmp"
  282. mv "$result_tmp" "$result_path"
  283. }
  284. # --- Execute and capture output ---
  285. stderr_file="$stderr_path"
  286. json_file="$events_path"
  287. prompt_file="$(mktemp)"
  288. trap 'rm -f "$prompt_file"' EXIT
  289. : > "$stderr_file"
  290. : > "$json_file"
  291. # Write prompt to a temp file and pipe from there to avoid shell argument
  292. # length issues and encoding problems with very long or multi-byte prompts.
  293. printf "%s\n" "$prompt" > "$prompt_file"
  294. # Run codex and capture its output.
  295. # We prefer `script` to allocate a pseudo-TTY, which forces codex to line-buffer
  296. # its output so progress events arrive in real time. However, `script` requires a
  297. # real controlling terminal and fails with "tcgetattr/ioctl: Operation not supported
  298. # on socket" in socket-based environments (e.g. some Claude Code sandboxes). We
  299. # detect this upfront and fall back to direct execution — output may arrive all at
  300. # once at the end, but the task still completes correctly.
  301. run_codex() {
  302. # BSD script (macOS): script [-q] [file [command...]]
  303. # util-linux script (Linux): script [-q] -c <command> [file]
  304. # Probe the local variant and use matching syntax for PTY allocation.
  305. # Falls back to direct execution if neither probe succeeds (e.g. socket stdin).
  306. local os
  307. os="$(uname -s)"
  308. if [[ "$os" == "Darwin" ]]; then
  309. if script -q /dev/null true >/dev/null 2>&1; then
  310. script -q /dev/null /bin/bash -c \
  311. "cd $(printf '%q' "$workspace") && $(printf '%q ' "${cmd[@]}") < $(printf '%q' "$prompt_file") 2>$(printf '%q' "$stderr_file")"
  312. return
  313. fi
  314. else
  315. if script -q -c "true" /dev/null >/dev/null 2>&1; then
  316. script -q -c \
  317. "cd $(printf '%q' "$workspace") && $(printf '%q ' "${cmd[@]}") < $(printf '%q' "$prompt_file") 2>$(printf '%q' "$stderr_file")" \
  318. /dev/null
  319. return
  320. fi
  321. fi
  322. # Fallback: direct execution (no PTY; progress events arrive in batch)
  323. (cd "$workspace" && "${cmd[@]}" < "$prompt_file" 2>"$stderr_file")
  324. }
  325. # Errexit is relaxed around the streaming pipeline so a non-zero codex exit still
  326. # lets us surface captured output / a clear error instead of aborting silently.
  327. started_at="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
  328. start_ts=$SECONDS
  329. codex_status=0
  330. set +e
  331. run_codex | while IFS= read -r line; do
  332. cleaned="${line//$'\r'/}"
  333. cleaned="${cleaned//$'\004'/}"
  334. [[ -z "$cleaned" ]] && continue
  335. if [[ "$cleaned" != \{* ]]; then
  336. if [[ "$cleaned" =~ (\{\"type\":.*)$ ]]; then
  337. cleaned="${BASH_REMATCH[1]}"
  338. else
  339. continue
  340. fi
  341. fi
  342. jq -e . >/dev/null 2>&1 <<<"$cleaned" || continue
  343. printf '%s\n' "$cleaned" >> "$json_file"
  344. case "$cleaned" in
  345. *'"item.started"'*|*'"item.completed"'*) print_progress "$cleaned" ;;
  346. esac
  347. done
  348. codex_status=${PIPESTATUS[0]}
  349. set -e
  350. elapsed=$(( SECONDS - start_ts ))
  351. # Extract the session and latest agent message before checking status so failed
  352. # runs still leave useful recovery metadata.
  353. thread_id="$(jq -r 'select(.type == "thread.started") | (.thread_id // .threadId // empty)' < "$json_file" | head -1)"
  354. [[ -z "$thread_id" ]] && thread_id="$session_id"
  355. summary_text="$(jq -rs 'map(select(.type == "item.completed" and .item.type == "agent_message") | .item.text) | (last // "")' < "$json_file" 2>/dev/null)"
  356. failure_text="$(jq -rs 'map(select(.type == "turn.failed" or .type == "error")) | (last // {}) | (.error.message // .message // "")' < "$json_file" 2>/dev/null)"
  357. if (( codex_status != 0 )) || [[ -n "$failure_text" ]]; then
  358. result_exit_code="$codex_status"
  359. (( result_exit_code == 0 )) && result_exit_code=1
  360. error_message="$failure_text"
  361. [[ -z "$error_message" ]] && error_message="Codex exited with code $result_exit_code"
  362. write_result "failed" "$result_exit_code" "$error_message"
  363. echo "[ERROR] Codex command failed (exit $result_exit_code)" >&2
  364. [[ -n "$failure_text" ]] && echo "$failure_text" >&2
  365. [[ -s "$stderr_file" ]] && cat "$stderr_file" >&2
  366. echo "status=failed"
  367. echo "runtime=$selected_runtime"
  368. [[ -n "$thread_id" ]] && echo "session_id=$thread_id"
  369. echo "result_path=$result_path"
  370. echo "events_path=$events_path"
  371. exit "$result_exit_code"
  372. fi
  373. if [[ -s "$stderr_file" ]]; then
  374. cat "$stderr_file" >&2
  375. fi
  376. # --- Process JSON output for new and resumed sessions ---
  377. # Execution trace: command executions (skipping pure file-reading/searching commands),
  378. # file write/patch operations, and any intermediate agent messages (the final one is
  379. # already shown as the summary above). Captured into a var so the section is omitted
  380. # entirely when empty (e.g. a pure read-only discussion).
  381. #
  382. # Note: zsh wraps commands in quotes, so after stripping the shell prefix the command
  383. # may start with " or ' — the regex accounts for this with [\"']?.
  384. details="$(
  385. {
  386. jq -r '
  387. select(.type == "item.completed" and .item.type == "command_execution")
  388. | .item
  389. | ((.command // "") | gsub("^/bin/zsh -lc "; "") | gsub("^/bin/bash -c "; "")) as $cmd
  390. | select($cmd | test("^[\"'"'"']?(sed |cat |head |tail |nl |rg |grep |awk |wc |find |ls )") | not)
  391. | "### Shell: `" + ($cmd[0:200]) + "`\n" + (.aggregated_output // "" | .[0:800])
  392. ' < "$json_file" 2>/dev/null
  393. jq -r '
  394. select(.type == "item.completed" and .item.type == "tool_call")
  395. | .item
  396. | if .name == "write_file" then
  397. "### File written: " + (.arguments | fromjson | .path // "unknown")
  398. elif .name == "patch_file" then
  399. "### File patched: " + (.arguments | fromjson | .path // "unknown")
  400. elif .name == "shell" then
  401. "### Shell: `" + (.arguments | fromjson | .command // "unknown")[0:200] + "`\n" + (.output // "" | .[0:800])
  402. else empty
  403. end
  404. ' < "$json_file" 2>/dev/null
  405. jq -rs 'map(select(.type == "item.completed" and .item.type == "agent_message") | .item.text) | .[:-1] | .[]' < "$json_file" 2>/dev/null
  406. }
  407. )"
  408. # Run metrics: command count + token usage (from the turn.completed event).
  409. cmd_count="$(jq -rs '[.[] | select(.type == "item.completed" and .item.type == "command_execution")] | length' < "$json_file" 2>/dev/null)"
  410. usage_footer="$(jq -rs '
  411. (map(select(.type == "turn.completed")) | last | .usage) as $u
  412. | if $u then "tokens in=\($u.input_tokens) (cached \($u.cached_input_tokens)) out=\($u.output_tokens) reasoning=\($u.reasoning_output_tokens)" else "" end
  413. ' < "$json_file" 2>/dev/null)"
  414. {
  415. [[ -n "$summary_text" ]] && printf '## Summary\n\n%s\n\n' "$summary_text"
  416. [[ -n "$details" ]] && printf '## Details\n\n%s\n\n' "$details"
  417. printf -- '---\nelapsed %ss · %s cmds' "$elapsed" "${cmd_count:-0}"
  418. [[ -n "$usage_footer" ]] && printf -- ' · %s' "$usage_footer"
  419. printf '\n'
  420. } > "$output_path"
  421. # If nothing was captured, write a fallback
  422. if [[ ! -s "$output_path" ]]; then
  423. echo "(no response from codex)" > "$output_path"
  424. fi
  425. write_result "completed" 0 ""
  426. # --- Desktop notification for long runs (opt-in via --notify or CODEX_NOTIFY=1) ---
  427. # Only fires past a minimum duration (default 30s) so quick tasks stay quiet.
  428. maybe_notify() {
  429. [[ "${CODEX_NOTIFY:-0}" == "1" || "$notify" == true ]] || return 0
  430. (( elapsed >= ${CODEX_NOTIFY_MIN_SECONDS:-30} )) || return 0
  431. local title="Codex done (${elapsed}s)"
  432. local body
  433. body="$(printf '%s' "${summary_text:-task complete}" | tr '\n' ' ' | cut -c1-120)"
  434. case "$(uname -s)" in
  435. Darwin)
  436. if command -v terminal-notifier >/dev/null 2>&1; then
  437. terminal-notifier -title "$title" -message "$body" >/dev/null 2>&1 || true
  438. else
  439. osascript -e "display notification \"${body//\"/\'}\" with title \"${title//\"/\'}\" sound name \"Glass\"" >/dev/null 2>&1 || true
  440. fi
  441. ;;
  442. Linux)
  443. command -v notify-send >/dev/null 2>&1 && notify-send "$title" "$body" >/dev/null 2>&1 || true
  444. ;;
  445. esac
  446. }
  447. maybe_notify
  448. # --- Output results ---
  449. if [[ -n "$thread_id" ]]; then
  450. echo "session_id=$thread_id"
  451. fi
  452. echo "runtime=$selected_runtime"
  453. echo "output_path=$output_path"
  454. echo "result_path=$result_path"
  455. echo "events_path=$events_path"
  456. echo "elapsed=${elapsed}s"

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.