New:Microsoft Teams Notifications Are Now Available in Socket.Learn more β†’
Get Started

@phuetz/code-buddy

Package Overview
Dependencies
Maintainers
1
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@phuetz/code-buddy

Open-source multi-provider AI coding agent for the terminal. Supports Grok, Claude, ChatGPT, Gemini, Ollama and LM Studio with 52+ tools, multi-channel messaging, skills system, and OpenClaw-inspired architecture.

Source
npmnpm
Version
0.3.0
Version published
Weekly downloads
270
629.73%
Maintainers
1
Weekly downloads
Β 
Created
Source
Code Buddy

Code Buddy

Your AI-Powered Development Tool & Personal Assistant

npm version License: MIT Node Version TypeScript Ask DeepWiki

Tests Coverage Build


A multi-AI terminal agent that writes code, runs commands, searches the web, talks to you, and manages your projects β€” from your terminal, your phone, or running 24/7 in the background.


Quick Start | Development Tool | Personal Assistant | Channels | Autonomous Agent | Security | CLI Reference | API

What is Code Buddy?

Code Buddy is an open-source multi-provider AI coding agent that runs in your terminal. It supports Grok, Claude, ChatGPT, Gemini, LM Studio, and Ollama via OpenAI-compatible APIs and provider-specific SDKs.

It works as two things at once:

  • A development tool β€” reads files, writes code, runs commands, creates PRs, plans complex tasks, and fixes its own mistakes across 5-50 tool calls per task.
  • A personal assistant β€” talks to you by voice, remembers your preferences, monitors your screen, sends notifications to your phone via Telegram/Discord/Slack, and runs scheduled tasks 24/7 in the background.

Key highlights:

  • 6 AI providers with automatic failover
  • 40 bundled skills (PR workflow, DevOps, creative tools, smart home, media)
  • 11 messaging channels (Terminal, Telegram, Discord, Slack, WhatsApp, Signal, Teams, Matrix, Google Chat, WebChat, HTTP API)
  • Daemon mode for 24/7 background operation
  • Multi-agent orchestration with self-healing
  • Voice conversation with wake word detection
  • OS sandbox with workspace-write mode (read-only / workspace-write / danger-full-access tiers)
  • Docker sandbox for untrusted code execution
  • Knowledge base injection (Knowledge.md files loaded into agent system prompt)
  • Wide Research mode (parallel sub-agents decompose and research topics concurrently)
  • Todo.md attention bias (task list appended to end of every LLM context turn β€” Manus AI pattern)
  • Lessons.md self-improvement loop (PATTERN/RULE/CONTEXT/INSIGHT lessons injected before every turn β€” persists corrections across sessions)
  • Workflow orchestration rules in system prompt (concrete plan triggers, auto-correction protocol, verification contract)
  • Restorable context compression (identifiers preserved, full content recoverable on demand)
  • Pre-compaction memory flush (facts saved to MEMORY.md before context is compacted β€” OpenClaw pattern)
  • Anthropic prompt cache breakpoints (stable/dynamic split β†’ 10Γ— token cost savings)
  • Per-channel streaming policies (Telegram, Discord, Slack, WhatsApp each get their own chunking/format rules)
  • SSRF guard on all outbound fetches (IPv4 + IPv6 bypass vector blocking)
  • Tool prefix naming convention (shell_exec, file_read, browser_search, … β€” Codex-style canonical aliases)

Quick Start

Prerequisites

  • Node.js 18.0.0 or higher
  • ripgrep (recommended for faster search)
  • Docker (required for CodeAct / Open Manus mode)
# macOS
brew install ripgrep

# Ubuntu/Debian
sudo apt-get install ripgrep

# Windows
choco install ripgrep

Install

# npm (recommended)
npm install -g @phuetz/code-buddy

# Or try without installing
npx @phuetz/code-buddy@latest

First Run

# Configure API key (Grok/xAI)
export GROK_API_KEY=your_api_key

# Start interactive mode
buddy

# Or with a specific task
buddy --prompt "analyze the codebase structure"

# Use with local LLM (LM Studio)
buddy --base-url http://localhost:1234/v1 --api-key lm-studio

# Full autonomy mode
YOLO_MODE=true buddy

Headless Mode (CI / Scripting)

# Single prompt, JSON output to stdout (logs go to stderr)
buddy -p "create a hello world Express app" --output-format json > result.json

# Pipe into other tools
buddy -p "explain this code" --output-format json 2>/dev/null | jq '.content'

# Use in CI with full autonomy
buddy -p "run tests and fix failures" \
  --dangerously-skip-permissions \
  --output-format json \
  --max-tool-rounds 30

# Auto-approve all tool executions (no confirmation prompts)
buddy -p "fix lint errors" --auto-approve --output-format text

Headless mode exits cleanly after completion β€” safe for timeout, shell scripts, and CI pipelines.

Session Management

# Continue the most recent session
buddy --continue

# Resume a specific session by ID (supports partial matching)
buddy --resume abc123

# Set a cost limit for the session
buddy --max-price 5.00

Typical Project Workflow

# 1. First-time setup
buddy --setup                # Quick API key setup wizard
buddy onboard                # Full interactive config wizard
buddy doctor                 # Verify environment & dependencies

# 2. Start coding
buddy                        # Launch interactive chat
buddy --vim                  # Launch with Vim keybindings

# 3. Describe what you want in natural language
> "Create a Node.js project with Express and Prisma"
> "Add Google OAuth authentication"
> "Write tests for the auth module"
> "Fix the typecheck errors"
> "Commit everything"

# 4. Advanced modes
buddy --model gemini-2.5-flash  # Switch AI model
buddy --system-prompt architect # Use architect system prompt
buddy --agent my-custom-agent   # Use custom agent from ~/.codebuddy/agents/
buddy speak                     # Voice conversation mode
buddy daemon start              # Run 24/7 in background
buddy server --port 3000        # Expose REST/WebSocket API

Code Buddy autonomously reads files, writes code, runs commands, and fixes errors β€” typically 5-15 tool calls per task (up to 50, or 400 in YOLO mode).

Development Tool

Agentic Coding

Code Buddy operates as an autonomous coding agent. It reads your codebase, makes changes, runs commands, and iterates until the task is done.

Built-in tools:

CategoryTools
File Operationsview_file, create_file, str_replace_editor, edit_file, multi_edit
Searchsearch, codebase_map
Systembash, docker, kubernetes
CodeActrun_script (Python/JS/TS in Docker), plan (Persistent Planner)
Webweb_search, web_fetch, browser
Patchingapply_patch (unified diff with fuzz factor, Codex-inspired)
Planningcreate_todo_list, get_todo_list, update_todo_list
Mediascreenshot, audio, video, ocr, clipboard
Documentspdf, document, archive
Knowledgeknowledge_search, knowledge_add β€” search/add knowledge base entries
Human Inputask_human β€” pause execution for mid-task user clarification (120s timeout)
Self-Extensioncreate_skill β€” write new SKILL.md files at runtime (self-authoring)
Self-Improvementlessons_add, lessons_search, lessons_list β€” persist and recall learned patterns across sessions
Verificationtask_verify β€” run tsc/tests/lint before marking tasks complete (Verification Contract)

