Skip to content
/ termai Public

termai: Rust terminal AI assistant using OpenAI APIs for intelligent CLI interactions.

License

kyco/termai

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

69 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

TermAI

A powerful, privacy-focused AI assistant for your terminal

TermAI is a versatile command-line AI assistant built in Rust that brings the power of modern large language models directly to your terminal. It supports both OpenAI and Anthropic Claude APIs (now with Claude Opus 4 support) with a focus on privacy, speed, and developer productivity.

Terminal AI Assistant Smart Context License: MIT Rust

โœจ Features

  • ๐ŸŽฏ Interactive Setup Wizard: Get started in under 2 minutes with guided configuration
  • ๐Ÿค– Multi-Provider Support: Works with both OpenAI and Claude APIs
  • ๐Ÿš€ Claude Opus 4: Now powered by Anthropic's most capable model with superior intelligence
  • ๐Ÿง  Smart Context Discovery: Revolutionary intelligent project analysis that automatically selects the most relevant files
  • ๐Ÿ”„ AI-Powered Git Integration: Complete Git workflow automation with intelligent commit messages, code reviews, and conflict resolution
  • ๐Ÿ“ Local Context Understanding: Analyze your code and files for more relevant responses
  • ๐Ÿ’ฌ Session Management: Save and restore conversations for later reference
  • ๐Ÿ”’ Privacy-Focused: Redact sensitive information before sending to APIs
  • โšก Developer-Optimized: Perfect for generating code, explaining concepts, and assisting with daily dev tasks
  • ๐Ÿ–ฅ๏ธ Fully Terminal-Based: No web interfaces or external dependencies needed
  • ๐ŸŽจ Beautiful Interface: Progress indicators, colors, and intuitive subcommands

๐Ÿš€ Quick Start

1. Install TermAI

# Prerequisites: Rust and Cargo (https://www.rust-lang.org/tools/install)
git clone https://github.com/kyco/termai.git
cd termai
cargo install --path .

2. Interactive Setup (โญ Recommended)

Get started instantly with our interactive setup wizard:

termai setup

The setup wizard will guide you through:

  • Provider Selection: Choose Claude, OpenAI, or both
  • API Key Configuration: Enter your keys with live validation
  • Default Provider: Set your preferred AI assistant

โœจ Takes less than 2 minutes and validates your API keys automatically!

3. Start Chatting

# Ask anything!
termai "What is the capital of France?"

# ๐Ÿง  Smart Context Discovery (auto-selects relevant files!)
termai --smart-context "Refactor this to use async/await" .

# Traditional local context
termai "Create a README for this project" .

# Work with specific files
termai "Explain this function" ./src/main.rs

๐Ÿง  Smart Context Discovery

The game-changer for developer productivity. Smart Context Discovery automatically analyzes your project and intelligently selects the most relevant files for your AI assistant, eliminating the need to manually specify files and ensuring optimal token usage.

๐ŸŽฏ Before vs After

โŒ Before (Manual Context):

# You had to guess which files were relevant
termai "Add error handling to the user authentication" \
  ./src/auth/login.rs \
  ./src/auth/middleware.rs \
  ./src/auth/tokens.rs \
  ./src/errors.rs \
  ./src/models/user.rs
# Often missing important files or including irrelevant ones

โœ… After (Smart Context Discovery):

# AI automatically finds ALL relevant files
termai --smart-context "Add error handling to the user authentication" .

# ๐Ÿง  Smart Context automatically discovered:
# โœ“ auth/login.rs (entry point, 95% relevance)  
# โœ“ auth/middleware.rs (dependency, 87% relevance)
# โœ“ auth/tokens.rs (dependency, 82% relevance) 
# โœ“ errors.rs (related functionality, 78% relevance)
# โœ“ models/user.rs (data model, 71% relevance)
# โœ— Excluded: tests, docs, config files (not relevant to request)

