@webdevtoday/grok-cli
Version:
A sophisticated CLI tool for interacting with xAI Grok 4, featuring conversation history, file reference, custom commands, memory system, and genetic development workflows
586 lines (450 loc) ⢠12.7 kB
Markdown
# Grok CLI
A sophisticated CLI tool for interacting with xAI Grok 4, featuring conversation history, file reference, custom commands, and genetic development workflows.
## Features
- š¤ **AI Chat Interface** - Interactive terminal chat with Grok 4
- š **Conversation History** - Persistent chat history with search and continuation
- š§ **Memory System** - Persistent project context with automatic AI enhancement
- š **File Reference System** - Smart file discovery and reference with `@` commands
- š§ **Custom Commands** - User-defined workflows for genetic development
- šŖ **Hook System** - Event-driven automation compatible with Claude Code patterns
- š ļø **Tool Integration** - Support for git, npm, python, docker, tmux, and more
- š **MCP Integration** - Full Model Context Protocol support for external tools
- š **Permission Management** - Configurable tool access control
- šÆ **Multi-Agent Support** - Tmux-based genetic development environments
## Installation
```bash
# Clone the repository
git clone <repository-url>
cd grok-cli
# Install dependencies
npm install
# Build the project
npm run build
# Link for global usage (optional)
npm link
```
## Quick Start
### First Time Setup
```bash
# Initialize Grok CLI (prompts for API key)
grok
# Or provide API key directly
grok --api-key your-xai-api-key
```
### Basic Usage
```bash
# Start interactive chat
grok
# Continue from last conversation
grok --continue
# Resume specific conversation
grok --resume session-id
# Use development mode with OpenAI
grok --dev
# Enable verbose logging
grok --verbose
```
## Core Features
### š Conversation History
Grok CLI automatically saves all conversations and provides powerful management:
```bash
# List recent conversations
/history list
# Search conversations
/history search "debugging"
# Show statistics
/history stats
# Delete conversation
/history delete session-id
# Continue from CLI
/continue
/continue session-id
```
**Storage Location:** `~/.grok-cli/history/`
### š File Reference System
Use `@` commands to reference and explore files:
```bash
# Search for files
@package.json
@src/cli.ts
# Special commands
@recent # Recently modified files
@git # Git tracked files
@ext:ts # Files by extension
# Get help
@
```
### š§ Custom Commands
Create reusable workflows for genetic development:
```bash
# List custom commands
/custom list
# Run a command
/custom run setup-test-env
# Initialize genetic development commands
/init-commands
# Get help
/custom help
```
### šŖ Hook System
Event-driven automation compatible with Claude Code:
```bash
# Test hooks
/hooks
# Configuration in .grok/settings.json
{
"hooks": {
"PreToolUse": [
{
"matcher": ".*",
"hooks": [
{
"type": "command",
"command": "echo 'About to execute tool'"
}
]
}
]
}
}
```
### š ļø Tool Integration
Built-in support for development tools:
- **Git** - Repository management
- **npm/yarn** - Package management
- **Python/uv** - Python environments
- **Docker** - Container management
- **tmux** - Multi-agent sessions
- **MySQL/PostgreSQL** - Database operations
### š§ Memory System
Persistent project context with automatic AI conversation enhancement:
```bash
# Create and manage memory
/memory create # Create GROK.md file
/memory status # Show memory statistics
/memory add "Important note for AI"
# Search and explore
/memory search "API" # Search across all memory
/memory show project # View project memory files
# Quick memory addition
#Remember: Database uses environment variables
```
**Memory Features:**
- Automatic GROK.md discovery (project, local, user levels)
- Import system with `@import` directives
- Automatic context injection into conversations
- Hierarchical memory loading with configurable depth
See [Memory System Guide](./memory-system.md) for complete documentation.
### š MCP Integration
Full Model Context Protocol support for external tool integration:
```bash
# Add MCP servers
/mcp add github "npx @modelcontextprotocol/server-github" "--token=$GITHUB_TOKEN"
/mcp add filesystem "npx @modelcontextprotocol/server-filesystem" "/path/to/dir"
# Manage servers
/mcp list --verbose # List all servers with status
/mcp status github # Show detailed server status
/mcp tools # List all available MCP tools
# Use MCP tools seamlessly
/mcp test github list_repositories '{"owner": "microsoft"}'
```
**Supported MCP Servers:**
- GitHub (repositories, issues, PRs)
- Filesystem (file operations)
- SQLite (database queries)
- Custom servers (Python, Node.js, etc.)
See [MCP Integration Guide](./mcp-integration.md) for complete documentation.
### š Enhanced Permission System
Advanced permission management with interactive prompts, persistence, and audit logging:
```bash
# Permission modes
grok --permission-mode ask # Interactive prompts with detailed info
grok --permission-mode plan # Show planned actions (no execution)
grok --permission-mode auto # Auto-approve all tools
grok --permission-mode full # No restrictions
# Tool allowlists/blocklists
grok --allowed-tools git,npm
grok --disallowed-tools docker
# Permission management commands
/permissions status # Show permission system status
/permissions audit # View security audit log
/permissions rules # Show persistent permission rules
/permissions clear # Clear session decisions
/permissions stats # Show permission statistics
```
**Enhanced Features:**
- **Interactive Prompts** - Detailed tool information, risk assessment, and parameter analysis
- **Persistent Rules** - "Always/Never" choices saved across sessions
- **Security Audit Log** - Complete history of permission decisions
- **Risk Assessment** - Automated security analysis of tools and parameters
- **Parameter Sensitivity** - Detection and redaction of sensitive data
- **Session Management** - Temporary permission caching within sessions
## Configuration
### Global Configuration
Location: `~/.grok/config.json`
```json
{
"model": "grok-4",
"apiKeys": {
"xai": "your-api-key",
"openai": "dev-api-key",
"composio": "composio-key"
},
"permissions": {
"mode": "ask",
"allowedTools": [],
"disallowedTools": []
},
"memory": {
"autoLoad": true,
"maxDepth": 5,
"excludePatterns": ["node_modules/**", ".git/**"]
}
}
```
### Project Configuration
Location: `.grok/settings.json`
```json
{
"hooks": {
"PreToolUse": [],
"PostToolUse": [],
"UserPromptSubmit": []
},
"permissions": {
"mode": "ask",
"allowedTools": [],
"disallowedTools": []
},
"mcp": {
"servers": {}
}
}
```
### Memory Files
Location: `GROK.md` (project root)
```markdown
# Grok CLI Memory
## Project Overview
Describe your project goals and architecture.
## Key Files
- `src/` - Main source code
- `tests/` - Test files
## Development Workflow
Build: npm run build
Test: npm test
## Custom Commands
Document project-specific workflows.
```
## Command Reference
### Slash Commands
| Command | Description |
|---------|-------------|
| `/help` | Show help message |
| `/status` | System status |
| `/config` | Show configuration |
| `/hooks` | Test hooks |
| `/tools` | List available tools |
| `/custom` | Manage custom commands |
| `/init-commands` | Initialize genetic dev commands |
| `/setup` | Project setup |
| `/history` | Conversation history |
| `/continue` | Continue conversation |
| `/memory` | Edit memory files |
| `/mcp` | MCP server management |
| `/permissions` | Permission system management |
### File Reference Commands
| Command | Description |
|---------|-------------|
| `@filename` | Search for files |
| `@path/to/file` | Reference specific file |
| `@recent` | Recently modified files |
| `@git` | Git tracked files |
| `@ext:js` | Files by extension |
### Memory Commands
| Command | Description |
|---------|-------------|
| `#note` | Add to memory |
## Development
### Project Structure
```
grok-cli/
āāā src/
ā āāā cli.ts # Main CLI interface
ā āāā types/ # TypeScript definitions
ā āāā core/ # Core systems
ā ā āāā config.ts # Configuration management
ā ā āāā session.ts # Session handling
ā ā āāā history.ts # Conversation history
ā ā āāā hooks.ts # Hook system
ā ā āāā file-reference.ts # File reference system
ā ā āāā setup.ts # First-time setup
ā āāā tools/ # Tool implementations
ā āāā base.ts # Tool abstraction
ā āāā bash.ts # Command execution
ā āāā read.ts # File reading
ā āāā write.ts # File writing
ā āāā tmux.ts # Multi-agent sessions
ā āāā custom.ts # Custom commands
āāā docs/ # Documentation
āāā .grok/ # Configuration
ā āāā settings.json # Project settings
ā āāā hooks/ # Hook scripts
ā āāā custom-commands-examples.json
āāā GROK.md # Project memory
```
### Building
```bash
npm run build # Compile TypeScript
npm run dev # Development mode
npm run lint # Lint code
npm run test # Run tests
```
### Hook Development
Create hooks in `.grok/hooks/`:
```javascript
// .grok/hooks/my-hook.js
process.stdin.setEncoding('utf8');
let input = '';
process.stdin.on('data', (chunk) => {
input += chunk;
});
process.stdin.on('end', () => {
const data = JSON.parse(input);
// Process hook event
console.log(JSON.stringify({
decision: 'approve',
continue: true
}));
});
```
### Custom Command Development
Add to `.grok/custom-commands.json`:
```json
{
"commands": [
{
"name": "setup-env",
"description": "Setup development environment",
"steps": [
{
"tool": "Bash",
"params": {
"command": "npm install"
}
}
]
}
]
}
```
## Genetic Development
Grok CLI is designed for genetic development workflows:
### Multi-Agent Sessions
```bash
# Create tmux session with multiple agents
/custom run spawn-agents
# Monitor agent activity
tmux ls
# Join specific agent session
tmux attach -t agent-1
```
### Example Genetic Workflow
1. **Planning Agent** - Analyzes requirements
2. **Implementation Agent** - Writes code
3. **Testing Agent** - Runs tests and validation
4. **Review Agent** - Code review and optimization
### Agent Communication
Agents communicate through:
- Shared file system
- tmux session passing
- Hook system events
- Custom command pipelines
## Troubleshooting
### Common Issues
**API Key Not Found**
```bash
/setup api-key
```
**Permission Denied**
```bash
# Check permission mode
/status
# Update permissions
grok --permission-mode auto
```
**Hook Execution Failed**
```bash
# Test hooks
/hooks
# Check hook configuration
/config
```
**File Reference Not Working**
```bash
# Update file cache
@recent
# Check git status
@git
```
### Debug Mode
```bash
grok --debug --verbose
```
### Reset Configuration
```bash
rm -rf ~/.grok-cli
rm -rf .grok
grok # Will prompt for setup
```
## API Reference
### Configuration Types
```typescript
interface GrokConfig {
model: string;
apiKeys: {
xai: string | undefined;
openai: string | undefined;
composio: string | undefined;
};
hooks: HookConfiguration;
permissions: PermissionConfiguration;
mcp: McpConfiguration;
memory: MemoryConfiguration;
}
```
### Hook System
```typescript
interface HookEvent {
sessionId: string;
transcriptPath: string;
cwd: string;
hookEventName: HookEventName;
toolName?: string;
toolInput?: Record<string, unknown>;
toolResponse?: Record<string, unknown>;
prompt?: string;
message?: string;
}
```
### Tool Interface
```typescript
interface BaseTool {
name: string;
description: string;
execute(params: Record<string, unknown>): Promise<ToolResult>;
validatePermissions(permissions: PermissionManager, params: Record<string, unknown>): boolean;
}
```
## Contributing
1. Fork the repository
2. Create feature branch
3. Implement changes with tests
4. Update documentation
5. Submit pull request
## License
[License information]
## Support
- GitHub Issues: [Repository issues]
- Documentation: [docs/]
- Examples: [.grok/custom-commands-examples.json]