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.1.22
Version published
Weekly downloads
270
629.73%
Maintainers
1
Weekly downloads
Β 
Created
Source
Code Buddy

Code Buddy

Multi-AI Personal Assistant with OpenClaw-Inspired Architecture

npm version License: MIT Node Version TypeScript Ask DeepWiki

Tests Coverage Build


A powerful multi-AI terminal agent inspired by OpenClaw architecture. Supports Grok, Claude, ChatGPT, Gemini, LM Studio, and Ollama with advanced memory, multi-channel messaging, and intelligent context management.


Quick Start | CLI Reference | Architecture | Channels | Security | API

What's New

OpenClaw-Inspired Features

Code Buddy incorporates advanced patterns from the OpenClaw project:

ModuleStatusDescription
Tool Policy Systemβœ… 100%Fine-grained tool permissions with allowlist/denylist
Bash Allowlistβœ… 100%Secure command execution with pattern matching
Context Window Guardβœ… 100%Automatic context management with 34 test cases
Smart Compactionβœ… 100%Multi-stage conversation compression
Context Pruningβœ… 100%TTL-based message expiration
Hybrid Searchβœ… 100%Combined keyword + semantic search
Lifecycle Hooksβœ… 100%Pre/post hooks with 52 test cases
Connection Profilesβœ… 100%Multi-provider switching with 57 tests
Desktop Automationβœ… 100%Screen capture, OCR, UI control
Gemini Visionβœ… 100%Native image support via inlineData (base64 data URLs)
Auto-Capture Memoryβœ… 100%Pattern-based memory extraction
Memory Lifecycleβœ… 100%Auto-recall and auto-capture hooks

Phase 3 β€” Streaming & Security

ModuleStatusDescription
Middleware Pipelineβœ… 100%Composable before/after turn hooks (cost limit, context warning, turn limit)
Reasoning Eventsβœ… 100%Streaming chain-of-thought display with collapsible UI
Trust Foldersβœ… 100%Directory-level tool permissions via .codebuddy-trust.json
Agent Profilesβœ… 100%Predefined agent configs (secure, minimal, power-user)
Tool Streamingβœ… 100%Real-time bash output via AsyncGenerator
TabbedQuestion UIβœ… 100%Multi-option interactive prompts

Phase 4 β€” Autonomous Agent

ModuleStatusDescription
Daemon Modeβœ… 100%Background process with PID management, auto-restart (max 3)
Cron-Agent Bridgeβœ… 100%Scheduled task execution via CodeBuddyAgent instances
Task Plannerβœ… 100%DAG-based decomposition with topological sort and parallel execution
Screen Observerβœ… 100%Periodic screenshots, perceptual diff, event triggers
Proactive Agentβœ… 100%Push notifications, question/response, rate limiting, quiet hours
Orchestratorβœ… 100%Multi-agent supervisor (sequential/parallel/race/all strategies)
Self-Healingβœ… 100%Error pattern recognition, auto-recovery with exponential backoff
Checkpoint Rollbackβœ… 100%Auto-checkpoint before risky ops, rollback to last good state
Shared Contextβœ… 100%Thread-safe key-value store with optimistic locking

Phase 5 β€” OpenClaw-Inspired Platform

ModuleStatusDescription
Doctor Commandβœ… 100%Environment/deps/config diagnostics (buddy doctor)
Onboarding Wizardβœ… 100%Interactive setup wizard (buddy onboard)
Model Failover Chainβœ… 100%Cascading provider fallback with health tracking
Webhook Triggersβœ… 100%HMAC-verified HTTP triggers + CLI + API routes
Typing Indicatorsβœ… 100%Presence & typing events for channels
Live Canvasβœ… 100%WebSocket-driven visual workspace (A2UI)
Docker Sandboxβœ… 100%Containerized command execution with resource limits
Skills Registryβœ… 100%Bundled/managed/workspace skills with YAML frontmatter
Media Pipelineβœ… 100%Ingest, track, transcode with transcription hooks
ACP Protocolβœ… 100%Inter-agent communication router with request/response
Extension Systemβœ… 100%Manifest-based plugin loader with lifecycle hooks
Copilot Proxyβœ… 100%IDE-compatible completions backend (/v1/completions)

