# @majkapp/majk-chat-cli

A powerful command-line interface for interacting with multiple LLM providers. Features interactive chat mode, tool execution, credential management, and rich command-line options.

## Features

- 💬 **Interactive Chat Mode**: Real-time conversation with LLMs
- 🛠️ **Tool Execution**: Execute bash commands and file operations with permission controls
- 🔑 **Smart Credential Management**: Auto-detect credentials from multiple sources
- 📁 **File I/O**: Read messages from files, save conversations
- 🎨 **Rich CLI**: Colored output, progress indicators, intuitive commands
- 🔄 **Multi-Provider**: Switch between providers on the fly
- 💾 **Session Management**: Persistent conversation storage and continuation
- 📂 **Directory-based Organization**: Sessions organized by working directory
- 🎯 **Privacy-First**: Optional session tracking with explicit user control
- ⚙️ **Configurable**: YAML/JSON configuration files

## Installation

### Option 1: Global Installation via npm

Install globally to use the `majk-chat` command anywhere:

```bash
npm install -g @majkapp/majk-chat-cli
```

After installation, you can use `majk-chat` from any directory:

```bash
majk-chat --help
majk-chat chat -M "Hello!" --provider openai
```

### Option 2: Standalone Executable (Zero Dependencies)

Download or build the standalone version that works without npm installation:

```bash
# Option A: Download from releases
curl -L https://github.com/your-org/majk-chat/releases/latest/download/majk-chat-standalone.cjs -o majk-chat-standalone.cjs
chmod +x majk-chat-standalone.cjs

# Option B: Build from source
git clone https://github.com/your-org/majk-chat
cd majk-chat
npm run build:all
cp majk-chat-cli/dist/majk-chat-standalone.cjs /your/path/

# Use directly without npm
./majk-chat-standalone.cjs --help
./majk-chat-standalone.cjs chat -M "Hello!" --provider openai
```

**Benefits of standalone version:**
- ✅ No Node.js dependencies to manage
- ✅ Single file deployment (2.9MB bundle)
- ✅ Identical functionality to npm version
- ✅ Perfect for CI/CD, containers, or restricted environments

### Option 3: Local Development Installation

```bash
npm install -g @majkapp/majk-chat-cli
```

### Option 4: Local Installation

```bash
npm install @majkapp/majk-chat-cli
```

## Quick Start

> **Note**: All examples below use the `majk-chat` command. If using the standalone version, replace `majk-chat` with `./majk-chat-standalone.cjs` in all examples.

### Basic Chat

```bash
# Send a simple message (uses default profile)
majk-chat chat -M "Hello, how are you?"

# Use a specific provider with work profile
majk-chat chat -p anthropic --profile work -M "Explain quantum computing"

# Use a specific model with personal profile
majk-chat chat -m gpt-4 --profile personal -M "Write a haiku"
```

### Profile Setup (First Time)

```bash
# Set up your API keys with profiles
majk-chat set-key --openai sk-your-openai-key --profile default
majk-chat set-key --anthropic sk-ant-your-anthropic-key --profile work

# Test your setup
majk-chat test-all-profiles

# Start chatting
majk-chat chat --profile work -M "Hello, I'm using my work profile!"
```

### Interactive Mode

```bash
# Start interactive chat with default profile
majk-chat interactive

# With specific profile and provider
majk-chat interactive --profile work -p anthropic -m claude-3-sonnet

# With tools enabled using production profile
majk-chat interactive --tools --auto-execute --profile production
```

### Session Management

```bash
# Create a session with title and profile
majk-chat chat --save-session --session-title "Web Development" --profile work -M "Help me build a React app"

# Continue the most recent session (inherits profile)
majk-chat chat --continue -M "Add user authentication"

# List all sessions in current directory
majk-chat chat --list-sessions

# Continue a specific session by UUID
majk-chat chat --session 550e8400-e29b-41d4-a716-446655440000 -M "Let's add more features"

# Delete a session
majk-chat chat --delete-session 550e8400-e29b-41d4-a716-446655440000
```

## Commands

### `chat` - Send a single message

```bash
majk-chat chat [options]
```

#### Options

