Skip to content

Latest commit

 

History

History
313 lines (254 loc) · 11.4 KB

File metadata and controls

313 lines (254 loc) · 11.4 KB

OpenCode Repository Structure Map

1. Project Overview

OpenCode is an open-source AI coding agent that provides intelligent assistance for software development. It's designed as a terminal-based tool with a client-server architecture, allowing AI agents to interact with codebases through various interfaces.

Key Characteristics:

  • 100% open source alternative to Claude Code
  • Provider-agnostic (supports Claude, OpenAI, Google, local models, etc.)
  • Built with terminal-first philosophy by neovim users
  • Client/server architecture supporting multiple frontends
  • Built-in LSP support and code analysis capabilities

2. Architecture

High-Level Architecture

┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   Frontends     │    │   Core Server    │    │  AI Providers   │
│                 │    │                  │    │                 │
│ • TUI (SolidJS) │◄──►│   (Hono/Bun)     │◄──►│ • Anthropic     │
│ • Desktop App   │    │                  │    │ • OpenAI        │
│ • Web Client    │    │ • Tool Registry  │    │ • Google        │
│ • VSCode Ext    │    │ • Session Mgmt   │    │ • Local Models  │
│ • GitHub Action │    │ • Agent System   │    │ • etc.          │
└─────────────────┘    └──────────────────┘    └─────────────────┘

Core Components

  • Server: Hono-based API server handling sessions, tools, and AI interactions
  • Tools: Extensible system for file operations, code analysis, web access, etc.
  • Agents: Different AI personalities with varying permissions and capabilities
  • Sessions: Persistent conversation contexts with project state management
  • Frontends: Multiple UI implementations using the same backend API

3. Package Structure

Core Packages (packages/)

opencode/ - Main CLI & Server

  • Purpose: Core business logic, CLI tool, and HTTP server
  • Key Files:
    • src/index.ts - CLI entry point with yargs command structure
    • src/server/server.ts - Main Hono server with API routes
    • src/agent/ - Agent definitions and configurations
    • src/tool/ - Tool implementations (edit, read, grep, etc.)
    • src/cli/cmd/tui/ - Terminal User Interface commands
    • bin/opencode - CLI binary entry point

app/ - Web Dashboard

  • Purpose: SolidJS-based web dashboard for OpenCode management
  • Tech: SolidJS, Vite, TailwindCSS
  • Usage: Project management, session history, configuration

desktop/ - Native Desktop App

  • Purpose: Tauri-based desktop application
  • Tech: Tauri, SolidJS, wraps the web app
  • Platforms: macOS, Windows, Linux

web/ - Documentation Site

  • Purpose: Astro-powered documentation website
  • Tech: Astro, Starlight, MDX
  • Deployment: docs.opencode.ai

console/ - Cloud Console & API

  • Structure: Monorepo with subpackages:
    • app/ - Main SolidJS console application
    • function/ - Cloudflare Workers API endpoints
    • core/ - Shared business logic
    • mail/ - Email functionality
    • resource/ - Resource management

function/ - Cloudflare Functions

  • Purpose: API endpoints for OpenCode cloud services
  • Tech: Hono, Cloudflare Workers
  • Routes: GitHub integration, authentication, etc.

