R
Author: retoor retoor@molodetz.nl
R is a command-line AI assistant written in C that provides an autonomous agent with full system access through function calling. It interfaces with OpenAI-compatible APIs and operates in an agentic loop, reasoning about tasks, executing tools, and iterating until goals are achieved.
Features
Autonomous Agent Architecture
- ReAct (Reasoning + Acting) pattern implementation
- Automatic tool execution loop with up to 300 iterations
- Intelligent response parsing to detect incomplete work
- Automatic continuation when tasks require multiple steps
- Built-in retry logic for API failures
AI Provider Support
- OpenAI API (default)
- Anthropic Claude
- Ollama (self-hosted)
- Grok
- Any OpenAI-compatible API endpoint
Tool System
The agent has access to 15+ tools exposed via JSON schema descriptions:
| Tool | Description |
|---|---|
linux_terminal_execute |
Execute shell commands with output capture |
linux_terminal_execute_interactive |
Execute interactive commands (vim, htop, etc.) |
read_file |
Read file contents |
write_file |
Write content to files with automatic parent directory creation |
directory_glob |
List directory contents with file metadata |
mkdir |
Create directories recursively |
chdir |
Change working directory |
getpwd |
Get current working directory |
http_fetch |
Fetch URL contents via HTTP GET |
web_search |
Search the web for information |
web_search_news |
Search for news articles |
db_set |
Store key-value pairs in local SQLite database |
db_get |
Retrieve values from database |
db_query |
Execute arbitrary SQL queries |
index_source_directory |
Index source files with contents |
python_execute |
Execute Python code and capture output |
Database
- Local SQLite database at
~/.r.db - Persistent key-value storage
- Full SQL query support
- File version history tracking
REPL Interface
- Readline integration with tab completion
- Persistent command history at
~/.r_history - Markdown syntax highlighting in terminal output
- Session management for separate conversation contexts
REPL Commands
| Command | Description |
|---|---|
!dump |
Show raw message JSON |
!clear |
Clear conversation history |
!session |
Display current session info |
!verbose |
Toggle verbose mode |
!tools |
List available tools |
!models |
Show available models |
!model <name> |
Switch AI model |
exit |
Exit the REPL |
Installation
Dependencies
libcurl json-c readline ncurses sqlite3 gnutls gmp openssl
On Debian/Ubuntu:
apt install libcurl4-openssl-dev libjson-c-dev libreadline-dev libncurses-dev libsqlite3-dev libgnutls28-dev libgmp-dev libssl-dev
Build
make build
The binary is output to bin/r and copied to ./r.
Cross-Compilation
make build_mingw # Windows executable
AppImage
make appimage # Creates portable r-x86_64.AppImage
Configuration
Environment Variables
| Variable | Description | Example |
|---|---|---|
R_KEY |
API key (takes precedence over OPENAI_API_KEY) | sk-... |
OPENAI_API_KEY |
OpenAI API key (fallback) | sk-... |
OPENROUTER_API_KEY |
OpenRouter API key | sk-or-... |
R_BASE_URL |
Custom API base URL (without /v1/...) | https://openrouter.ai/api |
R_MODEL |
AI model name | gpt-4o, x-ai/grok-code-fast-1 |
R_USE_TOOLS |
Enable/disable function calling | true, false, 1, 0 |
R_USE_STRICT |
Enable strict mode for tool schemas | true, false, 1, 0 |
R_SYSTEM_MESSAGE |
Custom system prompt injected at startup | Any text |
R_SESSION |
Default session name for conversation persistence | myproject, $(date) |
Context Files
.rcontext.txt- Project-specific context (current directory)~/.rcontext.txt- Global user context
Bash Integration
Integrate R as a fallback command handler in bash. When a command is not found, R will attempt to interpret it as a natural language query with automatic date-based sessions.
Add to ~/.bashrc:
export R_BASE_URL="https://openrouter.ai/api"
export R_KEY="$OPENROUTER_API_KEY"
export R_MODEL="x-ai/grok-code-fast-1"
export R_SESSION=$(date +%Y-%m-%d)
command_not_found_handle() {
script_path="/path/to/r"
first_argument="$1"
if "$script_path" "$@"; then
echo -e ""
else
echo "bash: $first_argument: command not found"
fi
}
This enables:
- Automatic session per day via
R_SESSION=$(date +%Y-%m-%d) - Natural language commands directly in terminal
- Fallback to standard "command not found" on failure
Why Terminal AI
Having an AI agent directly in your terminal eliminates context switching. Instead of copying error messages to a browser, describing your environment, or explaining file contents, the agent can see and act on everything directly.
Practical Examples
Debug errors instantly
./r "The build failed, check the error and fix it"
# Agent reads error output, identifies the issue, edits the file, rebuilds
Explore unfamiliar codebases
./r "How does authentication work in this project?"
# Agent searches files, reads relevant code, explains the flow
Automate repetitive tasks
./r "Rename all .jpeg files to .jpg and create a backup folder first"
# Agent creates directory, moves files with proper naming
System administration
./r "Check disk usage and find the largest files in /var/log"
# Agent runs du, finds large files, presents a summary
Database operations
./r "Show me all users who signed up last week"
# Agent queries the database, formats results
Web research while coding
./r "What's the correct syntax for a PostgreSQL upsert?"
# Agent searches the web, returns the answer with examples
Code generation
./r "Write a Python script that monitors CPU usage and alerts if above 90%"
# Agent writes the script, saves it, makes it executable
Git workflows
./r "Show what changed since yesterday and summarize the commits"
# Agent runs git log, git diff, provides summary
File operations
./r "Find all TODO comments in this project and list them by file"
# Agent greps through codebase, organizes findings
Data processing
cat data.csv | ./r --stdin "Calculate the average of the third column"
# Agent processes piped data, returns calculation
Multi-step tasks
./r "Set up a new Python virtualenv, install requests and pytest, create a basic test file"
# Agent executes multiple commands in sequence, creates files
Environment inspection
./r "What ports are in use and what processes are using them?"
# Agent runs netstat/lsof, explains the output
The agent maintains conversation context within sessions, so follow-up queries understand previous actions. Combined with the bash integration, any unrecognized command becomes a natural language query to the AI.
Usage
Interactive Mode
./r
Single Query
./r "What files are in the current directory?"
With Piped Input
cat error.log | ./r --stdin "Analyze these errors"
With Context File
./r --context project_docs.txt "Explain this project"
Session Management
./r --session=myproject # Named session
./r -s myproject # Short form
Options
| Flag | Description |
|---|---|
--verbose |
Enable verbose output |
--stdin |
Read prompt from stdin |
--context <file> |
Include file as context |
--py <file> |
Include Python file |
--session <name> |
Use named session |
--nh |
Disable syntax highlighting |
--free |
Use free tier API |
--api |
API mode |
Architecture
Header-Only Design
The codebase uses a header-only architecture where .h files contain both declarations and implementations. All code compiles through includes from main.c.
Core Components
| File | Purpose |
|---|---|
main.c |
Entry point, REPL loop, argument parsing |
agent.h |
Autonomous agent loop with ReAct pattern |
r.h |
Global configuration and environment handling |
auth.h |
API key resolution |
openai.h |
API communication |
chat.h |
JSON prompt construction |
messages.h |
Conversation history management |
tools.h |
Tool definitions and execution dispatcher |
http_curl.h |
libcurl wrapper for HTTP requests |
line.h |
Readline integration |
db_utils.h |
SQLite operations |
browse.h |
Web search functionality |
markdown.h |
Terminal markdown rendering |
utils.h |
Path utilities |
indexer.h |
Source directory indexing |
License
MIT
| include | |
| src | |
| .gitignore | |
| cmd.sh | |
| Dockerfile | |
| Makefile | |
| README.md |