Skip to content

Commit ea9da31

Browse files
committed
Add example of using local Codex agent
1 parent 9828a20 commit ea9da31

6 files changed

Lines changed: 545 additions & 0 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,4 @@ Gemfile.lock
1111
runs/
1212
my-bench/
1313
*.local.md
14+
.vscode/

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@ See [examples](./examples) for real-world extensions:
340340

341341
- [Apple Container backend](./examples/apple-container.rb)
342342
- [Claude Code agent](./examples/claude-code.rb)
343+
- [Codex agent](./examples/codex/README.md)
343344

344345
## CLI
345346

‎examples/codex/README.md‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# Codex agent
2+
3+
A Lemans extension that runs the Codex CLI using your ChatGPT subscription. It saves an ATIF trajectory for lemans-viewer and a native session checkpoint for recovery.
4+
5+
## Run
6+
7+
Use the installed `lemans` command, start Docker Desktop, and authenticate as described below. From your benchmark project's root, create `benches/codex/bench.yml` to reuse your root `bench.yml` and existing tasks:
8+
9+
```yaml
10+
inherit_from: ../../bench.yml
11+
tasks: ../../tasks
12+
13+
environment:
14+
backend: docker
15+
16+
agent:
17+
name: codex
18+
model: gpt-6.1-sol#medium
19+
timeout: 90m
20+
cost_limit: null
21+
environment:
22+
network:
23+
mode: allowlist
24+
hosts: [chatgpt.com, auth.openai.com]
25+
```
26+
27+
The inherited config supplies the Docker image, setup, and verifier. Preinstalling a pinned Codex CLI version in that image is recommended for faster setup and reliable recovery. If `codex` is absent, the adapter installs it automatically using the Codex installer; setup needs network access to download it.
28+
29+
Run from the same project root, assuming the Lemans checkout is at `tmp/lemans` (adjust `CODEX_AGENT` otherwise):
30+
31+
```sh
32+
export CODEX_AGENT="$PWD/tmp/lemans/examples/codex/agent.rb"
33+
34+
lemans -r "$CODEX_AGENT" run \
35+
--bench benches/codex \
36+
--task TASK_NAME \
37+
-c 1 \
38+
--runs-dir tmp/codex-runs
39+
```
40+
41+
Replace `TASK_NAME` with a task from your benchmark. The extension files must be available locally; they are not bundled with the gem.
42+
43+
## Recover
44+
45+
```sh
46+
lemans -r "$CODEX_AGENT" restart TASK_NAME__TRIAL_ID \
47+
--bench benches/codex \
48+
--recover --allow-scored \
49+
-c 1 \
50+
--runs-dir tmp/codex-runs
51+
```
52+
53+
Use the original trial ID. Recovery creates a new container, restores `agent.patch` and the native Codex session saved in `agent.result.json`, and continues the task. `--allow-scored` permits recovery of a timed-out run that Lemans already graded. Time, token usage, and estimated cost carry forward; increase `agent.timeout` before recovering if the original run exhausted it.
54+
55+
## Authentication
56+
57+
Log in on the host with file-backed credentials:
58+
59+
```sh
60+
codex -c 'cli_auth_credentials_store="file"' login
61+
```
62+
63+
The adapter reads `$CODEX_HOME/auth.json`, defaulting to `~/.codex/auth.json`. To use a separate copy, set:
64+
65+
```sh
66+
export LEMANS_CODEX_AUTH_FILE="$PWD/.codex/auth.json"
67+
```
68+
69+
Each trial receives an access-token snapshot in an isolated Codex home. The refresh token is removed from the snapshot; containers never refresh credentials or write them back to the host. The access token must have at least **10 hours** remaining when the adapter starts. Otherwise, refresh the host login and update any separate copy. Authentication is supplied again on recovery and is excluded from the saved session archive. API-key authentication is unsupported.
70+
71+
## Estimated price
72+
73+
`cost_usd` estimates the equivalent standard API token cost using the OpenAI model's prices in RubyLLM's model registry. Uncached input, cache reads/writes, and output are priced separately; cache rates fall back to the regular input rate when absent. Reasoning tokens are already included in output. This is a comparison metric, not your subscription charge. If the model's prices are unknown, cost is omitted.
74+
75+
## Known limitations
76+
77+
- Dollar budgets cannot be enforced: cost is calculated after Codex exits. Set `agent.cost_limit: null` and use `agent.timeout`. Lemans's `step_limit`, `exec_timeout`, and `max_output_tokens` are not forwarded to Codex.
78+
- Subscription usage limits and access-token expiry still apply; long runs cannot refresh their credentials.
79+
- Recovery needs a saved native checkpoint and the same model and Codex CLI version. Workspace files are restored through Git patches; ignored files and files outside the worktree are not recovered.
80+
- The ATIF conversion uses the CLI event stream. System prompts, timestamps, and per-call usage are absent; `total_steps` counts completed shell commands rather than model calls.