โšก Key Benefits

  • ๐ŸŽฏ 90%+ Accuracy: Finds the right files automatically using advanced relevance scoring
  • ๐Ÿš€ 10x Faster: No more manually hunting for relevant files
  • ๐Ÿ’ก Token Optimized: Stays within API limits while including maximum relevant context
  • ๐Ÿ” Multi-Language: Supports Rust, JavaScript/TypeScript, Python, Go, Java, Kotlin projects
  • ๐Ÿ“Š Intelligent Ranking: Prioritizes entry points, recent changes, and dependency relationships
  • โš™๏ธ Configurable: Use .termai.toml to customize patterns and preferences

๐Ÿ› ๏ธ How It Works

Smart Context Discovery uses sophisticated algorithms to analyze your project:

  1. ๐Ÿ” Project Detection: Automatically identifies project type (Rust, JS, Python, etc.)
  2. ๐Ÿ“ File Discovery: Scans project structure and identifies important files
  3. ๐Ÿงฎ Relevance Scoring: Analyzes file importance using multiple factors:
    • Recent Changes: Git history and staging status
    • Entry Points: main.rs, index.js, init.py, etc.
    • Dependencies: Cross-file import/reference analysis
    • File Types: Prioritizes source code over config/docs
    • Query Matching: Keywords in your request vs file content
  4. ๐ŸŽฏ Smart Selection: Optimally selects files within token budget
  5. โš–๏ธ Token Management: Automatically chunks large projects across multiple requests

๐Ÿš€ Usage Examples

Basic Smart Context

# Automatically find relevant files for any task
termai --smart-context "Optimize database queries" .
termai --smart-context "Add logging to error handlers" .
termai --smart-context "Implement user permissions" .

Large Projects (Automatic Chunking)

# Works even with massive codebases - chunks intelligently
termai --smart-context "Review security vulnerabilities" /path/to/large-project

# ๐Ÿ“Š Smart Context found 847 files (12,450 tokens)
# โš–๏ธ Exceeds budget (4,000 tokens) - using chunking strategy
# ๐ŸŽฏ Chunk 1/3: Core auth & security modules (3,892 tokens)
# ๐ŸŽฏ Chunk 2/3: API endpoints & middleware (3,745 tokens)  
# ๐ŸŽฏ Chunk 3/3: Database & validation logic (3,234 tokens)

Custom Configuration

# Create .termai.toml in your project root
cat > .termai.toml << EOF
[context]
max_tokens = 6000
include = ["src/**/*.rs", "tests/**/*.rs"]
exclude = ["target/**", "*.log"]
priority_patterns = ["main.rs", "lib.rs", "mod.rs"]

[project]  
type = "rust"
entry_points = ["src/main.rs", "src/lib.rs"]
EOF

# Smart context will respect your configuration
termai --smart-context "Add comprehensive error handling" .

๐ŸŽ›๏ธ Advanced Features

Context Preview

# See what files would be selected before processing
termai --smart-context --preview "Add authentication" .

# ๐Ÿ“Š Smart Context Selection Summary
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# ๐ŸŽฏ Selected 8 files
# ๐Ÿ“ Estimated tokens: ~3,247
# ๐Ÿ’พ Token budget: 4,000
# 
# ๐Ÿ“ Selected Files (by relevance):
#  1. โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ (89.2%) main.rs
#     ๐Ÿ’ฌ /src/main.rs
#     ๐Ÿท๏ธ EntryPoint, RecentlyModified
#  2. โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ (76.5%) auth.rs  
#     ๐Ÿ’ฌ /src/auth.rs
#     ๐Ÿท๏ธ QueryRelevant, Dependency

Multi-Session for Large Projects

# Automatically manages conversation across multiple sessions
termai --smart-context --session auth_refactor "Modernize authentication system" .

# Creates linked sessions for comprehensive project analysis:
# Session 1: auth_refactor_core (authentication logic)
# Session 2: auth_refactor_api (API endpoints) 
# Session 3: auth_refactor_db (database integration)

