Skip to content

feat: add OpenAI Codex CLI agent driver #497

Open

Description

@admarble

Tracking (2026-09-14). Probed against Codex 0.154 — results in docs/investigations/codex-driver-probe-2026-09.md (#1057) and the September comment. Split into a 3-node graph; this issue is the epic.

Design constraint: the driver is a subprocess, not the @openai/codex-sdk Codex class — --dangerously-bypass-hook-trust is CLI-only and without it sequant's guard hooks are silently skipped. Several ACs below are superseded by the comment; the nodes carry the current ones.

Summary

Add OpenAI Codex CLI as a third agent driver alongside Claude Code and Aider. Sequant's AgentDriver interface already supports pluggable agents — this issue covers implementing a CodexDriver, wiring it into the phase executor, and addressing the gaps between Codex CLI's execution model and Sequant's workflow assumptions.

Usage after implementation:

sequant run 123 --agent codex

Background

Sequant already supports two agent backends via the AgentDriver interface (src/lib/workflow/drivers/agent-driver.ts):

Driver Integration Style Status
ClaudeCodeDriver SDK (@anthropic-ai/claude-agent-sdk) Default, full-featured
AiderDriver CLI subprocess (aider --yes --message) Supported, self-contained prompts
CodexDriver CLI subprocess (codex exec) This issue

The AiderDriver proves the subprocess pattern works. Codex CLI's exec subcommand provides a similar non-interactive interface with structured JSONL output — a stronger integration surface than Aider's plain text.

Research Findings

Codex CLI Execution Model

Codex CLI (Rust-based, npm i -g @openai/codex) has a dedicated headless mode:

codex exec --json --full-auto -m o4-mini -C /path/to/worktree "prompt here"

Key capabilities for driver integration:

Capability Codex CLI How to Use
Non-interactive execution codex exec "prompt" Core driver method
Structured output --json flag → JSONL to stdout Parse events for result extraction
Working directory -C /path or --cd /path Pass worktree path
Model selection -m model-name From CodexSettings.model
Sandbox bypass --full-auto or --yolo Required for worktree writes
Session resumption codex exec resume <thread-id> Thread ID from thread.started event
Output capture Final message → stdout, progress → stderr Standard pipe capture
Project docs AGENTS.md loaded automatically Already generated by sequant init
Config overrides -c key=value Pass driver-specific settings
Save output to file -o result.txt Alternative capture method
Prompt via stdin echo "prompt" | codex exec For large prompts

JSONL event types (from --json):

  • thread.started → contains thread_id (for session resumption)
  • turn.started / turn.completed → agent turn lifecycle
  • item.started / item.completed → individual actions (commands, file changes, messages)
  • turn.failed / error → failure events with error details

Gap Analysis: Claude Code vs Codex vs Aider

1. Prompt Delivery & Project Context

Aspect Claude Code Aider Codex
Project docs CLAUDE.md (native) AGENTS.md (prepended to prompt) AGENTS.md (native — auto-loaded)
Phase prompts Short, invoke /skills Self-contained, full instructions Need: self-contained (like Aider)
Prompt source SDK query({ prompt }) CLI --message "prompt" CLI positional arg or stdin

Gap: Codex doesn't have Sequant skills, so it needs self-contained CODEX_PHASE_PROMPTS similar to AIDER_PHASE_PROMPTS. However, unlike Aider, Codex natively loads AGENTS.md — so the AGENTS.md content should NOT be prepended to prompts (would duplicate). The getPhasePrompt() function in phase-executor.ts needs a third branch.

2. Subagent / Task Spawning

Aspect Claude Code Aider Codex
Parallel subtasks Task() tool spawns subagents ❌ None ❌ None
Exploration agents Agent(subagent_type="Explore") Sequential execution Sequential execution

Gap: Skills like /spec, /exec, /qa reference Claude Code's Task tool for parallel work (e.g., running type checks while exploring code). Codex phase prompts must restructure these as sequential steps. Not a blocker — Aider already works without subagents.

3. Tool Naming & Capabilities

Tool Category Claude Code Codex
File read Read tool Shell commands (cat, head)
File edit Edit tool (surgical replacement) apply_patch or full file write
File search Glob, Grep tools Shell (find, grep, rg)
Shell execution Bash tool shell tool (sandboxed)
Web search WebSearch tool Built-in web search
MCP tools Native SDK integration Native config.toml integration

Gap: Phase prompts referencing Claude Code tool names (Read, Edit, Glob, Grep, Bash) won't map 1:1 to Codex. Codex phase prompts should use generic language ("read the file", "search for") rather than tool-specific names, letting the agent choose its own tools.

4. Hook System

Aspect Claude Code Codex
Hook mechanism .claude/settings.json + stdin JSON .codex/hooks.json (experimental, feature-flagged)
Pre-tool hooks PreToolUse event PreToolUse event (Bash only currently)
Post-tool hooks PostToolUse event PostToolUse event
Hook input JSON on stdin JSON on stdin (same pattern!)
Hook output Exit code (0=allow, 2=block) JSON response (deny/block decisions)

Gap: Hook systems are architecturally similar but differ in configuration format and response protocol. Sequant's sequant init generates .claude/hooks/ — it would need a parallel .codex/hooks.json generation path. This is P2 — hooks are optional for core workflow execution.

5. MCP Server Integration

Aspect Claude Code Codex
Config location .mcp.json at project root ~/.codex/config.toml under [mcp_servers]
Config format JSON (mcpServers wrapper) TOML (flat [mcp_servers.name])
Transport stdio, SSE stdio, streamable HTTP
Tool filtering N/A enabled_tools / disabled_tools per server
Per-tool approval N/A [mcp_servers.NAME.tools.TOOLNAME]

Gap: Sequant's MCP server (sequant serve) can work with Codex, but config format differs. sequant init would need to generate Codex-compatible MCP config alongside .mcp.json. The driver itself doesn't need to manage MCP — Codex loads its own MCP config natively. This is P2.

6. Session Resumption

Aspect Claude Code Codex
Resume mechanism SDK resume: sessionId option codex exec resume <thread-id>
Session ID source system.init message in SDK stream thread.started JSONL event
Cross-cwd safety Crashes if cwd changes Unknown — needs testing

Gap: Both support resumption. The CodexDriver should capture thread_id from JSONL events and return it as sessionId in AgentPhaseResult. Phase executor already guards against cross-worktree resumption.

7. Sandbox & Permissions

Aspect Claude Code Codex
Permission bypass permissionMode: "bypassPermissions" --full-auto or --yolo
Sandbox modes Container-based OS-native (Seatbelt/bubblewrap)
Write scope Unrestricted in bypass mode workspace-write = cwd only

Gap: Codex's workspace-write sandbox confines writes to the working directory. Since Sequant uses worktrees, this aligns well — -C /path/to/worktree + --full-auto should work. The --add-dir flag can add additional writable paths if needed. Need to verify that Codex can run gh CLI commands (for posting comments) under sandbox.

8. Output Parsing & QA Verdict Extraction

Aspect Claude Code Codex
Output structure SDK message types (assistant, system, result) JSONL events (item.completed, turn.completed)
Result extraction result.subtype === "success" Parse AgentMessage items from completed events
Token usage Not directly exposed turn.completed includes Usage object

Gap: The driver must parse JSONL to extract the agent's final text output, which phase-executor then scans for QA verdicts. JSONL parsing is actually better than Aider's approach (plain text) — structured events make it easy to separate agent messages from tool output.

Acceptance Criteria

P0 — Core Driver (MVP)

  • CodexDriver class in src/lib/workflow/drivers/codex.ts implementing AgentDriver
    • executePhase(prompt, config) — spawns codex exec subprocess
    • isAvailable() — checks which codex or codex --version
    • Passes --json --full-auto -C <cwd> for headless worktree execution
    • Parses JSONL stdout for agent messages and errors
    • Captures thread_id from thread.started for session resumption
    • Uses RingBuffer(50) for stdout/stderr tails (matching existing pattern)
    • Wires config.abortSignal to SIGTERM on subprocess
    • Streams output via config.onOutput?.() when verbose
    • Forwards config.env (SEQUANT_* variables) to subprocess
  • CodexSettings interface in src/lib/settings.ts
    • model?: string — model override (default: Codex CLI default)
    • sandboxMode?: string — sandbox override (default: "workspace-write")
    • extraArgs?: string[] — additional CLI flags
  • Driver registry updated in src/lib/workflow/drivers/index.ts
    • codex: (opts) => new CodexDriver(opts?.codexSettings)
  • CODEX_PHASE_PROMPTS in src/lib/workflow/phase-executor.ts
    • Self-contained prompts for all phases (spec, exec, qa, loop, etc.)
    • Use generic tool language, not Claude Code tool names
    • Include gh CLI commands for GitHub interaction
    • Do NOT prepend AGENTS.md (Codex loads it natively)
  • Prompt routing in getPhasePrompt() — three-way branch: claude-code → skills, aider → AIDER prompts + AGENTS.md, codex → CODEX prompts (no AGENTS.md prepend)
  • CLI wiring in bin/cli.ts — --agent codex works (already string-based, but verify)
  • Settings schema updated: RunSettings.codex?: CodexSettings

P1 — Session Resumption & Diagnostics

  • Session resumption via codex exec resume <thread-id> when config.sessionId is set
  • Token usage extraction from turn.completed events (log to phase metrics)
  • Error classification from JSONL turn.failed / error events (distinct from exit code)
  • doctor command validates Codex installation and API key (OPENAI_API_KEY)

P2 — Init & Configuration

  • sequant init --agent codex generates Codex-compatible project config
    • Creates .codex/config.toml with MCP server pointing to sequant serve
    • Generates AGENTS.md (already done)
    • Skips Claude Code-specific hooks/settings
  • Codex hook generation (.codex/hooks.json) for pre/post-tool hooks (if feature stabilizes)
  • Documentation: update README multi-agent section with Codex setup instructions

P3 — Advanced Integration

  • MCP bidirectional support: Codex as both MCP client (consuming sequant serve) and execution target
  • Codex-specific retry tuning: cold-start threshold may differ from Claude Code's 60s
  • Performance baseline: measure phase completion times vs Claude Code and Aider
  • Plugin packaging: .codex-plugin/ manifest for Codex marketplace (if applicable)

Implementation Notes

CodexDriver Skeleton

// src/lib/workflow/drivers/codex.ts
import { spawn } from "child_process";
import type {
  AgentDriver,
  AgentExecutionConfig,
  AgentPhaseResult,
} from "./agent-driver.js";
import { RingBuffer } from "../ring-buffer.js";

export interface CodexSettings {
  model?: string;
  sandboxMode?: string;
  extraArgs?: string[];
}

export class CodexDriver implements AgentDriver {
  name = "codex";
  private settings: CodexSettings;

  constructor(settings?: CodexSettings) {
    this.settings = settings ?? {};
  }

  async executePhase(
    prompt: string,
    config: AgentExecutionConfig,
  ): Promise<AgentPhaseResult> {
    const args = this.buildArgs(prompt, config);
    const child = spawn("codex", args, {
      cwd: config.cwd,
      env: config.env,
      stdio: ["pipe", "pipe", "pipe"],
    });

    // Parse JSONL from stdout, capture stderr
    // Extract thread_id from thread.started event
    // Extract agent messages from item.completed events
    // Wire abortSignal to SIGTERM
    // Return AgentPhaseResult
  }

  async isAvailable(): Promise<boolean> {
    try {
      execSync("which codex", { stdio: "pipe" });
      return true;
    } catch {
      return false;
    }
  }

  private buildArgs(
    prompt: string,
    config: AgentExecutionConfig,
  ): string[] {
    const args = ["exec", "--json", "--full-auto"];
    if (this.settings.model) args.push("-m", this.settings.model);
    if (config.sessionId) {
      return ["exec", "resume", config.sessionId, "--json", prompt];
    }
    if (this.settings.extraArgs) args.push(...this.settings.extraArgs);
    args.push(prompt);
    return args;
  }
}

JSONL Parsing Pattern

// Each line from stdout is a JSON event
for (const line of chunk.split("\n").filter(Boolean)) {
  const event = JSON.parse(line);
  switch (event.type) {
    case "thread.started":
      threadId = event.thread_id;
      break;
    case "item.completed":
      if (event.item?.type === "agent_message") {
        output += event.item.text;
        config.onOutput?.(event.item.text);
      }
      break;
    case "turn.completed":
      // Extract token usage from event.usage
      break;
    case "turn.failed":
    case "error":
      error = event.message || event.error;
      break;
  }
}

Phase Prompt Differences

Claude Code:  "Run the /spec {issue} workflow."     → invokes skill
Aider:        "Read issue #{issue} using gh..."      → self-contained + AGENTS.md prepended
Codex:        "Read issue #{issue} using gh..."      → self-contained, NO AGENTS.md prepend

Codex prompts should be similar to Aider's but NOT identical — Codex has different capabilities (web search, native MCP) that can be leveraged.

Key Differences from AiderDriver

Concern AiderDriver CodexDriver
Output format Plain text (stdout) JSONL events (stdout)
Session resumption Not supported Supported via thread_id
AGENTS.md handling Prepended to prompt NOT prepended (native loading)
Sandbox None (trusts aider) --full-auto (workspace-write)
File context --file flags Not needed (agent discovers files)
Auto-commits --no-auto-commits Agent manages git natively

Open Questions

  1. Codex sandbox + gh CLI: Does workspace-write sandbox allow outbound network for gh issue comment? May need --yolo or --add-dir for ~/.config/gh/.
  2. AGENTS.md double-loading: Codex auto-loads AGENTS.md — verify it doesn't conflict with worktree isolation (worktree may not have AGENTS.md copied).
  3. Codex hooks stability: The hook system is experimental and feature-flagged (codex_hooks = true). P2 work should wait for stabilization.
  4. Large prompt handling: Codex CLI positional args have shell length limits. For large phase prompts (QA with findings), stdin pipe may be needed.
  5. Cold-start threshold: Codex's Rust binary starts faster than Claude Code's Node.js SDK — the 60-second cold-start retry threshold may need tuning.

References

  • Codex CLI GitHub
  • Sequant driver interface: src/lib/workflow/drivers/agent-driver.ts
  • AiderDriver reference impl: src/lib/workflow/drivers/aider.ts
  • ClaudeCodeDriver reference impl: src/lib/workflow/drivers/claude-code.ts
  • Phase executor & prompts: src/lib/workflow/phase-executor.ts
  • AGENTS.md generation: src/lib/agents-md.ts

Activity

  1. added
    enhancement
    planned
    multi-agent
    complex
    on Apr 7, 2026
  2. admarble commented on Apr 8, 2026

    @admarble
    ContributorAuthor

    Architecture Update — Phase Registry Overlap

    #505 (Phase plugin registry) will replace the hardcoded PHASE_PROMPTS / AIDER_PHASE_PROMPTS maps in phase-executor.ts with a PhaseDefinition registry that includes a driverOverrides field for agent-specific prompts.

    Impact on this issue:

    No changes needed to the core scope — CodexDriver class, JSONL parsing, session resumption, --agent codex wiring, and sequant init --agent codex are all independent of the architecture issues.

  3. added
    backlog
    on Apr 15, 2026
  4. unitedideas commented on May 13, 2026

    @unitedideas

    The phase-registry overlap in #505 looks like the right place to keep Codex support from becoming a third copy of the same workflow rules. One extra acceptance check I would add is a migration fixture for non-equivalent harness behavior, not just command execution.

    For example, a Codex driver smoke could run against a fixture repo with:

    1. AGENTS.md at root plus a subpackage override.
    2. A Claude-oriented instruction file that mentions hooks, MCP env refs, and generated artifacts.
    3. A phase prompt that used to depend on Claude Code tool names or Task() spawning.
    4. A sequant init --agent codex output check that records what was preserved, what became advisory, and what was intentionally skipped.

    That would catch the drift class where the Codex driver technically runs but silently flattens Claude Code-specific behavior into generic prompt text.

    I wrote up the same validation shape for Claude Code -> Codex moves here, if useful as a checklist: https://bringyour.ai/codex-import-checklist.json

  5. m13v commented on May 29, 2026

    @m13v

    the gap that bit us wiring Claude Code and Codex behind one driver interface wasn't JSONL parsing, it was session resumption pretending to be symmetric. collapsing both into one sessionId on AgentPhaseResult hides that Claude Code's resume is bound to the cwd it started in and Codex's thread_id isn't. point a resumed phase at a different worktree and one backend rejects it while the other silently runs in the wrong context. same shape as your AGENTS.md double-load question: Codex auto-loads it, so a worktree missing AGENTS.md hands Codex a different prompt than Claude Code ever saw. normalize resume semantics in the driver, not just the args.

  6. admarble commented on May 30, 2026

    @admarble
    ContributorAuthor

    @m13v thank you — this is exactly right, and digging into it made it sharper. Confirmed against our code and both vendors' docs:

    • Today sessionId is a bare string on AgentPhaseResult / AgentExecutionConfig with no origin-cwd, and the only guard is canResume = sessionId && !worktreePath (phase-executor.ts:650). That blunt switch disables Claude Code resume entirely in worktree mode — it's safe only because it never actually resumes.
    • The asymmetry is real: Claude Code resume is cwd-bound (refuses/ignores a new cwd), while Codex's exec resume <thread-id> is cwd-free and silently runs in whatever cwd you hand it — sandbox roots follow along (Resuming a session silently switches the agent cwd to the caller’s directory openai/codex#4791, #4703, both closed without fixing runtime behavior). And AGENTS.md is re-discovered from the new cwd each exec, so your double-load point is the same root cause, not a separate one.
    • The trap is the next commit: wire Codex's thread_id into sessionId and relax the guard to make resume useful, and Claude Code stays safe while Codex silently runs a resumed phase in the wrong worktree.

    Fix is what you said — normalize in the driver: a structured ResumeHandle { token, originCwd, driver } plus a driver-owned canResume(handle, cwd) keyed on cwd equality, instead of one opaque id and one global boolean. Bonus, it lets resume actually work within a worktree across phases.

    Tracked in #674. Thanks again for the catch — if you're finding Sequant useful, a ⭐ on the repo is always appreciated.

  7. admarble commented on May 30, 2026

    @admarble
    ContributorAuthor

    Coordination note — #674 owns the resume-semantics contract.

    #674 (normalize agent-driver resume semantics) was spun out of this issue and owns the changes to the resume-eligibility path — AgentExecutionConfig / AgentPhaseResult and the canResume = sessionId && !worktreePath guard at phase-executor.ts:650 (replacing it with a driver-owned canResume(handle, targetCwd) + ResumeHandle { driver, token, originCwd }).

    When the Codex driver is implemented here, sequence it behind / in coordination with #674 so both don't independently edit the same resume guard. Per #674's ACs, the CodexDriver resume rule (never pass resume <thread-id> when cwd differs; AGENTS.md parity precondition) is enforced in the driver layer — implement Codex resume against that contract rather than re-deriving it. Avoids two PRs touching phase-executor.ts:650.

  8. added a commit that references this issue on May 31, 2026
  9. admarble commented on Jul 29, 2026

    @admarble
    ContributorAuthor

    July 2026 landscape update (from the multi-backend investigation behind #862 — full write-up in docs/investigations/multi-backend-2026-07.md):

    Several gap-analysis claims in this issue's body are now stale, mostly in Codex's favor:

    1. Hooks are no longer experimental/Bash-only. Codex hooks shipped v0.114 and are enabled by default (~v0.117+), with PreToolUse deny semantics (JSON permissionDecision: "deny" or exit 2) covering Bash, apply_patch, MCP tool calls, and local function tools — 10–11 events including SubagentStart/SubagentStop. The "P2, Bash-only, feature-flagged" framing in §4 can be upgraded: sequant's existing exit-2 bash hooks map over with a config translation, not a rewrite.
    2. Codex now has skills. .codex/skills/, ~/.codex/skills/, ~/.agents/skills/, plus CODEX_SKILLS_DIR. It still does not read .claude/skills/, so the "self-contained CODEX_PHASE_PROMPTS" plan in §1 has an alternative: mirror the skill tree into a Codex-readable path and keep the skills-driven workflow instead of aider-grade prompts. Note the industry is converging on .agents/skills/ as the neutral path (read by Codex, Gemini, Copilot CLI, Amp, Factory, Kilo, and opencode) — one mirror there serves every future backend, which likely obsoletes per-driver prompt rewrites as the default strategy.
    3. Subagents are GA (6 concurrent, TOML defs, Smart Approvals) — §2's "no parallel subtasks" row no longer holds.
    4. Since feat: add OpenAI Codex CLI agent driver #497 was written, AIDER_PHASE_PROMPTS was folded into the phase registry's driverOverrides — the "third branch in getPhasePrompt()" AC is now "add a codex key to driverOverrides" (or skip overrides entirely if going the skills-mirror route).

    Sequencing decision: #862 (opencode driver) is the first non-Claude backend target — opencode reads .claude/skills/ natively, so it inherits the full methodology with zero skill porting, and it's multi-provider. Codex remains the right second target/hedge (strong codex exec --json contract, hooks default-on, but OpenAI-locked and needs the skills mirror). The command-wrapper generation, init plumbing, and driver-settings patterns built for #862 (plus the #863 ready-gate plumbing fix) are all reusable here.

  10. added 2 commits that reference this issue on Sep 9, 2026
  11. admarble commented on Sep 14, 2026

    @admarble
    ContributorAuthor

    September 2026 update — probed against the real binary, four ACs change

    Codex CLI / @openai/codex-sdk 0.154.0 was run under sequant's actual assumptions (hermetic CODEX_HOME, throwaway repo + linked worktree, sequant's real 19 skills). Full write-up with evidence: docs/investigations/codex-driver-probe-2026-09.md (merged in #1057).

    Confirmed, and what it changes here:

    1. $skill works in headless exec, and all 19 sequant skills are discovered intact via an in-repo .agents/skills → ../.claude/skills symlink (bare names; a symlink into a different repo gets namespaced <repo-dir>:<name>). → Drop CODEX_PHASE_PROMPTS / driverOverrides.codex. resolvesSkills = true; the phase prompt is $<phase> <issue>.
    2. Hooks run in exec only with --dangerously-bypass-hook-trust; otherwise they are silently skipped — no stderr, no event. The flag is CLI-only (no config key; --strict-config proves [hooks] is a lenient table), and the SDK's arg list has no slot for it. → The driver is a subprocess codex exec --json; import the SDK for its ThreadEvent/ThreadItem/Usage types only. Bonus: the hook stdin payload is a superset of Claude Code's (tool_name: "Bash", tool_input.command, cwd, session_id), so the existing .claude/hooks/*.sh are candidates to run unmodified behind a .codex/config.toml wrapper.
    3. git commit inside a linked worktree succeeds under -s workspace-write. The open question on shared-.git writes is closed; no additionalDirectories needed.
    4. exec resume still adopts the caller's cwd (Resuming a session silently switches the agent cwd to the caller’s directory openai/codex#4791, run 4). @m13v's point holds in 0.154; refactor: normalize agent-driver resume semantics (origin-cwd-bound ResumeHandle, driver-owned validation) #674's canResume gate is the only guard.

    Two ACs to add: codex exec blocks on a non-TTY stdin until timeout (spawn with stdin: "ignore"); item.completed/error items are warnings (hook-trust banner, model-metadata notice) — only turn.failed and the top-level error event are fatal.

    Corrections to the body: auth env is CODEX_API_KEY, not OPENAI_API_KEY; exec defaults to a read-only sandbox; the canonical skills dir is .agents/skills (repo-scope, symlink-following), not .codex/skills; usage is per-turn with no per-model map; no maxTurns equivalent (capped stays undefined). Token metrics come free from turn.completed.usage.

    Not probed (first paid experiment of the fullsolve, not this comment): full-phase quality with the real /qa skill — 7 of 21 skills reference Task(, Agent(subagent_type, AskUserQuestion, or nested Skill(skill: "sequant:…"), none of which has a Codex equivalent; skill-body clamping on read; gh under the sandbox (network_access is the lever); ChatGPT-plan auth through exec; the hook deny path end-to-end.

    Sequencing is unchanged: #674, #862, #505 are all closed, so nothing blocks this. Build deferred until fullsolve. The recorded fixture for the parser is at src/lib/workflow/drivers/__fixtures__/codex-exec-skill-hook.jsonl.

  12. added 4 commits that reference this issue on Sep 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    backlogcomplexenhancementmulti-agentplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions