Class: AgentHarness::Providers::Codex
Overview
OpenAI Codex CLI provider
Provides integration with the OpenAI Codex CLI tool.
Constant Summary
collapse
- SUPPORTED_CLI_VERSION =
"0.116.0"
- SUPPORTED_CLI_REQUIREMENT =
Gem::Requirement.new(">= #{SUPPORTED_CLI_VERSION}", "< 0.117.0").freeze
- OAUTH_REFRESH_FAILURE_PATTERNS =
[
/refresh_token_reused/i,
/failed to refresh token\b.*\b401\b/im,
/failed to refresh token\b.*unauthorized/im,
/failed to refresh token\b.*\binvalid_client\b/im,
/failed to refresh token\b.*\binvalid_grant\b/im,
/failed to refresh token\b.*invalid.*refresh.*token/im,
/failed to refresh token\b.*refresh.*token.*invalid/im,
/your access token could not be refreshed because\b.*\b401\b/im,
/your access token could not be refreshed because\b.*unauthorized/im,
/your access token could not be refreshed because\b.*\binvalid_client\b/im,
/your access token could not be refreshed because\b.*\binvalid_grant\b/im,
/your access token could not be refreshed because\b.*invalid.*refresh.*token/im,
/your access token could not be refreshed because\b.*refresh.*token.*invalid/im,
/your access token could not be refreshed because\s+your refresh token .*already (?:been )?used/im,
/refresh token .*already (?:been )?used/im
].freeze
- OAUTH_REFRESH_TRANSIENT_PATTERNS =
[
/your access token could not be refreshed because\s+(?:the\s+)?auth(?:entication)? service(?:\s+(?:is|was))?\s+(?:temporarily\s+)?unavailable/im,
/your access token could not be refreshed because .*connection.*error/im,
/failed to refresh token\b.*connection.*error/im,
/failed to refresh token\b.*service(?:\s+(?:is|was))?\s+(?:temporarily\s+)?unavailable/im
].freeze
Constants inherited
from Base
Base::COMMON_ERROR_PATTERNS, Base::DEFAULT_SMOKE_TEST_CONTRACT
Instance Attribute Summary
Attributes inherited from Base
#config, #executor, #logger
Class Method Summary
collapse
Instance Method Summary
collapse
#cleanup_mcp_tempfiles!, #write_mcp_config_file
#parse_rate_limit_reset
Methods inherited from Base
#configure, #initialize, #parse_rate_limit_reset, #parse_test_error, #sandboxed_environment?, #send_chat_message
Methods included from Adapter
#auth_type, #chat_transport, #chat_transport_type, #fetch_mcp_servers, included, metadata_package_name, #noisy_error_patterns, normalize_metadata_installation, normalize_metadata_source_type, normalize_metadata_version_requirement, #parse_rate_limit_reset, #smoke_test, #smoke_test_contract, #supports_chat?, #supports_dangerous_mode?, #supports_text_mode?, #supports_token_counting?, #supports_tool_control?, #validate_mcp_servers!
Class Method Details
.binary_name ⇒ Object
45
46
47
|
# File 'lib/agent_harness/providers/codex.rb', line 45
def binary_name
"codex"
end
|
.discover_models ⇒ Object
83
84
85
86
87
88
89
|
# File 'lib/agent_harness/providers/codex.rb', line 83
def discover_models
return [] unless available?
[
{name: "codex", family: "codex", tier: "standard", provider: "codex"}
]
end
|
.firewall_requirements ⇒ Object
63
64
65
66
67
68
69
70
71
|
# File 'lib/agent_harness/providers/codex.rb', line 63
def firewall_requirements
{
domains: [
"api.openai.com",
"openai.com"
],
ip_ranges: []
}
end
|
.installation_contract(version: SUPPORTED_CLI_VERSION) ⇒ Object
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
|
# File 'lib/agent_harness/providers/codex.rb', line 91
def installation_contract(version: SUPPORTED_CLI_VERSION)
version = version.strip if version.respond_to?(:strip)
unless version.is_a?(String) && !version.empty?
raise ArgumentError,
"Unsupported Codex CLI version #{version.inspect}; " \
"supported versions must satisfy #{SUPPORTED_CLI_REQUIREMENT}"
end
parsed_version = begin
Gem::Version.new(version)
rescue ArgumentError
raise ArgumentError,
"Unsupported Codex CLI version #{version.inspect}; " \
"supported versions must satisfy #{SUPPORTED_CLI_REQUIREMENT}"
end
unless SUPPORTED_CLI_REQUIREMENT.satisfied_by?(parsed_version)
raise ArgumentError,
"Unsupported Codex CLI version #{version.inspect}; " \
"supported versions must satisfy #{SUPPORTED_CLI_REQUIREMENT}"
end
default_package = "@openai/codex@#{version}".freeze
install_command_prefix = ["npm", "install", "-g", "--ignore-scripts"].freeze
install_command = (install_command_prefix + [default_package]).freeze
supported_versions = [version].freeze
version_requirement = SUPPORTED_CLI_REQUIREMENT.requirements
.map { |op, ver| "#{op} #{ver}".freeze }
.freeze
contract = {
source: :npm,
package: default_package,
package_name: "@openai/codex",
version: version,
version_requirement: version_requirement,
binary_name: binary_name,
install_command_prefix: install_command_prefix,
install_command: install_command,
supported_versions: supported_versions
}
contract.each_value do |value|
value.freeze if value.is_a?(String)
end
contract.freeze
end
|
.instruction_file_paths ⇒ Object
73
74
75
76
77
78
79
80
81
|
# File 'lib/agent_harness/providers/codex.rb', line 73
def instruction_file_paths
[
{
path: "AGENTS.md",
description: "OpenAI Codex agent instructions",
symlink: false
}
]
end
|
.parse_cli_jsonl_transcript(raw_output, max_events: nil) ⇒ Object
144
145
146
147
148
149
150
|
# File 'lib/agent_harness/providers/codex.rb', line 144
def parse_cli_jsonl_transcript(raw_output, max_events: nil)
return new.send(:parse_jsonl_output, "") if max_events && max_events <= 0
output = max_events ? tail_nonempty_lines(raw_output, limit: max_events).join("\n") : raw_output
new.send(:parse_jsonl_output, output)
end
|
54
55
56
57
58
59
60
61
|
# File 'lib/agent_harness/providers/codex.rb', line 54
def provider_metadata_overrides
{
auth: {
service: :openai,
api_family: :openai
}
}
end
|
.provider_name ⇒ Object
41
42
43
|
# File 'lib/agent_harness/providers/codex.rb', line 41
def provider_name
:codex
end
|
.smoke_test_contract ⇒ Object
Instance Method Details
#api_key_env_var_names ⇒ Object
195
|
# File 'lib/agent_harness/providers/codex.rb', line 195
def api_key_env_var_names = ["OPENAI_API_KEY"]
|
#api_key_unset_vars ⇒ Object
197
|
# File 'lib/agent_harness/providers/codex.rb', line 197
def api_key_unset_vars = ["OPENAI_BASE_URL", "OPENAI_HEADER_X_AGENT_RUN_ID", "OPENAI_HEADER_X_PROXY_TOKEN"]
|
#auth_lock_config ⇒ Object
386
387
388
|
# File 'lib/agent_harness/providers/codex.rb', line 386
def auth_lock_config
{path: "/tmp/codex-auth.lock", timeout: 30}
end
|
#auth_status ⇒ Object
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
|
# File 'lib/agent_harness/providers/codex.rb', line 312
def auth_status
api_key = ENV["OPENAI_API_KEY"]
if api_key && !api_key.strip.empty?
if api_key.strip.start_with?("sk-")
return {valid: true, expires_at: nil, error: nil, auth_method: :api_key}
else
return {valid: false, expires_at: nil, error: "OPENAI_API_KEY is set but does not appear to be a valid OpenAI API key", auth_method: nil}
end
end
credentials = read_codex_credentials
if credentials
key = credentials["api_key"] || credentials["apiKey"] || credentials["OPENAI_API_KEY"]
if key.is_a?(String) && !key.strip.empty?
if key.strip.start_with?("sk-")
return {valid: true, expires_at: nil, error: nil, auth_method: :config_file}
else
return {valid: false, expires_at: nil, error: "Config file API key is set but does not appear to be a valid OpenAI API key", auth_method: nil}
end
end
end
{valid: false, expires_at: nil, error: "No OpenAI API key found. Set OPENAI_API_KEY or configure in #{codex_config_path}", auth_method: nil}
rescue IOError, JSON::ParserError => e
{valid: false, expires_at: nil, error: e.message, auth_method: nil}
end
|
#build_mcp_flags(mcp_servers, working_dir: nil) ⇒ Object
217
218
219
220
221
222
|
# File 'lib/agent_harness/providers/codex.rb', line 217
def build_mcp_flags(mcp_servers, working_dir: nil)
return [] if mcp_servers.empty?
config_path = write_mcp_config_file(mcp_servers, working_dir: working_dir)
["--mcp-config", config_path]
end
|
#capabilities ⇒ Object
183
184
185
186
187
188
189
190
191
192
193
|
# File 'lib/agent_harness/providers/codex.rb', line 183
def capabilities
{
streaming: false,
file_upload: false,
vision: false,
tool_use: true,
json_mode: false,
mcp: true,
dangerous_mode: true
}
end
|
#cli_env_overrides ⇒ Object
201
|
# File 'lib/agent_harness/providers/codex.rb', line 201
def cli_env_overrides = {"PAID_CODEX_SUBSCRIPTION_AUTH" => "1"}
|
#config_file_content(options = {}) ⇒ Object
368
369
370
371
372
373
374
375
376
|
# File 'lib/agent_harness/providers/codex.rb', line 368
def config_file_content(options = {})
<<~TOML
[chatgpt]
model_provider = "#{escape_toml_string(options[:model_provider])}"
base_url = "#{escape_toml_string(options[:base_url])}"
env_key = "#{escape_toml_string(options[:env_key])}"
wire_api = "#{escape_toml_string(options[:wire_api])}"
TOML
end
|
#configuration_schema ⇒ Object
175
176
177
178
179
180
181
|
# File 'lib/agent_harness/providers/codex.rb', line 175
def configuration_schema
{
fields: [],
auth_modes: [:api_key],
openai_compatible: true
}
end
|
#dangerous_mode_flags ⇒ Object
228
229
230
|
# File 'lib/agent_harness/providers/codex.rb', line 228
def dangerous_mode_flags
["--full-auto"]
end
|
#display_name ⇒ Object
171
172
173
|
# File 'lib/agent_harness/providers/codex.rb', line 171
def display_name
"OpenAI Codex CLI"
end
|
#error_classification_patterns ⇒ Object
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
|
# File 'lib/agent_harness/providers/codex.rb', line 287
def error_classification_patterns
super.merge(
auth_expired: [
/refresh_token_reused/i,
/refresh token has already been used/i,
/Please log out and sign in again/i,
/authentication_error/i,
/invalid_grant/i,
/Token is expired or invalid/i
],
abort: [
/free tier limit reached/i,
/please upgrade to a paid plan/i
]
)
end
|
#error_patterns ⇒ Object
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
|
# File 'lib/agent_harness/providers/codex.rb', line 264
def error_patterns
{
rate_limited: COMMON_ERROR_PATTERNS[:rate_limited],
timeout: [
/your access token could not be refreshed.*(?:timeout|timed.?out)/im,
/failed to refresh token\b.*(?:timeout|timed.?out)/im
],
transient: COMMON_ERROR_PATTERNS[:transient] + [
/connection.*reset/i
] + OAUTH_REFRESH_TRANSIENT_PATTERNS,
auth_expired: COMMON_ERROR_PATTERNS[:auth_expired] + [
/\b401\b/,
/incorrect.*api.*key/i
] + OAUTH_REFRESH_FAILURE_PATTERNS,
quota_exceeded: COMMON_ERROR_PATTERNS[:quota_exceeded],
sandbox_failure: [
/bwrap.*no permissions/i,
/no permissions to create a new namespace/i,
/unprivileged.*namespace/i
]
}
end
|
#execution_semantics ⇒ Object
242
243
244
245
246
247
248
249
250
251
252
253
|
# File 'lib/agent_harness/providers/codex.rb', line 242
def execution_semantics
{
prompt_delivery: :arg,
output_format: :json,
sandbox_aware: true,
uses_subcommand: true,
non_interactive_flag: nil,
legitimate_exit_codes: [0],
stderr_is_diagnostic: true,
parses_rate_limit_reset: false
}
end
|
#health_status ⇒ Object
339
340
341
342
343
344
345
346
347
348
349
350
|
# File 'lib/agent_harness/providers/codex.rb', line 339
def health_status
unless self.class.available?
return {healthy: false, message: "Codex CLI not found in PATH. Install from https://github.com/openai/codex"}
end
auth = auth_status
unless auth[:valid]
return {healthy: false, message: auth[:error]}
end
{healthy: true, message: "Codex CLI available and authenticated"}
end
|
#name ⇒ Object
167
168
169
|
# File 'lib/agent_harness/providers/codex.rb', line 167
def name
"codex"
end
|
#notify_hook_content ⇒ Object
378
379
380
381
382
383
384
|
# File 'lib/agent_harness/providers/codex.rb', line 378
def notify_hook_content
<<~TOML
[notify]
# Paid notification hook
TOML
end
|
#send_message(prompt:, **options) ⇒ Object
203
204
205
206
207
|
# File 'lib/agent_harness/providers/codex.rb', line 203
def send_message(prompt:, **options)
super
ensure
cleanup_mcp_tempfiles!
end
|
#session_flags(session_id) ⇒ Object
259
260
261
262
|
# File 'lib/agent_harness/providers/codex.rb', line 259
def session_flags(session_id)
return [] unless session_id && !session_id.empty?
["--session", session_id]
end
|
#subscription_unset_vars ⇒ Object
199
|
# File 'lib/agent_harness/providers/codex.rb', line 199
def subscription_unset_vars = ["OPENAI_API_KEY", "OPENAI_BASE_URL"] + api_key_unset_vars
|
#supported_mcp_transports ⇒ Object
213
214
215
|
# File 'lib/agent_harness/providers/codex.rb', line 213
def supported_mcp_transports
%w[stdio http sse]
end
|
#supports_mcp? ⇒ Boolean
209
210
211
|
# File 'lib/agent_harness/providers/codex.rb', line 209
def supports_mcp?
true
end
|
#supports_sessions? ⇒ Boolean
255
256
257
|
# File 'lib/agent_harness/providers/codex.rb', line 255
def supports_sessions?
true
end
|
#test_command_overrides ⇒ Object
224
225
226
|
# File 'lib/agent_harness/providers/codex.rb', line 224
def test_command_overrides
["--skip-git-repo-check", "--output-last-message"]
end
|
#token_usage_from_api_response(body) ⇒ Object
232
233
234
235
236
237
238
239
240
|
# File 'lib/agent_harness/providers/codex.rb', line 232
def token_usage_from_api_response(body)
usage = body&.dig("usage")
return {} unless usage
{
input_tokens: usage["prompt_tokens"].to_i,
output_tokens: usage["completion_tokens"].to_i
}
end
|
#translate_error(message) ⇒ Object
304
305
306
307
308
309
310
|
# File 'lib/agent_harness/providers/codex.rb', line 304
def translate_error(message)
case message
when /refresh_token_reused/i then "Codex authentication expired. Please re-authenticate."
when /free tier limit/i then "Codex free tier limit reached."
else message
end
end
|
#validate_config ⇒ Object
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
|
# File 'lib/agent_harness/providers/codex.rb', line 352
def validate_config
errors = []
flags = @config.default_flags
unless flags.nil?
if flags.is_a?(Array)
invalid = flags.reject { |f| f.is_a?(String) }
errors << "default_flags contains non-string values" if invalid.any?
else
errors << "default_flags must be an array of strings"
end
end
{valid: errors.empty?, errors: errors}
end
|