RAG-based tool selection filters tools per query to reduce prompt tokens β€” only relevant tools are included in each API call.

Code Intelligence

Web Search (5-Provider Fallback Chain):

PriorityProviderAPI Key RequiredFeatures
1Brave MCPBRAVE_API_KEY + MCP enabledFull MCP integration, richest results
2Brave APIBRAVE_API_KEYCountry, language, freshness filters
3PerplexityPERPLEXITY_API_KEY or OPENROUTER_API_KEYAI-synthesized answers with citations
4SerperSERPER_API_KEYGoogle Search results
5DuckDuckGoNoneFree fallback (no API key needed)

Search parameters: country (ISO 3166), search_lang, ui_lang, freshness (pd/pw/pm/py or date range), provider (force specific).

Context management uses smart multi-stage compaction (remove stale tool results, summarize older messages, aggressive truncation) to keep conversations within token limits across long sessions.

Hybrid search combines keyword + semantic search with configurable weights for memory retrieval.

πŸš€ Open Manus Features (CodeAct)

Code Buddy implements the Open Manus / CodeAct architecture in a structured, phased approach, allowing it to write and execute code (Python, TypeScript, Node.js) in a secure Docker sandbox instead of relying solely on pre-defined tools.

Phase 1: Sandboxed Execution (Hybrid Agent)

  • RunScriptTool: Writes and runs scripts in ephemeral Docker containers (ubuntu:latest, node:22-slim, python:3.11-slim).
  • Browser Automation: Uses Playwright in Docker to scrape websites, interact with SPAs, and take screenshots programmatically.
  • Safety First: Timeout (120s), Memory Limit (1GB), and ephemeral containers prevent runaway processes.

Phase 2: Persistent State & Planning

  • Persistent Workspace: Files created in .codebuddy/workspace persist between script executions, allowing multi-step workflows (e.g., scrape β†’ save CSV β†’ analyze CSV β†’ plot chart).
  • PlanTool: The agent maintains a PLAN.md file in your project root to track complex, multi-step objectives statefully.
  • Structured Loop: The system prompt enforces a strict PLAN β†’ THINK β†’ CODE β†’ OBSERVE β†’ UPDATE cognitive cycle to prevent chaotic behavior.

Phase 3: Wide Research (Parallel Agents)

  • WideResearchOrchestrator: Decomposes a topic into N independent subtopics via LLM, spawns N parallel CodeBuddyAgent workers (default: 5, max: 20), then aggregates results into a single comprehensive report.
  • Progress streaming: Emits real-time events as each worker completes.
  • CLI: buddy research "quantum computing breakthroughs" --workers 8 --output report.md

Phase 4: Context Engineering (Manus AI + OpenClaw patterns)

  • Todo.md Attention Bias β€” The agent maintains a todo.md task list that is automatically appended at the end of the LLM context on every turn. Because transformers attend more strongly to recent tokens, this keeps objectives in focus across long sessions without modifying the system prompt. Use buddy todo add/done/list or the todo_update tool.
  • Restorable Compression β€” When the context window is compressed, file paths and URLs are extracted as identifiers and the original content is stored. The agent can call restore_context("src/agent/types.ts") to retrieve the full content on demand, making compression lossless for structured identifiers.
  • Pre-compaction Memory Flush (NO_REPLY) β€” Before compaction triggers, a silent background LLM turn extracts durable facts and saves them to MEMORY.md. If the model returns the NO_REPLY sentinel with no meaningful content, the output is suppressed entirely (no notification spam).
  • Inline Citations β€” Web search results now include [1] [2] citation markers inline and a Sources block listing all referenced URLs.
  • Lessons.md Self-Improvement Loop β€” After any user correction, the agent calls lessons_add to persist the lesson (category: PATTERN, RULE, CONTEXT, or INSIGHT) to .codebuddy/lessons.md. On every turn, active lessons are injected as a <lessons_context> block BEFORE the todo suffix so learned patterns are always visible. Use buddy lessons add/search/list or the lessons_add/lessons_search tools. The task_verify tool runs the Verification Contract (tsc + tests + lint) before any task completion.

Example Prompts:

> "Go to Google News, scrape the top headlines about AI, save them to a CSV, and then use Python to analyze the sentiment."
> "Write a script to check broken links on my documentation site."
> "Calculate the Fibonacci sequence up to 1000 and plot the growth rate."

🧬 Roots & Comparison

Code Buddy is an evolution of the OpenClaw architecture, modernized for the TypeScript ecosystem and enhanced with Open Manus (CodeAct) autonomy.

FeatureOpenClawCode BuddyOpen Manus
LanguagePythonTypeScript / Node.jsPython
PhilosophyTool-BasedHybrid (Tool + CodeAct)Pure CodeAct
MessagingMulti-channel11+ Channels (Telegram focus)Web Interface
Task StateHeartbeatPersistent PLAN.md + WorkspaceTransient Session
ConcurrencyLane QueueAdvanced Lane Queue + DAGSequential
ExtensibilitySKILL.mdSkills Hub + Plugins + MCPCustom Scripts

Why Code Buddy? It combines the industrial-grade reliability of OpenClaw (concurrency control, security policies, multi-channel messaging) with the infinite flexibility of Open Manus (dynamic script generation and execution).

Manus AI influence: Wide Research (parallel sub-agent research workers), Knowledge Base injection, todo.md attention bias (task list at end of context each turn), and restorable context compression (identifier-based content recovery) are all inspired by Manus AI's context engineering research. The pre-compaction NO_REPLY flush pattern is from OpenClaw's compaction documentation.

Code Safety

Code Buddy validates everything before it touches your files:

FeatureDescription
Generated Code ValidatorPre-write scan for eval, XSS, SQL injection, hardcoded secrets, prototype pollution
Pre-Write Syntax ValidatorBalanced delimiters, template literals, indentation (JS/TS/Python/YAML/HTML/CSS/JSON)
Atomic Rollback (apply-patch)All-or-nothing patch application with full file state backup
Atomic Transactions (multi-edit)Multi-file edits rolled back on first failure
AST Bash Validationtree-sitter-based command parsing with centralized dangerous pattern checks
Bash CheckpointsPre-snapshot of files targeted by destructive commands (rm, mv, truncate)
Diff PreviewShows actual diffs before approval, magnitude-based re-confirmation for large changes
Semantic TruncationError-preserving output truncation (keeps error lines and stack traces)
Security Audit LoggingJSONL audit trail for all code generation security decisions

Task Planning

For complex multi-step requests, Code Buddy decomposes work into a DAG (directed acyclic graph) and executes steps in parallel where possible.

  • TaskPlanner β€” needsPlanning() heuristic detects complex requests, createPlan() produces a TaskGraph
  • Topological sort β€” determines execution order with dependency tracking
  • Parallel execution β€” independent steps run concurrently via dependency waves
  • Architect mode β€” --system-prompt architect enables plan-first coding with per-step checkpoints

CI/CD Integration

