Cloudflare VibeSDK

repository·main·Indexed 26 days ago

https://github.com/cloudflare/vibesdk

An open-source full-stack AI webapp generator that builds applications from natural language descriptions, previews them in sandboxed containers, and deploys them to Cloudflare Workers. Includes the @cf-vibesdk/sdk TypeScript library featuring PhasicClient, VibeClient, and AgenticClient for programmatic app generation and session management.

Tokens
49K
Snippets
113
Records
227
Agent score
90%

What's inside VibeSDK

  1. Overview of the Sandbox System

    main
    Sandboxes are ephemeral containers used to run user-generated applications in isolation. They are managed by a remote sandbox service and communicate via an HTTP API using bearer token authentication. Sandboxes are created on-demand and are destroyed automatically after a period of inactivity.
  2. Understand the Cloudflare Orange Build System Architecture

    main

    The Cloudflare Orange Build project is a multi-layered system designed for AI-powered application generation and deployment. It consists of:

    • Frontend: A React + Vite application providing a Dashboard, Real-time Chat (via WebSockets), and Live Previews.
    • API Gateway: A Hono-based router that directs requests to core services.
    • Core Services (Cloudflare Workers): Handles Authentication (JWT + OAuth), Agent Orchestration (WebSocket Management), and Sandbox Services (Container Orchestration).
    • Agent System (Durable Objects): Uses a CodeGenAgent (a deterministic state machine) to manage persistent AgentState.
    • AI Operations Pipeline: A series of specialized tasks including Blueprint Generation, Phase Planning, Implementation, Code Review, and Real-time Fixing.
    • Cloudflare Infrastructure: Utilizes D1 (Database), KV (Session/Cache), R2 (Assets/Templates), Cloudflare Containers (Sandbox Runtime), and AI Gateway (Multi-provider routing).
    • AI Providers: Routes through AI Gateway to providers like Gemini, OpenAI, Claude, and Cerebras.
  3. Use the Git System (isomorphic-git)

    main

    Vibesdk uses isomorphic-git to manage version control entirely within the browser or Worker environment, eliminating the need for a local git binary.

    Architecture

    • GitService: Provides high-level methods like commitFiles(), getCommitHistory(), and buildCloneRepository().
    • Storage: Uses a SQLite filesystem via an fs-adapter.ts. Git objects are stored as blobs and accessed via SQL queries.
    • Capabilities: Supports full commit history tracking and the Git clone protocol for generated repositories.
  4. Project Architecture and Tech Stack Overview

    main

    The vibesdk project is a full-stack application built on the Cloudflare platform. It uses a React frontend and a Cloudflare Workers backend with Durable Objects and D1 (SQLite) for data persistence.

    Tech Stack:

    • Frontend: React 18, TypeScript, Vite, TailwindCSS, React Router v7
    • Backend: Cloudflare Workers, Durable Objects, D1 (SQLite)
    • AI/LLM: OpenAI, Anthropic, Google AI Studio (Gemini)
    • WebSocket: PartySocket for real-time communication
    • Sandbox: Custom container service with CLI tools
    • Templates: Project scaffolding system with template catalog
  5. Review the Technology Stack

    main

    The Vibe SDK is built on a full-stack Cloudflare-native architecture:

    • Frontend: React 18, Vite, Tailwind CSS, shadcn/ui, and React Router.
    • Backend: Cloudflare Workers, Cloudflare Agents SDK, TypeScript, and Hono Router.
    • Data Layer: Cloudflare D1 (SQLite) with Drizzle ORM, Cloudflare KV, and Cloudflare R2.
    • AI & External: Cloudflare AI Gateway, OpenAI GPT-4, GitHub API, and OAuth providers.
    • Infrastructure: Cloudflare Containers, Cloudflare Sandbox SDK, WebSockets, and Workers Analytics.
  6. Understand the Code Generation State Machine

    main

    The code generation process follows a specific state machine defined by the CurrentDevState enum. Understanding these states is critical for managing or resuming generation tasks.

    States and Transitions

    1. IDLE: No active generation. Transition to PHASE_GENERATING when a user starts generation.
    2. PHASE_GENERATING: The LLM plans the next phase and determines which files to create. Transitions to PHASE_IMPLEMENTING once the plan is ready.
    3. PHASE_IMPLEMENTING: Files are generated (streaming), deployed to a sandbox, and checked for errors. Transitions to REVIEWING once files are deployed.
    4. REVIEWING: A code review agent analyzes files and identifies issues.
      • If more phases are needed, it loops back to PHASE_GENERATING.
      • If it is the final review, it transitions to FINALIZING.
    5. FINALIZING: Final code review and fixes are applied. Transitions to IDLE once complete.

    State Persistence

    State is stored in CodeGenState.currentDevState. This allows the generation process to survive page refreshes and resume if shouldBeGenerating is true while the state is IDLE.

  7. LLM Inference System Overview

    main

    The inference engine located at /worker/agents/inferutils/ provides centralized access to LLMs with the following capabilities:

    • Multi-provider support: Uses OpenAI and Anthropic via Cloudflare AI Gateway.
    • Streaming: Supports Server-Sent Events (SSE) for real-time code generation and conversation feedback.
    • Tool Calling: Supports recursive execution of tool calls with a configurable maximum depth.
    • Resiliency: Implements a retry loop (max 3 attempts) with exponential backoff (1s, 2s, 4s) for rate limits (429) and 5xx errors.
    • Cancellation: Supports AbortController to immediately stop nested operations and HTTP requests when a user cancels.
  8. Understand the Chat View Architecture

    main

    The Chat View is composed of a core layout and a state management system:

    Layout Structure

    • Left Panel (40%): Contains chat messages, the phase timeline, deployment controls, and the chat input.
    • Right Panel (60%): Displays the Editor view, a Preview iframe, or Blueprint markdown.

    State Management

    The use-chat hook manages the following state properties:

    • files: Array of FileType (generated files).
    • phaseTimeline: Array of PhaseTimelineItem (progress of implementation phases).
    • messages: Array of ChatMessage (chat history).
    • websocket: The active WebSocket connection.
    • isGenerating: Boolean indicating if the AI is currently generating.
    • previewUrl: The URL for the preview deployment.
  9. Understand the Database Architecture

    main

    The database layer is built on Cloudflare D1 (SQLite) using Drizzle ORM for type-safe queries. The architecture follows a layered approach:

    1. API Controllers: Handle HTTP requests and input validation.
    2. Domain Services: Contain business logic and transaction management (e.g., AppService, UserService). These extend BaseService.
    3. BaseService: Provides common utilities like database connection management, read replica access, and error handling.
    4. DatabaseService: Manages the primary connection (for writes) and read replica connections (for reads).
    5. Cloudflare D1: The underlying serverless SQLite storage with global distribution via primary and read replicas.
  10. Understand the SimpleCodeGeneratorAgent lifecycle

    main

    The SimpleCodeGeneratorAgent is a Durable Object that manages the app generation lifecycle through a state machine. Its core operations include:

    1. Blueprint Generation: Analyzes user prompts to create a PRD (project structure, tech stack, etc.).
    2. Phase Generation: Plans the files needed for the next development phase.
    3. Phase Implementation: Generates files and commits them to git using isomorphic-git in SQLite.
    4. Code Review & Fixing: Runs TypeScript static analysis to automatically fix common errors (e.g., TS2304, TS2307).
    5. Deployment to Sandbox: Syncs files to a remote container, installs dependencies, and starts a dev server.
    6. User Conversation: Handles real-time chat and feature requests via WebSockets.
    7. Deep Debugging: Spawns a DeepCodeDebugger to diagnose and fix runtime errors using logs and static analysis.
  11. Understand the Durable Object Agent Pattern

    main

    Each chat session is managed by a Durable Object instance, which separates state into two categories:

    Persistent State

    Stored in SQLite and survives page refreshes. This includes the blueprint, files, and history.

    Ephemeral State

    Stored in-memory and is lost on eviction. This includes abort controllers and active promises.

    Key Characteristics:

    • Lifecycle: Created on-demand and evicted after inactivity.
    • Concurrency: Single-threaded per Durable Object instance.
  12. Understand the AI Operations Pipeline

    main

    The AI generation process follows a structured pipeline controlled by a deterministic state machine:

    1. Planning Phase: Selects Cloudflare Stack Templates and generates a Blueprint (PRD + Architecture Design).
    2. State Machine Control: The generateAllFiles() controller manages transitions between states:
      • PHASE_GENERATING $\rightarrow$ PHASE_IMPLEMENTING $\rightarrow$ REVIEWING $\rightarrow$ FINALIZING $\rightarrow$ IDLE.
    3. Operations Layer: Executes specific tasks like Phase Implementation (using SCOF streaming format), Code Review, and Fast Code Fixing.
    4. Quality Assurance: Includes up to 5 review cycles, static analysis, and automated issue detection/fixing.
    5. AI Gateway: Routes requests to multiple providers (Gemini, GPT-4, Claude, Cerebras) via Cloudflare AI Gateway.