Class: Aidp::Providers::Codex

Inherits:
Base
  • Object
show all
Includes:
DebugMixin
Defined in:
lib/aidp/providers/codex.rb

Constant Summary collapse

MODEL_PATTERN =

Model name pattern for OpenAI models (since Codex uses OpenAI)

/^gpt-[\d.o-]+(?:-turbo)?(?:-mini)?$/i
LONG_PROMPT_THRESHOLD =
8000
LONG_PROMPT_TIMEOUT =

15 minutes for large prompts

900

Constants included from DebugMixin

DebugMixin::DEBUG_BASIC, DebugMixin::DEBUG_OFF, DebugMixin::DEBUG_VERBOSE

Constants inherited from Base

Base::ACTIVITY_STATES, Base::DEFAULT_STUCK_TIMEOUT, Base::TIER_TIMEOUT_MULTIPLIERS, Base::TIMEOUT_ARCHITECTURE_ANALYSIS, Base::TIMEOUT_DEFAULT, Base::TIMEOUT_DOCUMENTATION_ANALYSIS, Base::TIMEOUT_FUNCTIONALITY_ANALYSIS, Base::TIMEOUT_IMPLEMENTATION, Base::TIMEOUT_QUICK_MODE, Base::TIMEOUT_REFACTORING_RECOMMENDATIONS, Base::TIMEOUT_REPOSITORY_ANALYSIS, Base::TIMEOUT_STATIC_ANALYSIS, Base::TIMEOUT_TEST_ANALYSIS

Constants included from MessageDisplay

MessageDisplay::COLOR_MAP

Instance Attribute Summary

Attributes inherited from Base

#activity_state, #last_activity_time, #model, #start_time, #step_name, #stuck_timeout

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DebugMixin

#debug_basic?, #debug_command, #debug_enabled?, #debug_error, #debug_execute_command, #debug_level, #debug_log, #debug_logger, #debug_provider, #debug_step, #debug_timing, #debug_verbose?, included, shared_logger

Methods inherited from Base

#activity_summary, #configure, discover_models_from_registry, #execution_time, #fetch_mcp_servers, #harness_config, #harness_health_status, #harness_metrics, #harness_mode?, #initialize, #mark_completed, #mark_failed, #record_activity, #record_harness_request, #send_with_harness, #set_harness_context, #set_job_context, #setup_activity_monitoring, #stuck?, #supports_activity_monitoring?, #supports_mcp?, #time_since_last_activity, #update_activity_state

Methods included from Adapter

#capabilities, #classify_error, #dangerous_mode=, #dangerous_mode_enabled?, #dangerous_mode_flags, #error_metadata, #error_patterns, #fetch_mcp_servers, #health_status, #logging_metadata, #redact_secrets, #retryable_error?, #supports_dangerous_mode?, #supports_mcp?, #validate_config

Methods included from MessageDisplay

#display_message, included, #message_display_prompt

Constructor Details

This class inherits a constructor from Aidp::Providers::Base

Class Method Details

.available?Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/aidp/providers/codex.rb', line 18

def self.available?
  !!Aidp::Util.which("codex")
end

.discover_modelsArray<Hash>

Discover available models from registry

Note: Codex CLI doesn’t have a standard model listing command Returns registry-based models that match OpenAI patterns

Returns:

  • (Array<Hash>)

    Array of discovered models



36
37
38
39
40
# File 'lib/aidp/providers/codex.rb', line 36

def self.discover_models
  return [] unless available?

  discover_models_from_registry(MODEL_PATTERN, "codex")
end

.firewall_requirementsObject

Get firewall requirements for Codex provider Codex uses OpenAI APIs



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/aidp/providers/codex.rb', line 44

def self.firewall_requirements
  {
    domains: [
      "api.openai.com",
      "auth.openai.com",
      "openai.com",
      "chat.openai.com",
      "chatgpt.com",
      "cdn.openai.com",
      "oaiusercontent.com"
    ],
    ip_ranges: []
  }
end

.supports_model_family?(family_name) ⇒ Boolean

Check if this provider supports a given model family

Parameters:

  • family_name (String)

    The model family name

Returns:

  • (Boolean)

    True if it matches OpenAI model pattern



26
27
28
# File 'lib/aidp/providers/codex.rb', line 26

def self.supports_model_family?(family_name)
  MODEL_PATTERN.match?(family_name)
end

Instance Method Details

#available?Boolean

Returns:

  • (Boolean)


67
68
69
70
71
72
73
74
75
76
77
# File 'lib/aidp/providers/codex.rb', line 67

def available?
  return false unless self.class.available?

  # Additional check to ensure the CLI is properly configured
  begin
    result = Aidp::Util.execute_command("codex", ["--version"], timeout: 10)
    result.exit_status == 0
  rescue
    false
  end
end

#display_nameObject



63
64
65
# File 'lib/aidp/providers/codex.rb', line 63

def display_name
  "Codex CLI"
end

#harness_healthy?Boolean

Override health check for Codex specific considerations

Returns:

  • (Boolean)


191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/aidp/providers/codex.rb', line 191

def harness_healthy?
  return false unless super

  # Additional health checks specific to Codex CLI
  # Check if we can access the CLI (basic connectivity test)
  begin
    result = Aidp::Util.execute_command("codex", ["--help"], timeout: 5)
    result.exit_status == 0
  rescue
    false
  end
end

#nameObject



59
60
61
# File 'lib/aidp/providers/codex.rb', line 59

def name
  "codex"
end

#send_message(prompt:, session: nil, options: {}) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/aidp/providers/codex.rb', line 79

def send_message(prompt:, session: nil, options: {})
  raise "codex CLI not available" unless self.class.available?

  # Smart timeout calculation (store prompt length for adaptive logic)
  @current_codex_prompt_length = prompt.length
  timeout_seconds = calculate_timeout

  debug_provider("codex", "Starting execution", {timeout: timeout_seconds})
  debug_log("📝 Sending prompt to codex (length: #{prompt.length})", level: :info)

  # Set up activity monitoring
  setup_activity_monitoring("codex", method(:activity_callback))
  record_activity("Starting codex execution")

  # Create a spinner for activity display
  spinner = TTY::Spinner.new("[:spinner] :title", format: :dots, hide_cursor: true)
  spinner.auto_spin

  activity_display_thread = Thread.new do
    start_time = Time.now
    loop do
      sleep 0.5 # Update every 500ms to reduce spam
      elapsed = Time.now - start_time

      # Break if we've been running too long or state changed
      break if elapsed > timeout_seconds || @activity_state == :completed || @activity_state == :failed

      update_spinner_status(spinner, elapsed, "🤖 Codex CLI")
    end
  end

  begin
    # Use non-interactive mode (exec) for automation
    args = ["exec", prompt]

    # Add model if configured
    if @model && !@model.empty?
      args += ["--model", @model]
    end

    # Add session support if provided (codex may support session/thread continuation)
    if session && !session.empty?
      args += ["--session", session]
    end

    # In devcontainer, ensure sandbox mode and approval policy are set
    # These are already set via environment variables in devcontainer.json
    # but we verify and log them here for visibility
    if in_devcontainer_or_codespace?
      unless ENV["CODEX_SANDBOX_MODE"] == "danger-full-access"
        ENV["CODEX_SANDBOX_MODE"] = "danger-full-access"
        debug_log("🔓 Set CODEX_SANDBOX_MODE=danger-full-access for devcontainer", level: :info)
      end
      unless ENV["CODEX_APPROVAL_POLICY"] == "never"
        ENV["CODEX_APPROVAL_POLICY"] = "never"
        debug_log("🔓 Set CODEX_APPROVAL_POLICY=never for devcontainer", level: :info)
      end
    end

    # Use debug_execute_command for better debugging
    result = debug_execute_command("codex", args: args, timeout: timeout_seconds)

    # Log the results
    debug_command("codex", args: args, input: prompt, output: result.out, error: result.err, exit_code: result.exit_status)

    if result.exit_status == 0
      spinner.success("")
      mark_completed
      result.out
    else
      spinner.error("")
      mark_failed("codex failed with exit code #{result.exit_status}")
      debug_error(StandardError.new("codex failed"), {exit_code: result.exit_status, stderr: result.err})
      raise "codex failed with exit code #{result.exit_status}: #{result.err}"
    end
  rescue => e
    spinner&.error("")
    mark_failed("codex execution failed: #{e.message}")
    debug_error(e, {provider: "codex", prompt_length: prompt.length})
    raise
  ensure
    cleanup_activity_display(activity_display_thread, spinner)
    @current_codex_prompt_length = nil
  end
end

#send_with_options(prompt:, session: nil, model: nil, ask_for_approval: false) ⇒ Object

Enhanced send method with additional options



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/aidp/providers/codex.rb', line 166

def send_with_options(prompt:, session: nil, model: nil, ask_for_approval: false)
  args = ["exec", prompt]

  # Add session support
  if session && !session.empty?
    args += ["--session", session]
  end

  # Add model selection (from parameter or configured model)
  model_to_use = model || @model
  if model_to_use
    args += ["--model", model_to_use]
  end

  # Add approval flag - but warn about interactive behavior
  if ask_for_approval
    debug_log("⚠️  WARNING: --ask-for-approval flag may cause interactive prompts that could hang AIDP", level: :warn)
    args += ["--ask-for-approval"]
  end

  # Use the enhanced version of send
  send_with_custom_args(prompt: prompt, args: args)
end