FeatureDescription
CI WatcherGitHub Actions / GitLab CI / Jenkins alerts with "Fix it" auto-agent
Webhook TriggersHMAC-SHA256 verified HTTP triggers β€” connect CI, monitoring, or any service
Headless Modebuddy -p "run tests and fix failures" --dangerously-skip-permissions for CI pipelines

Git Workflow

Code Buddy handles the full Git lifecycle through natural language:

> "Create a PR for the auth changes"
> "Review the open PRs"
> "Fix the merge conflicts on feature-branch"
> "Commit everything with a good message"

Telegram enhanced commands for remote Git operations:

CommandDescription
/repoRepository info, recent commits, open PRs
/branch [name]Branch diff stats vs main
/pr [number]List or view PRs with merge/review buttons

Personal Assistant

Voice Conversation

Full hands-free voice interaction with wake word detection:

buddy speak "Hello, I am Code Buddy"         # Synthesize and play speech
buddy speak --voice af_bella "Hello world"    # Use a specific voice
buddy speak --list-voices                     # List available voices
buddy speak --speed 1.5 "Fast speech"         # Adjust speed (0.25-4.0)
buddy speak --format mp3 "Hello"              # Output format (wav, mp3)
buddy speak --url http://host:8000 "Hello"    # Custom AudioReader URL

7 TTS providers: Edge TTS, espeak, macOS say, Piper, OpenAI, ElevenLabs, AudioReader (Kokoro-82M local)

In-chat voice commands:

CommandDescription
/speak <text>Speak text with current TTS provider
/tts on|offEnable/disable TTS
/tts autoAuto-speak all agent responses
/tts provider audioreaderSwitch to AudioReader (Kokoro-82M, local, free)
/tts voice ff_siwisSet voice (e.g., ff_siwis FR, af_bella EN)

Wake word detection via Porcupine (Picovoice) with text-match fallback. Set PICOVOICE_ACCESS_KEY for hardware-accelerated detection, or use the built-in text matcher for free.

Infinite voice conversation: Enable continuousListening + autoSpeak with AudioReader for a hands-free loop: listen β†’ STT β†’ agent β†’ TTS β†’ listen.

Memory System

SubsystemStoragePurpose
Persistent MemoryMarkdown filesProject/user notes
Enhanced MemorySQLite + embeddingsSemantic search
Prospective MemorySQLiteTasks, goals, reminders
ICM (optional)ICM MCP serverPersistent cross-session memory via episodic + semantic dual architecture

Auto-capture detects and stores important information from conversations:

"Remember that..."        β†’ Stored as instruction
"I prefer..."             β†’ Stored as preference
"This project uses..."    β†’ Stored as project fact
"My email is..."          β†’ Stored as contact info
"We decided to..."        β†’ Stored as decision

Memory lifecycle hooks inject relevant memories before execution, capture important info after responses, and summarize conversations at session end. Deduplication via Jaccard similarity (0.95 threshold) prevents duplicates.

Knowledge Base