- `-p, --provider <provider>` - Provider to use (openai, anthropic, azure-openai, bedrock)
- `-m, --model <model>` - Model to use
- `-M, --message <message>` - Message to send
- `-f, --file <file>` - Read message from file
- `-s, --system <system>` - System message
- `-S, --system-file <file>` - Read system message from file
- `-t, --temperature <temp>` - Temperature (0-2)
- `--max-tokens <tokens>` - Maximum tokens
- `-j, --json` - Output JSON response
- `--tools` - Enable tool execution
- `--enable-core-tools` - Enable majk-chat-basic-tools (bash, ls, read, etc.)
- `--disable-tools` - Disable all tools (read-only tools including document analysis are enabled by default)
- `--tool-result-limit <limit>` - Truncate tool results over this character limit (default: 8000)
- `--max-steps <steps>` - Maximum tool execution steps
- `-c, --config <file>` - Configuration file
- `--profile <name>` - Use specific profile for credentials (default: "default")
- `--api-key <key>` - API key (overrides environment)
- `--api-key-file <file>` - Read API key from file
- `--bedrock-api-key <key>` - AWS Bedrock API key (bearer token)

#### Session Management Options

- `--save-session` - Save conversation to a persistent session
- `--continue` - Continue the most recent session in current directory
- `--session <uuid>` - Continue a specific session by UUID
- `--session-title <title>` - Set title for new session
- `--list-sessions` - List all sessions for current directory
- `--delete-session <uuid>` - Delete a specific session by UUID

#### Examples

```bash
# Simple message with default profile
majk-chat chat -M "What is the capital of France?"

# Use specific profile
majk-chat chat --profile work -M "Hello from work environment"

# With system message and profile
majk-chat chat -s "You are a helpful assistant" --profile personal -M "Hello"

# Read from file with specific profile
majk-chat chat -f prompt.txt --profile production

# With specific model and temperature using work profile  
majk-chat chat -m claude-3-sonnet -t 0.7 --profile work -M "Write a creative story"

# Enable tools with profile
majk-chat chat --tools --profile default -M "Create a file called test.txt with 'Hello World' in it"

# JSON output with profile
majk-chat chat -j --profile work -M "Hello" > response.json

# Use Bedrock with API key (bearer token)
majk-chat chat --provider bedrock --bedrock-api-key "bedrock-api-key-..." -M "Hello"

# Use Bedrock with environment variable
export AWS_BEARER_TOKEN_BEDROCK="bedrock-api-key-..."
majk-chat chat --provider bedrock -M "Explain quantum computing"

# Create a session with profile
majk-chat chat --save-session --session-title "Code Review" --profile work -M "Review this Python function"

# Continue a session (inherits profile from saved session)
majk-chat chat --continue -M "Fix the performance issues"

# List sessions
majk-chat chat --list-sessions

# Load specific session
majk-chat chat --session 550e8400-e29b-41d4-a716-446655440000 -M "Continue our discussion"
```

### `interactive` - Interactive chat mode

```bash
majk-chat interactive [options]
```

#### Options

- `-p, --provider <provider>` - Provider to use
- `-m, --model <model>` - Model to use
- `-s, --system <system>` - System message
- `-S, --system-file <file>` - Read system message from file
- `--tools` - Enable tool execution
- `--enable-core-tools` - Enable majk-chat-basic-tools (bash, ls, read, etc.)
- `--disable-tools` - Disable all tools (read-only tools including document analysis are enabled by default)
- `--tool-result-limit <limit>` - Truncate tool results over this character limit (default: 8000)
- `--auto-execute` - Auto-execute tools without confirmation
- `-c, --config <file>` - Configuration file
- `--profile <name>` - Use specific profile for credentials (default: "default")

#### Interactive Commands

Once in interactive mode, you can use these commands:

- `/help` - Show help message
- `/exit`, `/quit` - Exit interactive mode
- `/clear` - Clear conversation history
- `/history` - Show conversation history
- `/save <file>` - Save conversation to file
- `/load <file>` - Load conversation from file
- `/model <name>` - Set or show current model
- `/provider <name>` - Set or show current provider
- `/system <msg>` - Set or show system message
- `/tools` - Toggle tool execution
- `/auto` - Toggle auto-execute for tools
- `/multiline` - Enter multiline input (end with 'END')

#### Examples

```bash
# Start interactive mode with default profile
majk-chat interactive

# With specific profile and provider
majk-chat interactive --profile work -p anthropic -m claude-3-sonnet

# With tools and specific profile
majk-chat interactive --tools --profile production

You> /help
[Shows available commands]

You> Hello, how are you?
Assistant: I'm doing well, thank you! How can I help you today?

You> /model gpt-4
✓ Model set to: gpt-4

You> /save conversation.json
✓ Conversation saved to conversation.json

You> /multiline
Enter multiline input. Type END on a new line to finish:
... This is a
... multiline
... message
... END

You> /exit
Goodbye! 👋
```

