Version: 0.3.5 Last Updated: February 2026
- System Overview
- Core Architecture
- Component Diagram
- Core Components
- Multi-Mode System
- Tool Execution Pipeline
- Context Management
- Memory System
- Plugin Architecture
- MCP Integration
- Design Patterns
- Data Flow
XibeCode is an AI-powered autonomous coding assistant built on Claude AI (Anthropic). It features a sophisticated multi-mode architecture with 13 specialized agent personas, 95+ tools, neural memory, plugin support, and Model Context Protocol (MCP) integration.
- Autonomous Operation: Executes complex multi-step tasks independently
- Multi-Mode Architecture: 13 specialized personas with distinct capabilities
- Tool-Rich Environment: 95+ tools across 8 categories
- Neural Memory: Persistent learning across sessions
- Plugin Extensibility: Dynamic tool and skill loading
- MCP Protocol: Interoperability with external context servers
- Safety-First: Built-in risk assessment and safety checks
Runtime: Node.js >= 18.0.0
Language: TypeScript 5.3+
AI Model: Claude AI (Anthropic SDK 0.32+)
UI Framework: Ink (React for CLI)
Protocol: MCP SDK 1.26+XibeCode follows a layered agent architecture with clear separation of concerns:
┌─────────────────────────────────────────────────────────┐
│ CLI Interface │
│ (Commander + Ink UI) │
└──────────────────────┬──────────────────────────────────┘
│
┌──────────────────────┴──────────────────────────────────┐
│ Enhanced Agent Core │
│ • Agent Loop • Mode Orchestration │
│ • Event System • Loop Detection │
└──────────────────────┬──────────────────────────────────┘
│
┌─────────────────┼─────────────────┐
│ │ │
┌────▼───┐ ┌─────▼─────┐ ┌─────▼──────┐
│ Tools │ │ Modes │ │ Memory │
│ (95+) │ │ (13) │ │ (Neural) │
└────┬───┘ └─────┬─────┘ └─────┬──────┘
│ │ │
┌────▼────────────────▼────────────────▼────────┐
│ External Integrations │
│ • File System • Git • Network • MCP │
└───────────────────────────────────────────────┘
- Modularity: Each component has a single, well-defined responsibility
- Extensibility: Plugins and MCP servers add capabilities dynamically
- Safety: Risk assessment at every execution boundary
- Observability: Event-driven architecture for monitoring
- Stateful Intelligence: Neural memory persists learning
┌──────────────────┐
│ index.ts │
│ (Entry Point) │
└────────┬─────────┘
│
┌─────────────┴──────────────┐
│ │
┌─────▼──────┐ ┌────────▼────────┐
│ Commands │ │ Enhanced TUI │
│ (run/chat) │ │ (UI Layer) │
└─────┬──────┘ └─────────────────┘
│
┌─────▼──────────────────────────────────────┐
│ EnhancedAgent (agent.ts) │
│ ┌──────────────────────────────────────┐ │
│ │ Main Agent Loop │ │
│ │ • Message Processing │ │
│ │ • Streaming Response Handling │ │
│ │ • Tool Execution Orchestration │ │
│ └──────────────────────────────────────┘ │
└─────┬──────────────────────────────────────┘
│
┌────────┼────────┬─────────┬─────────┬────────┐
│ │ │ │ │ │
┌────▼───┐ ┌─▼──┐ ┌───▼────┐ ┌──▼───┐ ┌──▼────┐ ┌─▼────┐
│ Modes │ │Tools│ │Context │ │Memory│ │Editor │ │Skills│
│System │ │Exec │ │Manager │ │Neural│ │ File │ │ MCP │
└────────┘ └─────┘ └────────┘ └──────┘ └───────┘ └──────┘
Purpose: Main orchestration engine for the AI agent
Responsibilities:
- Execute the agent loop (request → think → act → repeat)
- Stream responses from Claude AI
- Coordinate tool execution
- Manage conversation history
- Emit events for UI updates
- Detect and prevent infinite loops
- Handle mode transitions
Key Methods:
runAgent(): Main loop that processes taskscallClaude(): Communicate with Claude AI APIexecuteTools(): Execute requested tools with safety checksfilterThinkTags(): Remove internal reasoning from output
Event Types Emitted:
'thinking' | 'tool_call' | 'tool_result' | 'response' |
'error' | 'warning' | 'complete' | 'iteration' |
'stream_start' | 'stream_text' | 'stream_end' |
'mode_changed' | 'mode_change_requested'Purpose: Multi-persona architecture with 13 specialized agent modes
Core Types:
AgentMode = 'plan' | 'agent' | 'tester' | 'debugger' | 'security' |
'review' | 'team_leader' | 'seo' | 'product' |
'architect' | 'engineer' | 'data' | 'researcher'Mode Orchestration:
- ModeState: Tracks current mode, history, and pending requests
- ModeOrchestrator: Manages transitions between modes
- ModeTransitionPolicy: Defines allowed transitions
- Tool Permissions: Each mode has specific tool access
Mode Configuration: Each mode defines:
personaName: Friendly name (e.g., "Aria the Architect")allowedCategories: Permitted tool categoriescanModify: File modification permissionsriskTolerance: Safety profile (low/medium/high)promptSuffix: Mode-specific instructions
Purpose: 95+ tools across 8 categories for AI agent actions
Tool Categories:
- Read-Only:
read_file,grep_code,get_context - Write FS:
write_file,edit_file,create_directory - Git Read:
get_git_status,get_git_diff - Git Mutation:
git_commit,git_reset,create_git_checkpoint - Shell Command:
run_command,interactive_shell - Tests:
run_tests,get_test_results - Network:
web_search,fetch_url,http_request - Context:
grep_code,find_files,get_context
Tool Execution Flow:
Tool Request → Safety Check → Permission Check → Execute →
Result Formatting → Error Handling → Return to Agent
Tool Interface:
{
name: string;
description: string;
input_schema: JSONSchema;
execute: (input: any) => Promise<ToolResult>;
}Purpose: Intelligent file editing with multiple strategies
Editing Strategies:
-
Search/Replace (Default - Most Reliable)
- Exact string matching and replacement
- Supports multi-line edits
- Validates changes before applying
-
Line Range Editing
- Replace specific line ranges
- Useful for large files
- Preserves surrounding context
-
Verified Editing
- Post-edit content verification
- Ensures expected changes applied
- Rollback on verification failure
-
Insert Editing
- Add content without replacing
- Supports append and prepend
- No existing content matching needed
Safety Features:
- Automatic backups before edits
- Edit validation and verification
- Rollback on failure
- Diff generation for review
Purpose: Smart discovery of relevant code context
Capabilities:
- Import Detection: Analyze file dependencies
- Related File Finding: Discover connected files
- Partial File Reading: Efficient context loading
- Token Management: Stay within context limits
- Smart Ranking: Prioritize most relevant files
Context Discovery Algorithm:
1. Parse imports/requires from target file
2. Resolve relative and node_modules paths
3. Rank files by relevance (direct deps > transitive)
4. Load files within token budget
5. Include file excerpts for large filesPurpose: Persistent learning across sessions
Memory Schema:
{
patterns: Record<string, string>; // Learned patterns
solutions: Record<string, string>; // Problem solutions
preferences: Record<string, string>; // User preferences
lastUpdated: string; // Timestamp
}Memory Operations:
- Load: Read memory on agent initialization
- Update: Add new learnings during execution
- Persist: Write to
.xibecode/memory.json - Query: Retrieve relevant memories for context
Use Cases:
- Remember project conventions
- Store frequently used commands
- Track user preferences
- Learn from past errors
Purpose: Dynamic loading of external skills and workflows
Skill Sources:
- Local Skills: Project-level (
.xibecode/skills/) - User Skills: User-level (
~/.xibecode/skills/) - Marketplace: Remote skill packages
Skill Structure:
{
name: string;
description: string;
prompt: string; // Skill instructions
tools?: string[]; // Required tools
mode?: AgentMode; // Preferred mode
}Skill Execution:
Skill Invocation → Load Skill Definition → Inject Prompt →
Execute in Agent Context → Return Results
Purpose: Extend agent capabilities with custom tools
Plugin Interface:
interface Plugin {
name: string;
version: string;
tools: Tool[];
init?: () => Promise<void>;
cleanup?: () => Promise<void>;
}Plugin Lifecycle:
- Discovery: Scan plugin directories
- Loading: Import and validate plugins
- Registration: Add tools to executor
- Initialization: Run plugin setup
- Cleanup: Shutdown on exit
Plugin Locations:
- Project:
.xibecode/plugins/ - User:
~/.xibecode/plugins/ - System:
/usr/local/share/xibecode/plugins/
Purpose: Model Context Protocol integration
MCP Features:
- Connect to external context servers
- Discover server-provided tools
- Execute remote tool calls
- Aggregate results into agent context
MCP Server Connection:
{
type: 'stdio' | 'sse' | 'websocket';
command?: string; // For stdio
url?: string; // For sse/websocket
env?: Record<string, string>;
}Supported MCP Servers:
- File system servers
- Database query servers
- API integration servers
- Documentation servers
- Custom domain-specific servers
Purpose: Risk assessment for agent operations
Risk Levels:
- Low: Read-only operations
- Medium: File modifications, reversible changes
- High: Git operations, deletions, system commands
Safety Checks:
- Command Validation: Block dangerous commands (
rm -rf /) - Path Validation: Prevent writes outside project
- Confirmation Required: High-risk operations need approval
- Dry-Run Mode: Preview changes without executing
Blocked Patterns:
- Recursive deletion of root
- System file modification
- Network attacks
- Data exfiltrationXibeCode uses a persona-based mode system where each mode represents a specialized agent with distinct capabilities, permissions, and personality.
| Mode | Persona | Role | Capabilities |
|---|---|---|---|
plan |
Aria | Architect | Read-only analysis, planning |
agent |
Blaze | Builder | Full coding capabilities |
tester |
Tess | QA Engineer | Test writing and execution |
debugger |
Dex | Detective | Bug investigation and fixing |
security |
Sentinel | Guardian | Security audits and hardening |
review |
Nova | Critic | Code review and quality checks |
team_leader |
Arya | Leader | Task delegation and orchestration |
seo |
Siri | Optimizer | SEO analysis and optimization |
product |
Agni | Strategist | Product strategy and roadmap |
architect |
Anna | Designer | System architecture design |
engineer |
Alex | Implementer | Feature implementation |
data |
David | Analyst | Data analysis and insights |
researcher |
Sanvi | Scholar | Deep research and investigation |
Transition Triggers:
- Explicit Request:
@mode:testerin user input - Task Completion: Agent requests mode change after finishing
- Error Recovery: Fallback to safer mode on errors
- Orchestration: Team leader delegates to specialized modes
Transition Flow:
Current Mode → Parse Request → Validate Transition →
Update State → Load New Persona → Continue Execution
Transition Policies:
- Automatic: Low-risk transitions (plan → agent)
- Confirmation Required: High-risk transitions (agent → security)
- Blocked: Transitions that violate security (plan → git_mutation)
Modes inherit and extend base capabilities:
Base Agent (Core Tools)
├─ Read-Only Modes (plan, researcher)
├─ Write Modes (agent, engineer, architect)
├─ Specialized Analysis (security, review, seo, data)
└─ Orchestration (team_leader, product)
┌─────────────────────────────────────────────────────┐
│ 1. Agent requests tool execution │
└──────────────┬──────────────────────────────────────┘
│
┌──────────────▼──────────────────────────────────────┐
│ 2. Loop Detection Check │
│ - Check for repeated tool calls │
│ - Prevent infinite loops │
└──────────────┬──────────────────────────────────────┘
│
┌──────────────▼──────────────────────────────────────┐
│ 3. Mode Permission Check │
│ - Verify tool category allowed in current mode │
│ - Block unauthorized tool access │
└──────────────┬──────────────────────────────────────┘
│
┌──────────────▼──────────────────────────────────────┐
│ 4. Safety Assessment │
│ - Analyze operation risk level │
│ - Check for dangerous patterns │
└──────────────┬──────────────────────────────────────┘
│
┌──────────────▼──────────────────────────────────────┐
│ 5. User Confirmation (if required) │
│ - High-risk operations need approval │
│ - Show preview of operation │
└──────────────┬──────────────────────────────────────┘
│
┌──────────────▼──────────────────────────────────────┐
│ 6. Tool Execution │
│ - Execute tool with validated input │
│ - Capture output and errors │
└──────────────┬──────────────────────────────────────┘
│
┌──────────────▼──────────────────────────────────────┐
│ 7. Result Formatting │
│ - Structure output for agent consumption │
│ - Include metadata and context │
└──────────────┬──────────────────────────────────────┘
│
┌──────────────▼──────────────────────────────────────┐
│ 8. Event Emission │
│ - Emit tool_call and tool_result events │
│ - Update UI with progress │
└──────────────┬──────────────────────────────────────┘
│
▼
Return to Agent
{
success: boolean;
output?: string;
error?: string;
metadata?: {
duration: number;
linesAffected?: number;
filesChanged?: string[];
...
}
}XibeCode intelligently discovers relevant code context to provide the agent with necessary information while staying within token limits.
-
Primary File Analysis
- Read requested file
- Parse imports and dependencies
- Identify referenced modules
-
Dependency Resolution
- Resolve relative imports
- Resolve node_modules packages
- Find local project dependencies
-
Relevance Ranking
- Direct dependencies: High priority
- Transitive dependencies: Medium priority
- Sibling files: Lower priority
-
Token Budget Management
- Allocate tokens to most relevant files
- Include partial content for large files
- Summarize less critical files
-
Context Assembly
- Combine primary file + dependencies
- Add file paths and line numbers
- Format for agent consumption
Strategies:
- Partial File Loading: Read only relevant sections
- Summarization: Condense large files
- Caching: Reuse previously loaded context
- Lazy Loading: Load context on-demand
XibeCode implements a persistent learning system that remembers patterns, solutions, and preferences across sessions.
.xibecode/
└── memory.json
├── patterns: {} # Learned code patterns
├── solutions: {} # Problem → Solution mappings
├── preferences: {} # User preferences
├── commands: {} # Frequently used commands
└── lastUpdated: "" # ISO timestamp
-
Pattern Memory
- Code style conventions
- Project structure patterns
- Naming conventions
-
Solution Memory
- Error → Fix mappings
- Problem → Solution strategies
- Test → Implementation patterns
-
Preference Memory
- User's coding style
- Preferred tools
- Workflow preferences
-
Command Memory
- Frequently used commands
- Custom workflows
- Aliases and shortcuts
Agent Start → Load Memory → Execute Task →
Learn from Execution → Update Memory → Persist to Disk
Memory is injected into the agent's system prompt:
You are XibeCode, an AI coding assistant.
## Learned Patterns
{patterns from memory}
## Known Solutions
{solutions from memory}
## User Preferences
{preferences from memory}
XibeCode supports dynamic plugin loading to extend agent capabilities without modifying core code.
// my-plugin.js
export default {
name: 'my-plugin',
version: '1.0.0',
// Tools provided by this plugin
tools: [
{
name: 'my_custom_tool',
description: 'Does something useful',
input_schema: { /* JSON Schema */ },
execute: async (input) => {
// Tool implementation
return { success: true, output: 'Result' };
}
}
],
// Optional lifecycle hooks
init: async () => {
// Initialize plugin resources
},
cleanup: async () => {
// Cleanup on shutdown
}
};- Scan plugin directories
- Load plugin modules
- Validate plugin interface
- Register tools with executor
- Run initialization hooks
- Sandboxing: Plugins run in isolated contexts
- Error Handling: Plugin errors don't crash agent
- Resource Limits: Prevent resource exhaustion
- Permission Model: Plugins declare required capabilities
XibeCode implements the Model Context Protocol to interoperate with external context servers.
┌─────────────────┐ ┌──────────────────┐
│ XibeCode │ │ MCP Server │
│ (MCP Client) │ ◄──────► │ (External) │
└─────────────────┘ └──────────────────┘
│ │
│ 1. List Tools │
│ ─────────────────────────► │
│ │
│ 2. Tool Schemas │
│ ◄───────────────────────── │
│ │
│ 3. Execute Tool │
│ ─────────────────────────► │
│ │
│ 4. Tool Result │
│ ◄───────────────────────── │
- File System Servers: Provide file access
- Database Servers: Query databases
- API Servers: Integrate external APIs
- Documentation Servers: Access docs
- Custom Servers: Domain-specific tools
{
"mcpServers": {
"filesystem": {
"type": "stdio",
"command": "mcp-server-filesystem",
"args": ["/path/to/workspace"]
},
"postgres": {
"type": "sse",
"url": "http://localhost:3000/sse"
}
}
}Continuous cycle of reasoning and action:
Perceive (read context) → Think (Claude AI) →
Act (execute tools) → Observe (results) → Repeat
All major actions emit events for observability:
agent.on('tool_call', (data) => { /* Update UI */ });
agent.on('error', (error) => { /* Handle error */ });Multiple editing strategies selected at runtime:
const strategy = selectEditStrategy(editType);
await strategy.apply(file, changes);Tool execution passes through multiple validators:
Request → Loop Detector → Permission Check →
Safety Check → Executor → Result Handler
Simple public API hiding complex internals:
const agent = new EnhancedAgent(config);
await agent.runAgent('Build a login page');UI components observe agent events:
agent.on('stream_text', (text) => updateDisplay(text));Dynamic loading of extensions:
const plugins = await loadPlugins();
plugins.forEach(p => registerTools(p.tools));┌─────────────────────────────────────────────────────┐
│ 1. User Input (CLI or Chat) │
└──────────────┬──────────────────────────────────────┘
│
┌──────────────▼──────────────────────────────────────┐
│ 2. Command Parsing │
│ - Extract mode hints (@mode:X) │
│ - Parse task description │
└──────────────┬──────────────────────────────────────┘
│
┌──────────────▼──────────────────────────────────────┐
│ 3. Agent Initialization │
│ - Load configuration │
│ - Load memory │
│ - Set initial mode │
│ - Load plugins/MCP tools │
└──────────────┬──────────────────────────────────────┘
│
┌──────────────▼──────────────────────────────────────┐
│ 4. Agent Loop Start │
│ Iteration 1...N (max 50) │
└──────────────┬──────────────────────────────────────┘
│
┌──────────────▼──────────────────────────────────────┐
│ 5. Call Claude AI │
│ - Send conversation history │
│ - Include available tools │
│ - Stream response │
└──────────────┬──────────────────────────────────────┘
│
┌───────┴───────┐
│ │
┌──────▼──────┐ ┌─────▼────────┐
│ 6a. Text │ │ 6b. Tool │
│ Response │ │ Request │
└──────┬──────┘ └─────┬────────┘
│ │
│ ┌─────▼──────────────────────────┐
│ │ 7. Execute Tools │
│ │ - Validate permissions │
│ │ - Run safety checks │
│ │ - Execute tool │
│ │ - Format results │
│ └─────┬──────────────────────────┘
│ │
│ ┌─────▼──────────────────────────┐
│ │ 8. Add Results to History │
│ └─────┬──────────────────────────┘
│ │
└───────┬───────┘
│
┌──────────────▼──────────────────────────────────────┐
│ 9. Check Completion │
│ - Task complete? │
│ - Max iterations reached? │
│ - Mode transition requested? │
└──────────────┬──────────────────────────────────────┘
│
┌───────┴───────┐
│ │
┌──────▼──────┐ ┌─────▼────────┐
│ 10a. Loop │ │ 10b. Complete│
│ Continue │ │ │
└──────┬──────┘ └─────┬────────┘
│ │
└───────┬───────┘
│
┌──────────────▼──────────────────────────────────────┐
│ 11. Update Memory │
│ - Store learnings │
│ - Save preferences │
└──────────────┬──────────────────────────────────────┘
│
┌──────────────▼──────────────────────────────────────┐
│ 12. Return Results to User │
└─────────────────────────────────────────────────────┘
- Cold Start: 1-3 seconds (load plugins, memory, config)
- API Call: 2-10 seconds (depends on Claude AI response)
- Tool Execution: 10ms - 5 seconds (varies by tool)
- File Operations: 1-100ms (depends on file size)
- Conversation Length: Supports 100+ message history
- Token Budget: 200K tokens for context window
- Tool Count: 95+ built-in, unlimited via plugins
- Plugin Count: No hard limit, practical limit ~50
- Memory: 50-200 MB typical
- CPU: Low (mostly I/O bound)
- Disk: Minimal (memory + logs)
- Network: API calls to Claude AI
- Malicious Tool Execution: Agent executes harmful commands
- Data Exfiltration: Agent leaks sensitive data
- Privilege Escalation: Agent gains unauthorized access
- Resource Exhaustion: Infinite loops or excessive API calls
- Safety Checker: Validates all commands before execution
- Permission Model: Mode-based tool access restrictions
- Confirmation Required: High-risk operations need approval
- Loop Detection: Prevents infinite loops
- Dry-Run Mode: Preview changes without executing
- Sandboxing: Plugins run in isolated contexts
- API Rate Limiting: Prevent excessive API usage
- Audit Logging: Track all operations
- Unit Tests: Individual component testing
- Integration Tests: Component interaction testing
- E2E Tests: Full workflow testing
- Safety Tests: Verify safety checks work
test/
├── unit/
│ ├── agent.test.ts
│ ├── modes.test.ts
│ ├── tools.test.ts
│ └── editor.test.ts
├── integration/
│ ├── plugin-loading.test.ts
│ ├── mcp-integration.test.ts
│ └── mode-transitions.test.ts
└── e2e/
├── build-feature.test.ts
├── fix-bug.test.ts
└── refactor-code.test.ts
- Multi-Agent Collaboration: Multiple agents working together
- Continuous Learning: Improved memory and adaptation
- Advanced Planning: Multi-step plan generation and execution
- Version Control Integration: Deeper git integration
- Testing Intelligence: Auto-generate comprehensive tests
- Performance Profiling: Built-in profiler integration
- Visual Debugging: Interactive debugging UI
- Cloud Sync: Sync memory and preferences across devices
- Reasoning Transparency: Better explanations of agent decisions
- Error Recovery: More sophisticated error handling
- Context Optimization: Better context selection algorithms
- Tool Synthesis: Generate tools on-the-fly
- Human-in-the-Loop: Better user interaction patterns
- API Reference
- Contributing Guide
- Coding Standards
- Tool Documentation
- Mode Documentation
- Plugin Development
Document Version: 1.0 Last Updated: February 14, 2026 Maintainer: XibeCode Team