Domain knowledge injected into the agent system prompt at startup (src/knowledge/knowledge-manager.ts):

  • Sources: Knowledge.md (project root), .codebuddy/knowledge/*.md (project-level), ~/.codebuddy/knowledge/*.md (global)
  • YAML frontmatter: title, tags, scope (restrict to specific agent modes), priority (injection order)
  • Agent tools: knowledge_search (keyword search across all entries), knowledge_add (persist new knowledge to disk)
  • Injection: Loaded entries are wrapped in a <knowledge> block and included in the system prompt automatically.
buddy knowledge list             # List all loaded knowledge entries
buddy knowledge show <title>     # Show a specific entry
buddy knowledge search "TypeScript conventions"
buddy knowledge add              # Interactive: add a new knowledge entry
buddy knowledge remove <title>   # Remove an entry
buddy knowledge context          # Show the full <knowledge> block the agent sees

Skills Library (40 Bundled Skills)

Code Buddy includes 40 built-in SKILL.md files that provide domain-specific knowledge, best practices, and MCP server integration. Skills are loaded contextually when relevant to your project.

CategorySkillDescription
PR Workflowreview-prCode review checklist, inline comments, approval criteria
prepare-prBranch naming, commit cleanup, PR description template
merge-prMerge strategies, conflict resolution, post-merge cleanup
Dev ToolsgithubIssues, releases, Actions workflows, gh CLI
gitlabGitLab API, glab CLI, CI/CD pipelines, merge requests
session-logsExport/search conversation history and session metadata
model-usageToken tracking, cost analysis, provider comparison
tmux-sessionsTerminal multiplexing, pane layouts, session management
healthcheckService monitoring, endpoint checks, alerting
Projectproject-best-practicesProject scaffolding, structure, linting, testing conventions
csharp-avaloniaCross-platform desktop/mobile with C# and Avalonia UI
coding-agentAutonomous multi-step coding with planning and validation
skill-creatorAuthor new SKILL.md files with YAML frontmatter
Creative & 3DblenderPython bpy scripting, CLI rendering, Geometry Nodes
unreal-engineRemote Control API, Python editor scripting, Movie Render Queue
davinci-resolveDaVinciResolveScript Python API, color grading, render queue
ableton-liveOSC protocol, MIDI Remote Scripts, Max for Live
DesignfigmaREST API, Plugin API, design tokens extraction
gimpPython-Fu / Script-Fu scripting, batch image processing
inkscapeExtensions API, CLI export, SVG manipulation
DevOps & Infrakuberneteskubectl, Helm, ArgoCD GitOps
terraform-ansibleTerraform IaC + Ansible configuration management
grafana-prometheusGrafana HTTP API, PromQL, alerting pipelines
jenkins-ciJenkins API, Groovy pipelines, shared libraries
Workflow & Datan8nREST API, webhook triggers, workflow automation
databasesPostgreSQL, MongoDB, Redis CLI and automation
game-enginesUnity C# + Godot GDScript, builds, scene management
UtilitiessummarizeText/file/URL summarization with configurable length
weatherWeather lookups via wttr.in and OpenWeatherMap
Mediaimage-genImage generation via DALL-E, Stable Diffusion, Midjourney
whisper-transcribeAudio/video transcription with OpenAI Whisper
pdf-toolsPDF creation, merging, text extraction, conversion
screenshotScreen capture, annotation, OCR text extraction
video-toolsFFmpeg video editing, conversion, thumbnails, GIFs
gif-searchGIF search via Giphy and Tenor APIs
Communicationemail-toolsEmail send/read via himalaya CLI and SMTP
notionNotion API for pages, databases, search, content blocks
blog-watcherRSS/Atom feed monitoring, web page change detection
Smart HomespotifySpotify playback control via spotify_player and Web API
smart-homePhilips Hue and Home Assistant control

Each skill includes Direct Control (CLI/API/scripting commands), MCP Server Integration (config for .codebuddy/mcp.json), and Common Workflows (step-by-step recipes). Skills are stored in .codebuddy/skills/bundled/ and can be extended with managed or workspace skills via the Skills Registry and Hub.

Self-authoring skills: The agent can extend its own skill set at runtime using the create_skill tool, writing new SKILL.md files to .codebuddy/skills/workspace/. The SkillRegistry hot-reloads them within ~250ms, so newly created skills are immediately available without restarting.

Proactive Notifications

The agent can reach out to you β€” not just respond:

  • Push notifications with priority levels (info, warning, critical)
  • Rate limiting prevents notification spam
  • Quiet hours β€” suppress non-critical notifications during configured periods
  • Multi-channel delivery β€” notifications route to Telegram, Discord, Slack, or any connected channel

Screen Observer

Monitor your screen and environment for events:

  • Periodic screenshots with perceptual diff detection
  • Event triggers β€” file_change, screen_change, time, webhook
  • Trigger registry β€” add/remove triggers dynamically
buddy trigger list             # List all event triggers
buddy trigger add <spec>       # Add a trigger (format: type:condition action:target)
buddy trigger remove <id>      # Remove a trigger

Multi-Channel Messaging

Code Buddy supports 11 messaging channels:

ChannelFeatures
TerminalNative CLI interface (Ink/React)
HTTP APIREST + WebSocket
WebChatBuilt-in HTTP + WebSocket with browser UI
DiscordBot integration, slash commands
TelegramBot API, pro features, scoped auth, CI watcher
SlackBolt framework, events
WhatsAppBaileys (QR pairing, media, reconnect)
Signalsignal-cli REST API (polling, groups)
Google ChatWorkspace API (JWT auth, webhook events)
Microsoft TeamsBot Framework (OAuth2, adaptive cards)
Matrixmatrix-js-sdk (E2EE, threads, media)

Telegram (Deep Dive)

Telegram is the most feature-rich channel, giving you full agent capabilities from your phone.

Setup:

  • Create a bot with @BotFather on Telegram (/newbot)
  • Configure the token:
export TELEGRAM_BOT_TOKEN=123456:ABC-DEF...

Or in .codebuddy/settings.json:

{
  "channels": {
    "telegram": {
      "type": "telegram",
      "token": "123456:ABC-DEF...",
      "adminUsers": ["your_telegram_user_id"],
      "defaultParseMode": "Markdown"
    }
  }
}
  • Start Code Buddy with Telegram:
buddy --channel telegram        # Interactive with Telegram
buddy daemon start              # 24/7 background mode

Deployment modes:

ModeConfigBest for
Polling (default)No extra configDevelopment, behind NAT
Webhook"webhookUrl": "https://your-domain.com/telegram"Production, lower latency

Supported message types: text, images, audio, video, documents, stickers, locations, contacts, inline buttons, reply threads, typing indicators.

What you can do via Telegram:

CategoryCapabilities
Remote CodingCode modifications, bug fixes, refactoring, file analysis, create commits & PRs
Bash ExecutionRun build, test, deploy commands β€” with confirmation for destructive ops
Rich MediaSend images β†’ Gemini Vision analysis, send files (code, logs) β†’ processed by agent
Voice MessagesSend voice notes β†’ STT transcription β†’ agent response
Daemon Mode24/7 background operation (buddy daemon start), cron jobs, proactive alerts
NotificationsBuild failures, test results, heartbeat alerts pushed to your Telegram
InteractiveInline buttons for confirmations, Markdown-formatted responses

Pro features:

FeatureDescription
Scoped AuthorizationTiered permissions: read-only β†’ write-patch β†’ run-tests β†’ deploy
Diff-First ModePreview all code changes before applying β€” Apply / Full Diff / Cancel buttons
Run TrackerStep-by-step timeline of agent runs with cost, duration, artifacts
CI WatcherGitHub Actions / GitLab CI / Jenkins alerts with "Fix it" auto-agent
Secret HandlesMap friendly names to env vars β€” secrets never enter LLM context
Context PinsPin important decisions or facts for the agent to remember

Enhanced commands:

CommandDescription
/repoRepository info, recent commits, open PRs
/branch [name]Branch diff stats vs main
/pr [number]List or view PRs with merge/review buttons
/task <desc>Create an agent task with objective
/runsList recent agent runs with timeline
/run <id>View run details with Re-run/Tests/Rollback buttons
/yolo [minutes]Timed full access (1-60 min, auto-revokes)
/pinsView pinned context

Example workflows:

Fix CI failure:

CI alert arrives β†’ cause analysis β†’ "Fix it" button
β†’ agent creates fix β†’ diff preview β†’ Apply/Cancel
β†’ changes applied β†’ tests re-run

Add feature + tests + PR:

/task "add user search with tests"
β†’ plan-first preview β†’ approve plan
β†’ diff-first preview β†’ apply changes
β†’ agent creates PR β†’ link in chat

DM Pairing (Access Control)

Prevents unauthorized users from consuming API credits:

  • Unknown user messages the bot β†’ receives a 6-character pairing code (expires in 15 min)
  • Bot owner approves via CLI: buddy pairing approve --channel telegram ABC123
  • User is added to the persistent allowlist (~/.codebuddy/credentials/telegram-allowFrom.json)

Security features: rate limiting (5 failed attempts β†’ 1h block), per-channel allowlists, admin bypass.

Pairing CLI commands:

buddy pairing status             # Show pairing system status
buddy pairing list               # List all approved users
buddy pairing pending            # List pending pairing requests
buddy pairing approve <code>     # Approve a pairing request by code
buddy pairing add <id>           # Manually add a user to the allowlist
buddy pairing revoke <id>        # Revoke access for a user

Other Channels

// Discord
const discord = new DiscordChannel({
  token: process.env.DISCORD_TOKEN,
  allowedGuilds: ['guild-id'],
});
await discord.connect();

// WhatsApp (Baileys, QR pairing)
const whatsapp = new WhatsAppChannel({ dataPath: '~/.codebuddy/whatsapp' });
await whatsapp.connect(); // Scan QR code

// Signal (signal-cli REST API)
const signal = new SignalChannel({ apiUrl: 'http://localhost:8080', phoneNumber: '+1234567890' });
await signal.connect();

// Matrix (E2EE, threads)
const matrix = new MatrixChannel({ homeserverUrl: 'https://matrix.org', accessToken: '...' });
await matrix.connect();

Autonomous Agent

Daemon Mode

Run Code Buddy 24/7 in the background:

buddy daemon start [--detach]  # Start background daemon
buddy daemon stop              # Stop daemon
buddy daemon restart           # Restart daemon
buddy daemon status            # Show daemon status and services
buddy daemon logs [--lines N]  # View daemon logs

Features:

  • PID file management with stale detection
  • Auto-restart on crash (max 3 retries)
  • Service registry and health monitoring (CPU, memory)
  • Heartbeat engine β€” periodic agent wake with HEARTBEAT.md checklist, smart suppression, active hours
buddy heartbeat start          # Start the heartbeat engine
buddy heartbeat stop           # Stop the heartbeat engine
buddy heartbeat status         # Show heartbeat status
buddy heartbeat tick           # Manually trigger a single tick

Multi-Agent Orchestration

The SupervisorAgent coordinates multiple agent instances:

  • Strategies β€” sequential, parallel, race, all
  • Shared context β€” thread-safe key-value store with optimistic locking
  • Self-healing β€” error pattern recognition (6 built-in patterns), auto-recovery with exponential backoff
  • Checkpoint rollback β€” auto-checkpoint before risky ops, rollback to last good state

YOLO Mode (Autonomous Execution)

Full autonomy with built-in guardrails for safe unattended operation:

# Enable via CLI
/yolo on           # Enable (50 auto-edits, 100 auto-commands)
/yolo safe         # Restricted mode (20 edits, 30 commands, limited paths)
/yolo off          # Disable
/yolo status       # Show limits, counters, allow/deny lists

# Or via environment
YOLO_MODE=true buddy   # Still requires /yolo on confirmation in chat

What changes in YOLO mode:

SettingNormalYOLO
Tool rounds50400
Cost limit$10$100 (cap $1,000)
File editsConfirm eachAuto-approve (up to limit)
Bash commandsConfirm eachAuto-execute safe commands

Autonomy levels (fine-grained control):

/autonomy suggest   # Confirm everything
/autonomy confirm   # Confirm important ops (default)
/autonomy auto      # Auto-approve safe ops, confirm dangerous
/autonomy full      # Auto-approve all except critical
/autonomy yolo      # Full auto with guardrails

Customize allow/deny lists:

/yolo allow "npm run dev"      # Add to auto-execute list
/yolo deny "docker rm -f"      # Block a command pattern

Built-in guardrails (always active, even in YOLO):

  • Blocked paths: .env, .git, node_modules, *.pem, *.key, credentials
  • Blocked commands: rm -rf /, sudo, git push --force origin main, DROP DATABASE
  • Per-session limits on edits and commands
  • Hard cost cap ($1,000 max even with MAX_COST override)

Cron & Scheduling

The Cron-Agent Bridge connects the scheduler to CodeBuddyAgent instances for recurring tasks:

buddy trigger add time:*/30 action:run-tests    # Run tests every 30 min
buddy trigger add webhook:deploy action:notify   # Notify on deploy webhook