### `models` - List available models

```bash
majk-chat models [options]
```

#### Options

- `-p, --provider <provider>` - Filter by provider
- `-c, --config <file>` - Configuration file
- `--profile <name>` - Use specific profile for credentials

#### Examples

```bash
# List all models using default profile
majk-chat models

# List models for specific provider using work profile
majk-chat models -p anthropic --profile work

# List models for specific profile
majk-chat models --profile production
```

### `config` - Configure providers and credentials

```bash
majk-chat config [options]
```

#### Options

- `--init` - Initialize configuration
- `--set <key=value>` - Set configuration value
- `--get <key>` - Get configuration value
- `--list` - List configuration

#### Examples

```bash
# Initialize configuration
majk-chat config --init

# Set a value
majk-chat config --set providers.openai.apiKey=sk-...

# Get a value
majk-chat config --get providers.openai.apiKey

# List all configuration
majk-chat config --list
```

### Profile Configuration Commands

#### `configure-provider` - Interactive provider setup

```bash
majk-chat configure-provider <provider> [options]
```

**Arguments:**
- `<provider>` - Provider to configure (openai, anthropic, azure-openai, bedrock)

**Options:**
- `--profile <name>` - Profile name (default: "default")
- `--skip-validation` - Skip API key validation

**Examples:**
```bash
# Interactive OpenAI setup with validation
majk-chat configure-provider openai

# Set up Anthropic for work profile
majk-chat configure-provider anthropic --profile work

# Set up Azure OpenAI without validation
majk-chat configure-provider azure-openai --profile production --skip-validation
```

#### `set-key` - Direct credential configuration

```bash
majk-chat set-key [options]
```

**Options:**
- `--openai <key>` - OpenAI API key
- `--anthropic <key>` - Anthropic API key  
- `--azure-openai <key> <endpoint> <deployment>` - Azure OpenAI credentials
- `--bedrock <accessKey> <secretKey> [region]` - AWS Bedrock traditional credentials
- `--profile <name>` - Profile to store configuration in (default: "default")
- `--skip-validation` - Skip API key validation

**Examples:**
```bash
# Set OpenAI key for default profile
majk-chat set-key --openai sk-your-key

# Set Anthropic key for work profile
majk-chat set-key --anthropic sk-ant-key --profile work

# Set Azure OpenAI (all parameters required)
majk-chat set-key --azure-openai key https://endpoint.com deployment --profile prod

# Set Bedrock with region
majk-chat set-key --bedrock access-key secret-key us-west-2 --profile aws
```

#### `list-profiles` - Show configured profiles

```bash
majk-chat list-profiles
```

**Example output:**
```
Configured profiles:
  default (openai, anthropic)
  work (anthropic, azure-openai)  
  aws-prod (bedrock)
```

#### `delete-profile` - Remove a profile

```bash
majk-chat delete-profile <name>
```

**Examples:**
```bash
majk-chat delete-profile old-work-profile
```

#### Profile Testing Commands

##### `test-profile` - Test all providers in a profile
```bash
majk-chat test-profile <name>
```

##### `test-all-profiles` - Test all profiles
```bash
majk-chat test-all-profiles
```

##### `test-provider` - Test specific provider in profile
```bash
majk-chat test-provider <provider> [--profile <name>]
```

**Examples:**
```bash
# Test work profile
majk-chat test-profile work
# Output:
# Testing profile: work
#   ✓ anthropic (model: claude-3-5-sonnet-20241022)  
#   ✗ azure-openai - Invalid endpoint

# Test all profiles
majk-chat test-all-profiles

# Test specific provider
majk-chat test-provider openai --profile default
```

## Core Tools Usage

The `--enable-core-tools` flag provides access to a comprehensive set of tools for file system operations, process management, and utility functions:

## Default Tools Usage

**Read-only tools including document analysis are now enabled by default!** This provides safe access to file operations and comprehensive document parsing without risk of modification. This is ideal for code analysis, research, and document processing scenarios.

