Codebase Analysis
Codebase Analysis
Section titled “Codebase Analysis”Quick Reference
- Project: Codebuff
- Type: Open-source AI Coding Assistant (CLI + SDK + Web Platform)
- Languages: TypeScript (100%)
- Runtime: Bun ≥1.3.5 (CLI/Backend), Node.js ≥18 (SDK)
- Frameworks: React 19 + Ink (CLI TUI), Next.js (Web), Drizzle ORM (DB)
- Repository: Bun monorepo with 8 workspaces
- License: Apache-2.0
- Lines of Code: ~50,000+ (estimated across all workspaces)
Architecture Overview
Section titled “Architecture Overview”graph TB subgraph CLI["🖥️ CLI (Terminal UI)"] TUI["Ink/React TUI"] CMD["Commander.js"] ZUS["Zustand State"] end
subgraph SDK["📦 SDK (@codebuff/sdk)"] CLIENT["CodebuffClient"] RUN["Run Engine"] TOOLS_SDK["Tool System"] end
subgraph AgentRuntime["⚙️ Agent Runtime"] STEP["Step Runner"] LLM["LLM API Layer"] STREAM["Stream Parser"] TOOLEXEC["Tool Executor"] MCP["MCP Integration"] end
subgraph Agents["🤖 Agents"] BASE["Base2 Agent"] EDITOR["Editor Agent"] FEXPLORE["File Explorer"] REVIEWER["Reviewer"] THINKER["Thinker"] RESEARCHER["Researcher"] end
subgraph Common["📚 Common"] TOOL_DEFS["Tool Definitions (33)"] TYPES["Shared Types"] SCHEMAS["Zod Schemas"] end
subgraph Web["🌐 Web (Next.js)"] PAGES["App Router Pages"] API["API Routes"] COMPONENTS["React Components"] end
subgraph Internal["🗄️ Internal"] DB["PostgreSQL (Drizzle)"] AUTH["NextAuth"] OPENROUTER["OpenRouter Provider"] BILLING["Stripe Billing"] end
TUI --> SDK SDK --> AgentRuntime AgentRuntime --> Agents AgentRuntime --> Common Web --> API API --> Internal Internal --> DB AgentRuntime --> LLM LLM --> OPENROUTERDirectory Structure
Section titled “Directory Structure”codebuff-main/├── cli/ # Terminal UI application│ ├── src/│ │ ├── index.tsx # Entry point (Commander + OpenTUI)│ │ ├── app.tsx # Root React component│ │ ├── chat.tsx # Main chat interface (~50KB)│ │ ├── commands/ # CLI commands (init, publish, help, image, referral)│ │ ├── components/ # 116 Ink/React components│ │ ├── hooks/ # 69 React hooks│ │ ├── state/ # Zustand state management│ │ ├── utils/ # 120 utility modules│ │ └── login/ # Authentication flow│ └── package.json # @codebuff/cli│├── common/ # Shared library│ └── src/│ ├── tools/ # 33 tool definitions + params│ ├── types/ # Message types, content parts, grants│ ├── constants/ # Analytics events, configuration│ ├── templates/ # Agent templates│ ├── testing/ # Test utilities│ └── util/ # File handling, parsing utilities│├── packages/│ ├── agent-runtime/ # Agent execution engine│ │ └── src/│ │ ├── run-agent-step.ts # Core step execution (~29KB)│ │ ├── tools/ # 39 tool handlers│ │ ├── llm-api/ # LLM provider abstraction│ │ ├── system-prompt/ # System prompt generation│ │ └── templates/ # Response templates│ ││ ├── internal/ # Backend services│ │ └── src/│ │ ├── db/ # Database layer (Drizzle ORM)│ │ │ ├── schema.ts # 18 tables (~797 lines)│ │ │ ├── migrations/ # 85 migration files│ │ │ └── transaction.ts # Transaction management│ │ ├── openrouter-ai-sdk/ # OpenRouter provider (27 files)│ │ ├── openai-compatible/ # OpenAI-compatible provider│ │ └── loops/ # Email automation│ ││ ├── billing/ # Stripe billing integration│ ├── code-map/ # Code analysis & mapping│ ├── bigquery/ # Analytics pipeline│ └── build-tools/ # Build utilities│├── sdk/ # Published npm SDK│ └── src/│ ├── index.ts # Public exports│ ├── client.ts # CodebuffClient class│ ├── run.ts # Run engine (~23KB)│ ├── run-state.ts # State machine (~22KB)│ ├── credentials.ts # Auth credential handling│ ├── tools/ # 9 built-in tools│ └── impl/ # Implementation details│├── agents/ # Agent definitions│ ├── base2/ # Primary coding agent (10 variants)│ ├── editor/ # Code editing specialist│ ├── file-explorer/ # File system navigation│ ├── reviewer/ # Code review agent│ ├── thinker/ # Deep reasoning agent│ ├── researcher/ # Research agent│ └── commander.ts # Agent orchestration│├── web/ # Next.js web application│ └── src/│ ├── app/ # App Router (20 route groups)│ │ ├── api/ # 124 API route files│ │ ├── admin/ # Admin dashboard│ │ ├── store/ # Agent Store│ │ ├── orgs/ # Organization management│ │ ├── profile/ # User profile│ │ ├── publishers/ # Publisher management│ │ └── pricing/ # Pricing page│ ├── components/ # 129 React components│ └── lib/ # 25 library modules│├── evals/ # Evaluation framework├── scripts/ # Dev and CI scripts└── .agents/ # User-facing agent typesTech Stack
Section titled “Tech Stack”| Layer | Technology | Version | Purpose |
|---|---|---|---|
| Runtime | Bun | ≥1.3.5 | Package manager, bundler, test runner |
| Language | TypeScript | 5.5.4 | Type-safe development |
| CLI Framework | OpenTUI + React | 0.1.74 / 19.0 | Terminal UI rendering |
| CLI Parser | Commander.js | 14.0 | Argument parsing |
| State | Zustand | 5.0.8 | CLI state management |
| Web Framework | Next.js | Latest | Web application |
| Database | PostgreSQL | - | Primary data store |
| ORM | Drizzle | Latest | Type-safe database access |
| Auth | NextAuth | 4.24 | Authentication |
| Payments | Stripe | 16.11 | Billing & subscriptions |
| AI SDK | Vercel AI SDK | 5.0 | LLM provider abstraction |
| LLM Provider | OpenRouter | - | Multi-model routing |
| MCP | @modelcontextprotocol/sdk | 1.18 | Tool protocol |
| Analytics | PostHog | 5.8 | Product analytics |
| Validation | Zod | 4.2 | Runtime schema validation |
| Code Analysis | tree-sitter | 0.25 | AST parsing (SDK) |
| Sandbox | QuickJS (WASM) | 0.31 | Sandboxed JS execution (SDK) |
Tools System
Section titled “Tools System”Codebuff provides 33 tools that agents can use:
| Category | Tools | Description |
|---|---|---|
| File Operations | read_files, write_file, str_replace, apply_patch, find_files, glob, list_directory, read_subtree | Read, write, search, and navigate files |
| Code Intelligence | code_search, read_docs, web_search | Semantic code search, documentation lookup, web search |
| Terminal | run_terminal_command, browser_logs | Execute shell commands, capture browser output |
| Agent Control | spawn_agents, spawn_agent_inline, end_turn, task_completed | Multi-agent orchestration and lifecycle |
| Planning | create_plan, add_subgoal, update_subgoal, write_todos, think_deeply | Structured reasoning and planning |
| Communication | ask_user, add_message, set_messages, suggest_followups | User interaction and messaging |
| Review | propose_str_replace, propose_write_file, run_file_change_hooks | Code review and validation |
| Misc | skill, lookup_agent_info, set_output | Skill system, agent registry, output management |
(common/src/tools/list.ts)
Agent Architecture
Section titled “Agent Architecture”Codebuff uses a multi-agent system where specialized agents collaborate:
graph TB User["👤 User Prompt"] Base["🤖 Base2 Agent (Orchestrator)"] Editor["✏️ Editor Agent"] FileExplorer["📁 File Explorer"] Reviewer["🔍 Reviewer Agent"] Thinker["🧠 Thinker Agent"] Researcher["🔬 Researcher Agent"] Commander["📋 Commander"]
User --> Base Base --> Commander Commander --> Editor Commander --> FileExplorer Commander --> Reviewer Commander --> Thinker Commander --> Researcher| Agent | File | Purpose | Key Capability |
|---|---|---|---|
| Base2 | agents/base2/base2.ts | Primary orchestrator | Routes tasks to sub-agents |
| Base2 Max | agents/base2/base2-max.ts | High-capability mode | Uses most powerful model |
| Base2 Free | agents/base2/base2-free.ts | Free tier mode | Cost-optimized |
| Base2 Plan | agents/base2/base2-plan.ts | Planning mode | Architecture planning |
| Editor | agents/editor/ | Code editing | Precise file modifications |
| File Explorer | agents/file-explorer/ | File system scan | Project structure understanding |
| Reviewer | agents/reviewer/ | Code review | Validates changes |
| Thinker | agents/thinker/ | Deep reasoning | Complex problem solving |
| Researcher | agents/researcher/ | Research | Documentation and web search |
| Commander | agents/commander.ts | Orchestration | Agent spawning and coordination |
(agents/base2/base2.ts, agents/commander.ts)
Database Schema
Section titled “Database Schema”Engine: PostgreSQL with Drizzle ORM
Tables: 18 | Migrations: 85
erDiagram user ||--o{ account : "has" user ||--o{ session : "has" user ||--o{ creditLedger : "has credits" user ||--o{ subscription : "subscribes" user ||--o{ referral : "refers" user ||--o{ message : "generates" user ||--o{ agentRun : "runs" user ||--o{ adImpression : "sees ads" user ||--o{ orgMember : "belongs to" org ||--o{ orgMember : "has members" org ||--o{ orgInvite : "sends invites" org ||--o{ orgRepo : "tracks repos" org ||--o{ orgFeature : "has features" publisher ||--o{ agentConfig : "publishes" agentRun ||--o{ agentStep : "contains"Core Tables
Section titled “Core Tables”| Table | Purpose | Key Columns |
|---|---|---|
user | User accounts | id, email, handle, stripe_customer_id, referral_code, banned |
account | OAuth accounts (NextAuth) | userId, provider, providerAccountId, access_token |
session | Auth sessions | sessionToken, userId, type (web/pat/cli) |
message | LLM API call logs | model, request, response, input_tokens, output_tokens, cost, credits |
creditLedger | Credit transactions | user_id, principal, balance, type, priority, expires_at |
subscription | Stripe subscriptions | stripe_subscription_id, user_id, tier, status, billing_period |
org | Organizations | name, slug, owner_id, stripe_customer_id, credit_limit |
orgMember | Org memberships | org_id, user_id, role (owner/admin/member) |
orgInvite | Org invitations | email, role, token, expires_at |
orgRepo | Tracked repositories | org_id, repo_url, repo_name, is_active |
orgFeature | Feature flags | org_id, feature, config, is_active |
agentRun | Agent execution logs | agent_id, status, ancestor_run_ids, total_credits |
agentStep | Individual agent steps | agent_run_id, step_number, credits, child_run_ids |
agentConfig | Published agent configs | publisher_id, version, data (agent definition) |
publisher | Agent Store publishers | id, name, user_id or org_id, verified |
referral | Referral tracking | referrer_id, referred_id, status, credits |
adImpression | Ad tracking | user_id, ad_text, payout, credits_granted |
limitOverride | Rate limit overrides | user_id, credits_per_block, block_duration_hours |
(packages/internal/src/db/schema.ts)
Web Application Routes
Section titled “Web Application Routes”Framework: Next.js App Router
| Route Group | Path | Description |
|---|---|---|
| Home | / | Landing page |
| Auth | /login | Login page |
| Admin | /admin/* | Admin dashboard (14 sub-routes) |
| API | /api/* | REST API (124 route files) |
| Store | /store/* | Agent Store marketplace |
| Orgs | /orgs/* | Organization management |
| Profile | /profile/* | User profile & settings |
| Publishers | /publishers/* | Publisher dashboard |
| Pricing | /pricing/* | Subscription plans |
| Docs | /docs/* | Documentation |
| Evals | /evals/* | Evaluation dashboard |
| Affiliates | /affiliates/* | Affiliate program |
| Onboard | /onboard/* | User onboarding |
| Referrals | /referrals/* | Referral program |
| Legal | /privacy-policy, /terms-of-service | Legal pages |
(web/src/app/)
Environment Configuration
Section titled “Environment Configuration”| Variable | Category | Purpose |
|---|---|---|
OPEN_ROUTER_API_KEY | AI | OpenRouter multi-model API |
OPENAI_API_KEY | AI | OpenAI direct access |
ANTHROPIC_API_KEY | AI | Anthropic direct access |
DATABASE_URL | Database | PostgreSQL connection |
CODEBUFF_GITHUB_ID/SECRET | Auth | GitHub OAuth |
NEXTAUTH_SECRET | Auth | Session encryption |
STRIPE_SECRET_KEY | Billing | Stripe payments |
STRIPE_WEBHOOK_SECRET_KEY | Billing | Stripe webhooks |
NEXT_PUBLIC_POSTHOG_API_KEY | Analytics | PostHog tracking |
DISCORD_BOT_TOKEN | Integration | Discord bot |
LOOPS_API_KEY | Email automation | |
LINKUP_API_KEY | External | External service |
(.env.example)
Dependencies Overview
Section titled “Dependencies Overview”| Category | Package | Version | Purpose |
|---|---|---|---|
| AI/LLM | ai (Vercel AI SDK) | 5.0.52 | LLM provider abstraction |
| AI/LLM | @ai-sdk/anthropic | 2.0.50 | Anthropic integration |
| AI/LLM | @modelcontextprotocol/sdk | 1.18.2 | MCP protocol support |
| Code | web-tree-sitter | 0.25.6 | AST parsing |
| Code | @jitl/quickjs-wasmfile-release-sync | 0.31.0 | Sandboxed JS execution |
| DB | drizzle-orm | Latest | Type-safe ORM |
| DB | pg | 8.14 | PostgreSQL driver |
| Auth | next-auth | 4.24 | Authentication framework |
| Billing | stripe | 16.11 | Payment processing |
| UI (CLI) | @opentui/core + @opentui/react | 0.1.74 | Terminal rendering |
| UI (CLI) | commander | 14.0 | CLI argument parsing |
| UI (CLI) | zustand | 5.0.8 | State management |
| UI (CLI) | react | 19.0 | Component rendering |
| UI (Web) | @tanstack/react-query | 5.90 | Server state management |
| Validation | zod | 4.2 | Schema validation |
| Analytics | posthog-node | 5.8 | Product analytics |
Test Coverage
Section titled “Test Coverage”| Workspace | Framework | Test Location | Test Files |
|---|---|---|---|
cli | Bun Test | cli/src/__tests__/ | 28 files |
common | Bun Test | common/src/__tests__/ | 6 files |
sdk | Bun Test | sdk/test/, sdk/e2e/ | 48+ files |
agent-runtime | Bun Test | packages/agent-runtime/src/__tests__/ | 24 files |
web | Jest + Playwright | web/test/, web/src/__tests__/ | 7+ files |
agents | Bun Test | agents/__tests__/ | 7 files |
Test Commands:
bun test— Run all workspace testscd cli && bun test— CLI tests onlycd sdk && bun test:e2e— SDK e2e testscd web && npx playwright test— Web e2e tests
Key Files
Section titled “Key Files”| File | Role | Size |
|---|---|---|
cli/src/index.tsx | CLI entry point | 359 lines |
cli/src/chat.tsx | Main chat interface | ~50KB |
cli/src/commands/router.ts | Command routing | ~15KB |
agents/base2/base2.ts | Primary agent definition | ~26KB |
agents/context-pruner.ts | Context window management | ~37KB |
packages/agent-runtime/src/run-agent-step.ts | Agent step execution | ~29KB |
packages/agent-runtime/src/tools/tool-executor.ts | Tool execution engine | ~19KB |
packages/internal/src/db/schema.ts | Database schema (18 tables) | 797 lines |
sdk/src/run.ts | SDK run engine | ~23KB |
sdk/src/run-state.ts | SDK state machine | ~22KB |
sdk/src/client.ts | Public SDK client | ~5KB |
common/src/tools/list.ts | Tool registry (33 tools) | 157 lines |
Related Pages
Section titled “Related Pages”- Architecture — System design deep-dive
- Database — Full schema documentation
- Deployment — Setup and deployment guide
- Data Flow — Data flow diagrams
- API Reference — API documentation