Cloudflare VibeSDK
repository·main·Indexed 26 days ago
https://github.com/cloudflare/vibesdkAn 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.
What's inside VibeSDK
- 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.
Understand the Cloudflare Orange Build System Architecture
mainThe 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 persistentAgentState. - 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.
Use the Git System (isomorphic-git)
mainVibesdk uses
isomorphic-gitto 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(), andbuildCloneRepository(). - 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.
- GitService: Provides high-level methods like
Project Architecture and Tech Stack Overview
mainThe
vibesdkproject 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
Review the Technology Stack
mainThe 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.
Understand the Code Generation State Machine
mainThe code generation process follows a specific state machine defined by the
CurrentDevStateenum. Understanding these states is critical for managing or resuming generation tasks.States and Transitions
- IDLE: No active generation. Transition to
PHASE_GENERATINGwhen a user starts generation. - PHASE_GENERATING: The LLM plans the next phase and determines which files to create. Transitions to
PHASE_IMPLEMENTINGonce the plan is ready. - PHASE_IMPLEMENTING: Files are generated (streaming), deployed to a sandbox, and checked for errors. Transitions to
REVIEWINGonce files are deployed. - 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.
- If more phases are needed, it loops back to
- FINALIZING: Final code review and fixes are applied. Transitions to
IDLEonce complete.
State Persistence
State is stored in
CodeGenState.currentDevState. This allows the generation process to survive page refreshes and resume ifshouldBeGeneratingis true while the state isIDLE.- IDLE: No active generation. Transition to
LLM Inference System Overview
mainThe 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
AbortControllerto immediately stop nested operations and HTTP requests when a user cancels.
Understand the Chat View Architecture
mainThe 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-chathook manages the following state properties:files: Array ofFileType(generated files).phaseTimeline: Array ofPhaseTimelineItem(progress of implementation phases).messages: Array ofChatMessage(chat history).websocket: The activeWebSocketconnection.isGenerating: Boolean indicating if the AI is currently generating.previewUrl: The URL for the preview deployment.
Understand the Database Architecture
mainThe database layer is built on Cloudflare D1 (SQLite) using Drizzle ORM for type-safe queries. The architecture follows a layered approach:
- API Controllers: Handle HTTP requests and input validation.
- Domain Services: Contain business logic and transaction management (e.g.,
AppService,UserService). These extendBaseService. - BaseService: Provides common utilities like database connection management, read replica access, and error handling.
- DatabaseService: Manages the primary connection (for writes) and read replica connections (for reads).
- Cloudflare D1: The underlying serverless SQLite storage with global distribution via primary and read replicas.
Understand the SimpleCodeGeneratorAgent lifecycle
mainThe
SimpleCodeGeneratorAgentis a Durable Object that manages the app generation lifecycle through a state machine. Its core operations include:- Blueprint Generation: Analyzes user prompts to create a PRD (project structure, tech stack, etc.).
- Phase Generation: Plans the files needed for the next development phase.
- Phase Implementation: Generates files and commits them to git using
isomorphic-gitin SQLite. - Code Review & Fixing: Runs TypeScript static analysis to automatically fix common errors (e.g.,
TS2304,TS2307). - Deployment to Sandbox: Syncs files to a remote container, installs dependencies, and starts a dev server.
- User Conversation: Handles real-time chat and feature requests via WebSockets.
- Deep Debugging: Spawns a
DeepCodeDebuggerto diagnose and fix runtime errors using logs and static analysis.
Understand the Durable Object Agent Pattern
mainEach 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, andhistory.Ephemeral State
Stored in-memory and is lost on eviction. This includes
abort controllersandactive promises.Key Characteristics:
- Lifecycle: Created on-demand and evicted after inactivity.
- Concurrency: Single-threaded per Durable Object instance.
Understand the AI Operations Pipeline
mainThe AI generation process follows a structured pipeline controlled by a deterministic state machine:
- Planning Phase: Selects Cloudflare Stack Templates and generates a Blueprint (PRD + Architecture Design).
- State Machine Control: The
generateAllFiles()controller manages transitions between states:PHASE_GENERATING$\rightarrow$PHASE_IMPLEMENTING$\rightarrow$REVIEWING$\rightarrow$FINALIZING$\rightarrow$IDLE.
- Operations Layer: Executes specific tasks like Phase Implementation (using SCOF streaming format), Code Review, and Fast Code Fixing.
- Quality Assurance: Includes up to 5 review cycles, static analysis, and automated issue detection/fixing.
- AI Gateway: Routes requests to multiple providers (Gemini, GPT-4, Claude, Cerebras) via Cloudflare AI Gateway.