### Document Analysis (Enabled by Default)
- **PDF parsing**: Extract text and metadata from PDF files
- **Excel analysis**: Parse XLSX/XLS files with data extraction and analysis  
- **CSV processing**: Intelligent parsing with type detection and column analysis
- **Text analysis**: Process various text-based document formats
- **Universal analyzer**: Automatically detects file types and applies appropriate parsers

### Available Read-Only Tools

- **ls**: List files and directories with filtering
- **read**: Read file contents with configurable limits and offsets  
- **glob**: Fast file pattern matching using glob patterns
- **grep**: Search for text patterns in files using regular expressions
- **pwd**: Print working directory
- **cd**: Change directory for navigation
- **bash_output**: Monitor and retrieve output from background processes
- **todo_write**: Manage structured task lists for session tracking
- **web_fetch**: Fetch content from URLs (read-only web access)
- **read_tool_result**: Read back large tool results that were truncated

### Safety Features

The read-only tools flag specifically excludes:
- ❌ **bash**: Cannot execute arbitrary commands
- ❌ **edit/write**: Cannot modify or create files
- ❌ **kill_bash**: Cannot terminate processes
- ❌ **multi_edit**: Cannot make file modifications

This makes it perfect for:
- 🔍 Exploring unfamiliar codebases safely
- 📚 Learning and research without risk
- 🔒 Allowing LLMs to analyze code in production environments
- 📖 Documentation generation and code review

### Usage Examples (Tools Enabled by Default)

```bash
# Document analysis - works out of the box!
majk-chat chat -M "Analyze this Excel file: sales_data.xlsx"

# PDF analysis - no flags needed
majk-chat chat -M "Summarize the key points from report.pdf"

# Cross-document analysis
majk-chat chat -M "Compare the revenue projections in budget.xlsx with the targets in contract.pdf"

# Safely explore a codebase
majk-chat chat -M "Analyze the architecture of this project"

# Research and understand code patterns
majk-chat chat -M "Find all API endpoints in this codebase"

# Generate documentation safely
majk-chat chat -M "Document all the functions in the utils directory"

# Disable tools if needed
majk-chat chat -M "Just chat without file access" --disable-tools
```

### Tool Access Levels

| Feature | Default (Read-Only + Document Analysis) | `--enable-core-tools` | `--disable-tools` |
|---------|----------------------------------------|----------------------|-------------------|
| Read files | ✅ | ✅ | ❌ |
| Document analysis (PDF, Excel, CSV) | ✅ | ✅ | ❌ |
| Search/grep | ✅ | ✅ | ❌ |
| List directories | ✅ | ✅ | ❌ |
| Web fetch | ✅ | ✅ | ❌ |
| Execute commands | ❌ | ✅ | ❌ |
| Edit files | ❌ | ✅ | ❌ |
| Create files | ❌ | ✅ | ❌ |
| Delete files | ❌ | ✅ | ❌ |
| **Best for** | **Document analysis, code review, research** | **Development, automation** | **Simple chat only** |

## Core Tools Usage (Full Access)

The `--enable-core-tools` flag provides access to a comprehensive set of tools for file system operations, process management, and utility functions:

### Available Core Tools

- **bash**: Execute bash commands with optional background execution
- **kill_bash**: Terminate background bash processes
- **bash_output**: Monitor and retrieve output from background processes
- **ls**: List files and directories with filtering
- **read**: Read file contents with configurable limits and offsets
- **glob**: Fast file pattern matching using glob patterns
- **grep**: Search for text patterns in files using regular expressions
- **edit**: Perform exact string replacements in files
- **multi_edit**: Make multiple edits to a single file atomically
- **write**: Write content to files with encoding support
- **web_fetch**: Fetch content from URLs using HTTP/HTTPS
- **todo_write**: Manage structured task lists for session tracking
- **read_tool_result**: Read back large tool results that were truncated

### Basic Usage

```bash
# Enable core tools with basic usage (uses default profile)
majk-chat chat -M "List all JavaScript files in the src directory" --enable-core-tools

# Enable with custom result limit using work profile
majk-chat chat -M "Show me the contents of package.json" --enable-core-tools --tool-result-limit 4000 --profile work

# Filter specific tools (only allow file operations) with production profile
majk-chat chat -M "Read and analyze config files" --enable-core-tools --allowed-tools "ls,read,glob,grep" --profile production

# Exclude potentially dangerous tools using personal profile
majk-chat chat -M "Analyze the codebase" --enable-core-tools --disallowed-tools "bash,kill_bash,web_fetch" --profile personal
```

