|
| 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