Webhook triggers use HMAC-SHA256 verification with template placeholders for flexible integration.

AI Providers

Code Buddy supports multiple AI providers with automatic failover:

ProviderModelsContextConfiguration
Grok (xAI)grok-4, grok-code-fast-1128KGROK_API_KEY
Claude (Anthropic)claude-sonnet-4, opus200KANTHROPIC_API_KEY
ChatGPT (OpenAI)gpt-4o, gpt-4-turbo128KOPENAI_API_KEY
Gemini (Google)gemini-2.0-flash (+ vision)2MGOOGLE_API_KEY
LM StudioAny local modelVaries--base-url http://localhost:1234/v1
Ollamallama3, codellama, etc.Varies--base-url http://localhost:11434/v1

Model failover chain β€” cascading provider fallback with health tracking and cooldown periods.

Connection Profiles

# Use LM Studio (local)
buddy --base-url http://localhost:1234/v1 --api-key lm-studio

# Use Ollama (local)
buddy --base-url http://localhost:11434/v1 --model llama3

# Use a specific model
buddy --model grok-code-fast-1

Profile configuration in ~/.codebuddy/user-settings.json:

{
  "connection": {
    "activeProfileId": "grok",
    "profiles": [
      {
        "id": "grok",
        "name": "Grok API (xAI)",
        "provider": "grok",
        "baseURL": "https://api.x.ai/v1",
        "model": "grok-4-latest"
      },
      {
        "id": "lmstudio",
        "name": "LM Studio Local",
        "provider": "lmstudio",
        "baseURL": "http://localhost:1234/v1",
        "apiKey": "lm-studio"
      }
    ]
  }
}

Auth profile manager β€” API key rotation (round-robin/priority/random strategies), session stickiness, exponential backoff on failures.

buddy auth-profile list                   # List authentication profiles
buddy auth-profile add <id> <provider>    # Add a profile
buddy auth-profile remove <id>            # Remove a profile
buddy auth-profile reset                  # Reset all cooldowns

Security & Trust

Tool Policy & Bash Allowlist

Fine-grained control over what tools the agent can use:

// Tool-level allow/deny
const policy = new ToolPolicy({
  allowlist: ['read_file', 'search', 'web_fetch'],
  denylist: ['bash', 'write_file'],
  requireConfirmation: ['delete_file'],
});

// Bash command patterns
const bashPolicy = new BashAllowlist({
  patterns: [/^npm (install|test|run)/, /^git (status|diff|log)/],
  blocked: [/rm -rf/, /sudo/, /curl.*\|.*sh/],
});

Security Modes

ModeDescription
suggestConfirm all operations
auto-editAuto-approve safe ops
full-autoFull autonomy (YOLO)
/mode suggest    # Maximum safety
/mode full-auto  # Full autonomy

Trust Folders & Agent Profiles

  • Trust folders β€” directory-level tool permissions via .codebuddy-trust.json
  • Agent profiles β€” predefined configs: secure (read-only), minimal, power-user
  • Per-model tool config β€” capabilities, context window, and patch format per model family

OS Sandbox β€” Workspace-Write Mode

Three sandbox tiers for native OS-level isolation (Codex-inspired):

ModeWrite AccessUse Case
read-onlyNoneUntrusted analysis tasks
workspace-writeGit workspace root onlyNormal development (default)
danger-full-accessUnrestrictedDeployment/release scripts

.git, .codebuddy, .ssh, .gnupg, .aws are always read-only regardless of mode.

const sandbox = await createSandboxForMode('workspace-write', '/my/project');
await sandbox.exec('npm', ['test']);

Exec Policy β€” Prefix Rules

Codex-inspired command authorization with token-array prefix matching (safer than regex β€” bypasses quoting/encoding tricks):

buddy execpolicy check "git push --force"          # evaluate a shell string
buddy execpolicy check-argv git push --force       # token-array (prefix rules first)
buddy execpolicy add-prefix git push --action deny # block git push with longest-match
buddy execpolicy dashboard                         # full policy overview

SSRF Guard

Comprehensive Server-Side Request Forgery protection on all outbound HTTP calls:

  • Blocks RFC-1918 private ranges + loopback + link-local
  • Blocks IPv4 bypass vectors: octal (0177.0.0.1), hex (0x7f000001), short form (127.1)
  • Blocks IPv6 transition addresses: NAT64 (64:ff9b::/96), 6to4, Teredo, IPv4-mapped (::ffff:127.0.0.1)
  • Async DNS resolution check before every fetch

Docker Sandbox

Containerized command execution for untrusted operations:

const sandbox = new DockerSandbox({
  image: 'codebuddy/sandbox:latest',
  memoryLimit: '512m',
  networkMode: 'none',
  timeout: 30000,
});

Auto-sandbox router automatically routes dangerous commands (npm, pip, cargo, make) to Docker when available.

Safety Rails

RailDescription
Diff-First ModeAll code changes are previewed before applying. Users see file summaries, line counts, and can view the full unified diff.
Plan-First ModeMulti-step tasks show the execution plan for approval before any changes are made.
Scoped PermissionsUsers get only the access they need: read-only β†’ write-patch β†’ run-tests β†’ deploy.
Audit TrailEvery tool execution, confirmation, and security decision is logged.
Secret HandlesAPI tokens and credentials are referenced by handle name only β€” actual values are resolved from env vars at runtime, never exposed to the LLM context.
2-Step ConfirmationRisky operations (rollback, deploy) require double confirmation with a 2-minute timeout window.
Timed YOLO/yolo grants temporary full access that auto-revokes after the specified duration.
DM PairingUnknown users must be approved before they can interact with the bot.