### 🔍 Dry Run Mode

Preview and approve tool operations before execution for safe testing and verification:

```bash
# Preview mode - see what would happen without executing
majk-chat chat --dry-run --enable-core-tools -M "Refactor this codebase and add tests"

# Interactive review mode - approve/reject each operation
majk-chat chat --dry-run-review --enable-core-tools -M "Set up a new React project"
```

#### How Dry Run Works

1. **Planning Phase**: All tool operations are captured and analyzed instead of executed
2. **Risk Assessment**: Each operation is classified as low/medium/high risk  
3. **Preview Generation**: Shows file diffs, command effects, and safety warnings
4. **User Review**: Interactive approval/rejection of individual operations
5. **Selective Execution**: Only approved operations are actually executed

#### Dry Run Examples

```bash
# Basic dry run - shows planned operations
majk-chat chat --dry-run --enable-core-tools -M "Write a hello world script and run it"

# Output:
# 🔍 Dry run mode enabled
# 📋 Planned 2 operations:
#   1. [LOW] Write to file: hello.py (67 characters)
#   2. [MEDIUM] Execute bash command: python hello.py
# 
# Use --dry-run-review to interactively review and execute operations.

# Interactive review mode
majk-chat chat --dry-run-review --enable-core-tools -M "Update package.json and install dependencies"

# Interactive flow:
# 🔍 Reviewing 2 planned operations
# 
# 📋 Operation 1/2
# ──────────────────────────────────────────────────
# Tool: edit
# Risk: LOW
# Category: filesystem
# Description: Replace first occurrence of "version": "1.0.0" with "version": "1.0.1" in package.json
# 
# Preview:
# File: /path/to/package.json
# - "version": "1.0.0",
# + "version": "1.0.1",
# 
# Options:
#   a - Approve this operation
#   r - Reject this operation
#   s - Skip (decide later)
#   p - Show/hide preview
#   d - Show detailed arguments
# Choice (a/r/s/p/d): a
```

#### Dry Run Safety Features

- **Risk Assessment**: Automatic classification of operations
  - 🟢 **Low Risk**: Simple file reads, basic edits
  - 🟡 **Medium Risk**: Config files, package installs, git operations
  - 🔴 **High Risk**: System files, destructive commands, sudo operations

- **Operation Previews**: 
  - File operations show diffs and content previews
  - Bash commands show potential effects and warnings
  - Network operations show URLs and request details

- **Safety Warnings**: Automatic detection of dangerous patterns
  - `rm -rf` commands
  - `sudo` usage
  - Script downloads (`curl | bash`)
  - Eval/exec operations

#### Dry Run Options

- `--dry-run` - Plan operations without executing (shows summary)
- `--dry-run-review` - Plan operations with interactive review and execution

### Interactive Mode with Core Tools

```bash
# Start interactive session with core tools using default profile
majk-chat interactive --enable-core-tools

# Start with specific profile for development work
majk-chat interactive --enable-core-tools --profile development

# Example conversation:
User: Find all TypeScript files and show me the first 50 lines of the main entry point

# The LLM will use tools like:
# 1. glob --pattern "**/*.ts" 
# 2. read --file-path "./src/index.ts" --limit 2000
```

### Background Process Management

```bash
# Start a long-running task with development profile
majk-chat chat -M "Start a development server in the background and monitor its output" --enable-core-tools --profile development

# The LLM can use:
# 1. bash --command "npm run dev" --run-in-background
# 2. bash_output --process-id "bg_xxx" --list-all
# 3. kill_bash --process-id "bg_xxx" (if needed)
```

### Tool Result Management

When tool results exceed the `--tool-result-limit` (default: 8000 characters):

1. **Automatic Truncation**: Large results are automatically truncated with preview + tail
2. **Auto-Registration**: `read_tool_result` tool is automatically registered on first truncation
3. **Full Access**: Complete results remain accessible through unique IDs

```bash
# Example with large output
majk-chat chat -M "Find all log files and show their contents" --enable-core-tools --tool-result-limit 2000

# Output will show:
# "Result truncated (25000 chars). Use read_tool_result with ID: conv_1234567890_abcdef"

# The LLM can then use:
# read_tool_result --result-id "conv_1234567890_abcdef" --offset 0 --limit 5000
```

### Tool Filtering Examples