Phase 6 β€” Robustness & Developer Experience

ModuleStatusDescription
Web Search 5-Provider Chainβœ… 100%Brave MCP β†’ Brave API β†’ Perplexity β†’ Serper β†’ DuckDuckGo with country/freshness/lang
Apply Patch Toolβœ… 100%Unified diff parser and applier with fuzz factor (Codex-inspired)
Bash Parserβœ… 100%AST-based command parsing via tree-sitter-bash with state-machine fallback
Per-Model Tool Configβœ… 100%Capabilities, context window, patch format per model family
Head/Tail Truncationβœ… 100%Smart output truncation keeping start + end of large results
Session Locksβœ… 100%PID-based file locking with stale detection
Skill Scannerβœ… 100%Static analysis of SKILL.md files for dangerous patterns (24 rules)
History Repairβœ… 100%5-pass self-repair for malformed LLM message sequences
Cache Traceβœ… 100%Debug prompt construction stages (CACHE_TRACE=true)
Turn Diff Trackerβœ… 100%Per-turn file change tracking with rollback capability
MCP Predefined Serversβœ… 100%Brave Search, Playwright, Exa pre-configured in MCP
Headless Mode Fixesβœ… 100%Clean JSON stdout, process.exit(0), Gemini message sanitization
Gemini Conversation Repairβœ… 100%3-pass sanitization after context compression (orphan cleanup, role merge, user-start)

Phase 7 β€” Code Generation Security

ModuleStatusDescription
Centralized Dangerous Patternsβœ… 100%Single registry for all dangerous patterns (bash, code, skills) with severity levels
Generated Code Validatorβœ… 100%Pre-write security scan for eval, XSS, SQL injection, hardcoded secrets, prototype pollution
Pre-Write Syntax Validatorβœ… 100%Balanced delimiters, template literals, indentation (JS/TS/Python/YAML/HTML/CSS/JSON)
Atomic Rollback (apply-patch)βœ… 100%All-or-nothing patch application with full file state backup
Atomic Transactions (multi-edit)βœ… 100%Multi-file edits rolled back on first failure
AST Bash Command Validationβœ… 100%tree-sitter integration in command validator with centralized pattern checks
Bash Checkpointβœ… 100%Pre-snapshot of files targeted by destructive commands (rm, mv, truncate)
Shell Injection Fixβœ… 100%Code formatter uses spawnSync stdin pipe instead of execSync echo
Diff Preview in Confirmationβœ… 100%Shows actual diffs before approval, magnitude-based re-confirmation for large changes
Architect Parallel Executionβœ… 100%Dependency-wave-based parallel step execution with DAG ordering
Semantic Truncationβœ… 100%Error-preserving output truncation (keeps error lines, stack traces from middle sections)
Auto-Sandbox Routerβœ… 100%Automatic Docker routing for dangerous commands (npm, pip, cargo, make)
Security Audit Loggingβœ… 100%JSONL audit trail for all code generation security decisions
Copilot Proxy Hardeningβœ… 100%Per-IP rate limiting, token clamping, auth bypass fix, sanitized error messages

Phase 8 β€” OpenClaw Parity (Final)

ModuleStatusDescription
Skills Auto-Discoveryβœ… 100%Agent auto-finds/installs skills from hub when tool confidence is low
Device Node Connectorsβœ… 100%Real SSH, ADB, and local transports with platform-specific commands
Canvas Bidirectional Eventsβœ… 100%Browserβ†’agent event routing, data binding observers, state queries

Installation

Prerequisites

  • Node.js 18.0.0 or higher
  • ripgrep (recommended for faster search)
  • tree-sitter + tree-sitter-bash (optional, for AST-based bash command parsing)
# macOS
brew install ripgrep

# Ubuntu/Debian
sudo apt-get install ripgrep

# Windows
choco install ripgrep

# Optional: tree-sitter for enhanced bash security parsing
npm install tree-sitter tree-sitter-bash

Install Code Buddy

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

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

Quick Start

# 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).

Architecture

Code Buddy uses a facade architecture for clean separation of concerns:

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 (Phase 4)

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)

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

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

Connection Profiles

