# 🔍 Research CLI

> **AI-powered research assistant with web search capabilities**  
> Transform any question into comprehensive research in seconds.

[![TypeScript](https://img.shields.io/badge/TypeScript-007ACC?style=for-the-badge&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
[![Node.js](https://img.shields.io/badge/Node.js-43853D?style=for-the-badge&logo=node.js&logoColor=white)](https://nodejs.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge)](https://opensource.org/licenses/MIT)

## ✨ What Makes This Special

Research CLI is a **zero-install TypeScript CLI tool** that brings the power of multiple AI providers to your terminal with beautiful, professional output and secure credential management.

### 🎯 Perfect For

- **Developers** researching APIs, frameworks, and best practices
- **Researchers** gathering information with citations and sources
- **Content creators** exploring topics with web-enhanced AI responses
- **Students** getting quick explanations with optional deep-dives
- **Teams** standardizing research workflows with shared configurations

---

## 🚀 Quick Start

### Option 1: Interactive Setup (Recommended for New Users)
```bash
npx research-cli easymode
```
Guides you through provider selection, API key setup, and your first query!

### Option 2: Direct Usage (For Quick Queries)
```bash
# Basic research
npx research-cli "What are the latest developments in quantum computing?"

# With web search
npx research-cli "TypeScript 5.0 new features" --web

# Specific provider and model
npx research-cli "Explain React hooks" --provider openai --model gpt-4o
```

---

## 🎨 Beautiful Terminal Experience

### Professional Output Formatting
```bash
research-cli "Explain GraphQL" --web
```

Features beautiful colored output with:
- 🎨 **Semantic Color Themes** - Provider-specific branding
- 📊 **Real-time Progress Bars** - Visual feedback during API calls
- 🔍 **Web Search Indicators** - See when tools are being used
- ⚡ **Streaming Responses** - Watch results appear in real-time

### Interactive Setup Flow
```bash
research-cli easymode
```

Beautiful guided setup with:
- 🎯 **Provider Selection Menu** - Choose from OpenAI, Claude, Perplexity, Gemini
- 🔐 **Secure Key Entry** - Masked input with format validation
- 🧪 **Connection Testing** - Automatic API key validation
- 🚀 **Quick Demo** - Try your first query immediately

---

## 🛠 Comprehensive Features

### 🤖 Multi-Provider AI Support
- **OpenAI** - GPT-4, GPT-4o, o3 models
- **Anthropic Claude** - Claude 3.5 Sonnet, Haiku models  
- **Perplexity** - Research-focused with built-in web search
- **Google Gemini** - Gemini Pro, Ultra models

### 🔐 Enterprise-Grade Security
- **Secure Storage** - API keys stored in system keychain (macOS, Windows, Linux)
- **Environment Support** - Respects `OPENAI_API_KEY`, `CLAUDE_API_KEY`, etc.
- **Never Logged** - Credentials redacted in dry-run mode
- **Migration Tools** - Safely move from config files to secure storage

### 📊 Multiple Output Formats
- **Markdown** (`--format md`) - Beautiful terminal rendering (default)
- **JSON** (`--format json`) - Structured data for automation
- **JSONL** (`--format jsonl`) - Event stream for real-time processing
- **Raw** (`--format raw`) - Plain text for simple integration

### 🌐 Web Search Integration
```bash
# Enable web search for current information
research-cli "Latest AI research papers 2024" --web

# Control search depth
research-cli "Stock market today" --web --web-search-context-size high
```

### ⚙️ Flexible Configuration
```bash
# Save preferences
research-cli config set defaultProvider openai
research-cli config set defaultModel gpt-4o

# View current config
research-cli config show

# Reset to defaults
research-cli config reset
```

---

## 📚 Complete Command Reference

### 🔍 Research Commands
```bash
# Basic usage (default command)
research-cli "your question here"
research-cli research "your question here"  # explicit

# Research options
research-cli "question" \
  --provider openai \           # openai, claude, perplexity, gemini
  --model gpt-4o \             # provider-specific models
  --web \                      # enable web search
  --format json \              # md, json, jsonl, raw
  --output results.md \        # save to file
  --temperature 0.7 \          # generation creativity
  --max-tokens 1000 \          # response length limit
  --verbose                    # detailed logging
```

### 🎯 Setup & Onboarding
```bash
research-cli easymode                    # Interactive guided setup
research-cli easymode --provider openai  # Skip provider selection
research-cli setup                       # Alternative command name
research-cli easy                        # Short alias
```

### 🔐 Authentication Management
```bash
# Setup and login
research-cli auth login openai           # Interactive API key setup
research-cli auth login openai --key sk-... # Direct key provision

# Status and testing
research-cli auth list                   # Show all configured providers
research-cli auth status                 # Legacy status command
research-cli auth test openai           # Test specific provider
research-cli auth keyring-status         # Check system keyring

# Key management
research-cli auth logout openai          # Remove API key
research-cli auth logout openai --force  # Skip confirmation
research-cli auth migrate                # Move from config to keyring
```

### ⚙️ Configuration
```bash
# Configuration management
research-cli config init                 # Create default config
research-cli config show                 # Display current settings
research-cli config get defaultProvider  # Get specific value
research-cli config set theme dark       # Set configuration value
research-cli config reset                # Reset to defaults
research-cli config reset --force        # Skip confirmation
```

### 🛠 Utility & Debug
```bash
# Debug and development
research-cli "test query" --dry-run      # Preview request payload
research-cli "question" --verbose        # Detailed execution logging
research-cli --version                   # Show version info
research-cli --help                      # Comprehensive help
```

---

## 🏗 Advanced Usage Patterns

### 🔄 Automation & Scripting
```bash
# Batch processing with JSONL output
echo "Question 1\nQuestion 2\nQuestion 3" | \
while read question; do
  research-cli "$question" --format jsonl >> results.jsonl
done

# CI/CD integration
OPENAI_API_KEY=$SECRET research-cli \
  "Analyze this codebase for security issues" \
  --format json \
  --output security-report.json
```

### 🎨 Custom Workflows
```bash
# Research pipeline with web search
research-cli "Latest React patterns 2024" --web --format json | \
  jq '.content' | \
  research-cli "Summarize this in 3 bullet points" --format md
```

### 🔧 Development Integration
```bash
# IDE integration (VS Code task)
{
  "label": "Research Topic",
  "type": "shell",
  "command": "research-cli",
  "args": ["${input:topic}", "--web", "--format", "md"],
  "group": "build"
}
```

---

## 🧠 Smart Features

### 🎯 Progressive Disclosure Design
- **Beginners**: Start with `easymode` for guided setup
- **Intermediate**: Use basic commands with helpful defaults
- **Advanced**: Access full option set for complex workflows

### 🔍 Intelligent Defaults
- **Auto-detect** best provider based on query type
- **Smart formatting** based on output destination (TTY vs file)
- **Context-aware** web search activation
- **Graceful fallbacks** when providers are unavailable

### 📱 Cross-Platform Excellence
- **macOS**: Native keychain integration
- **Windows**: Windows Credential Store support  
- **Linux**: Secret Service API compatibility
- **CI/CD**: Environment variable fallbacks

---

## 🛡 Security & Privacy

### 🔐 Credential Security
- ✅ **Never stored in plaintext** - System keychain only
- ✅ **Automatic redaction** - Sensitive data masked in logs
- ✅ **Secure transmission** - HTTPS/TLS for all API calls
- ✅ **Local processing** - No data sent to third parties

### 🔒 Best Practices
- API keys stored using native OS credential managers
- Environment variables supported for ephemeral use
- Dry-run mode for testing without API calls
- Comprehensive error handling with specific error codes

---

## 🚀 Installation & Setup

### System Requirements
- **Node.js 20+** (required for stable fetch and stream APIs)
- **TypeScript** (included in dependencies)
- **System keychain** (macOS Keychain, Windows Credential Store, Linux Secret Service)

### Installation Options

#### Option 1: Direct Usage (Recommended)
```bash
npx research-cli easymode
```
Zero installation required - downloads and runs latest version.

#### Option 2: Global Installation
```bash
npm install -g research-cli
research-cli easymode
```

#### Option 3: Local Development
```bash
git clone https://github.com/your-username/research-cli.git
cd research-cli
pnpm install
pnpm build
pnpm dev "your question here"
```

### First-Time Setup
1. **Run easymode**: `research-cli easymode`
2. **Choose provider**: OpenAI, Claude, Perplexity, or Gemini
3. **Add API key**: Securely stored in system keychain
4. **Test connection**: Automatic validation
5. **Start researching**: You're ready to go!

---

## 🔧 Development

### Tech Stack
- **TypeScript** - Strict mode, ESM modules
- **Clipanion** - Modern CLI framework with decorators
- **Chalk** - Terminal styling and semantic colors
- **terminal-kit** - Interactive prompts and progress
- **keytar** - Cross-platform credential storage
- **Biome** - Code formatting and linting

### Development Commands
```bash
# Development
pnpm dev "test query"        # Run with ts-node
pnpm build                   # Compile TypeScript
pnpm clean                   # Remove dist/

# Quality assurance
pnpm typecheck              # TypeScript checking
pnpm lint                   # ESLint + Biome
pnpm biome check --write    # Format and fix

# Testing
pnpm test                   # Run test suite
node dist/cli.js --dry-run  # Manual testing
```

### Project Structure
```
src/
├── cli.ts                  # Clipanion CLI entry point
├── types.ts               # Core TypeScript interfaces
├── auth/
│   └── keyring-manager.ts # Secure credential storage
├── commands/
│   ├── auth.ts           # Authentication commands
│   ├── config.ts         # Configuration management
│   ├── easymode.ts       # Interactive setup
│   ├── query.ts          # Core research logic
│   └── research.ts       # Main research command
├── providers/
│   └── openai.ts         # OpenAI API integration
├── render/
│   └── markdown.ts       # Terminal output formatting
├── ui/
│   ├── styles.ts         # Chalk color system
│   ├── formatters.ts     # Message formatting
│   ├── progress.ts       # Progress bar management
│   ├── interactive.ts    # Terminal-kit prompts
│   └── boxes.ts          # Layout components
└── utils/
    └── credentials.ts    # API key utilities
```

---

## 🎓 Examples & Tutorials

### Academic Research
```bash
# Literature review with citations
research-cli "Recent advances in machine learning 2024" \
  --web \
  --web-search-context-size high \
  --output literature-review.md

# Technical deep-dive
research-cli "Explain transformer architecture in detail" \
  --provider claude \
  --model claude-3-5-sonnet \
  --max-tokens 2000
```

### Development Workflow
```bash
# API documentation research
research-cli "How to use React Server Components" --web

# Framework comparison
research-cli "Next.js vs Nuxt.js vs SvelteKit comparison 2024" \
  --format json \
  --output framework-comparison.json

# Debugging assistance
research-cli "Why is my TypeScript build failing with module resolution error?" \
  --provider openai \
  --temperature 0.1
```

### Content Creation
```bash
# Blog post research
research-cli "Latest trends in web development 2024" \
  --web \
  --format md \
  --output blog-research.md

# Social media content
research-cli "Create engaging tweet about AI developments" \
  --max-tokens 280 \
  --temperature 0.8
```

---

## 🐛 Troubleshooting

### Common Issues

#### API Key Problems
```bash
# Check API key status
research-cli auth list

# Test specific provider
research-cli auth test openai

# Re-setup provider
research-cli auth logout openai
research-cli auth login openai
```

#### Connection Issues
```bash
# Verbose logging for debugging
research-cli "test query" --verbose

# Test with dry-run (no API call)
research-cli "test query" --dry-run

# Check keyring status
research-cli auth keyring-status
```

#### Configuration Problems
```bash
# Reset configuration
research-cli config reset --force

# Reinitialize
research-cli config init

# Manual configuration check
cat ~/.config/research-cli/config.json
```

### Error Codes
- `PROVIDER_TIMEOUT` - API request timeout
- `API_KEY_MISSING` - No API key found
- `INVALID_PROVIDER` - Unsupported provider specified
- `KEYRING_UNAVAILABLE` - System keychain access failed
- `CONFIG_PARSE_ERROR` - Configuration file corruption

---

## 📊 Comparison

### vs. ChatGPT Web Interface
✅ **Terminal-native** - No browser switching  
✅ **Scriptable** - Automation and CI/CD integration  
✅ **Multiple providers** - Not locked to one service  
✅ **Local storage** - Your data stays on your machine  

### vs. curl + API
✅ **User-friendly** - No JSON payload construction  
✅ **Secure credentials** - Automatic key management  
✅ **Beautiful output** - Formatted for humans  
✅ **Error handling** - Meaningful error messages  

### vs. Other CLI Tools
✅ **Multi-provider** - OpenAI, Claude, Perplexity, Gemini  
✅ **Web search** - Enhanced with real-time information  
✅ **Professional UI** - Progress bars, colors, interactivity  
✅ **TypeScript native** - Type-safe from the ground up  

---

## 🗺 Roadmap

### 🚧 Coming Soon
- [ ] **Plugin System** - Custom providers and formatters
- [ ] **Template Engine** - Reusable prompt templates
- [ ] **Conversation Mode** - Multi-turn research sessions
- [ ] **File Input** - Research documents and codebases
- [ ] **Export Formats** - PDF, DOCX, HTML output

### 🔮 Future Ideas
- [ ] **Voice Input** - Speech-to-text research queries
- [ ] **Visual Output** - Charts and graphs generation
- [ ] **Collaboration** - Shared research sessions
- [ ] **Analytics** - Usage metrics and insights
- [ ] **Mobile App** - iOS/Android companion

---

## 🤝 Contributing

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

### 🐛 Bug Reports
- Use the issue template
- Include command that failed
- Attach error output (with credentials redacted)
- Specify your OS and Node.js version

### ✨ Feature Requests
- Describe the use case
- Explain the expected behavior
- Consider backward compatibility
- Provide implementation ideas if possible

### 🔧 Development Contributions
1. **Fork the repository**
2. **Create feature branch**: `git checkout -b feature/amazing-feature`
3. **Follow code style**: Run `pnpm biome check --write`
4. **Add tests**: Ensure new features are tested
5. **Update docs**: Keep README and help text current
6. **Submit PR**: Include detailed description

---

## 🙏 Acknowledgments

### Technologies That Made This Possible
- **[Clipanion](https://github.com/arcanis/clipanion)** - Elegant CLI framework
- **[Chalk](https://github.com/chalk/chalk)** - Terminal styling
- **[terminal-kit](https://github.com/cronvel/terminal-kit)** - Interactive components
- **[keytar](https://github.com/atom/node-keytar)** - Secure credential storage
- **[OpenAI](https://openai.com)** - GPT models and API
- **[Anthropic](https://anthropic.com)** - Claude models
- **[Perplexity](https://perplexity.ai)** - Research-focused AI

### Inspiration
- **[GitHub CLI](https://cli.github.com/)** - Excellence in CLI design
- **[Vercel CLI](https://vercel.com/cli)** - Developer experience focus
- **[Stripe CLI](https://stripe.com/docs/stripe-cli)** - Professional API tooling

---

## 📄 License

**MIT License** - Feel free to use this in your personal and commercial projects.

See [LICENSE](LICENSE) for full details.

---

<div align="center">

**Made with ❤️ for developers, researchers, and curious minds everywhere**

⭐ **Star this repo** • 🐛 **Report bugs** • 💡 **Request features**

</div>