```bash
# Only filesystem operations
--allowed-tools "ls,read,write,glob,grep,edit"

# Everything except web access
--disallowed-tools "web_fetch"

# Wildcard patterns (bash tools only)
--allowed-tools "bash*"

# Multiple patterns
--allowed-tools "ls,read,bash*" --disallowed-tools "*kill*"
```

### Configuration File Integration

Add core tools to your configuration file:

```yaml
# ~/.majk-chat/config.yaml
tools:
  enableCoreTools: true
  toolResultLimit: 10000
  allowedTools: ["ls", "read", "glob", "grep", "edit", "write"]
  
defaultProvider: "anthropic"
providers:
  anthropic:
    apiKey: "your-key-here"
```

### Best Practices

1. **Start Conservative**: Begin with limited tools and expand as needed
2. **Use Filtering**: Always consider `--allowed-tools` for security
3. **Monitor Resources**: Large results are automatically managed with truncation
4. **Background Tasks**: Use background execution for long-running operations
5. **Result Management**: Let the system auto-register `read_tool_result` when needed

### Security Considerations

- Core tools have full filesystem access when enabled
- `bash` tool can execute any system command
- Use `--allowed-tools` to restrict capabilities
- Consider running in isolated environments for untrusted operations
- Tool results are stored in memory and cleaned up automatically

## Session Management

The CLI includes comprehensive session management for persistent conversations. Sessions allow you to save, continue, and organize your chat conversations across CLI invocations.

### Key Features

- **Privacy-First**: Sessions are only saved when explicitly requested with `--save-session`
- **Directory Organization**: Sessions are automatically organized by working directory
- **UUID-based**: Each session has a unique identifier for easy reference
- **Auto-cleanup**: Old sessions are automatically cleaned up based on age and count limits
- **Smart Titles**: Automatic title generation from first user message

### Session Storage

Sessions are stored in `~/.majk/chat-sessions/` organized by working directory:

```
~/.majk/chat-sessions/
├── users_jules_projects_webapp/
│   ├── 550e8400-e29b-41d4-a716-446655440000.json
│   └── 6ba7b810-9dad-11d1-80b4-00c04fd430c8.json
└── users_jules_documents/
    └── f47ac10b-58cc-4372-a567-0e02b2c3d479.json
```

### Session Commands

#### Creating Sessions

```bash
# Create session with auto-generated title
majk-chat chat --save-session -M "Help me build a React app"

# Create session with custom title
majk-chat chat --save-session --session-title "React Tutorial" -M "Getting started with React"
```

#### Continuing Sessions

```bash
# Continue most recent session in current directory
majk-chat chat --continue -M "Add user authentication"

# Continue specific session by UUID
majk-chat chat --session 550e8400-e29b-41d4-a716-446655440000 -M "Let's add more features"
```

#### Managing Sessions

```bash
# List all sessions in current directory
majk-chat chat --list-sessions

# Sample output:
# Sessions in current directory:
#   550e8400-e29b-41d4-a716-446655440000
#     Title: React Tutorial
#     Created: 12/1/2023 10:30:00 AM
#     Updated: 12/1/2023 11:45:00 AM
#     Messages: 8
#     Last: Let's add error handling to the authentication

# Delete a session
majk-chat chat --delete-session 550e8400-e29b-41d4-a716-446655440000
```

### Session Workflow Examples

#### Project Development Session

```bash
# Start a new project session
cd ~/projects/my-app
majk-chat chat --save-session --session-title "My App Development" -M "Help me design a REST API"

# Continue working on it later
cd ~/projects/my-app
majk-chat chat --continue -M "Add database integration"

# Work on it from another day
cd ~/projects/my-app
majk-chat chat --continue -M "How do I deploy this API?"
```

#### Learning Session

```bash
# Learning session
majk-chat chat --save-session --session-title "Learning Python" -M "Explain Python decorators"

# Continue learning
majk-chat chat --continue -M "Show me practical examples of decorators"
```

### Session Data Format

Each session file contains:

```json
{
  "metadata": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "workingDirectory": "/Users/jules/projects/myapp",
    "createdAt": "2024-01-15T10:30:00.000Z",
    "updatedAt": "2024-01-15T11:45:00.000Z",
    "title": "React Tutorial",
    "provider": "anthropic",
    "model": "claude-3-sonnet-20240229",
    "totalMessages": 8
  },
  "messages": [
    {
      "role": "user",
      "content": "Help me build a React app"
    },
    {
      "role": "assistant",
      "content": "I'll help you build a React app...",
      "tool_calls": [...]
    }
  ]
}
```