sdk/js/ - TypeScript SDK

  • Purpose: Auto-generated client SDK from OpenAPI spec
  • Exports: ./client, ./server, ./v2/*
  • Usage: For frontend integrations and third-party developers

plugin/ - Plugin System

  • Purpose: Define plugin APIs and tool interfaces
  • Exports: Plugin types and tool definitions
  • Usage: For extending OpenCode with custom tools

ui/ - Shared UI Components

  • Purpose: Reusable SolidJS components
  • Tech: SolidJS, TailwindCSS
  • Usage: Shared across web and desktop apps

util/ - Shared Utilities

  • Purpose: Common TypeScript utilities and helpers
  • Exports: Error handling, types, validation schemas

enterprise/ - Enterprise Features

  • Purpose: Self-hosted enterprise deployment
  • Features: SSO, team management, private models

slack/ - Slack Integration

  • Purpose: Slack bot integration for team usage
  • Tech: Slack API, Bolt framework

script/ - Build & Dev Scripts

  • Purpose: Development automation and build tooling

SDK Packages (sdks/)

  • vscode/ - Visual Studio Code extension
    • Keyboard shortcuts: Cmd+Esc (open), Cmd+Shift+Esc (new tab)
    • Terminal integration with filepath insertion

4. Key Directories

Infrastructure (infra/)

  • app.ts - SST configuration for main API and web assets
  • console.ts - SST configuration for console app and database
  • enterprise.ts - Enterprise deployment configuration
  • stage.ts - Stage/environment settings

Build & Deploy (script/, .github/)

  • script/generate.ts - SDK generation from API specs
  • script/publish-*.ts - Package publishing automation
  • .github/workflows/ - CI/CD pipelines
  • .husky/pre-push - Pre-push hooks (type checking, bun version)

Configuration

  • sst.config.ts - SST deployment configuration
  • turbo.json - Turborepo build orchestration
  • bun.lock - Bun package manager lock file

5. Core Technologies

Runtime & Language

  • Bun 1.3+: Primary runtime, package manager, and build tool
  • TypeScript 5.8: Main development language with strict typing
  • ESM: Pure ES modules throughout

Backend

  • Hono: HTTP framework for API server
  • Cloudflare Workers: Serverless deployment platform
  • SST (Serverless Stack): Infrastructure as Code
  • Durable Objects: For WebSocket connections and sync
  • PlanetScale: Managed MySQL database
  • Stripe: Payment processing

Frontend

  • SolidJS: Reactive UI framework
  • OpenTUI: Terminal User Interface library
  • Tauri: Desktop app framework
  • Astro: Documentation site generator
  • TailwindCSS 4: CSS framework and styling

AI Integration

  • Vercel AI SDK: Unified AI provider interface
  • Multiple Providers: Anthropic, OpenAI, Google, Groq, etc.
  • MCP (Model Context Protocol): For external tool integration

Development Tools

  • Turborepo: Monorepo build system
  • Zod: Runtime validation and schema definitions
  • Tree-sitter: Syntax highlighting and code parsing
  • LSP: Language Server Protocol integration

6. Entry Points

CLI Entry Point

# Main CLI command
opencode [command] [options]

# Key commands:
opencode dev              # Start TUI in current directory
opencode serve --port 4096 # Start server mode
opencode attach http://... # Connect to remote server
opencode github run        # GitHub Action integration

Server Entry Points

  • packages/opencode/src/index.ts - CLI bootstrap
  • packages/opencode/src/server/server.ts - HTTP server
  • packages/function/src/api.ts - Cloud API functions
  • packages/console/app/src/entry.tsx - Web console

Frontend Entry Points

  • TUI: packages/opencode/src/cli/cmd/tui/
  • Desktop: packages/desktop/src-tauri/src/main.rs
  • Web: packages/app/src/index.tsx
  • VSCode: sdks/vscode/src/extension.ts

7. Key Files

Root Configuration

  • package.json - Workspace configuration and shared dependencies
  • sst.config.ts - Infrastructure deployment configuration
  • turbo.json - Monorepo build pipeline
  • bun.lock - Dependency lock file

Core Logic

  • packages/opencode/src/server/server.ts - Main API server
  • packages/opencode/src/agent/agent.ts - Agent system
  • packages/opencode/src/tool/registry.ts - Tool registry
  • packages/opencode/src/session/ - Session management

Build & Deploy

  • script/generate.ts - SDK generation from OpenAPI specs
  • script/publish-complete.ts - Package publishing pipeline
  • .github/workflows/deploy.yml - CI/CD deployment

Documentation

  • README.md - Main project documentation
  • CONTRIBUTING.md - Contribution guidelines
  • AGENTS.md - Agent development guidelines
  • STYLE_GUIDE.md - Code style conventions

8. Development Workflow

Local Development

# Install dependencies
bun install

# Start development
bun dev                # Starts TUI in packages/opencode
bun turbo typecheck    # Type checking across all packages

# Testing
bun test              # Run tests in packages/opencode
bun turbo build        # Build all packages

Build Pipeline

  1. Type Check: bun turbo typecheck across all packages
  2. Build: Individual packages with dependency resolution
  3. Generate: script/generate.ts for SDK from API specs
  4. Deploy: sst deploy to Cloudflare Workers

Code Quality

  • Pre-push hooks: Type checking and bun version validation
  • Style Guide: Minimalist approach, single-function patterns
  • Error Handling: Result patterns, avoid exceptions in tools
  • Logging: Structured logging with Log.create({ service: "name" })

Release Process

  • Version: Managed in package.json files
  • Publish: Automated through GitHub Actions
  • Distribution: npm, Homebrew, package managers, GitHub releases

9. Extension Points

Tool System

// Custom tool implementation
export const CustomTool = Tool.define({
  name: "custom_tool",
  description: "Custom functionality",
  input: z.object({ /* schema */ }),
  async execute(input, context) {
    // Tool implementation
  }
})

Agent System

// Custom agent definition
export const CustomAgent = {
  name: "custom",
  description: "Custom agent",
  permission: {
    edit: "allow",
    bash: { "default": "allow" }
  },
  tools: { /* tool permissions */ },
  prompt: "Custom system prompt"
}

Plugin System

  • Tools: Extend with custom functionality
  • Providers: Add new AI providers
  • Formatters: Add language-specific code formatting
  • LSPs: Add new language server support

Frontend Extensions

  • TUI: Extend SolidJS components in packages/opencode/src/cli/cmd/tui/
  • Web App: Add routes and components in packages/app/
  • Desktop: Extend Tauri functionality

10. Dependencies

Key Runtime Dependencies

  • AI/ML: @ai-sdk/* packages for provider abstraction
  • Web Framework: hono for API server
  • CLI: yargs for command-line interface
  • UI: @opentui/*, solid-js for terminal and web UI
  • File Operations: @parcel/watcher, chokidar, ignore
  • Code Analysis: tree-sitter, vscode-languageserver-types

Development Dependencies

  • Build Tools: vite, esbuild, typescript
  • Testing: Built-in Bun test runner
  • Linting: prettier, husky for code quality
  • Infrastructure: sst, @cloudflare/workers-types

External Services

  • Database: PlanetScale MySQL
  • Storage: Cloudflare R2 buckets
  • Authentication: GitHub OAuth, Google OAuth
  • Payment: Stripe for enterprise features
  • Monitoring: Honeycomb for log processing

This repository represents a sophisticated, production-ready AI coding assistant with a clean architecture designed for extensibility and maintainability. The modular structure allows for easy development of new features, tools, and integrations while maintaining consistency across all components.