Skip to content

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)
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 --> OPENROUTER
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 types
LayerTechnologyVersionPurpose
RuntimeBun≥1.3.5Package manager, bundler, test runner
LanguageTypeScript5.5.4Type-safe development
CLI FrameworkOpenTUI + React0.1.74 / 19.0Terminal UI rendering
CLI ParserCommander.js14.0Argument parsing
StateZustand5.0.8CLI state management
Web FrameworkNext.jsLatestWeb application
DatabasePostgreSQL-Primary data store
ORMDrizzleLatestType-safe database access
AuthNextAuth4.24Authentication
PaymentsStripe16.11Billing & subscriptions
AI SDKVercel AI SDK5.0LLM provider abstraction
LLM ProviderOpenRouter-Multi-model routing
MCP@modelcontextprotocol/sdk1.18Tool protocol
AnalyticsPostHog5.8Product analytics
ValidationZod4.2Runtime schema validation
Code Analysistree-sitter0.25AST parsing (SDK)
SandboxQuickJS (WASM)0.31Sandboxed JS execution (SDK)

Codebuff provides 33 tools that agents can use:

CategoryToolsDescription
File Operationsread_files, write_file, str_replace, apply_patch, find_files, glob, list_directory, read_subtreeRead, write, search, and navigate files
Code Intelligencecode_search, read_docs, web_searchSemantic code search, documentation lookup, web search
Terminalrun_terminal_command, browser_logsExecute shell commands, capture browser output
Agent Controlspawn_agents, spawn_agent_inline, end_turn, task_completedMulti-agent orchestration and lifecycle
Planningcreate_plan, add_subgoal, update_subgoal, write_todos, think_deeplyStructured reasoning and planning
Communicationask_user, add_message, set_messages, suggest_followupsUser interaction and messaging
Reviewpropose_str_replace, propose_write_file, run_file_change_hooksCode review and validation
Miscskill, lookup_agent_info, set_outputSkill system, agent registry, output management

(common/src/tools/list.ts)

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
AgentFilePurposeKey Capability
Base2agents/base2/base2.tsPrimary orchestratorRoutes tasks to sub-agents
Base2 Maxagents/base2/base2-max.tsHigh-capability modeUses most powerful model
Base2 Freeagents/base2/base2-free.tsFree tier modeCost-optimized
Base2 Planagents/base2/base2-plan.tsPlanning modeArchitecture planning
Editoragents/editor/Code editingPrecise file modifications
File Exploreragents/file-explorer/File system scanProject structure understanding
Revieweragents/reviewer/Code reviewValidates changes
Thinkeragents/thinker/Deep reasoningComplex problem solving
Researcheragents/researcher/ResearchDocumentation and web search
Commanderagents/commander.tsOrchestrationAgent spawning and coordination

(agents/base2/base2.ts, agents/commander.ts)

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"
TablePurposeKey Columns
userUser accountsid, email, handle, stripe_customer_id, referral_code, banned
accountOAuth accounts (NextAuth)userId, provider, providerAccountId, access_token
sessionAuth sessionssessionToken, userId, type (web/pat/cli)
messageLLM API call logsmodel, request, response, input_tokens, output_tokens, cost, credits
creditLedgerCredit transactionsuser_id, principal, balance, type, priority, expires_at
subscriptionStripe subscriptionsstripe_subscription_id, user_id, tier, status, billing_period
orgOrganizationsname, slug, owner_id, stripe_customer_id, credit_limit
orgMemberOrg membershipsorg_id, user_id, role (owner/admin/member)
orgInviteOrg invitationsemail, role, token, expires_at
orgRepoTracked repositoriesorg_id, repo_url, repo_name, is_active
orgFeatureFeature flagsorg_id, feature, config, is_active
agentRunAgent execution logsagent_id, status, ancestor_run_ids, total_credits
agentStepIndividual agent stepsagent_run_id, step_number, credits, child_run_ids
agentConfigPublished agent configspublisher_id, version, data (agent definition)
publisherAgent Store publishersid, name, user_id or org_id, verified
referralReferral trackingreferrer_id, referred_id, status, credits
adImpressionAd trackinguser_id, ad_text, payout, credits_granted
limitOverrideRate limit overridesuser_id, credits_per_block, block_duration_hours

(packages/internal/src/db/schema.ts)

Framework: Next.js App Router

Route GroupPathDescription
Home/Landing page
Auth/loginLogin 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-serviceLegal pages

(web/src/app/)

VariableCategoryPurpose
OPEN_ROUTER_API_KEYAIOpenRouter multi-model API
OPENAI_API_KEYAIOpenAI direct access
ANTHROPIC_API_KEYAIAnthropic direct access
DATABASE_URLDatabasePostgreSQL connection
CODEBUFF_GITHUB_ID/SECRETAuthGitHub OAuth
NEXTAUTH_SECRETAuthSession encryption
STRIPE_SECRET_KEYBillingStripe payments
STRIPE_WEBHOOK_SECRET_KEYBillingStripe webhooks
NEXT_PUBLIC_POSTHOG_API_KEYAnalyticsPostHog tracking
DISCORD_BOT_TOKENIntegrationDiscord bot
LOOPS_API_KEYEmailEmail automation
LINKUP_API_KEYExternalExternal service

(.env.example)

CategoryPackageVersionPurpose
AI/LLMai (Vercel AI SDK)5.0.52LLM provider abstraction
AI/LLM@ai-sdk/anthropic2.0.50Anthropic integration
AI/LLM@modelcontextprotocol/sdk1.18.2MCP protocol support
Codeweb-tree-sitter0.25.6AST parsing
Code@jitl/quickjs-wasmfile-release-sync0.31.0Sandboxed JS execution
DBdrizzle-ormLatestType-safe ORM
DBpg8.14PostgreSQL driver
Authnext-auth4.24Authentication framework
Billingstripe16.11Payment processing
UI (CLI)@opentui/core + @opentui/react0.1.74Terminal rendering
UI (CLI)commander14.0CLI argument parsing
UI (CLI)zustand5.0.8State management
UI (CLI)react19.0Component rendering
UI (Web)@tanstack/react-query5.90Server state management
Validationzod4.2Schema validation
Analyticsposthog-node5.8Product analytics
WorkspaceFrameworkTest LocationTest Files
cliBun Testcli/src/__tests__/28 files
commonBun Testcommon/src/__tests__/6 files
sdkBun Testsdk/test/, sdk/e2e/48+ files
agent-runtimeBun Testpackages/agent-runtime/src/__tests__/24 files
webJest + Playwrightweb/test/, web/src/__tests__/7+ files
agentsBun Testagents/__tests__/7 files

Test Commands:

  • bun test — Run all workspace tests
  • cd cli && bun test — CLI tests only
  • cd sdk && bun test:e2e — SDK e2e tests
  • cd web && npx playwright test — Web e2e tests
FileRoleSize
cli/src/index.tsxCLI entry point359 lines
cli/src/chat.tsxMain chat interface~50KB
cli/src/commands/router.tsCommand routing~15KB
agents/base2/base2.tsPrimary agent definition~26KB
agents/context-pruner.tsContext window management~37KB
packages/agent-runtime/src/run-agent-step.tsAgent step execution~29KB
packages/agent-runtime/src/tools/tool-executor.tsTool execution engine~19KB
packages/internal/src/db/schema.tsDatabase schema (18 tables)797 lines
sdk/src/run.tsSDK run engine~23KB
sdk/src/run-state.tsSDK state machine~22KB
sdk/src/client.tsPublic SDK client~5KB
common/src/tools/list.tsTool registry (33 tools)157 lines