Architecture

Facade Architecture

CodeBuddyAgent
    β”‚
    β”œβ”€β”€ AgentContextFacade      # Context window and memory management
    β”‚       - Token counting, compression, memory retrieval
    β”‚
    β”œβ”€β”€ SessionFacade           # Session persistence and checkpoints
    β”‚       - Save/load, checkpoint creation, rewind
    β”‚
    β”œβ”€β”€ ModelRoutingFacade      # Model routing and cost tracking
    β”‚       - Provider selection, cost calculation
    β”‚
    β”œβ”€β”€ InfrastructureFacade    # MCP, sandbox, hooks, plugins
    β”‚       - Hook execution, plugin loading
    β”‚
    └── MessageHistoryManager   # Chat and LLM message history

Autonomy Layer

CodeBuddyAgent
    β”‚
    β”œβ”€β”€ TaskPlanner             # DAG decomposition of complex requests
    β”‚       - needsPlanning() heuristic
    β”‚       - createPlan() β†’ TaskGraph β†’ parallel execution
    β”‚
    β”œβ”€β”€ SupervisorAgent         # Multi-agent orchestration
    β”‚       - Sequential, parallel, race, all strategies
    β”‚       - SharedContext with optimistic locking
    β”‚
    β”œβ”€β”€ SelfHealing             # Automatic error recovery
    β”‚       - Pattern recognition (6 built-in patterns)
    β”‚       - Retry with exponential backoff
    β”‚
    β”œβ”€β”€ ScreenObserver          # Environment monitoring
    β”‚       - Periodic screenshots with perceptual diff
    β”‚       - Event triggers (file_change, screen_change, time, webhook)
    β”‚
    β”œβ”€β”€ ProactiveAgent          # Agent-initiated communication
    β”‚       - Push notifications with priority levels
    β”‚       - Rate limiting and quiet hours
    β”‚
    └── DaemonManager           # Background process lifecycle
            - PID file management, auto-restart
            - Service registry, health monitoring

Core Flow

User Input β†’ ChatInterface (Ink/React) β†’ CodeBuddyAgent β†’ AI Provider
                                              β”‚
                                         Tool Calls (max 50/400 rounds)
                                              β”‚
                                      Tool Execution + Confirmation
                                              β”‚
                                        Results back to API (loop)

API Server & Integrations

REST API

buddy server --port 3000
EndpointMethodDescription
/api/healthGETHealth check
/api/metricsGETPrometheus metrics
/api/chatPOSTChat completion
/api/chat/completionsPOSTOpenAI-compatible
/api/toolsGETList tools
/api/tools/{name}/executePOSTExecute tool
/api/sessionsGET/POSTSession management
/api/memoryGET/POSTMemory entries
/api/daemon/statusGETDaemon status
/api/daemon/healthGETHealth metrics (CPU, memory)
/api/cron/jobsGETList cron jobs
/api/cron/jobs/{id}/triggerPOSTTrigger a cron job
/api/notifications/preferencesGET/POSTNotification settings
/api/heartbeat/statusGETHeartbeat engine status
/api/heartbeat/start|stop|tickPOSTHeartbeat control
/api/hub/search?q=...GETSearch skills marketplace
/api/hub/installedGETList installed hub skills
/api/hub/installPOSTInstall a skill
/api/hub/{name}DELETEUninstall a skill
/api/identityGETList loaded identity files
/api/identity/promptGETCombined identity prompt
/api/identity/{name}PUTUpdate an identity file
/api/groups/status|listGETGroup security status/config
/api/groups/blockPOSTBlock a user globally
/api/groups/block/{userId}DELETEUnblock a user
/api/auth-profilesGET/POST/DELETEAuth profile CRUD
/api/auth-profiles/resetPOSTReset all cooldowns

WebSocket Events

const ws = new WebSocket('ws://localhost:3000/ws');

// Authenticate
ws.send(JSON.stringify({
  type: 'authenticate',
  payload: { token: 'jwt-token' }
}));

// Stream chat
ws.send(JSON.stringify({
  type: 'chat_stream',
  payload: { messages: [{ role: 'user', content: 'Hello' }] }
}));

MCP Servers

Four MCP servers are pre-configured (disabled by default):

buddy mcp add brave-search    # Brave Web Search (needs BRAVE_API_KEY)
buddy mcp add playwright      # Browser automation (no key needed)
buddy mcp add exa-search      # Exa neural search (needs EXA_API_KEY)
buddy mcp add icm             # Infinite Context Memory (needs `cargo install icm`)
buddy mcp list                # Show all configured servers

Plugin System

Plugins extend Code Buddy with custom tools, commands, and providers:

~/.codebuddy/plugins/
  my-plugin/
    manifest.json
    index.js

Plugin types: Tool, Provider (LLM/embedding/search), Command, Hook

const plugin: Plugin = {
  async activate(context: PluginContext) {
    context.registerTool({
      name: 'my_tool',
      description: 'Custom tool',
      execute: async (args) => {
        return { success: true, output: 'Done!' };
      }
    });

    context.registerProvider({
      id: 'my-llm',
      type: 'llm',
      async chat(messages) { return 'response'; }
    });
  }
};

Extensions

Manifest-based extension system with lifecycle hooks and config schema. Extensions live in .codebuddy/extensions/.

Copilot Proxy

IDE-compatible completions backend β€” serves /v1/completions with bearer auth, per-IP rate limiting, and token clamping.

External Tools (RTK & ICM)

ToolInstallPurpose
RTKcargo install --git https://github.com/rtk-ai/rtkCLI proxy that wraps commands to reduce LLM token usage 60-90%
ICMcargo install --git https://github.com/rtk-ai/icmMCP server for persistent cross-session memory

RTK is automatically integrated via a before-hook β€” supported bash commands are prefixed with rtk transparently. Configure in .codebuddy/config.toml under [integrations].

CLI Reference

Global Options

FlagShortDescriptionDefault
--version-VShow version number-
--directory <dir>-dSet working directory.
--api-key <key>-kAPI key (or GROK_API_KEY env)-
--base-url <url>-uAPI base URL (or GROK_BASE_URL env)-
--model <model>-mAI model to use (or GROK_MODEL env)auto-detect
--prompt <prompt>-pSingle prompt, headless mode-
--browser-bLaunch browser UI instead of terminalfalse
--max-tool-rounds <n>Max tool execution rounds400
--security-mode <mode>-ssuggest, auto-edit, or full-autosuggest
--output-format <fmt>-oHeadless output: json, stream-json, text, markdownjson
--context <patterns>-cGlob patterns to load into context-

Session & Cost

FlagDescriptionDefault
--continueResume the most recent saved session-
--resume <id>Resume a specific session (supports partial ID matching)-
--max-price <dollars>Maximum cost in dollars before stopping10.0
--no-cacheDisable response caching-

Autonomy & Permissions

