## 🎯 Overview Complete TypeScript rewrite with comprehensive testing, modular architecture, and enhanced user experience. Adds 9 pre-configured model variants matching Codex CLI presets and a beautiful OAuth success page. ## ✨ New Features ### Configuration System - **9 Model Variants**: Pre-configured reasoning levels (Low/Medium/High) for both gpt-5-codex and gpt-5, plus Minimal variants - **Full Config Example**: `config/full-opencode.json` with all variants ready to use - **Minimal Config Example**: `config/minimal-opencode.json` for basic setup - **Config Documentation**: Comprehensive guide in `config/README.md` ### OAuth Enhancement - **Animated Success Page**: Beautiful terminal-style UI with matrix rain effect, animated checkmark, and glowing effects - **Interactive Elements**: Mouse-responsive matrix rain and parallax effects - **Professional Branding**: OpenCode logo with pulse animations ### Developer Experience - **TypeScript Rewrite**: Complete migration from .mjs to .ts with strict typing - **93 Comprehensive Tests**: Full test coverage using Vitest - **Modular Architecture**: 10 focused helper functions, each < 40 lines - **Centralized Constants**: All magic values in `lib/constants.ts` - **CI/CD Pipeline**: GitHub Actions workflow for automated testing ### Documentation - **AGENTS.md**: Complete guide for AI assistants maintaining the codebase - **Enhanced README**: Updated with new configuration options and examples - **Inline JSDoc**: Comprehensive documentation for all public functions ## 🏗️ Technical Changes ### Architecture Improvements - Extracted 10 focused helper functions from monolithic fetch() - Centralized all constants and error messages - Separated concerns: auth, browser, codex, server, etc. - Type-safe discriminated unions for result types ### Build System - TypeScript compilation with declarations and source maps - Automatic HTML asset copying in build process - Test files excluded from distribution bundle - Clean dist/ output with only production code ### Testing Infrastructure - Vitest test runner with UI mode - 93 tests across 7 test files - Mock-based testing for external dependencies - Coverage reporting capability ## 📁 New Structure ``` opencode-openai-codex-auth/ ├── index.ts # Main plugin (TypeScript) ├── lib/ │ ├── auth.ts # OAuth logic │ ├── browser.ts # Platform-specific browser opening │ ├── codex.ts # Codex instructions │ ├── server.ts # OAuth callback server │ ├── fetch-helpers.ts # 10 focused helpers │ ├── constants.ts # All magic values │ ├── types.ts # TypeScript types │ ├── oauth-success.html # Animated success page │ └── ... ├── config/ │ ├── full-opencode.json # Complete config with variants │ ├── minimal-opencode.json # Basic config │ └── README.md # Config docs ├── test/ # 93 comprehensive tests ├── AGENTS.md # AI maintenance guide └── tsconfig.json # TypeScript config ``` ## 🔄 Migration Notes ### Breaking Changes - Plugin now requires TypeScript compilation (dist/ folder) - Configuration structure enhanced (backward compatible) - OAuth success page replaces plain HTML response ### Upgrade Path 1. Use new config from `config/full-opencode.json` for best experience 2. Or continue with minimal config (uses plugin defaults) 3. Rebuild plugin: `npm run build` ## 📊 Metrics - **Lines of Code**: Modular design with functions < 70 lines - **Test Coverage**: 93 tests covering all functionality - **Type Safety**: Strict TypeScript with no `any` types - **Dependencies**: Still minimal (only @openauthjs/openauth) - **Model Variants**: 9 pre-configured options for users ## 🎨 User Experience - **Codex CLI Parity**: Match official CLI reasoning presets - **Beautiful OAuth**: Professional animated success page - **Clear Documentation**: Step-by-step guides and examples - **Flexible Config**: From minimal to comprehensive setups Co-authored-by: Hanzo Dev <[email protected]>
17 KiB
OpenAI ChatGPT OAuth Plugin for opencode
This plugin enables opencode to use OpenAI's Codex backend via ChatGPT Plus/Pro OAuth authentication, allowing you to use your ChatGPT subscription instead of OpenAI Platform API credits.
Found this useful? Follow me on X @nummanthinks for future updates and more projects!
Features
- ✅ ChatGPT Plus/Pro OAuth authentication - Use your existing subscription
- ✅ 9 pre-configured model variants - Low/Medium/High reasoning for both gpt-5 and gpt-5-codex
- ✅ Zero external dependencies - Lightweight with only @openauthjs/openauth
- ✅ Auto-refreshing tokens - Handles token expiration automatically
- ✅ Smart auto-updating Codex instructions - Tracks latest stable release with ETag caching
- ✅ Full tool support - write, edit, bash, grep, glob, and more
- ✅ Automatic tool remapping - Codex tools → opencode tools
- ✅ Configurable reasoning - Control effort, summary verbosity, and text output
- ✅ Type-safe & tested - Strict TypeScript with 93 comprehensive tests
- ✅ Modular architecture - Easy to maintain and extend
Installation
Quick Start
No npm install needed! opencode automatically installs plugins when you add them to your config.
Recommended: Full Configuration (Codex CLI Experience)
For the complete experience with all reasoning variants matching the official Codex CLI:
- Copy the full configuration from
config/full-opencode.jsonto your opencode config file:
{
"$schema": "https://opencode.ai/config.json",
"plugin": [
"opencode-openai-codex-auth"
],
"provider": {
"openai": {
"options": {
"reasoningEffort": "medium",
"reasoningSummary": "auto",
"textVerbosity": "medium",
"include": [
"reasoning.encrypted_content"
]
},
"models": {
"GPT 5 Codex Low (ChatGPT Subscription)": {
"id": "gpt-5-codex",
"options": {
"reasoningEffort": "low",
"reasoningSummary": "auto",
"textVerbosity": "medium"
}
},
"GPT 5 Codex Medium (ChatGPT Subscription)": {
"id": "gpt-5-codex",
"options": {
"reasoningEffort": "medium",
"reasoningSummary": "auto",
"textVerbosity": "medium"
}
},
"GPT 5 Codex High (ChatGPT Subscription)": {
"id": "gpt-5-codex",
"options": {
"reasoningEffort": "high",
"reasoningSummary": "detailed",
"textVerbosity": "medium"
}
},
"GPT 5 Minimal (ChatGPT Subscription)": {
"id": "gpt-5",
"options": {
"reasoningEffort": "minimal",
"reasoningSummary": "auto",
"textVerbosity": "low"
}
},
"GPT 5 Low (ChatGPT Subscription)": {
"id": "gpt-5",
"options": {
"reasoningEffort": "low",
"reasoningSummary": "auto",
"textVerbosity": "low"
}
},
"GPT 5 Medium (ChatGPT Subscription)": {
"id": "gpt-5",
"options": {
"reasoningEffort": "medium",
"reasoningSummary": "auto",
"textVerbosity": "medium"
}
},
"GPT 5 High (ChatGPT Subscription)": {
"id": "gpt-5",
"options": {
"reasoningEffort": "high",
"reasoningSummary": "detailed",
"textVerbosity": "high"
}
},
"gpt-5-mini": {
"options": {
"reasoningEffort": "low",
"reasoningSummary": "auto",
"textVerbosity": "low"
}
},
"gpt-5-nano": {
"options": {
"reasoningEffort": "minimal",
"reasoningSummary": "auto",
"textVerbosity": "low"
}
}
}
}
}
}
Global config: ~/.config/opencode/opencode.json
Project config: <project>/.opencode.json
This gives you 9 model variants with different reasoning levels:
- GPT 5 Codex (Low/Medium/High)
- GPT 5 (Minimal/Low/Medium/High)
- gpt-5-mini and gpt-5-nano (these are to support the default opencode model selector)
All appear in the opencode model selector with optimal settings for each reasoning level.
Optional: You can remove
(ChatGPT Subscription)from model names if you prefer cleaner labels in the model selector.
Alternative: Minimal Configuration
For a simpler setup (uses plugin defaults: medium reasoning, auto summaries):
{
"$schema": "https://opencode.ai/config.json",
"plugin": [
"opencode-openai-codex-auth"
],
"model": "openai/gpt-5-codex"
}
Note: This gives you basic functionality but you won't see the different reasoning variants in the model selector.
-
That's it! opencode will auto-install the plugin on first run.
Note on Updates: Sometimes opencode does NOT automatically update plugins to new versions. To update:
- Pin to a specific version:
"[email protected]"and change the number when updating - Or clear the plugin cache:
rm -rf ~/.cache/opencode/node_modules/opencode-openai-codex-auth
Check releases for the latest version.
- Pin to a specific version:
New to opencode? Learn more:
Alternative: Local Development
For testing or development, you can use a local file path:
{
"plugin": [
"file:///absolute/path/to/opencode-openai-codex-auth"
]
}
Authentication
Login with ChatGPT OAuth:
opencode auth login
Select "OpenAI" and choose:
- "ChatGPT Plus/Pro (Codex Subscription)" - Opens browser automatically for OAuth flow
Important
: Make sure the official Codex CLI is not running during first login, as both use port 1455 for OAuth callback. After initial authentication, this won't be an issue.
Usage
If using the full configuration, select from the model picker in opencode, or specify via command line:
# Use different reasoning levels for gpt-5-codex
opencode run "simple task" --model="openai/GPT 5 Codex Low (ChatGPT Subscription)"
opencode run "complex task" --model="openai/GPT 5 Codex High (ChatGPT Subscription)"
# Use different reasoning levels for gpt-5
opencode run "quick question" --model="openai/GPT 5 Minimal (ChatGPT Subscription)"
opencode run "deep analysis" --model="openai/GPT 5 High (ChatGPT Subscription)"
# Or with minimal config (uses defaults)
opencode run "create a hello world file" --model=openai/gpt-5-codex
opencode run "solve this complex problem" --model=openai/gpt-5
Available Model Variants (Full Config)
When using config/full-opencode.json, you get these pre-configured variants:
| Model Variant | Reasoning Effort | Best For |
|---|---|---|
| GPT 5 Codex Low | Low | Fast code generation |
| GPT 5 Codex Medium | Medium | Balanced code tasks |
| GPT 5 Codex High | High | Complex code & tools |
| GPT 5 Minimal | Minimal | Quick answers, simple tasks |
| GPT 5 Low | Low | Faster responses with light reasoning |
| GPT 5 Medium | Medium | Balanced general-purpose tasks |
| GPT 5 High | High | Deep reasoning, complex problems |
| gpt-5-mini | Low | Lightweight tasks |
| gpt-5-nano | Minimal | Maximum speed |
All accessed via your ChatGPT Plus/Pro subscription.
Plugin Defaults
When no configuration is specified, the plugin uses these defaults for all GPT-5 models:
{
"reasoningEffort": "medium",
"reasoningSummary": "auto",
"textVerbosity": "medium"
}
reasoningEffort: "medium"- Balanced computational effort for reasoningreasoningSummary: "auto"- Automatically adapts summary verbositytextVerbosity: "medium"- Balanced output length
These defaults match the official Codex CLI behavior and can be customized (see Configuration below).
Configuration
Recommended: Use Pre-Configured File
The easiest way to get started is to use config/full-opencode.json, which provides:
- 9 pre-configured model variants matching Codex CLI presets
- Optimal settings for each reasoning level
- All variants visible in the opencode model selector
See Installation for setup instructions.
Custom Configuration
If you want to customize settings yourself, you can configure options at provider or model level.
Available Settings
⚠️ Important: The two base models have different supported values.
| Setting | GPT-5 Values | GPT-5-Codex Values | Plugin Default |
|---|---|---|---|
reasoningEffort |
minimal, low, medium, high |
low, medium, high |
medium |
reasoningSummary |
auto, detailed |
auto, detailed |
auto |
textVerbosity |
low, medium, high |
medium only |
medium |
include |
Array of strings | Array of strings | ["reasoning.encrypted_content"] |
Note
:
minimaleffort is auto-normalized tolowfor gpt-5-codex (not supported by the API).
Global Configuration Example
Apply settings to all models:
{
"$schema": "https://opencode.ai/config.json",
"plugin": ["opencode-openai-codex-auth"],
"model": "openai/gpt-5-codex",
"provider": {
"openai": {
"options": {
"reasoningEffort": "high",
"reasoningSummary": "detailed"
}
}
}
}
Custom Model Variants Example
Create your own named variants in the model selector:
{
"$schema": "https://opencode.ai/config.json",
"plugin": ["opencode-openai-codex-auth"],
"provider": {
"openai": {
"models": {
"My Fast Codex": {
"id": "gpt-5-codex",
"options": {
"reasoningEffort": "low"
}
},
"My Smart GPT-5": {
"id": "gpt-5",
"options": {
"reasoningEffort": "high",
"textVerbosity": "high"
}
}
}
}
}
}
The id field determines which base model is used (gpt-5-codex or gpt-5), and the name is what appears in the model selector.
Configuration Files
This repository includes ready-to-use configuration examples:
config/full-opencode.json- Complete configuration with 9 model variants (recommended)config/minimal-opencode.json- Minimal configuration for basic usageconfig/README.md- Detailed configuration documentation
Copy the appropriate file to your opencode configuration location and customize as needed.
How It Works
The plugin implements a 7-step fetch flow in TypeScript:
- Token Management: Checks and refreshes OAuth tokens if needed
- URL Rewriting: Transforms requests to
https://chatgpt.com/backend-api/codex/responses - Request Transformation:
- Model normalization (
gpt-5-codexvariants →gpt-5-codex,gpt-5variants →gpt-5) - Injects Codex instructions from latest openai/codex release
- Applies reasoning configuration (effort, summary, verbosity)
- Adds tool remapping instructions (
apply_patch→edit,update_plan→todowrite) - Filters conversation history (removes stored IDs for stateless operation)
- Model normalization (
- Headers: Adds OAuth token and ChatGPT account ID headers
- Request Execution: Sends to Codex backend API
- Response Logging: Optional debug logging (when
ENABLE_PLUGIN_REQUEST_LOGGING=1) - Response Handling: Converts SSE to JSON or returns error details
Key Features
- Modular Design: 10 focused helper functions, each < 40 lines
- Type-Safe: Strict TypeScript with comprehensive type definitions
- Tested: 93 tests covering all functionality
- Zero Dependencies: Only uses @openauthjs/openauth
- Codex Instructions: ETag-cached from GitHub, auto-updates on new releases
- Stateless Operation: Uses
store: falsewith encrypted reasoning content for multi-turn conversations
Limitations
- ChatGPT Plus/Pro required: Must have an active ChatGPT Plus or Pro subscription
Troubleshooting
Authentication Issues
- Ensure you have an active ChatGPT Plus or Pro subscription
- Try re-logging in with
opencode auth login - Check browser console during OAuth flow if auto-login fails
Tool Execution Issues
- Verify plugin is loaded in
opencode.json - Check that model is set to
openai/gpt-5-codex - Check
~/.opencode/cache/for cached instructions (auto-downloads from GitHub)
Request Errors
- 401 Unauthorized: Token expired, run
opencode auth loginagain - 400 Bad Request: Check console output for specific error details
- 403 Forbidden: Subscription may be expired or invalid
Plugin Issues
If you encounter issues with the latest version, you can pin to a specific stable release:
{
"plugin": [
"[email protected]"
]
}
Check releases for available versions and their release notes.
Debugging
Enable Request Logging
For debugging purposes, you can enable detailed request logging to inspect what's being sent to the Codex API:
ENABLE_PLUGIN_REQUEST_LOGGING=1 opencode run "your prompt"
Logs are saved to ~/.opencode/logs/codex-plugin/ with detailed information about:
- Original request from opencode
- Transformed request sent to Codex
- Response status and headers
- Error details (if any)
Each request generates 3-4 JSON files:
request-N-before-transform.json- Original requestrequest-N-after-transform.json- Transformed requestrequest-N-response.json- Response metadatarequest-N-error-response.json- Error details (if failed)
Note: Logging is disabled by default to avoid cluttering your disk. Only enable it when debugging issues.
Project Structure
opencode-openai-codex-auth/
├── index.ts # Main plugin entry point
├── lib/
│ ├── auth.ts # OAuth authentication logic
│ ├── codex.ts # Codex instructions & tool remapping
│ ├── server.ts # Local OAuth callback server
│ ├── browser.ts # Platform-specific browser opening
│ ├── logger.ts # Request logging (debug mode)
│ ├── request-transformer.ts # Request body transformations
│ ├── response-handler.ts # SSE to JSON conversion
│ ├── fetch-helpers.ts # Focused helper functions
│ ├── constants.ts # All magic values and URLs
│ └── types.ts # TypeScript type definitions
├── config/
│ ├── full-opencode.json # Complete config with all variants
│ ├── minimal-opencode.json # Minimal config example
│ └── README.md # Configuration documentation
├── test/ # Comprehensive test suite (93 tests)
├── AGENTS.md # AI agent maintenance guide
├── package.json
├── README.md
└── LICENSE
Module Overview
- index.ts: Main plugin export and fetch() orchestration (7-step flow)
- lib/auth.ts: OAuth flow, PKCE, token exchange, JWT decoding
- lib/codex.ts: Fetches/caches Codex instructions from GitHub, tool remapping
- lib/server.ts: Local HTTP server for OAuth callback handling
- lib/browser.ts: Platform detection and browser opening
- lib/logger.ts: Debug logging (controlled by environment variable)
- lib/request-transformer.ts: Request transformations (model normalization, reasoning config)
- lib/response-handler.ts: Response handling (SSE to JSON conversion)
- lib/fetch-helpers.ts: 10 focused helper functions for main fetch flow
- lib/constants.ts: Centralized constants, URLs, error messages
- lib/types.ts: TypeScript type definitions
Credits
Based on research and working implementations from:
- ben-vargas/ai-sdk-provider-chatgpt-oauth
- ben-vargas/ai-opencode-chatgpt-auth
- openai/codex OAuth flow
- sst/opencode
License
MIT