Supported Project Types

Language Project Files Entry Points Dependencies
Rust Cargo.toml main.rs, lib.rs mod declarations, use statements
JavaScript/TypeScript package.json index.js/ts, main.js/ts import/require statements
Python pyproject.toml, setup.py main.py, init.py import statements
Go go.mod main.go import declarations
Java pom.xml, build.gradle Main.java, Application.java import statements
Kotlin build.gradle.kts Main.kt, Application.kt import declarations

โš™๏ธ Configuration Options

Create a .termai.toml file in your project root:

[context]
max_tokens = 4000              # Token budget per request
include = ["src/**/*.rs"]      # Files to include (glob patterns)  
exclude = ["target/**"]        # Files to exclude (glob patterns)
priority_patterns = ["main.rs"] # High-priority file patterns
enable_cache = true            # Cache analysis results

[project]
type = "rust"                  # Override project type detection
entry_points = ["src/main.rs"] # Override entry point detection

๐Ÿ“‹ Commands Reference

TermAI offers intuitive subcommands for all your AI assistant needs:

๐Ÿš€ Quick Start Commands

# Interactive setup (recommended first step)
termai setup

# Ask a quick question
termai ask "How do I implement binary search in Rust?"

# Start a conversation
termai chat
termai chat "Let's discuss software architecture"

# Smart context analysis
termai chat --smart-context "Refactor this authentication system" .

๐Ÿง  Smart Context Discovery

# Automatic file discovery and analysis
termai ask --smart-context "Add error handling" .
termai chat --smart-context "Review security issues" .

# Preview what files would be selected
termai ask --smart-context --preview-context "Optimize performance" .

# Customize token limits and chunking
termai ask --smart-context --max-context-tokens 6000 "Explain the codebase" .
termai chat --smart-context --chunked-analysis --chunk-strategy hierarchical "Full code review" .

# Target specific context
termai ask --smart-context --context-query "database connections" "Fix connection pooling" .

โš™๏ธ Configuration Management

# Interactive setup wizard
termai setup                           # Complete guided setup
termai setup --auto-accept            # Non-interactive with defaults
termai setup --skip-validation        # Skip API key validation

# View and manage configuration
termai config show                     # Display current settings
termai config env                      # Show environment variables
termai config reset                    # Clear all configuration

# Set API keys and providers
termai config set-claude KEY           # Configure Claude API
termai config set-openai KEY           # Configure OpenAI API  
termai config set-provider claude      # Set default provider

๐Ÿ’ฌ Session Management

# List and manage sessions
termai sessions list                   # Show all sessions
termai sessions list --limit 5 --sort date # Show recent 5 sessions
termai sessions show session_name      # View session details
termai sessions delete session_name    # Remove a session

# Use sessions in conversations
termai chat --session my_project       # Continue specific session
termai ask --session code_review "Explain this function" ./src/lib.rs

๐Ÿ”’ Privacy & Redaction

# Manage redaction patterns
termai redact add "SECRET_KEY"          # Add sensitive text pattern
termai redact add "user_.*@company.com" # Add regex pattern
termai redact list                      # Show all patterns
termai redact remove "SECRET_KEY"       # Remove a pattern
termai redact reset                     # Clear all patterns

๐Ÿ”ง Advanced Features

# Custom context directories
termai ask --directories src,tests,docs "Document this project" .
termai chat --directory src --exclude "*.test.js,node_modules" "Review the code" .

# Provider and model selection
termai ask --provider openai "Generate API documentation" .
termai chat --provider claude --model claude-3-5-sonnet-20241022 "Code review" .

# System prompts and customization
termai ask --system-prompt "You are a Rust expert" "Optimize this code" ./main.rs
termai chat --session rust_tutor --system-prompt "Act as a patient teacher"

๐Ÿš Shell Completion