FlagDescriptionDefault
--auto-approveAutomatically approve all tool executionsfalse
--dangerously-skip-permissionsBypass all permission checks (trusted containers only)false
--no-self-healDisable self-healing auto-correction-
--allow-outsideAllow file operations outside workspace directoryfalse

Tool Control

FlagDescriptionExample
--force-toolsForce-enable function calling for local models-
--probe-toolsAuto-detect tool support at startup-
--enabled-tools <patterns>Only enable matching tools (glob, comma-separated)bash,*file*,search
--disabled-tools <patterns>Disable matching tools (glob, comma-separated)bash,web_*
--allowed-tools <patterns>Alias for --enabled-tools (Claude Code compat)-

Agent & Prompt Configuration

FlagDescriptionDefault
--system-prompt <id>System prompt: default, minimal, secure, code-reviewer, architect (or custom from ~/.codebuddy/prompts/)default
--list-promptsList available system prompts and exit-
--agent <name>Use a custom agent from ~/.codebuddy/agents/-
--list-agentsList available custom agents and exit-

Display & Debugging

FlagDescription
--plainMinimal formatting (plain text output)
--no-colorDisable colored output
--no-emojiDisable emoji in output
--vimEnable Vim keybindings for input
--mcp-debugEnable MCP protocol debugging output

Setup & Init

FlagDescription
--initInitialize .codebuddy/ directory with templates
--dry-runPreview changes without applying (simulation mode)
--setupRun interactive API key setup wizard
--list-modelsList available models from the API and exit

Commands

Slash Commands (In-Chat)

CommandDescription
/helpShow help
/model [name]Change model
/mode [mode]Change security mode
/profile [id]Switch connection profile
/thinkEnable reasoning (4K tokens)
/megathinkDeep reasoning (10K tokens)
/ultrathinkExhaustive reasoning (32K tokens)
/costShow cost dashboard
/memoryMemory management
/hooks listList lifecycle hooks
/plugin listList plugins
/speak <text>Speak text with current TTS provider
/tts on|off|autoTTS control
/yolo on|off|safe|statusYOLO mode control
/autonomy suggest|confirm|auto|full|yoloAutonomy level

CLI Subcommands

# Daemon
buddy daemon start|stop|restart|status|logs

# Triggers
buddy trigger list|add|remove

# Webhooks
buddy webhook list|add|remove

# Skills Hub
buddy hub search|install|uninstall|update|list|info|publish|sync

# Heartbeat
buddy heartbeat start|stop|status|tick

# Identity
buddy identity show|get|set|prompt

# Groups
buddy groups status|list|block|unblock

# Auth Profiles
buddy auth-profile list|add|remove|reset

# Devices
buddy device list|pair|remove|snap|screenshot|record|run

# Config
buddy config show|validate|get

# Security
buddy security-audit [--deep] [--fix] [--json]

# Voice
buddy speak [text] [--voice <name>] [--list-voices] [--speed <n>] [--format <fmt>]

# Knowledge Base
buddy knowledge list|show|search|add|remove|context

# DM Pairing
buddy pairing status|list|pending|approve <code>|add <id>|revoke <id>

# Wide Research
buddy research "<topic>" [--workers N] [--rounds N] [--output file.md]

# Task List (todo.md attention bias β€” injected at end of every agent turn)
buddy todo list                     # Show all items
buddy todo add "task description" [-p high|medium|low]
buddy todo done <id>                # Mark completed
buddy todo update <id> [-s in_progress] [-t "new text"]
buddy todo remove <id>              # Delete item
buddy todo clear-done               # Remove all completed
buddy todo context                  # Preview the block injected into the agent

# Lessons (self-improvement loop β€” injected before every agent turn)
buddy lessons list [--category PATTERN|RULE|CONTEXT|INSIGHT]
buddy lessons add "what went wrong β†’ correct approach" --category PATTERN
buddy lessons search "tsc"                 # Find relevant lessons before a task
buddy lessons clear [--category RULE] --yes
buddy lessons context                      # Preview the <lessons_context> block

# Setup
buddy onboard          # Interactive setup wizard
buddy doctor           # Environment diagnostics

Configuration

Environment Variables

VariableDescriptionDefault
GROK_API_KEYxAI API keyRequired
ANTHROPIC_API_KEYAnthropic API key-
OPENAI_API_KEYOpenAI API key-
GOOGLE_API_KEYGoogle AI API key-
SERPER_API_KEYWeb search API key-
GROK_BASE_URLCustom API endpoint-
GROK_MODELDefault model-
BRAVE_API_KEYBrave Search API key-
EXA_API_KEYExa neural search API key-
PERPLEXITY_API_KEYPerplexity AI search key (pplx-...)-
OPENROUTER_API_KEYOpenRouter key for Perplexity (sk-or-...)-
PERPLEXITY_MODELPerplexity modelperplexity/sonar-pro
PICOVOICE_ACCESS_KEYPorcupine wake word detection-
CACHE_TRACEDebug prompt construction stagesfalse
YOLO_MODEFull autonomyfalse
MAX_COSTCost limit ($)10
JWT_SECRETAPI server authRequired in prod
TELEGRAM_BOT_TOKENTelegram bot token (from @BotFather)-
DISCORD_TOKENDiscord bot token-
SLACK_BOT_TOKENSlack bot token-

Optional Rust tools:

ToolInstallPurpose
RTKcargo install --git https://github.com/rtk-ai/rtkCLI proxy that wraps commands to reduce LLM token usage 60-90%
ICMcargo install --git https://github.com/rtk-ai/icmMCP server for persistent cross-session memory

Project Settings

Create .codebuddy/settings.json:

{
  "systemPrompt": "You are working on a TypeScript project.",
  "tools": {
    "enabled": ["read_file", "search", "bash"],
    "disabled": ["web_search"]
  },
  "security": {
    "mode": "auto-edit",
    "bashAllowlist": ["npm *", "git *"]
  }
}

Development

# Clone and install
git clone https://github.com/phuetz/code-buddy.git
cd code-buddy
npm install

# Development mode
npm run dev

# Run tests
npm test

# Validate before commit
npm run validate

# Build
npm run build

Test Coverage

23,700+ tests across 554+ suites covering:
- Core: Tool Policy, Bash Allowlist, Context Window Guard, Compaction
- Agent: Middleware Pipeline, Profiles, Reasoning, Streaming
- Autonomy: Daemon, Cron Bridge, Task Planner, Delegation Engine
- Observation: Screen Observer, Triggers, Proactive Notifications
- Orchestration: Supervisor, Shared Context, Self-Healing, Rollback
- Providers: Gemini (vision + conversation), OpenAI-compat, Failover
- Security: Trust Folders, Skill Scanner, Bash Parser, Session Locks
- Infrastructure: MCP Client, Webhooks, Extensions, ACP Protocol, RTK Compressor, ICM Bridge
- Voice: Wake Word, TTS Providers, Voice Control Loop
- UI: ChatHistory, ChatInterface, TabbedQuestion

Research & Inspiration

Code Buddy implements techniques from academic research and draws architectural inspiration from leading open-source projects.

Scientific Papers

Reasoning & Planning:

PaperReferenceImplementation
Tree of ThoughtsYao et al., 2023 β€” arXiv:2305.10601src/agent/reasoning/tree-of-thought.ts
RethinkMCTSZhang et al., 2024 β€” arXiv:2409.09584src/agent/reasoning/mcts.ts
TALE (Token-Budget-Aware Reasoning)arXiv:2412.18547src/agent/token-budget-reasoning.ts β€” 68.9% token reduction
FrugalGPTStanford, 2023 β€” arXiv:2305.05176src/optimization/model-routing.ts β€” 30-70% cost reduction
LLMCompilerarXiv:2312.04511src/optimization/parallel-executor.ts β€” 2.5-4.6x speedup

Program Repair:

PaperReferenceImplementation
ChatRepairXia et al., ISSTA 2024 β€” arXiv:2403.12538src/agent/repair/iterative-repair.ts
ITERarXiv:2403.00418src/agent/repair/repair-templates.ts β€” iterative template repair
RepairAgentICSE 2024src/agent/repair/repair-engine.ts β€” autonomous LLM-based repair
AgentCoderHuang et al., 2023src/agent/multi-agent/multi-agent-system.ts β€” hierarchical multi-agent code generation

RAG & Context Management:

PaperReferenceImplementation
CodeRAGarXiv:2509.16112src/context/multi-path-retrieval.ts, src/context/dependency-aware-rag.ts
RAG-MCParXiv:2505.03275src/tools/tool-selector.ts
ToolLLMICLR'24 β€” arXiv:2307.16789src/agent/execution/tool-selection-strategy.ts
Comprehensive RAG SurveyarXiv:2506.00054src/context/codebase-rag/codebase-rag.ts
Recurrent Context CompressionarXiv:2406.06110src/context/context-manager-v2.ts

Observation & Optimization:

PaperReferenceImplementation
JetBrains Context ManagementJetBrains Research, 2024src/context/observation-masking.ts β€” -7% cost, +2.6% success
Complexity TraparXiv:2508.21433src/context/observation-masking.ts
Less-is-More (Tool Filtering)arXiv, 2024src/optimization/tool-filtering.ts β€” 70% execution time reduction
The Prompt ReportarXiv:2406.06608src/prompts/system-base.ts

Testing & Memory:

PaperReferenceImplementation
TDD + LLMICSE 2024src/testing/tdd-mode.ts β€” TDD improves Pass@1 by 45.97%
MemGPTUC Berkeley, 2023src/memory/prospective-memory.ts β€” stateful AI agents

Fault Localization: Ochiai, DStar, and Tarantula (Jones et al., 2002) spectrum-based techniques in src/agent/repair/fault-localization.ts.

Inspiration Projects

Code Buddy's architecture draws from these open-source projects:

ProjectInspirationKey Files
OpenClawMulti-channel messaging, DM pairing, lane queue concurrency, memory lifecycle, tool policy, skills system, heartbeat, identity system, group security, hub marketplace40+ files across src/channels/, src/concurrency/, src/memory/, src/security/, src/skills/
OpenAI Codex CLIApply-patch unified diff, head/tail truncation, per-model tool config, turn diff tracker, security modes, OS sandbox workspace-write tiers, shell-free exec, SSRF guard, exec policy prefix rules, shell env policy, named config profiles, tool prefix naming convention, stable JSON serialization, session fork/rollout unificationsrc/tools/apply-patch.ts, src/sandbox/os-sandbox.ts, src/security/ssrf-guard.ts, src/sandbox/execpolicy.ts, src/tools/registry/tool-aliases.ts, src/utils/stable-json.ts, src/observability/run-store.ts
Claude CodeHook system, slash commands, MCP config, extended thinking, parallel subagents, headless output, Anthropic prompt cache breakpointssrc/hooks/, src/commands/slash-commands.ts, src/mcp/config.ts, src/optimization/cache-breakpoints.ts
Gemini CLIPersistent checkpoints, context files, compress command, shell prefix, multimodal inputsrc/checkpoints/, src/context/context-files.ts, src/input/multimodal-input.ts
AiderRepository map, voice input, unified diff editor, watch mode (IDE comments)src/context/repository-map.ts, src/tools/voice-input.ts, src/commands/watch-mode.ts
Cursor.cursorrules config, parallel agent system, sandboxed terminals, embedded browsersrc/config/codebuddyrules.ts, src/agent/parallel/, src/browser/embedded-browser.ts
Mistral VibeExternal markdown prompts, TOML config, tool permission system, fuzzy match, update notifiersrc/prompts/, src/config/toml-config.ts, src/utils/fuzzy-match.ts
ConductorSpec-driven development, track systemsrc/tracks/
RTKCommand proxy for 60-90% token reductionsrc/utils/rtk-compressor.ts
ICMPersistent cross-session memory via MCPsrc/memory/icm-bridge.ts
Manus AIWide Research (parallel sub-agent research workers), Knowledge Base injection, todo.md attention bias, restorable context compression, pre-compaction NO_REPLY flush, inline web-search citations, observation variator (anti-repetition), structured prompt variation, tool result compaction guard, disk-backed tool results, response prefill modes (tool_choice control), WebSearchMode + domain policy, message queue debounce/cap/overflowsrc/agent/wide-research.ts, src/context/observation-variator.ts, src/agent/response-constraint.ts, src/tools/web-search.ts, src/agent/message-queue.ts
OpenClawMulti-channel messaging, DM pairing, lane queue concurrency, memory lifecycle, tool policy, skills system, heartbeat, identity system, group security, hub marketplace, daily session reset, per-channel streaming policiessrc/channels/streaming-policy.ts, src/channels/, src/skills/, src/daemon/daily-reset.ts

Other influences: Rust (Result<T, E> pattern), AutoGPT, MetaGPT, CrewAI, ChatDev (role-based multi-agent), ReAct (reasoning + acting paradigm), Qodo/PR-Agent (RAG for code repos).

Benchmarks referenced: SWE-bench, HumanEval, MBPP, BigCodeBench, WebArena, Berkeley Function Calling Leaderboard.

For detailed research notes, see docs/RESEARCH_IMPROVEMENTS.md, docs/RAG_TOOL_SELECTION.md, and deep_research/ai-coding-assistant-improvements/.

Troubleshooting

API key not working

echo $GROK_API_KEY  # Verify key is set
buddy --prompt "test"

Switching providers doesn't work

# Verify connection to local model
buddy --base-url http://localhost:1234/v1 --api-key lm-studio --prompt "test"

# List available models
buddy --list-models

Memory not persisting

# Check memory directory
ls ~/.codebuddy/memory/

# Clear and reinitialize
rm -rf ~/.codebuddy/memory/
buddy

High latency

  • Use a faster model: buddy --model grok-code-fast-1
  • Use local LLM: buddy --base-url http://localhost:11434/v1 --model llama3

Debug mode

DEBUG=codebuddy:* buddy

License

MIT License - see LICENSE for details.

Report Bug | Request Feature | Star on GitHub

Multi-AI: Grok | Claude | ChatGPT | Gemini | LM Studio | Ollama

Keywords

cli

FAQs

Package last updated on 22 Feb 2026

Related posts