### Privacy and Control

- **No tracking by default**: Conversations are not saved unless `--save-session` is used
- **User explicit consent**: Sessions are only created when explicitly requested
- **Local storage only**: All session data stays on your machine
- **Easy cleanup**: Sessions can be deleted individually or cleaned up automatically
- **Profile inheritance**: Sessions remember the profile used when created and continue using it automatically

## Profile Configuration (AWS-Style)

The CLI now supports AWS-style profiles for managing multiple sets of credentials. This is the recommended way to manage API keys.

### Quick Setup

```bash
# Direct configuration (recommended for simple setups)
majk-chat set-key --openai sk-your-openai-key --profile default
majk-chat set-key --anthropic sk-ant-your-anthropic-key --profile work

# Interactive configuration (recommended for complex setups)
majk-chat configure-provider openai --profile personal
majk-chat configure-provider azure-openai --profile production
```

### Profile Management

```bash
# List all configured profiles
majk-chat list-profiles
# Output: 
# Configured profiles:
#   default (openai)
#   work (anthropic)
#   production (azure-openai)

# Test profile configurations
majk-chat test-profile work
majk-chat test-all-profiles
majk-chat test-provider openai --profile default

# Delete a profile
majk-chat delete-profile old-profile
```

### Using Profiles

```bash
# Use specific profile for chat
majk-chat chat --profile work -M "Hello from work environment"

# Interactive mode with profile
majk-chat interactive --profile production

# Models command with profile
majk-chat models --profile work
```

### Provider Configuration Commands

#### Interactive Configuration
```bash
# OpenAI
majk-chat configure-provider openai [--profile name] [--skip-validation]

# Anthropic
majk-chat configure-provider anthropic [--profile name] [--skip-validation]

# Azure OpenAI (prompts for key, endpoint, deployment)
majk-chat configure-provider azure-openai [--profile name] [--skip-validation]

# AWS Bedrock (prompts for API key or access key, secret key, region)
majk-chat configure-provider bedrock [--profile name] [--skip-validation]
```

#### Direct Configuration
```bash
# OpenAI
majk-chat set-key --openai sk-your-key [--profile name] [--skip-validation]

# Anthropic
majk-chat set-key --anthropic sk-ant-your-key [--profile name] [--skip-validation]

# Azure OpenAI (requires all three parameters)
majk-chat set-key --azure-openai your-key https://your-endpoint.com deployment-name [--profile name]

# AWS Bedrock (requires access key and secret key, region optional)
majk-chat set-key --bedrock access-key secret-key us-east-1 [--profile name]
```

### Profile Configuration File

Profiles are stored in `~/.magic/chat/config.json`:

```json
{
  "profiles": {
    "default": {
      "providers": {
        "openai": {
          "apiKey": "sk-...",
          "organizationId": "org-..."
        }
      }
    },
    "work": {
      "providers": {
        "anthropic": {
          "apiKey": "sk-ant-..."
        },
        "azure-openai": {
          "apiKey": "...",
          "endpoint": "https://work.openai.azure.com",
          "deploymentName": "gpt-4-work"
        }
      }
    },
    "aws-prod": {
      "providers": {
        "bedrock": {
          "bearerToken": "bedrock-api-key-...",
          "region": "us-west-2"
        }
      }
    }
  }
}
```

### Credential Sources (Resolution Chain)

The CLI looks for credentials in the following order (highest to lowest precedence):

1. **Command-line options** (`--openai-api-key`, `--api-key`, etc.)
2. **API key files** (`--api-key-file`)
3. **Environment variables**:
   - OpenAI: `OPENAI_API_KEY`, `OPENAI_ORG_ID`
   - Anthropic: `ANTHROPIC_API_KEY`
   - Azure: `AZURE_OPENAI_API_KEY`, `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_DEPLOYMENT`
   - AWS Bedrock: `AWS_BEARER_TOKEN_BEDROCK` (API keys) or `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION` (traditional)
4. **Standard provider locations**:
   - `~/.openai/api_key`
   - `~/.anthropic/api_key`
   - `~/.config/openai/api_key`
   - `~/.config/anthropic/api_key`
5. **Legacy configuration files** (`~/.majk-chat/config.yaml`)
6. **Profile-based configuration** (`~/.magic/chat/config.json`) ⭐ **NEW**

### Validation and Testing

```bash
# Test specific profile
majk-chat test-profile work
# Output:
# Testing profile: work
#   ✓ anthropic (model: claude-3-5-sonnet-20241022)
#   ✗ openai - 401 Incorrect API key

# Test all profiles
majk-chat test-all-profiles

# Test specific provider in profile
majk-chat test-provider openai --profile default
```

## Tool Support

### Bash Tool

Execute bash commands with permission controls:

```bash
# In interactive mode with tools enabled
You> Can you list the files in the current directory?

⚠️  Tool execution request:
Tool: bash
Command: ls -la
Do you want to execute this command? (y/n) y

Executing: ls -la
[Output shows files]
```

### File System Tool

Perform file operations:

```bash
You> Create a file called hello.txt with "Hello World" in it

⚠️  File system operation request:
Operation: write
Path: hello.txt
Content: Hello World
Do you want to write this file/directory? (y/n) y
```

### Auto-execution

Enable auto-execution to skip confirmation prompts:

```bash
majk-chat interactive --tools --auto-execute
```

## Advanced Usage

### Piping and Redirection

```bash
# Pipe input
echo "Explain Docker" | majk-chat chat

# Read from file, output to file
majk-chat chat -f prompt.txt > response.txt

# Use with other tools
cat code.js | majk-chat chat -M "Review this code"
```

### Scripting

```bash
#!/bin/bash

# Use in scripts
response=$(majk-chat chat -M "Generate a random number between 1 and 100" -j)
echo $response | jq '.choices[0].message.content'
```

### Multiple Providers with Profiles

```bash
# Compare responses from different providers using different profiles
majk-chat chat -p openai --profile personal -M "What is love?"
echo "---"
majk-chat chat -p anthropic --profile work -M "What is love?"
echo "---"

# Use different profiles for different environments
majk-chat chat --profile development -M "Test message"
majk-chat chat --profile production -M "Production query"
```

## Environment Variables

- `OPENAI_API_KEY` - OpenAI API key
- `ANTHROPIC_API_KEY` - Anthropic API key
- `AZURE_OPENAI_API_KEY` - Azure OpenAI API key
- `AZURE_OPENAI_ENDPOINT` - Azure OpenAI endpoint
- `AZURE_OPENAI_DEPLOYMENT` - Azure OpenAI deployment name
- `AWS_BEARER_TOKEN_BEDROCK` - AWS Bedrock API key (bearer token)
- `AWS_ACCESS_KEY_ID` - AWS access key (traditional credentials)
- `AWS_SECRET_ACCESS_KEY` - AWS secret key (traditional credentials)
- `AWS_REGION` - AWS region
- `NO_COLOR` - Disable colored output

## Troubleshooting

### No API Key Found

```bash
Error: No valid API credentials found

Solution (recommended - profiles):
1. Set up profile: majk-chat set-key --openai sk-... --profile default
2. Use specific profile: majk-chat chat --profile work -M "Hello"
3. Test your setup: majk-chat test-all-profiles

Traditional solutions:
1. Set environment variable: export OPENAI_API_KEY=sk-...
2. Use --api-key flag: majk-chat chat --api-key sk-...
3. Create config file: majk-chat config --init
```

### Profile Issues

```bash
Error: Profile 'work' not found

Solution:
1. List profiles: majk-chat list-profiles
2. Create profile: majk-chat set-key --anthropic sk-... --profile work
3. Use existing profile: majk-chat chat --profile default

Error: Provider validation failed

Solution:
1. Test configuration: majk-chat test-profile work
2. Reconfigure: majk-chat configure-provider anthropic --profile work
3. Skip validation: majk-chat set-key --anthropic sk-... --skip-validation
```

### Rate Limiting

```bash
Error: Rate limit exceeded

Solution:
1. Wait and retry
2. Use a different provider
3. Reduce request frequency
```

### Tool Execution Denied

```bash
Error: Permission denied for tool

Solution:
1. Review the command carefully
2. Use --auto-execute with caution
3. Ensure you trust the LLM's tool usage
```

## Security

- **Credentials**: Never commit API keys to version control
- **Tool Execution**: Always review commands before execution
- **File Operations**: Be cautious with write/delete operations
- **Auto-execution**: Only use in trusted environments

## License

MIT

## Contributing

Contributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.

## Support

For issues, questions, or suggestions, please file an issue on our GitHub repository.