# Generate completion scripts
termai completion bash                  # Basic Bash completion
termai completion zsh                   # Basic Zsh completion  
termai completion fish                  # Basic Fish completion
termai completion powershell            # PowerShell completion

# Enhanced completions with dynamic features
termai completion enhanced bash         # Bash with session name completion
termai completion enhanced zsh          # Zsh with smart suggestions
termai completion enhanced fish         # Fish with context-aware completion

# Installation examples
termai completion bash > ~/.termai-completion.bash
echo 'source ~/.termai-completion.bash' >> ~/.bashrc

๐Ÿ” Environment Variables

TermAI supports environment variables for flexible configuration:

# API Keys
export OPENAI_API_KEY="your-key"
export CLAUDE_API_KEY="your-key"

# Provider settings  
export TERMAI_PROVIDER="claude"
export TERMAI_MODEL="claude-3-5-sonnet-20241022"

# Context settings
export TERMAI_MAX_CONTEXT_TOKENS="4000"
export TERMAI_SYSTEM_PROMPT="You are a helpful coding assistant"

# View current environment
termai config env

๐Ÿ“– Usage Examples

๐ŸŽฏ Common Workflows

Development Assistant

# Quick coding questions
termai ask "How do I implement a thread pool in Rust?"
termai ask "Best practices for error handling in REST APIs"

# Code analysis with smart context
termai ask --smart-context "Find potential memory leaks" .
termai ask --smart-context "Suggest performance optimizations" .

# Interactive development session
termai chat --session dev_work --smart-context
# Then continue the conversation naturally

Code Review & Documentation

# Review recent changes
git diff | termai ask "Review this code change for potential issues"

# Generate commit messages
git diff --staged | termai ask "Write a clear commit message for these changes"

# Document your code
termai ask --smart-context "Generate comprehensive README documentation" .
termai ask --directory src "Create API documentation for these modules" .

Learning & Exploration

# Understand complex codebases
termai ask --smart-context --preview-context "Explain the architecture" .
termai chat --session learning --smart-context "How does the authentication system work?" .

# Deep dive into specific topics
termai chat --session rust_patterns --system-prompt "You are a Rust expert"

Project Management

# Analyze project health
termai ask --smart-context "Identify technical debt and areas for refactoring" .
termai ask --smart-context "Suggest project structure improvements" .

# Generate project assets
termai ask --smart-context "Create a comprehensive test plan" .
termai ask --directories src,docs "Generate a contributing guide" .

๐Ÿ”„ AI-Powered Git Integration

TermAI revolutionizes Git workflows with intelligent automation that understands your code and context. Say goodbye to repetitive Git tasks and hello to AI-powered development workflows.

โœจ Complete Git Workflow Automation

๐Ÿค– Smart Commit Generation

# AI analyzes your staged changes and generates perfect commit messages
termai commit
> ๐Ÿ“ Analyzing staged changes...
> 
> Suggested commit message:
> feat(auth): add OAuth2 integration with token refresh
> 
> - Add OAuth2Provider trait implementation
> - Implement token refresh mechanism  
> - Add comprehensive error handling
> - Update tests for new auth flow
> 
> [e]dit, [a]ccept, [r]egenerate, [c]ancel?

# Quick auto-commit mode
termai commit --auto

๐Ÿ” Intelligent Code Review

# Get AI-powered code review before committing
termai review
> ๐Ÿ” Reviewing staged changes...
> 
> โš ๏ธ  Security Issues:
> src/auth.rs:42 - Use SecretString instead of String for passwords
> 
> ๐Ÿš€ Performance:
> src/auth.rs:58 - Consider caching OAuth tokens to reduce API calls
> 
> โœ… Positive Findings:
> - Excellent test coverage for new functionality
> - Follows consistent error handling patterns

# Focus on specific areas
termai review --security --performance

๐ŸŒฟ Smart Branch Management

# Analyze your current branch with AI insights
termai branch-summary
> ๐Ÿ“Š Branch: feature/oauth (5 commits ahead of main)
> 
> AI Analysis:
> - No breaking changes detected
> - Well-structured commits with clear progression
> - Good test coverage maintained
> 
> Suggested PR Description:
> ## OAuth2 Integration
> This PR adds comprehensive OAuth2 authentication support...

# Generate PR/MR descriptions automatically
termai branch-summary --pr-description

โš”๏ธ Conflict Resolution Assistant

# AI-powered merge conflict analysis and resolution
termai conflicts detect
> โš”๏ธ  Found 3 merge conflicts in 2 files
> 
> src/auth.rs:
> - Complexity: Medium (structural changes to auth module)
> - Strategy: Manual review recommended (business logic conflict)
> - Confidence: 85% - can suggest resolution approach
> 
> tests/auth_test.rs:
> - Complexity: Low (test assertion updates)  
> - Strategy: Auto-resolution possible
> - Confidence: 95% - safe to auto-resolve

# Interactive conflict resolution
termai conflicts resolve --interactive

๐Ÿ”„ Interactive Rebase Guidance

# AI-assisted interactive rebase with smart suggestions
termai rebase start main --count 5
> ๐Ÿ”„ Planning interactive rebase of last 5 commits
> 
> AI Recommendations:
> โœ… Squash commits #2 and #3 (both fix typos in same function)
> โœ… Reword commit #4 (improve message clarity)
> โš ๏ธ  Keep commit #1 separate (substantial feature addition)
> 
> [a]pply suggestions, [m]anual edit, [c]ancel?

# Continue interrupted rebase with AI guidance
termai rebase continue

๐Ÿท๏ธ Release Management

# AI-powered tag creation with semantic versioning
termai tag create --from-tag v1.2.0
> ๐Ÿท๏ธ  Analyzing changes since v1.2.0...
> 
> Detected Changes:
> - 3 new features (OAuth, rate limiting, caching)
> - 2 bug fixes (auth timeout, memory leak)
> - No breaking changes
> 
> Suggested Version: v1.3.0 (minor)
> 
> Generated Release Notes:
> ## v1.3.0 - Enhanced Authentication & Performance
> 
> ### ๐Ÿš€ New Features
> - OAuth2 integration with multiple providers
> - Advanced rate limiting system
> - Intelligent response caching

๐Ÿช Git Hooks Automation

# Install AI-powered Git hooks for automated quality assurance
termai hooks install-all
> ๐Ÿช Installing TermAI Git hooks...
> โœ… Pre-commit: Code quality analysis
> โœ… Commit-msg: Message validation
> โœ… Pre-push: Final review check
> โœ… Post-commit: Success insights

# Check hooks status
termai hooks status

๐ŸŽฏ Smart Git Commands Reference

Command Purpose AI Features
termai commit Generate commit messages Analyzes diffs, follows conventions, suggests scope
termai review Code review assistance Security scan, performance check, style validation
termai branch-summary Branch analysis Change summary, PR descriptions, impact analysis
termai conflicts Merge conflict help Strategy suggestions, complexity analysis, auto-resolution
termai rebase Interactive rebase guide Commit squashing, message improvements, conflict prediction
termai tag Release management Semantic versioning, release notes, change categorization
termai hooks Git hooks management Quality gates, automation, integration with existing tools
termai stash Stash operations Smart naming, conflict detection, restoration guidance

๐Ÿš€ Workflow Examples

Daily Development Flow

# Make changes
git add .

# AI-powered commit
termai commit
> feat(api): add user profile endpoints with validation

# AI code review
termai review
> โœ… No issues found, ready to push!

# Push with confidence
git push

Feature Branch Workflow

# Create and work on feature branch
git checkout -b feature/user-profiles

# Multiple commits...
git add . && termai commit --auto
git add . && termai commit --auto

# Clean up commits before merging
termai rebase start main --interactive
> Squashed 3 commits into coherent feature story

