# Cortex Code

<div align="center">

**AI-powered command-line tool for Snowflake Cortex**

[Installation](#installation) • [Quick Start](#quick-start) • [Features](#key-features) • [Documentation](#documentation)

</div>

Cortex Code is a powerful command-line AI workflow tool forked from [Qwen Code](https://github.com/QwenLM/qwen-code), specifically optimized to use **Snowflake Cortex** for LLM inference. It enhances your development workflow with advanced code understanding, automated tasks, and intelligent assistance powered by Snowflake's enterprise-grade AI platform.

## 💡 Why Cortex Code?

- **Enterprise-Ready**: Leverage Snowflake Cortex's secure, scalable infrastructure
- **Multiple Models**: Access Claude, Mistral, Llama, Reka, and more through a single interface
- **Flexible Authentication**: Support for JWT (key-pair), OAuth, and access tokens
- **Data Governance**: Keep your data secure within your Snowflake environment
- **Cost-Effective**: Pay only for what you use with Snowflake's consumption-based pricing

## Key Features

- **Code Understanding & Editing** - Query and edit large codebases with Snowflake Cortex models
- **Workflow Automation** - Automate operational tasks like handling pull requests and complex rebases
- **Multi-Model Support** - Choose from Claude 3.7 Sonnet, Mistral Large 2, Llama 3.1, and more
- **Secure Authentication** - Multiple authentication methods including JWT and OAuth

## Installation

### Prerequisites

Ensure you have [Node.js version 20](https://nodejs.org/en/download) or higher installed.

```bash
curl -qL https://www.npmjs.com/install.sh | sh
```

### Install from npm

```bash
npm install -g @cortex-code/cortex-code@latest
cortex --version
```

### Install from source

```bash
git clone https://github.com/YOUR_USERNAME/cortex-code.git
cd cortex-code
npm install
npm install -g .
```

## Quick Start

### 1. Configure Snowflake Authentication

Cortex Code supports three authentication methods:

#### Method 1: JWT Authentication (Key Pair) - Recommended

```bash
# Set your Snowflake account and credentials
export SNOWFLAKE_ACCOUNT="myorg-myaccount"
export SNOWFLAKE_USER="myusername"
export SNOWFLAKE_PRIVATE_KEY_PATH="/path/to/private_key.pem"
export SNOWFLAKE_PRIVATE_KEY_PASSPHRASE="your_passphrase"  # Optional

# Optional: Configure warehouse, role, etc.
export SNOWFLAKE_WAREHOUSE="MY_WAREHOUSE"
export SNOWFLAKE_ROLE="MY_ROLE"
export SNOWFLAKE_MODEL="mistral-large2"  # Default model
```

#### Method 2: Access Token (JWT or PAT)

```bash
export SNOWFLAKE_ACCOUNT="myorg-myaccount"
export SNOWFLAKE_ACCESS_TOKEN="your_jwt_or_pat_token"
export SNOWFLAKE_MODEL="claude-3-7-sonnet"
```

#### Method 3: OAuth Token

```bash
export SNOWFLAKE_ACCOUNT="myorg-myaccount"
export SNOWFLAKE_OAUTH_TOKEN="your_oauth_token"
export SNOWFLAKE_MODEL="mistral-large2"
```

### 2. Start Cortex Code

```bash
cortex
```

### 3. Start Coding!

```bash
# Example commands
> Explain this codebase structure
> Help me refactor this function
> Generate unit tests for this module
```

## Available Models

Cortex Code supports all Snowflake Cortex LLM models:

| Model | Context Window | Max Output | Best For |
|-------|----------------|------------|----------|
| **claude-3-7-sonnet** | 200K tokens | 8K tokens | Complex reasoning, code generation |
| **claude-3.5-sonnet** | 200K tokens | 8K tokens | Balanced performance |
| **claude-3.5-haiku** | 200K tokens | 8K tokens | Fast responses |
| **mistral-large2** | 128K tokens | 8K tokens | General purpose (default) |
| **llama3.1-70b** | 128K tokens | 4K tokens | Open-source alternative |
| **reka-core** | 128K tokens | 8K tokens | Multilingual support |
| **snowflake-arctic** | 128K tokens | 4K tokens | Snowflake-optimized |
| **jamba-1.5-large** | 256K tokens | 16K tokens | Long context tasks |

## Configuration

### Environment Variables

Create a `.env` file in your project root or set environment variables:

```bash
# Required
SNOWFLAKE_ACCOUNT=myorg-myaccount          # Your Snowflake account identifier

# Authentication (choose one method)
SNOWFLAKE_PRIVATE_KEY_PATH=/path/to/key.pem
SNOWFLAKE_USER=myusername
# OR
SNOWFLAKE_ACCESS_TOKEN=your_token
# OR
SNOWFLAKE_OAUTH_TOKEN=your_oauth_token

# Optional
SNOWFLAKE_WAREHOUSE=MY_WAREHOUSE            # Warehouse to use for queries
SNOWFLAKE_ROLE=MY_ROLE                      # Role for authentication
SNOWFLAKE_DATABASE=MY_DATABASE              # Default database
SNOWFLAKE_SCHEMA=MY_SCHEMA                  # Default schema
SNOWFLAKE_MODEL=mistral-large2              # Default: mistral-large2
```

### Generating Key Pair for JWT Authentication

1. Generate a private key:
```bash
openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out rsa_key.p8 -nocrypt
```

2. Generate public key:
```bash
openssl rsa -in rsa_key.p8 -pubout -out rsa_key.pub
```

3. Add the public key to your Snowflake user:
```sql
ALTER USER myusername SET RSA_PUBLIC_KEY='MIIBIjANBg...';
```

4. Configure Cortex Code:
```bash
export SNOWFLAKE_PRIVATE_KEY_PATH="/path/to/rsa_key.p8"
export SNOWFLAKE_USER="myusername"
export SNOWFLAKE_ACCOUNT="myorg-myaccount"
```

## Session Management

Control your token usage with configurable session limits:

### Configure Session Token Limit

Create or edit `.cortex/settings.json` in your home directory:

```json
{
  "sessionTokenLimit": 32000
}
```

### Session Commands

- **`/compress`** - Compress conversation history to continue within token limits
- **`/clear`** - Clear all conversation history and start fresh
- **`/stats`** - Check current token usage and limits

## Usage Examples

### 🔍 Explore Codebases

```bash
cd your-project/
cortex

# Architecture analysis
> Describe the main pieces of this system's architecture
> What are the key dependencies and how do they interact?
> Find all API endpoints and their authentication methods
```

### 💻 Code Development

```bash
# Refactoring
> Refactor this function to improve readability and performance
> Convert this class to use dependency injection

# Code generation
> Create a REST API endpoint for user management
> Generate unit tests for the authentication module
```

### 🔄 Automate Workflows

```bash
# Git automation
> Analyze git commits from the last 7 days
> Create a changelog from recent commits

# File operations
> Rename all test files to follow the *.test.ts pattern
> Find and remove all console.log statements
```

## Commands & Shortcuts

### Session Commands

- `/help` - Display available commands
- `/clear` - Clear conversation history
- `/compress` - Compress history to save tokens
- `/stats` - Show current session information
- `/exit` or `/quit` - Exit Cortex Code

### Keyboard Shortcuts

- `Ctrl+C` - Cancel current operation
- `Ctrl+D` - Exit (on empty line)
- `Up/Down` - Navigate command history

## Architecture

Cortex Code is built on a modular architecture:

- **CLI Package** (`packages/cli`) - User-facing interface
- **Core Package** (`packages/core`) - Backend logic and tool orchestration
- **Snowflake Module** (`packages/core/src/snowflake`) - Snowflake Cortex integration
  - Authentication (JWT, OAuth, PAT)
  - Token management
  - Provider implementation

For detailed architecture documentation, see [CLAUDE.md](./CLAUDE.md).

## Development

### Build from Source

```bash
# Install dependencies
npm install

# Build the project
npm run build

# Run from source
npm start
```

### Testing

```bash
# Unit tests
npm run test

# Integration tests
npm run test:e2e

# Linting
npm run lint
npm run lint:fix

# Type checking
npm run typecheck
```

## Troubleshooting

### Authentication Errors

**Issue**: `Failed to initialize Snowflake Cortex: No valid authentication method`

**Solution**: Ensure you have set at least one authentication method:
- JWT: Set `SNOWFLAKE_PRIVATE_KEY_PATH` and `SNOWFLAKE_USER`
- Access Token: Set `SNOWFLAKE_ACCESS_TOKEN`
- OAuth: Set `SNOWFLAKE_OAUTH_TOKEN`

### Connection Errors

**Issue**: Connection timeout or "account not found"

**Solution**: Verify your `SNOWFLAKE_ACCOUNT` identifier format:
- Correct: `myorg-myaccount` or `xy12345.us-east-1`
- The account identifier can be found in your Snowflake URL

### Model Not Found

**Issue**: Model name not recognized

**Solution**: Use the exact model names as listed in [Available Models](#available-models). Model names are case-sensitive.

## Security Best Practices

1. **Never commit credentials**: Add `.env` to your `.gitignore`
2. **Use encrypted keys**: Protect your private keys with passphrases
3. **Rotate tokens regularly**: Refresh OAuth and access tokens periodically
4. **Limit permissions**: Use Snowflake roles with minimal required permissions
5. **Store keys securely**: Use secure key management systems in production

## Contributing

We welcome contributions! Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.

## License

[Apache-2.0](./LICENSE)

## Acknowledgments

This project is forked from [Qwen Code](https://github.com/QwenLM/qwen-code), which is based on [Google Gemini CLI](https://github.com/google-gemini/gemini-cli). We acknowledge and appreciate the excellent work of both teams.

## Links

- [Snowflake Cortex Documentation](https://docs.snowflake.com/en/user-guide/snowflake-cortex)
- [Snowflake Cortex REST API](https://docs.snowflake.com/en/user-guide/snowflake-cortex/cortex-rest-api)
- [Issue Tracker](https://github.com/YOUR_USERNAME/cortex-code/issues)
