# UniShell

AI-powered natural language command execution with cloud gateway integration.

## Features

- **Natural Language Commands**: Execute system operations using plain English
- **Gateway Integration**: Remote command execution through cloud gateway
- **Desktop Agent Mode**: Run as background agent for remote management
- **Action Registry**: 90+ pre-built actions for system, file, app, and network operations
- **Multi-LLM Support**: Works with OpenAI, Azure OpenAI, and local models
- **Safe Execution**: Built-in policy engine and rollback capabilities

## Installation

```bash
pip install unishell-q
```

## Quick Start

### Local Interactive Mode

```bash
# Basic usage
unishell

# With Azure OpenAI
unishell --model azure/gpt-4o --api_key YOUR_KEY --api_base YOUR_ENDPOINT --api_version 2024-08-01-preview

# With OpenAI
export OPENAI_API_KEY=your-key
unishell --model gpt-4o

# Auto-run mode (skip approval)
unishell -y
```

### Desktop Agent Mode (Gateway Integration)

Run UniShell as a background agent that executes commands from a cloud gateway:

```bash
# Start agent with gateway connection
unishell --model azure/gpt-4o --api_key YOUR_KEY --api_base YOUR_ENDPOINT --api_version 2024-08-01-preview --agent

# Configure gateway on first run
Gateway URL: http://192.168.100.227:8000
Device Token: <your-device-token>

# Agent runs in background, CLI accepts commands
> open notepad.exe
> create folder test in C:\Users\Desktop
```

**How Agent Mode Works:**
1. Agent polls gateway for pending commands
2. Executes commands locally on your desktop
3. Reports results back to gateway
4. Cloud UI shows execution status

### Gateway Configuration

Agent credentials are stored in `~/.unishell/gateway_config.json`:

```json
{
  "gateway_enabled": true,
  "gateway_url": "http://192.168.100.227:8000",
  "device_token": "your-device-token"
}
```

To reconfigure, delete the file and restart with `--agent` flag.

## Usage Examples

### System Operations
```bash
> lock my screen
> shutdown system in 60 seconds
> get system info
> check CPU and RAM usage
```

### File Operations
```bash
> create a file named test.txt in desktop
> copy file.txt to backup folder
> delete old_file.txt
> rename document.txt to report.txt
```

### Application Management
```bash
> open notepad.exe
> install chrome
> force close firefox
> list installed apps
```

### Network Operations
```bash
> ping google.com
> flush DNS cache
> check my IP address
> disconnect wifi
```

## Python API

```python
from unishell import unishell

# Configure LLM
unishell.llm.model = "gpt-4o"
unishell.llm.api_key = "your-key"

# Execute commands
unishell.chat("Create a Python script")

# Use gateway orchestrator
from unishell.core.gateway import ExecutionOrchestrator
from unishell.core.intent import LLMIntentClassifier, LLMParameterExtractor
from unishell.core.action_registry import DynamicActionLoader

loader = DynamicActionLoader()
registry = loader.load_all()

classifier = LLMIntentClassifier(llm_client, model_name="gpt-4o")
extractor = LLMParameterExtractor(llm_client, model_name="gpt-4o")

orchestrator = ExecutionOrchestrator(classifier, extractor, registry)
result = orchestrator.execute("open notepad", dry_run=False)
```

## Architecture

### Local Mode
```
User Input → Intent Classifier → Parameter Extractor → Policy Engine → Executor → Result
```

### Gateway Mode
```
Cloud UI → Gateway (Redis) → Desktop Agent → Local Executor → Gateway → Cloud UI
         ↓                      ↑
    Stores Action          Polls & Reports
```

## Command Line Options

```bash
# Model Configuration
--model, -m          Language model to use
--api_key, -ak       API key for LLM
--api_base, -ab      API base URL
--api_version, -av   API version
--temperature, -t    Model temperature

# Agent Mode
--agent, -ag         Start desktop agent mode
--gateway_url, -gu   Gateway URL for agent
--device_token, -dtoken  Device token for authentication

# Execution Options
--auto_run, -y       Automatically run generated code
--verbose, -v        Print detailed logs
--safe_mode          Enable safety mechanisms (off/ask/auto)

# Other Options
--profile, -p        Load configuration profile
--offline, -o        Disable online features
--version            Show version number
```

## Action Registry

UniShell includes 90+ pre-built actions across categories:

- **Application**: open, install, uninstall, update, force_close, list
- **File**: create, read, write, delete, copy, move, rename, search
- **Folder**: create, delete, list
- **System**: shutdown, restart, sleep, hibernate, lock, info, resources
- **Network**: ping, check_ip, flush_dns, wifi_connect, wifi_disconnect
- **Service**: start, stop, restart, enable, disable
- **Process**: kill, list
- **Monitoring**: cpu_threshold, ram_spike, disk_full, error_logs

Actions are defined in `unishell/core/action_registry/actions/`.

## Gateway Integration

### Desktop Registration

1. Access gateway UI: `http://your-gateway:8000`
2. Login with credentials
3. Register desktop to get device token
4. Use token with `--agent` flag

### Remote Command Execution

1. Submit command through gateway UI
2. Gateway queues action (PENDING)
3. Desktop agent polls and retrieves action
4. Agent executes locally (RUNNING)
5. Agent reports result (COMPLETED/FAILED)
6. UI displays result

### Agent Configuration

First run prompts for configuration:
```bash
🤖 Desktop Agent Configuration
==================================================
Gateway URL: http://192.168.100.227:8000
Device Token: <paste-your-token>
```

Or provide via command line:
```bash
unishell --agent --gateway_url http://gateway:8000 --device_token YOUR_TOKEN
```

## Security

- **Policy Engine**: Validates permissions before execution
- **Dry Run Mode**: Preview actions without executing
- **Path Validation**: Prevents directory traversal attacks
- **Safe Mode**: Optional code scanning and confirmation
- **Device Authentication**: Token-based gateway access

## Troubleshooting

### Agent Not Connecting
```bash
# Check gateway URL is accessible
curl http://192.168.100.227:8000/health

# Verify device token is valid
# Delete config and reconfigure
rm ~/.unishell/gateway_config.json
unishell --agent
```

### Command Execution Fails
```bash
# Run with verbose logging
unishell --agent --verbose

# Check action exists
# View available actions in unishell/core/action_registry/actions/
```

### Application Not Found
```bash
# Use full executable name
> open notepad.exe  # ✓ Correct
> open notepad      # ✗ May fail

# Check app is installed
> list installed apps
```

## Development

```bash
# Clone repository
git clone <repo-url>
cd unishell

# Install in development mode
pip install -e .

# Run tests
pytest tests/

# Add new action
# Create JSON definition in unishell/core/action_registry/actions/
# Implement handler in unishell/core/execution/safe_os_adapter.py
```

## Version

**Current Version**: 0.5.2