Skip to content

Built-in harness integration: Codex #1389

Closed

Description

@cwing-nvidia
No description provided.

Activity

  1. ritaneves commented on Jun 25, 2026

    @ritaneves
    Contributor

    Can be done by next week, unblocked now by sandboxing work

  2. ffrujeri commented on Jul 18, 2026

    @ffrujeri
    Contributor

    Part of #1042 (built-in harness integrations). Companion to the Claude Code integration, which this design deliberately mirrors: responses_api_agents/claude_code_agent is the reference implementation, and the Codex agent reuses its architecture (per-request isolated CLI invocation, seed → rollout → verify loop, skills staging, rollout correlation) wherever the two CLIs are equivalent.

    Goal

    Run the OpenAI Codex CLI (codex exec) as a NeMo Gym agent server, so any Gym environment can evaluate models inside the Codex harness — against OpenAI directly, or against any model backend Gym serves (vLLM, inference providers) via a Gym model server.

    The central constraint: Codex only speaks the Responses API over SSE

    Codex removed wire_api = "chat" (deprecation Dec 2025, removal Feb 2026 — openai/codex#7782). A custom provider must implement POST /v1/responses returning a streaming SSE response; a plain JSON response is rejected (stream closed before response.completed, verified empirically against codex-cli 0.144.4).

    This shapes the whole design: where Claude Code needed an Anthropic Messages ↔ Responses mapping (/v1/messages on SimpleResponsesAPIModel), Codex needs the native Gym format plus a streaming envelope and tolerance for Codex's wire dialect.

    Design

    Two parts, mirroring the Claude Code split of agent vs. model-server seam:

    1. Core seam: every Gym model server speaks the streaming Responses dialect

    New module nemo_gym/responses_streaming.py + a dispatch route on SimpleResponsesAPIModel (/v1/responses → responses_dispatch):

    • Non-streaming requests are unchanged — strict validation against NeMoGymResponseCreateParamsNonStreaming, delegate to the server's own responses(). Existing envs see identical behavior (same 422 shape on invalid bodies).
    • stream: true requests (Codex always sends this) are sanitized onto the strict params model, delegated to the same responses(), and the complete response is re-emitted as a synthesized SSE stream: response.created → response.output_item.done per output item → response.completed. Codex builds its view of the turn from output_item.done events and treats response.completed (id + usage) as terminal, so this is the minimal sufficient sequence (verified against 0.144.4).

    The sanitizer handles the dialect gap between Codex's wire format and the pinned OpenAI SDK types, with graceful degradation as the guiding principle (a dropped field or tool is recoverable; a 422 kills the rollout):

    Codex sends Gym handling
    stream, client_metadata, prompt_cache_key, other unknown top-level fields dropped (params model is extra="forbid")
    namespace tool specs (MCP tools grouped under e.g. mcp__weather) flattened to plain function tools named <namespace>__<tool>; function calls the model emits under the joined name are split back into namespace + name fields in the synthesized SSE (the wire shape Codex's tool router requires)
    namespaced function_call items replayed in input history rewritten to the joined name so the conversation stays self-consistent for the backend
    additional_tools input item (code-mode carrier; not representable in the Gym input union) plain/namespaced function tools hoisted into tools; non-function tools (the freeform JS exec orchestrator) dropped with a warning
    several leading developer messages and no instructions (newer model families) hoisted into instructions, which the Responses→Chat conversion renders as a single leading system message — strict chat backends (e.g. litellm-fronted endpoints) reject system-role messages anywhere but position 0
    nested fields newer than the pinned SDK (e.g. reasoning.context) generic prune-and-retry validation: any extra_forbidden error loc is deleted and validation retried, so only genuinely unfixable errors surface

    Two converter fixes ride along in nemo_gym/responses_converter.py:

    • instructions was silently dropped in Responses→ChatCompletions conversion (chat params ignore unknown kwargs). It is now mapped to a leading system message — this also fixes a latent bug on the Claude Code path, where the Anthropic system prompt lands in params.instructions.
    • When instructions is present, the leading run of system/developer messages is folded into that single system message (chat backends commonly admit exactly one system message, at position 0).

    Note: the capture middleware already anticipated streamed /v1/responses (_TERMINAL_SSE_LINES["responses"], _reconstruct_responses_sse), so per-rollout model-call capture works unchanged for the synthesized stream.

    2. The agent: responses_api_agents/codex_agent/

    Runs codex exec --json --ephemeral --skip-git-repo-check as an async subprocess per request and parses the JSONL event stream into NeMoGym output items.

    Per-request isolation. Each request gets a fresh CODEX_HOME (analog of the Claude agent's per-run CLAUDE_CONFIG_DIR) with a generated config.toml, plus a fresh scratch working directory passed via --cd; both are removed afterwards. The generated config pins:

    • a Gym-owned model provider (wire_api = "responses", env_key = a Gym env var) — bypasses codex login/auth.json entirely; any API key string works for local endpoints
    • approval_policy = "never" (non-interactive), sandbox_mode configurable (danger-full-access default — Gym environments are expected to provide their own isolation, mirroring the Claude agent's --dangerously-skip-permissions; OS-level sandboxing is unavailable in many containers)
    • reproducibility/isolation: analytics.enabled = false, history.persistence = "none", check_for_update_on_startup = false, web_search = "disabled", features.multi_agent = false, features.code_mode = false
    • stream_idle_timeout_ms defaults to timeout * 1000: Gym model servers emit the synthesized SSE only once the full response is computed, so the provider's idle budget must cover an entire generation

    Model-name pinning. For models Codex recognizes (its own model catalog), it applies model-family feature gating — notably code mode, which moves tools out of the tools param into an additional_tools carrier with a freeform JS exec tool that chat-served models cannot drive (shell access only exists inside the JS orchestrator). An explicit — even unknown — model name avoids this and keeps classic function tools (exec_command, write_stdin, …). When model: null and a model_server ref is set, the agent writes a gym-policy-model placeholder; Gym model servers substitute their configured model anyway.

    Gym MCP tools. When the resources server is an MCPResourcesServer, /seed_session metadata becomes a per-rollout mcp_servers entry in the generated config: a streamable-HTTP server pointing at the resources server's /mcp, with the per-rollout session token on a custom header via http_headers (supported natively by Codex's MCP client). Codex advertises these to the model as a namespace tool spec; the core seam's flatten/split makes them callable by any backend. Verified end-to-end: namespaced function_call → Codex executes the MCP tool over HTTP with the session header → mcp_tool_call item → function_call_output back to the model.

    Timeout as the only bound. Codex has no --max-turns equivalent, so timeout (default 600 s) is the runaway bound. On timeout the rollout degrades gracefully: kill Codex, return empty output, pad an empty assistant message, verify still runs (reward 0). One subtlety found live: codex on PATH is an npm shim whose child is the real vendored binary — killing only the shim leaves an orphan holding the stdout pipe, blocking the post-kill communicate(). The subprocess therefore runs in its own process group (start_new_session=True) and timeout kills the whole group.

    Event parsing. item.completed events map to a uniform trajectory shape (one function_call + function_call_output pair per tool-shaped item, so verifiers see the same structure across harnesses):

    Codex item NeMoGym items
    agent_message assistant message (buffered reasoning prepended in <think> tags, mirroring the Claude agent)
    reasoning buffered; a run ending on reasoning is surfaced as a think-tagged message rather than dropped (vLLM reasoning parsers sometimes route the final answer through the reasoning channel)
    command_execution function_call (exec_command, {"cmd": ...}) + output (nonzero exit codes annotated)
    mcp_tool_call function_call (tool name) + output (result content text / error)
    file_change / web_search / todo_list function_call (apply_patch / web_search / update_plan) + output
    turn.completed usage NeMoGymResponseUsage incl. cached and reasoning token details
    error / turn.failed collected into metadata and logged

    Everything else mirrors the Claude Code agent: model_server ref vs. direct openai_base_url, rollout-capture correlation via the /ng-rollout/<id> base-url prefix (only when a model server is configured — a real endpoint has no prefix-stripping middleware), skills staged into CODEX_HOME/skills/ from the run-level skills_ref (Codex discovers them natively — no discovery flag needed, unlike --bare), turns_used/finished_naturally on the verify response, npm/local-Node auto-install on startup, and an extra_config deep-merge knob for arbitrary config.toml content (per-rollout Gym MCP entries win name collisions).

    Subprocess detail: stdin is explicitly /dev/null — with a piped stdin, codex exec blocks waiting to append it to the prompt.

    Configs

    • responses_api_agents/codex_agent/configs/codex_agent.yaml — base agent config
    • resources_servers/reasoning_gym/configs/reasoning_gym_codex_agent.yaml — direct Responses-native endpoint (OpenAI)
    • resources_servers/reasoning_gym/configs/reasoning_gym_codex_agent_model_server.yaml — via a Gym model server (policy_model); needs no openai_* vars and works with chat-completions-only backends
    gym env start \
      --resources-server reasoning_gym/reasoning_gym_codex_agent_model_server \
      --model-type vllm_model
    
    gym eval run --no-serve \
      --agent reasoning_gym_codex_agent_model_server \
      --input resources_servers/reasoning_gym/data/example.jsonl \
      --output codex_rollout.jsonl --limit 1

    Validation

    All behaviors above were verified against the real CLI (codex-cli 0.144.4), not just mocks:

    • Unit tests: ~45 agent tests (command/config/TOML generation, home staging + cleanup, timeout/process-group kill, MCP config, rollout correlation, event parsing) and ~25 core tests (sanitizer, SSE synthesis, dispatch route incl. strict non-streaming regression, converter instructions mapping). Full suite: 1270 passed.
    • Live CLI ↔ Gym model server: Codex called exec_command, Gym (vLLM dialect → chat completions → Qwen endpoint) returned the tool call, Codex executed echo $((17*23)) → 391, multi-turn history (reasoning + function_call + output replay) validated round trip.
    • Live MCP round trip: header-gated streamable-HTTP FastMCP server (the Gym resources-server stack) → namespaced tool call → executed with per-rollout session token.
    • Full gym eval run: 2 reasoning_gym rollouts through the composed config, producing rollout JSONL + aggregate metrics (incl. one rollout exercising the timeout → reward-0 degradation path).

    Limitations / follow-ups

    • Eval only — token IDs / logprobs not wired up (same as Claude Code agent).
    • Token counts come from Codex's own turn.completed usage reporting.
    • turns_used counts assistant messages, not tool calls.
    • No --max-turns equivalent; timeout is the only runaway bound.
    • Code mode (JS tool orchestration) is fundamentally incompatible with chat-served backends; the seam degrades it gracefully (function tools preserved, JS exec dropped with a warning) but the supported path is classic function tools via explicit model naming.
    • reasoning_gym_codex_agent* configs are verified: false pending reward-profile baselining.
  3. moved this from Dev Todo to Dev WIP in NeMo Gym 0.5.0 - Aug 5on Jul 20, 2026
  4. added
    waiting-on-maintainers
    on Jul 23, 2026
  5. removed
    waiting-on-maintainers
    on Jul 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions