Codex SDK for Ruby (Unofficial)
⚠️ This is an unofficial, community-maintained Ruby SDK for the Codex CLI.
This SDK wraps the Codex CLI binary to enable embedding the Codex agent in your Ruby workflows and apps. It is based on the official TypeScript SDK architecture but is not officially maintained.
Important Notes
- Unofficial SDK: This is a community project. See DISCLAIMER.md for details.
- Requires Codex CLI: You must have the Codex CLI binary installed.
- Community Maintained: Contributions welcome, but no official support.
Installation
Prerequisites: Install the Codex CLI binary and ensure it's available in your PATH or specify its location.
Add this line to your application's Gemfile:
gem 'codex-sdk'And then execute:
bundle installOr install it yourself as:
gem install codex-sdkQuick Start
require 'codex_sdk'
# Create a Codex instance
codex = CodexSdk.new(api_key: ENV['CODEX_API_KEY'])
# Start a new conversation thread
thread = codex.start_thread(
working_directory: '/path/to/your/project'
)
# Run a turn and get the response
result = thread.run("Diagnose the test failure in my project")
puts result[:final_response]
# => "I found the issue in your test suite..."
puts "Items: #{result[:items].size}"
puts "Usage: #{result[:usage]}"Features
- Multi-turn conversations - Maintain context across multiple interactions
- Thread persistence - Resume conversations by thread ID
- Streaming support - Stream events as they arrive
- Structured output - Use JSON schemas for validated responses
- Sandbox modes - Control file system access levels
- Zero dependencies - Uses only Ruby standard library
Usage
Basic Usage
# Create a Codex client
codex = CodexSdk.new
# Start a thread
thread = codex.start_thread
# Send a message
result = thread.run("What is the purpose of this codebase?")
puts result[:final_response]Streaming Events
Stream events as they arrive for real-time updates:
thread = codex.start_thread
thread.run_streamed("Fix the bug in user authentication").each do |event|
case event['type']
when 'item.started'
puts "Started: #{event['item']['type']}"
when 'item.completed'
item = event['item']
puts "Completed: #{item['type']}"
puts "Content: #{item['text']}" if item['text']
when 'turn.completed'
puts "Turn completed. Usage: #{event['usage']}"
end
endMulti-turn Conversations
thread = codex.start_thread
# First turn
result1 = thread.run("What files handle user authentication?")
puts result1[:final_response]
# Second turn - maintains context
result2 = thread.run("Add two-factor authentication to those files")
puts result2[:final_response]
# Save thread ID for later
thread_id = thread.idResuming Threads
# Resume a previous conversation
thread = codex.resume_thread("thread-abc-123")
# Continue the conversation
result = thread.run("What was my last request?")
puts result[:final_response]Structured Output with JSON Schema
schema = {
type: "object",
properties: {
summary: { type: "string" },
priority: { type: "string", enum: ["high", "medium", "low"] },
files: {
type: "array",
items: { type: "string" }
}
},
required: ["summary", "priority"]
}
result = thread.run(
"Analyze the critical issues in this codebase",
output_schema: schema
)
# Parse the structured response
data = JSON.parse(result[:final_response])
puts "Summary: #{data['summary']}"
puts "Priority: #{data['priority']}"
puts "Files: #{data['files'].join(', ')}"Configuration Options
Codex Options
codex = CodexSdk.new(
api_key: "sk-...", # API key (default: ENV['CODEX_API_KEY'])
base_url: "https://api.custom.com", # Custom API endpoint
codex_path_override: "/path/to/codex" # Custom binary path (for testing)
)Thread Options
thread = codex.start_thread(
model: "gpt-4", # Model to use
working_directory: "/path/to/dir", # Working directory
sandbox_mode: "workspace-write", # Sandbox mode
skip_git_repo_check: false # Skip git repository check
)Sandbox Modes:
-
read-only- Read-only access to files -
workspace-write- Can write within workspace -
danger-full-access- Full file system access
Error Handling
begin
result = thread.run("Perform a complex task")
puts result[:final_response]
rescue CodexSdk::ThreadError => e
puts "Thread error: #{e.message}"
rescue CodexSdk::ProcessError => e
puts "Process error: #{e.message}"
rescue CodexSdk::ValidationError => e
puts "Validation error: #{e.message}"
endEvent Types
The SDK emits the following event types during streaming:
-
thread.started- Thread has been created -
turn.started- A new turn has started -
item.started- A new item is being generated -
item.updated- An item is being updated (streaming) -
item.completed- An item has been completed -
turn.completed- Turn completed successfully -
turn.failed- Turn failed with an error -
error- An error occurred
Item Types
Items represent different types of content in the conversation:
-
agent_message- Message from the agent -
reasoning- Agent's reasoning/thinking -
command_execution- Command execution (bash, etc.) -
file_change- File modifications -
mcp_tool_call- MCP tool invocations -
web_search- Web search results -
todo_list- Task list updates -
error- Error information
Examples
Example 1: Code Review
codex = CodexSdk.new
thread = codex.start_thread(
working_directory: '/path/to/project',
sandbox_mode: 'read-only'
)
result = thread.run("Review the code in src/main.rb and suggest improvements")
result[:items].each do |item|
case item['type']
when 'agent_message'
puts "Review: #{item['text']}"
when 'reasoning'
puts "Thinking: #{item['text']}"
end
endExample 2: Automated Testing
codex = CodexSdk.new
thread = codex.start_thread(
working_directory: '/path/to/project',
sandbox_mode: 'workspace-write'
)
# Run tests
result = thread.run("Run the test suite and fix any failures")
if result[:final_response].include?("All tests passed")
puts "✓ Success!"
else
puts "Some tests failed, running again..."
thread.run("Try fixing the remaining test failures")
endExample 3: Documentation Generation
schema = {
type: "object",
properties: {
summary: { type: "string" },
api_endpoints: {
type: "array",
items: {
type: "object",
properties: {
path: { type: "string" },
method: { type: "string" },
description: { type: "string" }
}
}
}
}
}
result = thread.run(
"Analyze the API endpoints and generate documentation",
output_schema: schema
)
docs = JSON.parse(result[:final_response])
puts "API Summary: #{docs['summary']}"
docs['api_endpoints'].each do |endpoint|
puts "#{endpoint['method']} #{endpoint['path']} - #{endpoint['description']}"
endDevelopment
After checking out the repo, run:
bundle installRun tests:
bundle exec rspecRun linting:
bundle exec rubocopRun both tests and linting:
bundle exec rake checkPlatform Support
The SDK supports the following platforms:
- macOS: x86_64, ARM64 (Apple Silicon)
- Linux: x86_64, ARM64
- Windows: x86_64, ARM64
Platform-specific binaries are automatically selected at runtime.
Requirements
- Ruby >= 2.7.0
- No external dependencies (uses Ruby stdlib only)
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/ya-luotao/codex-sdk-ruby.
This is an unofficial SDK. For issues with the Codex CLI binary itself, please refer to the official Codex documentation.
License
The gem is available as open source under the terms of the MIT License.
Resources
- Official TypeScript SDK (Reference)
- This Repository
Support
Note: This is an unofficial SDK. For questions about this Ruby SDK:
- Open an issue on GitHub
For questions about the Codex CLI itself:
- Refer to the official Codex CLI documentation