‎examples/codex/agent.rb‎

Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
# frozen_string_literal: true
2+
3+
require "base64"
4+
require "json"
5+
require "shellwords"
6+
require "tempfile"
7+
require "time"
8+
9+
class CodexAgent < Lemans::Agent
10+
NAME = "codex"
11+
12+
PATH = "export PATH=$HOME/.local/bin:$PATH;"
13+
AUTH_HOSTS = %w[chatgpt.com auth.openai.com].freeze
14+
AUTH_HOME = "/tmp/lemans-codex-home"
15+
AUTH_PATH = "#{AUTH_HOME}/auth.json".freeze
16+
STREAM_PATH = "/tmp/lemans-codex.jsonl"
17+
18+
def self.recoverable? = true
19+
20+
def initialize(...)
21+
super
22+
@auth_file = File.expand_path(ENV["LEMANS_CODEX_AUTH_FILE"] || File.join(ENV.fetch("CODEX_HOME", "~/.codex"), "auth.json"))
23+
24+
# Cost estimates are available only after Codex exits, so they cannot enforce a budget.
25+
if profile.cost_limit
26+
raise Lemans::ConfigError, "codex: dollar budgets are unsupported; set agent.cost_limit to null and use agent.timeout"
27+
end
28+
29+
policy = profile.environment.network
30+
unless policy.public? || (policy.allowlist? && (AUTH_HOSTS - policy.domains).empty?)
31+
raise Lemans::ConfigError, "codex: the agent network must reach #{AUTH_HOSTS.join(", ")} " \
32+
"(agent.environment.network: public, or an allowlist listing them)"
33+
end
34+
35+
@auth_json = auth_snapshot
36+
end
37+
38+
def install(_task, environment)
39+
environment.exec!("set -o pipefail; #{PATH} command -v codex || { curl -fsSL https://chatgpt.com/codex/install.sh | sh && command -v codex; }",
40+
timeout: 300)
41+
environment.exec!("install -d -m 700 #{AUTH_HOME}")
42+
Tempfile.create(%w[lemans-codex-auth .json]) do |file|
43+
file.write(@auth_json)
44+
file.flush
45+
environment.upload(file.path, AUTH_PATH)
46+
end
47+
environment.exec!("chmod 600 #{AUTH_PATH}")
48+
end
49+
50+
def run(task, environment, history: nil)
51+
checkpoint = Checkpoint.new(model:, history:)
52+
version = environment.exec!("#{PATH} codex --version").output.strip.delete_prefix("codex-cli ")
53+
checkpoint.restore(environment, version:) if history
54+
remaining = (timeout - checkpoint.elapsed).floor
55+
return response_for(task, checkpoint, exit_code: 124, output: "agent.timeout already exhausted") unless remaining.positive?
56+
57+
session_id = checkpoint.session_id if history
58+
prompt = history ? Checkpoint::CONTINUATION_PROMPT : task.instruction
59+
finished = environment.exec("#{command_for(task, session_id:, prompt:)} > #{STREAM_PATH}",
60+
timeout: remaining, env: { "CODEX_HOME" => AUTH_HOME })
61+
checkpoint.capture(environment, stream: download_stream(environment), prompt:, version:, elapsed: finished.duration)
62+
response_for(task, checkpoint, exit_code: finished.exit_code, output: finished.output)
63+
end
64+
65+
private
66+
67+
def response_for(task, checkpoint, exit_code:, output:)
68+
events = checkpoint.events
69+
report = checkpoint.report
70+
usage = usage_for(events, token_usage: checkpoint.token_usage)
71+
trajectory = Trajectory.new(events:, instruction: task.instruction, model:, usage:, exit_code:,
72+
segments: checkpoint.trajectory_segments, version: checkpoint.version,
73+
token_usage: checkpoint.token_usage) unless events.empty?
74+
raw_result = JSON.generate(checkpoint.as_json)
75+
artifacts = checkpoint.stream.empty? ? {} : { "codex.jsonl" => checkpoint.stream }
76+
if exit_code == 124
77+
return Lemans::Agent::Response.new(outcome: Lemans::Result::Outcome.new(:agent_timeout), usage:, trajectory:, raw_result:, artifacts:)
78+
end
79+
80+
unless exit_code.zero? && report&.fetch("type") == "turn.completed"
81+
error = report&.dig("error", "message") || events.reverse.find { it["type"] == "error" }&.fetch("message", nil)
82+
error ||= "no completed turn in the stream"
83+
return Lemans::Agent::Response.new(usage:, trajectory:, raw_result:, artifacts:,
84+
error: "codex: #{error} (exit #{exit_code}): #{output.to_s[0, 2000]}")
85+
end
86+
unless report["usage"]
87+
return Lemans::Agent::Response.new(usage:, trajectory:, raw_result:, artifacts:, error: "codex: no usage in the completed turn")
88+
end
89+
90+
Lemans::Agent::Response.new(outcome: Lemans::Result::Outcome.new(:completed), usage:, trajectory:, raw_result:, artifacts:)
91+
end
92+
93+
def auth_snapshot
94+
auth = JSON.parse(File.read(@auth_file))
95+
tokens = auth.fetch("tokens")
96+
payload = tokens.fetch("access_token").split(".").fetch(1)
97+
payload += "=" * ((4 - payload.length % 4) % 4)
98+
claims = JSON.parse(Base64.urlsafe_decode64(payload))
99+
expires_at = Time.at(Integer(claims.fetch("exp"))).utc
100+
remaining = expires_at - Time.now
101+
if remaining < 10 * 60 * 60
102+
raise Lemans::ConfigError, "codex: access token expires at #{expires_at.iso8601} " \
103+
"(#{(remaining / 3600).round(1)} hours remaining); at least 10 hours are required. " \
104+
"Refresh the host Codex login, update #{@auth_file}, and rerun the benchmark"
105+
end
106+
107+
auth["auth_mode"] = "chatgptAuthTokens"
108+
# Codex requires this field even when the host manages refresh.
109+
tokens["refresh_token"] = ""
110+
JSON.generate(auth)
111+
rescue Errno::ENOENT, Errno::EACCES => e
112+
raise Lemans::ConfigError, "codex: cannot use #{@auth_file}: #{e.message}; " \
113+
"run codex -c 'cli_auth_credentials_store=\"file\"' login, " \
114+
"or set LEMANS_CODEX_AUTH_FILE"
115+
rescue JSON::ParserError, KeyError, IndexError, ArgumentError, TypeError
116+
raise Lemans::ConfigError, "codex: cannot read access-token expiry from #{@auth_file}; " \
117+
"refresh the host Codex login and update this file"
118+
end
119+
120+
def command_for(task, session_id: nil, prompt: task.instruction)
121+
argv = [ "codex", "exec", "--color", "never" ]
122+
argv << "resume" if session_id
123+
argv += [ "--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check" ]
124+
name, effort = model.to_s.split("#", 2)
125+
argv += [ "--model", name ] unless name.to_s.empty?
126+
argv += [ "--config", "model_reasoning_effort=#{JSON.generate(effort)}" ] if effort
127+
argv += [ "--config", 'cli_auth_credentials_store="file"', "--config", 'forced_login_method="chatgpt"' ]
128+
argv << "--"
129+
argv << session_id if session_id
130+
argv << prompt
131+
"#{PATH} cd #{Shellwords.escape(task.environment.workdir)} && #{argv.map { Shellwords.escape(it.to_s) }.join(" ")}"
132+
end
133+
134+
def download_stream(environment)
135+
Tempfile.create(%w[codex .jsonl]) do |file|
136+
environment.download(STREAM_PATH, file.path)
137+
File.read(file.path)
138+
end
139+
rescue Lemans::InfrastructureError
140+
nil
141+
end
142+
143+
def usage_for(events, token_usage: nil)
144+
totals = token_usage ? [ token_usage ] : events.select { it["type"] == "turn.completed" }.filter_map { it["usage"] }.last(1)
145+
info = priced_model unless totals.empty?
146+
Lemans::Result::Usage.new(
147+
input_tokens: totals.sum { it["input_tokens"].to_i },
148+
output_tokens: totals.sum { it["output_tokens"].to_i },
149+
cached_tokens: totals.sum { it["cached_input_tokens"].to_i },
150+
steps: events.count { it["type"] == "item.completed" && it.dig("item", "type") == "command_execution" },
151+
cost_usd: estimated_cost(totals, info),
152+
cost_source: cost_source(info)
153+
)
154+
end
155+
156+
def priced_model
157+
info = RubyLLM.models.find(model.to_s.split("#", 2).first, "openai")
158+
info if info.input_price_per_million.is_a?(Numeric) && info.output_price_per_million.is_a?(Numeric)
159+
rescue RubyLLM::ModelNotFoundError
160+
nil
161+
end
162+
163+
# Estimate standard API token cost; subscription billing is separate.
164+
def estimated_cost(totals, info)
165+
return unless info
166+
167+
input = info.input_price_per_million
168+
output = info.output_price_per_million
169+
cache_read = info.cache_read_input_price_per_million || input
170+
cache_write = info.cache_write_input_price_per_million || input
171+
totals.sum do |tokens|
172+
cached = tokens["cached_input_tokens"].to_i
173+
written = tokens["cache_write_input_tokens"].to_i
174+
# Codex includes cache reads/writes in input and reasoning in output.
175+
uncached = tokens["input_tokens"].to_i - cached - written
176+
(uncached * input) + (cached * cache_read) + (written * cache_write) + (tokens["output_tokens"].to_i * output)
177+
end / 1_000_000.0
178+
end
179+
180+
def cost_source(info)
181+
return unless info
182+
183+
Lemans::Result::CostSource.build(name: :model_registry, model:,
184+
priced_as: "#{info.provider}/#{info.id}", registry: Miniswen.registry_revision)
185+
end
186+
end
187+
188+
require_relative "checkpoint"
189+
require_relative "trajectory"
190+
191+
Lemans::Agents.register(CodexAgent::NAME, CodexAgent)

0 commit comments

Comments
 (0)