Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/TASK_DEFINITION_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,8 @@ validates its own keys at YAML load:
dataclass; framework-managed keys (`model`, `allowed_tools`,
`permission_mode`, `hooks`, `mcp_servers`, …) are rejected. See the
[Claude Code guide](agents/CLAUDE_CODE.md).
- `codex` — only `effort`, sent as the reasoning effort of every turn. See the
[Codex guide](agents/CODEX.md#reasoning-effort).
- `delegate` — only `effort`. See the [Delegate guide](agents/DELEGATE.md).

Deep-merged across the 5-layer config chain. Override via CLI with the
Expand All @@ -220,7 +222,7 @@ See [Codex](agents/CODEX.md#tool-output-cap).
> **Codex note:** `permission_mode` confines the **`claude-code`** agent only. The **`codex`** agent always runs full-access regardless of the mode — its in-process OS sandbox is redundant given Coder Eval's docker/tempdir isolation and unusable on our CI hosts (and on Windows). Run adversarial or untrusted Codex evals under the **docker driver**, which is the OS-level write boundary; the tempdir/host driver is a working directory, not a confinement boundary.

**Agent Types:**
- `claude-code` (default) — Claude Code SDK agent. Supports `sdk_options`, `claude_settings`, and all permission modes.
- `claude-code` (default) — Claude Code SDK agent. Supports `claude_settings` and all permission modes.
- `codex` — OpenAI Codex agent (requires `[codex]` extra; set `CODEX_API_KEY` and optional `CODEX_BASE_URL` environment variables).
- `none` — No-op agent: no coding agent runs and no model API call is made. See [No-op / System Tasks](#no-op--system-tasks-type-none) below.

Expand Down
9 changes: 9 additions & 0 deletions docs/agents/CODEX.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,15 @@ default). Before this change Codex applied its own default (10000 tokens for cat
10,000 bytes for models outside its bundled catalog such as `gpt-6.1-sol`), so compare trend
lines across this commit with that in mind.

### Reasoning Effort

`agent.sdk_options.effort` is sent as the `effort` of every turn, which overrides the
`model_reasoning_effort` in `$CODEX_HOME/config.toml`. It is one of Codex's tiers: `none`,
`minimal`, `low`, `medium`, `high`, `xhigh`, `max`, `ultra`; a model may accept fewer, and
another key or tier is a validation error at load. Unset, the host's
`config.toml` value applies, or else the model's default. It is the same `sdk_options.effort`
key Claude Code and Delegate take, so `-D agent.sdk_options.effort=high` drives all three.

### Skills Discovery

The agent sets up SKILL.md files (Agent Skills open standard) in `.agents/skills/` directory:
Expand Down
2 changes: 1 addition & 1 deletion docs/agents/DELEGATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ Run-limit semantics per harness: [Run-Limit Parity](HARNESS_PARITY.md).
2. **`max_turns` is enforced by coder_eval, not by the host.** The host's `maxSteps` option on `send` does not stop the turn (confirmed live: `maxSteps: 2` ran 7 steps and only reported `maxStepsReached: true`), so this agent does not send it. It counts a call on the call's first streamed text, or on its `usage` frame when the call streams none. The host runs a batched reply's tools one at a time, so tool events do not mark a call. See [Run-Limit Parity](HARNESS_PARITY.md).
A turn cut at `max_turns`, or by a cooperative early stop, keeps the token usage and cost of every model call that finished before the cut, as on the other agents. The host sends a `usage` frame for each call before that call's tool results. Which side of the cut the crossing call lands on depends on its shape. A call that streams text is cut at that text, before its `usage` frame and before any of its tools, so its usage is dropped. A tool-only call is cut at its own `usage` frame, so its usage is booked, and its first tool can start before the kill: the host starts a call's tools right after the frame, and the stream gives no earlier boundary. When the `result` arrives, the agent compares its own call count with the host's `turnUsages` and logs a warning if they differ, because a change in the host's frame order would move the cap. A host that does not send `usage` frames reports usage only on its final `result` frame, which a cut turn never gets: that turn has no usage, and the agent logs a warning.
3. **Only three backend failures get a specific diagnosis.** A Cloudflare WAF block page is reported as a content-filter failure and is not retried: the same prompt or tool result is blocked again. An SSE connect timeout is reported as a connection failure and is retried. A session conflict ("A reply is already being generated") is retried in a new conversation when no turn of that conversation has finished. After a finished turn, or with a `session_id` set in the config, the retry stays in the same conversation, so the agent never continues without its earlier turns: the retry succeeds once the backend releases the conversation (it stops the reply when the host disconnects), or the task ends as an error. There is no first-response stall detection: a stalled turn ends at its turn timeout. Every other crash ends the turn as an `AgentCrashError`, which is retried unless its message matches a category that is not retried (a timeout, or an auth, billing or content-filter error).
4. **`sdk_options` accepts only `effort`.** Reasoning effort uses the same `sdk_options.effort` key as Claude Code, so `-D agent.sdk_options.effort=high` works for both agents. Any other key, or an `effort` that is not a string, is a validation error. The host checks the tier itself: it logs a tier it does not recognize and uses the model's default. `project_id`, `session_id` and `enable_computer_use` are typed config fields.
4. **`sdk_options` accepts only `effort`.** Reasoning effort uses the same `sdk_options.effort` key as Claude Code and Codex, so `-D agent.sdk_options.effort=high` works for all three. Any other key, or an `effort` that is not a string, is a validation error. The host checks the tier itself: it logs a tier it does not recognize and uses the model's default. `project_id`, `session_id` and `enable_computer_use` are typed config fields.
5. **`enable_computer_use: true` requires local permissions and is unavailable on Linux.** macOS needs Accessibility + Screen Recording grants; the SDK throws unconditionally on Linux when this is enabled.

## Testing
Expand Down
11 changes: 10 additions & 1 deletion src/coder_eval/agents/codex_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -1803,6 +1803,15 @@ def _build_thread_options(self) -> dict[str, Any]:

return options

def _build_turn_options(self) -> dict[str, Any]:
"""Build ``thread.turn`` options from agent config: the reasoning effort, when one is set."""
effort = self.config.sdk_options.get("effort")
if effort is None:
return {}
from openai_codex.api import ReasoningEffort # pyright: ignore[reportPrivateImportUsage]

return {"effort": ReasoningEffort(effort)}

def _log_config_enforcement(self) -> None:
"""Log configuration settings."""
if self.config.allowed_tools:
Expand Down Expand Up @@ -1855,7 +1864,7 @@ async def _run_turn_with_streaming(
latches on) and BEFORE the next notification is pulled.
"""
# Starts the turn without blocking, and opens the event stream.
turn_handle = await self._run_async(self.thread.turn, state.user_input)
turn_handle = await self._run_async(self.thread.turn, state.user_input, **self._build_turn_options())
self._active_turn_handle = turn_handle
stream = await self._run_async(turn_handle.stream)

Expand Down
63 changes: 49 additions & 14 deletions src/coder_eval/models/agent_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,11 +367,52 @@ def check_single_auto_compact_source(self) -> Self:
return self


_EFFORT_ONLY_SDK_OPTION_FIELDS: frozenset[str] = frozenset({"effort"})
# openai_codex.api.ReasoningEffort at the pinned SDK, listed here because base installs load this
# module without the SDK. A model may accept fewer tiers than Codex knows.
_CODEX_EFFORT_TIERS: frozenset[str] = frozenset({"none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"})


def _validate_effort_only_sdk_options(
v: dict[str, Any], *, options: str, tiers: frozenset[str] | None = None
) -> dict[str, Any]:
"""Reject every ``sdk_options`` key but ``effort``, and an ``effort`` that is not a string in ``tiers``.

``options`` names the keys' owner in the error, e.g. ``"Codex options"``. ``tiers=None``
accepts any string.
"""
unknown = sorted(set(v) - _EFFORT_ONLY_SDK_OPTION_FIELDS)
if unknown:
raise ValueError(
f"sdk_options keys {unknown} are not {options} coder_eval forwards "
+ f"(valid keys: {sorted(_EFFORT_ONLY_SDK_OPTION_FIELDS)})"
)
if "effort" not in v:
return v
effort = v["effort"]
if not isinstance(effort, str):
raise ValueError(f"sdk_options.effort must be a string tier, got {effort!r}")
if tiers is not None and effort not in tiers:
raise ValueError(f"sdk_options.effort must be one of {sorted(tiers)}, got {effort!r}")
return v


class CodexAgentConfig(BaseAgentConfig):
"""Codex agent configuration."""

type: Literal[AgentKind.CODEX] # type: ignore[assignment]

sdk_options: dict[str, Any] = Field(
default_factory=dict,
description=(
"Pass-through options coder_eval forwards to Codex. Allowed keys: "
f"{sorted(_EFFORT_ONLY_SDK_OPTION_FIELDS)}. 'effort' is the reasoning-effort tier, sent "
f"as the effort of every turn; one of {sorted(_CODEX_EFFORT_TIERS)}, of which a model "
"may accept fewer. Unset leaves the model_reasoning_effort in the host "
"$CODEX_HOME/config.toml, or else the model's default."
),
)

# Codex clamps the value to the model's catalog maximum itself and compacts at 90% of it.
# The floor rejects a window too small to work in, such as a dropped "000" or a YAML
# `yes` that loads as 1.
Expand All @@ -392,6 +433,11 @@ class CodexAgentConfig(BaseAgentConfig):
),
)

@field_validator("sdk_options")
@classmethod
def _validate_sdk_options(cls, v: dict[str, Any]) -> dict[str, Any]:
return _validate_effort_only_sdk_options(v, options="Codex options", tiers=_CODEX_EFFORT_TIERS)

def egress_hosts(self, env: Mapping[str, str]) -> tuple[str, ...]:
"""The ``CODEX_BASE_URL`` host when it is forwarded, else ``api.openai.com``.

Expand Down Expand Up @@ -527,9 +573,6 @@ def egress_hosts(self, env: Mapping[str, str]) -> tuple[str, ...]:
return (_PI_PROVIDER_HOSTS.get(provider if model_id else "", "openrouter.ai:443"),)


_DELEGATE_SDK_OPTION_FIELDS: frozenset[str] = frozenset({"effort"})


class DelegateAgentConfig(BaseAgentConfig):
"""Delegate agent configuration (UiPath Autopilot's Delegate agent).

Expand All @@ -554,7 +597,7 @@ class DelegateAgentConfig(BaseAgentConfig):
default_factory=dict,
description=(
"Pass-through dict of delegate-stdio init options that coder_eval does not own "
f"directly. Allowed keys: {sorted(_DELEGATE_SDK_OPTION_FIELDS)}. 'effort' is the "
f"directly. Allowed keys: {sorted(_EFFORT_ONLY_SDK_OPTION_FIELDS)}. 'effort' is the "
"reasoning-effort tier (documented values: low/medium/high/xhigh/max): it must be a "
"string, forwarded as-is, and the host ignores a tier it does not recognize."
),
Expand Down Expand Up @@ -587,16 +630,8 @@ class DelegateAgentConfig(BaseAgentConfig):

@field_validator("sdk_options")
@classmethod
def _validate_sdk_options_keys(cls, v: dict[str, Any]) -> dict[str, Any]:
unknown = sorted(set(v) - _DELEGATE_SDK_OPTION_FIELDS)
if unknown:
raise ValueError(
f"sdk_options keys {unknown} are not delegate-stdio init options coder_eval forwards "
+ f"(valid keys: {sorted(_DELEGATE_SDK_OPTION_FIELDS)})"
)
if "effort" in v and not isinstance(v["effort"], str):
raise ValueError(f"sdk_options.effort must be a string tier, got {v['effort']!r}")
return v
def _validate_sdk_options(cls, v: dict[str, Any]) -> dict[str, Any]:
return _validate_effort_only_sdk_options(v, options="delegate-stdio init options")


class NoneAgentConfig(BaseAgentConfig):
Expand Down
7 changes: 7 additions & 0 deletions src/coder_eval/reports/markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@ def collect_agent_settings_rows(
run is visibly an append run rather than indistinguishable from a
pre-marker one; when absent (older runs) the regime is inferred from the
persisted prompt's shape and only surfaced if it was ``replace``.

An ``agent_config`` source (``is_sdk`` false) shows its ``sdk_options.effort``, so
a Codex run, which records no SDK options, still shows its effort.
"""
rows: list[tuple[str, str]] = [
("Permission Mode", str(settings_source.get("permission_mode", "N/A"))),
Expand Down Expand Up @@ -153,6 +156,10 @@ def collect_agent_settings_rows(
prompt_mode = system_prompt_semantics or inferred_mode
if prompt_mode is not None:
rows.append(("System Prompt Mode", prompt_mode))
else:
configured = settings_source.get("sdk_options")
if isinstance(configured, dict) and configured.get("effort") is not None:
rows.append(("Effort", str(configured["effort"])))

plugins = settings_source.get("plugins")
if isinstance(plugins, list):
Expand Down
71 changes: 71 additions & 0 deletions tests/test_codex_reasoning_effort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""``agent.sdk_options.effort`` on Codex: the reasoning-effort tier, sent as the effort of every turn."""

from __future__ import annotations

import os
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import patch

import pytest
from pydantic import ValidationError

from coder_eval.models import AgentKind, parse_agent_config
from coder_eval.models.agent_config import _CODEX_EFFORT_TIERS
from coder_eval.reports.markdown import collect_agent_settings_rows


async def _turn_options(working_dir: Path, **config_kwargs: Any) -> dict[str, Any]:
"""The keyword options one ``communicate()`` passes to ``thread.turn``."""
pytest.importorskip("openai_codex")
from coder_eval.agents.codex_agent import CodexAgent
from tests._fixtures.golden_streams.codex_fixtures import CODEX_SCENARIOS, _FakeThread

seen: list[dict[str, Any]] = []

class _RecordingThread(_FakeThread):
def turn(self, user_input: str, **options: Any) -> Any:
seen.append(options)
return super().turn(user_input)

scenario = next(s for s in CODEX_SCENARIOS if s.name == "a_agent_message_only")
agent = CodexAgent(parse_agent_config(type=AgentKind.CODEX, model="example-model", **config_kwargs))
agent.working_directory = working_dir
agent.codex_client = SimpleNamespace(close=lambda: None)
agent.thread = _RecordingThread(scenario.notifications)
with patch.dict(os.environ, {"CODEX_HOME": str(working_dir)}):
await agent.communicate("do it")
assert len(seen) == 1
return seen[0]


class TestTurnOptions:
async def test_an_effort_reaches_the_turn(self, tmp_path):
api = pytest.importorskip("openai_codex.api")
options = await _turn_options(tmp_path, sdk_options={"effort": "high"})
assert options == {"effort": api.ReasoningEffort.high}

async def test_no_effort_leaves_the_codex_default(self, tmp_path):
assert await _turn_options(tmp_path) == {}


class TestValidation:
def test_the_tiers_match_the_sdk(self):
api = pytest.importorskip("openai_codex.api")
assert {tier.value for tier in api.ReasoningEffort} == _CODEX_EFFORT_TIERS

def test_a_key_codex_is_not_sent_is_rejected(self):
with pytest.raises(ValidationError, match="are not Codex options"):
parse_agent_config(type=AgentKind.CODEX, sdk_options={"max_thinking_tokens": 1024})

@pytest.mark.parametrize("effort", ["extreme", 3, None, ["high"], {"tier": "high"}])
def test_an_effort_codex_does_not_know_is_rejected(self, effort):
with pytest.raises(ValidationError, match=r"sdk_options\.effort must be"):
parse_agent_config(type=AgentKind.CODEX, sdk_options={"effort": effort})


def test_the_agent_settings_show_the_effort():
config = parse_agent_config(type=AgentKind.CODEX, sdk_options={"effort": "high"})
rows = dict(collect_agent_settings_rows(config.model_dump(), is_sdk=False))
assert rows["Effort"] == "high"
Loading
Loading