npm package: @hobeeliu/codex-switch
Description: A CLI tool for managing Codex configuration profiles
Author: Hobee Liu
Latest version: 1.1.1

# Codex Switch

[中文 README](README.zh.md) | English

[![npm version](https://badge.fury.io/js/%40hobeeliu%2Fcodex-switch.svg)](https://badge.fury.io/js/%40hobeeliu%2Fcodex-switch)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A powerful CLI tool for managing multiple Codex configuration profiles and seamlessly switching between different AI coding environments. Perfect for developers working with different projects, environments, or AI models that require distinct configurations.

## ✨ Features

- 🔧 **Profile Management**: Create, edit, copy, move, and delete Codex configuration profiles
- 📋 **Template System**: Built-in template for quick profile creation with template copy/rename operations
- 🔄 **Import/Export**: Share profiles using `.cxs` files with optional secret exclusion
- 🧪 **Configuration Testing**: Comprehensive testing (connectivity & authentication, model availability, end-to-end) with automatic config backup/restore
- 📝 **Rich CLI Interface**: Interactive commands with prompts, validation, and colorized output
- 🌐 **Web Interface**: Visual management interface accessible at http://localhost:13500
- 🔒 **Secure Configuration**: Handles sensitive data with optional exclusion during export
- 📊 **History & State Tracking**: Keep track of profile changes, usage history, and current state
- 🌍 **Cross-Platform**: Works seamlessly on macOS, Linux, and Windows
- ⚡ **Real Configuration Changes**: Applies actual changes to `~/.codex/` configuration files

## 📦 Installation

### Via npm (Recommended)

```bash
npm install -g @hobeeliu/codex-switch
```

### Via Go

```bash
go install github.com/HoBeedzc/codex-switch@latest
```

### From Source

```bash
git clone https://github.com/HoBeedzc/codex-switch.git
cd codex-switch
npm run build
npm install -g .
```

## 🚀 Quick Start

1. **Initialize the configuration directory:**
   ```bash
   codex-switch init
   ```

2. **Create your first profile:**
   ```bash
   codex-switch new my-development-profile --interactive
   ```

3. **Switch to your profile:**
   ```bash
   codex-switch use my-development-profile
   ```

4. **List all profiles:**
   ```bash
   codex-switch list --verbose
   ```

5. **Start the web interface (optional):**
   ```bash
   codex-switch web
   ```

6. **Test your configuration:**
   ```bash
   codex-switch test
   ```

## 📚 Commands Reference

### Web Interface

#### `codex-switch web`
Start a local web server for visual profile management.

```bash
# Start web interface on default port 13500
codex-switch web

# Start on custom port
codex-switch web --port 9090

# Specify custom host
codex-switch web --host 0.0.0.0 --port 8080

# Don't open browser automatically
codex-switch web --no-browser

# Enable debug mode for development
codex-switch web --debug
```

**Features:**
- Visual profile creation and editing
- Easy profile switching with one click
- Comprehensive testing (connectivity & authentication, model availability, end-to-end)
- Import/export functionality with drag-and-drop support
- Real-time configuration preview
- Dashboard with usage analytics and health metrics

### Core Profile Management

#### `codex-switch new [profile-name]`
Create a new profile with comprehensive configuration options.

```bash
# Interactive creation with prompts
codex-switch new --interactive

# Create with specific name and description
codex-switch new work-env --description "Work environment settings"

# Create from built-in template
codex-switch new prod-config --template production

# Create with specific model and settings
codex-switch new test-profile --model gpt-4 --temperature 0.5 --max-tokens 4096

# Create empty profile for manual configuration
codex-switch new empty-profile --empty
```

**Available Options:**
- `-d, --description`: Profile description
- `-t, --template`: Use template (basic, advanced, development, production, creative, conservative)
- `-e, --empty`: Create empty profile
- `-i, --interactive`: Force interactive configuration
- `-m, --model`: AI model (gpt-3.5-turbo, gpt-4, gpt-4-turbo, gpt-5, etc.)
- `--api-key`: OpenAI API key
- `--base-url`: API base URL (default: https://api.codex.com/v1)
- `--max-tokens`: Maximum tokens (1-4096)
- `--temperature`: Creativity level (0.0-2.0)
- `--tags`: Comma-separated tags for organization

#### `codex-switch use [profile-name]`
Switch to a profile and apply real configuration changes.

```bash
# Switch to specific profile
codex-switch use work-env

# Interactive selection from available profiles
codex-switch use

# Force interactive mode and show current profile
codex-switch use -i

# Use empty mode (clear all configurations for OAuth login)
codex-switch use --empty

# Empty mode with launch
codex-switch use -e -l
```

**What happens when switching:**
- Updates `~/.codex/auth.json` with API credentials
- Updates `~/.codex/config.toml` with model settings

**Empty Mode:**
- `--empty` or `-e`: Clears all Codex configurations
- Removes `~/.codex/auth.json` and `~/.codex/config.toml`
- Allows using OpenAI OAuth login in Codex CLI
- Available in interactive mode as "Empty Mode" option
- Updates current profile state
\- In interactive mode (`-i` or no profile arg), the selector shows the currently active profile and defaults the cursor to it

#### `codex-switch list`
Display all available profiles or templates.

```bash
# Basic profile listing
codex-switch list

# Detailed view with creation dates and full descriptions
codex-switch list --verbose

# Show only currently active profile
codex-switch list --current

# Alternative short form
codex-switch ls -v

# List templates (built-in and custom)
codex-switch list --template

# Templates with more details (model, tags)
codex-switch list -t -v
```

#### `codex-switch current`
Show information about the currently active profile.

```bash
# Show current profile details
codex-switch current

# Show only profile name
codex-switch current --name-only

# Show with full configuration
codex-switch current --verbose
```

### Profile Operations

#### `codex-switch view [name]`
View detailed profile or template configuration.

```bash
# View specific profile
codex-switch view my-profile

# View raw YAML of profile
codex-switch view my-profile --raw

# View a template
codex-switch view -t default

# View raw YAML of a template
codex-switch view -t default --raw

# Interactive template selection
codex-switch view -t -i
```

#### `codex-switch edit [profile-name]`
Edit profile in your default text editor.

```bash
# Edit profile with default editor
codex-switch edit my-profile

# Edit current active profile and apply changes immediately
codex-switch edit --current
codex-switch edit -c

# Use specific editor
codex-switch edit my-profile --editor nano

# Edit template instead of profile
codex-switch edit --template my-template
```

#### `codex-switch cp <source> <destination>`
Copy an existing profile or template to create a new one.

**Profile Operations:**
```bash
# Copy profile
codex-switch cp work-env staging

# Force overwrite if destination exists
codex-switch cp dev prod --force

# Interactive source selection (shows and defaults to current)
codex-switch cp -i

# No-arg interactive (pick source, then enter new name)
codex-switch cp
```

**Template Operations:**
```bash
# Copy built-in template to custom template
codex-switch cp -t default my-custom-template

# Copy template with default naming (copy-of-{source})
codex-switch cp -t default

# Interactive template selection and naming
codex-switch cp -t

# Force overwrite existing template
codex-switch cp -t my-template updated-template --force

# Copy custom template to another name
codex-switch cp -t my-template team-template
```

**Template Copy Features:**
- ✅ Copy from built-in templates to custom templates
- ✅ Copy between custom templates
- ✅ Interactive selection shows built-in templates marked as "(built-in)"
- ✅ Default destination naming: "copy-of-{source-name}"
- ✅ Built-in template protection (cannot overwrite built-in templates)
- ✅ Force overwrite for custom templates with `--force`

#### `codex-switch mv <old-name> <new-name>`
Rename an existing profile or template.

**Profile Operations:**
```bash
# Rename profile
codex-switch mv old-name new-name

# Force rename with overwrite
codex-switch mv development prod --force

# Interactive source selection (shows and defaults to current)
codex-switch mv -i

# No-arg interactive (pick source, then enter new name)
codex-switch mv
```

**Template Operations:**
```bash
# Rename custom template
codex-switch mv -t my-template my-updated-template

# Interactive template selection (custom templates only)
codex-switch mv -t

# Interactive template selection with specific source
codex-switch mv -t my-template

# Force overwrite when renaming
codex-switch mv -t old-template existing-name --force
```

**Template Rename Features:**
- ✅ Rename custom templates only (built-in templates are protected)
- ✅ Interactive selection shows only custom templates
- ✅ Cannot rename to built-in template names
- ✅ Force overwrite existing custom templates with `--force`
- ✅ YAML content automatically updated with new name
- ⚠️ **Note**: Built-in templates (like "default") cannot be renamed

#### `codex-switch rm <profile-name>`
Remove a profile permanently with confirmation.

```bash
# Remove with confirmation prompt (interactive)
codex-switch rm old-profile

# Force removal without confirmation
codex-switch rm unused-profile --force

# No-arg interactive selection (shows and defaults to current)
codex-switch rm

# Always prompt for confirmation (does not force selector)
codex-switch rm -i my-profile
```

**Safety Features:**
- Interactive confirmation prevents accidental deletion
- Clearly warns when deleting the current active profile
- Provides profile information before deletion
- Backup recommendations for important profiles

### Import/Export Operations

#### `codex-switch export <profile-name> [output-file]`
Export profile to shareable file format.

```bash
# Export to default filename (profile-name.cxs)
codex-switch export my-profile

# Export to specific file
codex-switch export my-config ~/exports/my-config.cxs

# Include sensitive data (API keys, etc.)
codex-switch export my-profile --include-secrets

# Export as YAML format
codex-switch export my-profile config.yaml --format yaml

# Export with custom metadata
codex-switch export shared-profile --exclude-secrets --format cxs
```

#### `codex-switch import <file-path> [profile-name]`
Import profile from exported file.

```bash
# Import with original name
codex-switch import shared-config.cxs

# Import with new name
codex-switch import shared-config.cxs team-config

# Force overwrite existing profile
codex-switch import shared-config.cxs existing-name --force

# Auto-rename if conflict exists
codex-switch import config.cxs --rename
```

### Configuration Testing

#### `codex-switch test [profile-name]`
Test profile configuration with comprehensive validation including API connectivity, authentication, model availability, and end-to-end testing.

**Testing Stages:**
1. **Connectivity & Authentication**: Validates API endpoint and API key (calls `GET {BaseURL}/models`)
2. **Model Availability**: Checks if the specified model exists (calls `GET {BaseURL}/models/{model}`, warning level - 404 is acceptable)
3. **End-to-End Test**: Executes real `codex exec "hi"` to verify complete functionality

**Important Notes:**
- Without API Key: Only connectivity test is performed (HEAD request to BaseURL), authentication and end-to-end tests are skipped
- End-to-end test requires codex CLI installed locally (automatically skipped if not found)
- Test temporarily writes to `~/.codex/auth.json` and `~/.codex/config.toml`, then automatically restores original configuration (interruptions may leave temporary config)

```bash
# Interactive mode - choose profile to test
codex-switch test

# Test specific profile
codex-switch test my-profile

# Test with detailed output showing command execution and responses
codex-switch test my-config --verbose

# Test all profiles sequentially
codex-switch test --all

# Test currently active profile
codex-switch test --current

# Test with custom timeout (default: 30 seconds)
codex-switch test my-profile --timeout 60

# Test with retry mechanism
codex-switch test my-profile --retry 3      # Retry 3 times on failure
codex-switch test my-profile --retry -1     # Infinite retry until success
codex-switch test my-profile --retry 0      # No retry (default)
```

**Features:**
- Automatic configuration backup and restore during testing
- API key sanitization in output (masked in test output; Web API shows first 8 + last 4 chars; CLI list/view shows first 4 + last 4 chars)
- Graceful handling when codex CLI is not installed
- Real-time duration tracking for each test phase

### System Management

#### `codex-switch init`
Initialize the configuration directory structure.

```bash
# Create initial directory structure and templates
codex-switch init

# Reinitialize with fresh templates
codex-switch init --force
```

## 🗂️ Configuration Structure

Codex Switch stores all configurations in `~/.codex-switch/` with organized structure:

```
~/.codex-switch/
├── profiles/              # Individual profile configurations (.yaml files)
│   ├── my-config.yaml
│   └── work-config.yaml
├── templates/             # Built-in and custom templates
│   └── default.yaml
├── state.yaml            # Current active profile and application state
├── config.yaml           # Global application settings
└── history.yaml          # Command and usage history
```

### Profile Configuration Schema

Each profile contains comprehensive configuration options:

```yaml
name: work-environment
description: "Work environment with standard settings"
created_at: 2024-01-15T14:30:00Z
updated_at: 2024-01-15T16:45:00Z
tags:
  - work
  - standard
config:
  # Core API Configuration
  api_key: "sk-your-api-key-here"
  base_url: "https://api.codex.com/v1"
  model: "gpt-5"
  model_reasoning_effort: "medium"
  disable_response_storage: false
  requires_openai_auth: false
```

### Built-in Templates

Codex Switch includes a default template for quick profile creation and supports custom template management:

| Template | Use Case | Key Features |
|----------|----------|--------------|
| **default** | General purpose | Standard settings for typical usage |

#### Template Management Operations

**Copy Templates:**
- Copy built-in templates to create custom variants
- Copy custom templates for different use cases  
- Built-in templates are protected from overwriting
- Interactive selection with built-in template indicators

**Rename Templates:**
- Rename custom templates only (built-in templates protected)
- Cannot rename to built-in template names
- YAML content automatically updated
- Interactive selection for custom templates

**Template Protection Rules:**
- ✅ Copy FROM built-in templates (like "default") TO custom names
- ❌ Rename built-in templates  
- ❌ Overwrite built-in templates
- ❌ Rename TO built-in template names
- ✅ All operations on custom templates (with confirmation/force flags)

## 🎯 Usage Examples

### Template Management Workflow

```bash
# Create custom template from built-in default
codex-switch cp -t default my-work-template

# Create profile from custom template
codex-switch new work-profile --template my-work-template

# Create variations of templates
codex-switch cp -t my-work-template my-personal-template
codex-switch cp -t my-work-template team-shared-template

# Rename templates for better organization
codex-switch mv -t my-personal-template personal-dev-template
codex-switch mv -t team-shared-template team-standard-template

# Interactive template management
codex-switch cp -t    # Select source and enter destination
codex-switch mv -t    # Select custom template to rename
```

### Basic Workflow

```bash
# Set up a new profile
codex-switch new work-env --template default --interactive
codex-switch use work-env

# Test the configuration
codex-switch test work-env --verbose

# Create a variant for different use
codex-switch cp work-env personal-env
codex-switch edit personal-env  # Adjust settings

# Export for sharing
codex-switch export work-env team-config.cxs --exclude-secrets
```

### Multi-Environment Management

```bash
# Create environment-specific profiles
codex-switch new local-dev --template default --model gpt-3.5-turbo
codex-switch new staging --template default --model gpt-4
codex-switch new production --template default --model gpt-4

# Quick environment switching
codex-switch use local-dev    # For local development
codex-switch use staging      # For staging tests
codex-switch use production   # For production deployment

# Monitor current environment
codex-switch current --name-only
```

### Team Configuration Sharing

```bash
# Team lead exports standard configuration
codex-switch export team-standard team-config.cxs --exclude-secrets

# Team members import and customize
codex-switch import team-config.cxs my-team-config
codex-switch edit my-team-config  # Add personal API key and preferences
codex-switch use my-team-config
```

### Configuration Export and Sharing

```bash
# Export all configurations for sharing
codex-switch list --verbose  # List all profiles  
codex-switch export profile1 shared/profile1.cxs --include-secrets
codex-switch export profile2 shared/profile2.cxs --include-secrets

# Import on new machine
codex-switch init
codex-switch import shared/profile1.cxs
codex-switch import shared/profile2.cxs
codex-switch use profile1
```

## 🔧 Advanced Configuration

### Custom Templates

Create custom templates in `~/.codex-switch/templates/`:

```yaml
# ~/.codex-switch/templates/my-custom.yaml
name: "custom-template"
description: "My custom configuration template"
config:
  model: "gpt-4"
  temperature: 0.9
  max_tokens: 2048
```

Use custom template:
```bash
codex-switch new my-profile --template default
```

## 🔍 API Reference

### Configuration Fields

| Field | Type | Range/Options | Description | Default |
|-------|------|---------------|-------------|---------|
| `api_key` | string | - | OpenAI API key | - |
| `base_url` | string | URL | API endpoint URL | https://api.codex.com/v1 |
| `model` | string | Model names | AI model identifier | gpt-5 |
| `model_reasoning_effort` | string | low/medium/high | Model reasoning effort level | medium |
| `disable_response_storage` | boolean | true/false | Disable response storage | false |
| `requires_openai_auth` | boolean | true/false | Whether requires OpenAI authentication | false |

## 🐛 Troubleshooting

### Common Issues and Solutions

#### 1. Profile Not Found
```bash
# Check available profiles
codex-switch list

# Initialize if directory is missing  
codex-switch init

# Verify profile name spelling
codex-switch list --verbose
```

#### 2. API Connection Failed
```bash
# Test configuration with detailed output
codex-switch test my-profile --verbose

# Verify API key and endpoint
codex-switch view my-profile --config-only

# Check network connectivity (test uses HEAD to base_url, then GET to /models)
curl -I https://api.codex.com/v1  # HEAD request to base_url
curl https://api.codex.com/v1/models  # GET request for authentication test

# Note: Some servers may not support HEAD requests properly
# If HEAD fails, try GET for verification
```

#### 3. Web Interface Issues
```bash
# Check if port is already in use
lsof -i :13500

# Start on different port
codex-switch web --port 8080

# Check web server logs
codex-switch web --debug

# Access via different host
codex-switch web --host 0.0.0.0 --port 13500
```

#### 4. Permission Errors
```bash
# Check directory permissions
ls -la ~/.codex-switch/

# Fix permissions if needed
chmod 755 ~/.codex-switch/
chmod 644 ~/.codex-switch/*.yaml

# Reinitialize if needed
codex-switch init --force
```

#### 5. Configuration Corruption
```bash
# List all available profiles
codex-switch list --verbose

# Import from exported file  
codex-switch import exported-file.cxs --force

# Reset to clean state
rm -rf ~/.codex-switch/
codex-switch init
```

### Debug Mode

Enable verbose output for detailed troubleshooting:

```bash
# Test with full debugging output
codex-switch test my-profile --verbose --timeout 120

# View complete configuration
codex-switch view my-profile --yaml

# Check current state
codex-switch current --verbose
```

### Log Analysis

Check application logs for detailed error information:

```bash
# Check recent command history
cat ~/.codex-switch/history.yaml

# View current application state
cat ~/.codex-switch/state.yaml

# Examine specific profile
cat ~/.codex-switch/profiles/my-profile.yaml
```

## 🤝 Contributing

We welcome contributions! Here's how to get started:

### Development Setup

```bash
# Clone the repository
git clone https://github.com/HoBeedzc/codex-switch.git
cd codex-switch

# Install Go dependencies
go mod download

# Install Node.js dependencies for packaging
npm install

# Build the application
npm run build

# Run tests
npm test
```

### Building and Testing

```bash
# Build for current platform
go build -o codex-switch .

# Build for all platforms
npm run build

# Run Go tests with coverage
go test -v -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

# Test specific package
go test -v ./internal/config
go test -v ./internal/exporter
go test -v ./internal/importer
```

### Project Structure

```
codex-switch/
├── cmd/                   # CLI command implementations
│   ├── root.go           # Root command and version info
│   ├── list.go           # Profile listing functionality
│   ├── new.go            # Profile creation
│   ├── use.go            # Profile switching
│   ├── view.go           # Profile viewing
│   ├── edit.go           # Profile editing
│   ├── cp.go, mv.go, rm.go # Profile operations
│   ├── import.go, export.go # Import/export functionality
│   ├── test.go           # Configuration testing
│   └── init.go           # Initialization
├── internal/             # Internal packages
│   ├── config/           # Configuration management
│   ├── templates/        # Template system
│   ├── exporter/         # Export functionality
│   ├── importer/         # Import functionality
│   ├── tester/           # Configuration testing
│   └── ui/               # User interface utilities
├── scripts/              # Build and installation scripts
├── main.go               # Application entry point
├── package.json          # NPM packaging configuration
└── go.mod               # Go module definition
```

### Contribution Guidelines

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Write tests for new functionality
4. Ensure all tests pass (`go test ./...`)
5. Update documentation as needed
6. Commit your changes (`git commit -m 'Add amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🙏 Acknowledgments

- Inspired by configuration management tools and AI development workflows
- Built with [Cobra](https://github.com/spf13/cobra) CLI framework for robust command-line interface
- Uses [promptui](https://github.com/manifoldco/promptui) for interactive user prompts
- Leverages [color](https://github.com/fatih/color) for beautiful terminal output
- Configuration management powered by [yaml.v3](https://gopkg.in/yaml.v3)

## 📞 Support

- 📚 [Documentation](https://github.com/HoBeedzc/codex-switch#readme)
- 🐛 [Issue Tracker](https://github.com/HoBeedzc/codex-switch/issues)
- 💬 [Discussions](https://github.com/HoBeedzc/codex-switch/discussions)
- 📧 [Email Support:Hobee.Liu@gmail.com](mailto:Hobee.Liu@gmail.com)

---

**Made with ❤️ for the AI development community**