# Generate PR description
termai branch-summary --pr-description
> ## User Profile Management
> Comprehensive user profile system with validation...

# Create PR with generated description

Release Preparation

# Analyze changes for release
termai tag create
> Suggested version: v2.1.0
> 
> Breaking Changes: None
> New Features: 4
> Bug Fixes: 2

# Create release with AI-generated notes
git tag v2.1.0 -m "$(termai tag release-notes --from v2.0.0)"

๐ŸŽฌ Workflow Demos

See TermAI's Git integration in action:

Commit Generation Demo AI-powered commit message generation with interactive refinement

Code Review Demo Comprehensive code review with security and performance analysis

Branch Analysis Demo Smart branch analysis and PR description generation

Conflict Resolution Demo AI-assisted merge conflict resolution with strategy recommendations

๐ŸŽจ Beautiful Terminal Experience

All Git commands feature:

  • ๐ŸŽจ Rich Colors: Visual distinction for different types of information
  • ๐Ÿ“Š Progress Indicators: Real-time feedback during analysis
  • ๐ŸŽฏ Interactive Prompts: Smart defaults with easy customization
  • ๐Ÿ’ก Contextual Tips: Learning opportunities built into the workflow
  • โšก Fast Performance: Efficient analysis even for large repositories

๐Ÿ”ง Configuration & Customization

Create .termai.toml in your project root:

[git]
# Commit message preferences
commit_template = "conventional"  # conventional, minimal, detailed
auto_stage = false               # Auto-stage files before commit
require_scope = true            # Require scope in commit messages

# Code review settings  
review_depth = "standard"       # quick, standard, thorough
security_focus = true          # Enable security analysis
performance_focus = true       # Enable performance analysis

# Hook configuration
hooks_enabled = ["pre-commit", "commit-msg"]
hook_strictness = "warn"       # warn, error, off

๐ŸŽฏ Session-Based Workflows

# Start focused development sessions
termai chat --session auth_refactor --smart-context "Let's refactor the authentication system" .

# Continue multi-part conversations
termai chat --session auth_refactor  # Resumes previous conversation

# Organize work by project
termai sessions list                  # See all active sessions
termai sessions show auth_refactor    # Review session history
termai sessions delete old_session    # Clean up completed work

๐Ÿ”’ Privacy-First Development

# Set up redaction patterns for your organization
termai redact add "ACME_API_KEY_.*"           # Redact API keys
termai redact add "user_\d+@company\.com"     # Redact user emails  
termai redact add "password.*=.*"             # Redact password assignments

# Verify redaction is working
termai redact list                            # Check active patterns

# Safe analysis of sensitive codebases
termai ask --smart-context "Review security practices" .  # Redaction applied automatically

๐Ÿ—๏ธ Architecture

TermAI is built with a clean architecture focusing on:

  • Repository Pattern: Data access through well-defined interfaces
  • Service Layer: Business logic separated from presentation
  • Modular Design: Support for multiple LLM providers
  • Local Storage: SQLite for configuration and session persistence

๐Ÿค Contributing

Contributions are welcome! Here's how to get started:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit your changes: git commit -m 'Add amazing feature'
  4. Push to the branch: git push origin feature/amazing-feature
  5. Open a Pull Request

Please ensure your code follows the project's coding style and includes appropriate tests.

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ”ฎ Future Plans

  • Stream responses for faster feedback
  • โœ… Enhanced shell completion with dynamic session/model completion
  • Voice input/output support
  • Additional LLM providers (Gemini, Cohere, etc.)
  • Custom fine-tuned models
  • Enhanced smart context with semantic code analysis
  • Team collaboration features for shared context templates
  • Man page generation for offline documentation
  • Command discovery aids with intelligent suggestions

Made with โค๏ธ by kyco

About

termai: Rust terminal AI assistant using OpenAI APIs for intelligent CLI interactions.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •  

Languages