Switch between providers using CLI options or configuration:

# 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

// ~/.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"
      }
    ]
  }
}

Memory System

Code Buddy features a sophisticated memory system inspired by OpenClaw:

Three Memory Subsystems

SubsystemStoragePurpose
Persistent MemoryMarkdown filesProject/user notes
Enhanced MemorySQLite + embeddingsSemantic search
Prospective MemorySQLiteTasks, goals, reminders

Auto-Capture (OpenClaw Pattern)

Automatically detects and stores important information:

// Detected patterns (English + French)
"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

// Before execution: Inject relevant memories
beforeExecute(context) β†’ { injectedContext, recalledMemories }

// After response: Capture important info
afterResponse(context) β†’ { capturedCount, capturedMemories }

// Session end: Summarize conversation
sessionEnd(sessionId) β†’ { summaryId, memoriesStored }

Deduplication

  • Jaccard similarity threshold: 0.95
  • Hash-based recent capture cache
  • Automatic duplicate detection

Multi-Channel Support

Code Buddy supports multiple messaging channels:

ChannelStatusFeatures
Terminalβœ… FullNative CLI interface (Ink/React)
HTTP APIβœ… FullREST + WebSocket
WebChatβœ… FullBuilt-in HTTP + WebSocket with browser UI
Discord🟑 BaseBot integration, slash commands
Telegram🟑 BaseBot API, message handlers
Slack🟑 BaseBolt framework, events
WhatsApp🟑 BaseBaileys (QR pairing, media, reconnect)
Signal🟑 Basesignal-cli REST API (polling, groups)
Google Chat🟑 BaseWorkspace API (JWT auth, webhook events)
Microsoft Teams🟑 BaseBot Framework (OAuth2, adaptive cards)
Matrix🟑 Basematrix-js-sdk (E2EE, threads, media)

Channel Configuration

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

Security

Tool Policy System

Fine-grained control over tool execution:

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

Bash Allowlist

Secure command execution:

const bashPolicy = new BashAllowlist({
  patterns: [
    /^npm (install|test|run)/,
    /^git (status|diff|log)/,
    /^ls -la?/,
  ],
  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

Sandbox Isolation

Docker-based execution environment:

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

Context Management

Context Window Guard

Automatic context management with configurable thresholds:

const guard = new ContextWindowGuard({
  maxTokens: 128000,
  warningThreshold: 0.8,  // Warn at 80%
  compactionThreshold: 0.9,  // Compact at 90%
});

Smart Compaction

Multi-stage compression:

  • Stage 1: Remove tool results older than TTL
  • Stage 2: Summarize older messages
  • Stage 3: Aggressive truncation if needed

Combined keyword + semantic search:

const results = await hybridSearch({
  query: "authentication flow",
  keywordWeight: 0.3,
  semanticWeight: 0.7,
});

Tools

Built-in Tools

CategoryTools
File Operationsview_file, create_file, str_replace_editor, edit_file, multi_edit
Searchsearch, codebase_map
Systembash, docker, kubernetes
Webweb_search, web_fetch, browser
Patchingapply_patch (unified diff)
Planningcreate_todo_list, get_todo_list, update_todo_list
Mediascreenshot, audio, video, ocr, clipboard
Documentspdf, document, archive

Web Search (5-Provider Fallback Chain)

Code Buddy automatically cascades through available search providers:

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).

MCP Predefined Servers

Three 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 list                # Show all configured servers

RAG-Based Tool Selection

Tools are selected based on query relevance:

// Query: "what's the weather in Paris?"
// Selected tools: web_search, web_fetch
// Not selected: bash, edit_file, etc.

API Server

REST API with WebSocket support:

Starting the Server

buddy server --port 3000

Endpoints

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/startPOSTStart heartbeat
/api/heartbeat/stopPOSTStop heartbeat
/api/heartbeat/tickPOSTTrigger a single tick
/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/statusGETGroup security status
/api/groups/listGETList configured groups
/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' }] }
}));

Slash Commands

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

Daemon Commands

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

Trigger Commands

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

Webhook Commands

buddy webhook list                          # List registered webhooks
buddy webhook add <name> <message> [opts]   # Register a new webhook
buddy webhook remove <id>                   # Remove a webhook

Hub Commands (Skills Marketplace)

buddy hub search <query>       # Search for skills
buddy hub install <name>       # Install a skill from the hub
buddy hub uninstall <name>     # Uninstall a skill
buddy hub update [name]        # Update all or a specific skill
buddy hub list                 # List installed skills
buddy hub info <name>          # Show details about a skill
buddy hub publish <path>       # Publish a skill to the hub
buddy hub sync                 # Sync installed skills with lockfile

Heartbeat Commands

buddy heartbeat start [opts]   # 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

Identity Commands

buddy identity show            # Show loaded identity files (SOUL.md, USER.md, etc.)
buddy identity get <name>      # Show content of a specific identity file
buddy identity set <name> <c>  # Set content of an identity file
buddy identity prompt          # Show the combined identity prompt injection

Group Security Commands

buddy groups status            # Show group security status
buddy groups list              # List configured groups
buddy groups block <userId>    # Add a user to the global blocklist
buddy groups unblock <userId>  # Remove a user from the blocklist

Auth Profile Commands

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

Device Commands

buddy device list                         # List paired devices
buddy device pair --id <id> --name <name> --transport <ssh|adb|local>  # Pair a device
buddy device remove <id>                  # Remove a paired device
buddy device snap <id> [-o output.png]    # Take a screenshot on device
buddy device screenshot <id> [-o out.png] # Alias for snap
buddy device record <id> [-d 10] [-o out] # Record screen (duration in seconds)
buddy device run <id> -- <command>        # Run a command on device

Config Commands

buddy config show [--json]     # Show all environment variables and values
buddy config validate          # Validate current environment configuration
buddy config get <name>        # Show value and definition of a variable

Security Audit

buddy security-audit           # Run security audit of your environment
buddy security-audit --deep    # Deep scan (git history, npm audit)
buddy security-audit --fix     # Auto-fix file permission issues
buddy security-audit --json    # Output as JSON

Voice & TTS Commands

buddy speak "Bonjour, je suis 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

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)

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

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

Plugin System

Plugin Structure

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

Plugin Types

  • Tool Plugins: Add custom tools
  • Provider Plugins: Add LLM/embedding/search providers
  • Command Plugins: Add slash commands
  • Hook Plugins: Add lifecycle hooks

Example Plugin

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'; }
    });
  }
};

Bundled Skills (40)

Code Buddy includes 40 built-in SKILL.md files that provide domain-specific knowledge, best practices, and MCP server integration for popular software. 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.

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
- Voice: Wake Word, TTS Providers, Voice Control Loop
- UI: ChatHistory, ChatInterface, TabbedQuestion

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

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 *"]
  }
}

Roadmap

Planned Features

FeaturePriorityStatus
Daemon Mode (background agent)HIGHβœ… Done
Task Planner (DAG decomposition)HIGHβœ… Done
Screen Observer & TriggersHIGHβœ… Done
Proactive Agent (push notifications)HIGHβœ… Done
Multi-Agent OrchestratorHIGHβœ… Done
Self-Healing & Checkpoint RollbackHIGHβœ… Done
Canvas A2UI Visual WorkspaceHIGHβœ… Done
ClawHub Skills RegistryMEDIUMβœ… Done
Web Search 5-Provider ChainHIGHβœ… Done
Apply Patch & Bash ParserHIGHβœ… Done
Per-Model Tool ConfigMEDIUMβœ… Done
Voice Wake Word DetectionMEDIUMβœ… Done
TTS Providers (OpenAI, ElevenLabs, AudioReader)MEDIUMβœ… Done
Code Generation Security (Phase 7)HIGHβœ… Done
Auto-Sandbox RouterHIGHβœ… Done
Semantic Output TruncationMEDIUMβœ… Done
Gateway WebSocket Control PlaneHIGHπŸ”² Planned
OAuth AuthenticationMEDIUMπŸ”² Planned
Companion Apps (iOS, Android, macOS)LOWπŸ”² Planned
Tailscale IntegrationLOWπŸ”² Planned

Troubleshooting

Common Issues

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

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

Keywords

cli

FAQs

Package last updated on 17 Feb 2026

Related posts